file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
formdata.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::error::{Fallible}; use dom::bindings::codegen::FormDataBinding; use dom::bindings::js::JS;
use dom::blob::Blob; use dom::htmlformelement::HTMLFormElement; use dom::window::Window; use servo_util::str::DOMString; use collections::hashmap::HashMap; #[deriving(Encodable)] pub enum FormDatum { StringData(DOMString), BlobData { blob: JS<Blob>, name: DOMString } } #[deriving(Encodable)] pub struct FormData { data: HashMap<DOMString, FormDatum>, reflector_: Reflector, window: JS<Window>, form: Option<JS<HTMLFormElement>> } impl FormData { pub fn new_inherited(form: Option<JS<HTMLFormElement>>, window: JS<Window>) -> FormData { FormData { data: HashMap::new(), reflector_: Reflector::new(), window: window, form: form } } pub fn new(form: Option<JS<HTMLFormElement>>, window: &JS<Window>) -> JS<FormData> { reflect_dom_object(~FormData::new_inherited(form, window.clone()), window, FormDataBinding::Wrap) } pub fn Constructor(window: &JS<Window>, form: Option<JS<HTMLFormElement>>) -> Fallible<JS<FormData>> { Ok(FormData::new(form, window)) } pub fn Append(&mut self, name: DOMString, value: &JS<Blob>, filename: Option<DOMString>) { let blob = BlobData { blob: value.clone(), name: filename.unwrap_or(~"default") }; self.data.insert(name.clone(), blob); } pub fn Append_(&mut self, name: DOMString, value: DOMString) { self.data.insert(name, StringData(value)); } } impl Reflectable for FormData { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector { &mut self.reflector_ } }
random_line_split
events.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate glfw; use glfw::{Action, Context, Key}; fn main()
window.set_close_polling(true); window.set_refresh_polling(true); window.set_focus_polling(true); window.set_iconify_polling(true); window.set_framebuffer_size_polling(true); window.set_key_polling(true); window.set_char_polling(true); window.set_char_mods_polling(true); window.set_mouse_button_polling(true); window.set_cursor_pos_polling(true); window.set_cursor_enter_polling(true); window.set_scroll_polling(true); window.set_maximize_polling(true); window.set_content_scale_polling(true); // Alternatively, all event types may be set to poll at once. Note that // in this example, this call is redundant as all events have been set // to poll in the above code. window.set_all_polling(true); window.make_current(); while!window.should_close() { glfw.poll_events(); for event in glfw::flush_messages(&events) { handle_window_event(&mut window, event); } } } fn handle_window_event(window: &mut glfw::Window, (time, event): (f64, glfw::WindowEvent)) { match event { glfw::WindowEvent::Pos(x, y) => { window.set_title(&format!("Time: {:?}, Window pos: ({:?}, {:?})", time, x, y)) } glfw::WindowEvent::Size(w, h) => window.set_title(&format!( "Time: {:?}, Window size: ({:?}, {:?})", time, w, h )), glfw::WindowEvent::Close => println!("Time: {:?}, Window close requested.", time), glfw::WindowEvent::Refresh => { println!("Time: {:?}, Window refresh callback triggered.", time) } glfw::WindowEvent::Focus(true) => println!("Time: {:?}, Window focus gained.", time), glfw::WindowEvent::Focus(false) => println!("Time: {:?}, Window focus lost.", time), glfw::WindowEvent::Iconify(true) => println!("Time: {:?}, Window was minimised", time), glfw::WindowEvent::Iconify(false) => println!("Time: {:?}, Window was maximised.", time), glfw::WindowEvent::FramebufferSize(w, h) => { println!("Time: {:?}, Framebuffer size: ({:?}, {:?})", time, w, h) } glfw::WindowEvent::Char(character) => { println!("Time: {:?}, Character: {:?}", time, character) } glfw::WindowEvent::CharModifiers(character, mods) => println!( "Time: {:?}, Character: {:?}, Modifiers: [{:?}]", time, character, mods ), glfw::WindowEvent::MouseButton(btn, action, mods) => println!( "Time: {:?}, Button: {:?}, Action: {:?}, Modifiers: [{:?}]", time, glfw::DebugAliases(btn), action, mods ), glfw::WindowEvent::CursorPos(xpos, ypos) => window.set_title(&format!( "Time: {:?}, Cursor position: ({:?}, {:?})", time, xpos, ypos )), glfw::WindowEvent::CursorEnter(true) => { println!("Time: {:?}, Cursor entered window.", time) } glfw::WindowEvent::CursorEnter(false) => println!("Time: {:?}, Cursor left window.", time), glfw::WindowEvent::Scroll(x, y) => window.set_title(&format!( "Time: {:?}, Scroll offset: ({:?}, {:?})", time, x, y )), glfw::WindowEvent::Key(key, scancode, action, mods) => { println!( "Time: {:?}, Key: {:?}, ScanCode: {:?}, Action: {:?}, Modifiers: [{:?}]", time, key, scancode, action, mods ); match (key, action) { (Key::Escape, Action::Press) => window.set_should_close(true), (Key::R, Action::Press) => { // Resize should cause the window to "refresh" let (window_width, window_height) = window.get_size(); window.set_size(window_width + 1, window_height); window.set_size(window_width, window_height); } _ => {} } } glfw::WindowEvent::FileDrop(paths) => { println!("Time: {:?}, Files dropped: {:?}", time, paths) } glfw::WindowEvent::Maximize(maximized) => { println!("Time: {:?}, Window maximized: {:?}.", time, maximized) } glfw::WindowEvent::ContentScale(xscale, yscale) => println!( "Time: {:?}, Content scale x: {:?}, Content scale y: {:?}", time, xscale, yscale ), } }
{ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::Resizable(true)); let (mut window, events) = glfw .create_window( 800, 600, "Hello, I am a window.", glfw::WindowMode::Windowed, ) .expect("Failed to create GLFW window."); window.set_sticky_keys(true); // Polling of events can be turned on and off by the specific event type window.set_pos_polling(true); window.set_all_polling(true); window.set_size_polling(true);
identifier_body
events.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate glfw; use glfw::{Action, Context, Key}; fn main() { let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::Resizable(true)); let (mut window, events) = glfw .create_window( 800, 600, "Hello, I am a window.", glfw::WindowMode::Windowed, ) .expect("Failed to create GLFW window."); window.set_sticky_keys(true); // Polling of events can be turned on and off by the specific event type window.set_pos_polling(true); window.set_all_polling(true); window.set_size_polling(true); window.set_close_polling(true); window.set_refresh_polling(true); window.set_focus_polling(true); window.set_iconify_polling(true); window.set_framebuffer_size_polling(true); window.set_key_polling(true); window.set_char_polling(true); window.set_char_mods_polling(true); window.set_mouse_button_polling(true); window.set_cursor_pos_polling(true); window.set_cursor_enter_polling(true); window.set_scroll_polling(true); window.set_maximize_polling(true); window.set_content_scale_polling(true); // Alternatively, all event types may be set to poll at once. Note that // in this example, this call is redundant as all events have been set // to poll in the above code. window.set_all_polling(true); window.make_current(); while!window.should_close() { glfw.poll_events(); for event in glfw::flush_messages(&events) { handle_window_event(&mut window, event); } } } fn handle_window_event(window: &mut glfw::Window, (time, event): (f64, glfw::WindowEvent)) { match event { glfw::WindowEvent::Pos(x, y) => { window.set_title(&format!("Time: {:?}, Window pos: ({:?}, {:?})", time, x, y)) } glfw::WindowEvent::Size(w, h) => window.set_title(&format!( "Time: {:?}, Window size: ({:?}, {:?})", time, w, h )), glfw::WindowEvent::Close => println!("Time: {:?}, Window close requested.", time), glfw::WindowEvent::Refresh => { println!("Time: {:?}, Window refresh callback triggered.", time) } glfw::WindowEvent::Focus(true) => println!("Time: {:?}, Window focus gained.", time), glfw::WindowEvent::Focus(false) => println!("Time: {:?}, Window focus lost.", time), glfw::WindowEvent::Iconify(true) => println!("Time: {:?}, Window was minimised", time), glfw::WindowEvent::Iconify(false) => println!("Time: {:?}, Window was maximised.", time), glfw::WindowEvent::FramebufferSize(w, h) => { println!("Time: {:?}, Framebuffer size: ({:?}, {:?})", time, w, h) } glfw::WindowEvent::Char(character) => { println!("Time: {:?}, Character: {:?}", time, character) } glfw::WindowEvent::CharModifiers(character, mods) => println!( "Time: {:?}, Character: {:?}, Modifiers: [{:?}]", time, character, mods ), glfw::WindowEvent::MouseButton(btn, action, mods) => println!( "Time: {:?}, Button: {:?}, Action: {:?}, Modifiers: [{:?}]", time, glfw::DebugAliases(btn), action, mods ), glfw::WindowEvent::CursorPos(xpos, ypos) => window.set_title(&format!( "Time: {:?}, Cursor position: ({:?}, {:?})", time, xpos, ypos )), glfw::WindowEvent::CursorEnter(true) => { println!("Time: {:?}, Cursor entered window.", time) } glfw::WindowEvent::CursorEnter(false) => println!("Time: {:?}, Cursor left window.", time), glfw::WindowEvent::Scroll(x, y) => window.set_title(&format!( "Time: {:?}, Scroll offset: ({:?}, {:?})", time, x, y )), glfw::WindowEvent::Key(key, scancode, action, mods) => { println!( "Time: {:?}, Key: {:?}, ScanCode: {:?}, Action: {:?}, Modifiers: [{:?}]", time, key, scancode, action, mods ); match (key, action) { (Key::Escape, Action::Press) => window.set_should_close(true), (Key::R, Action::Press) => {
let (window_width, window_height) = window.get_size(); window.set_size(window_width + 1, window_height); window.set_size(window_width, window_height); } _ => {} } } glfw::WindowEvent::FileDrop(paths) => { println!("Time: {:?}, Files dropped: {:?}", time, paths) } glfw::WindowEvent::Maximize(maximized) => { println!("Time: {:?}, Window maximized: {:?}.", time, maximized) } glfw::WindowEvent::ContentScale(xscale, yscale) => println!( "Time: {:?}, Content scale x: {:?}, Content scale y: {:?}", time, xscale, yscale ), } }
// Resize should cause the window to "refresh"
random_line_split
events.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate glfw; use glfw::{Action, Context, Key}; fn main() { let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::Resizable(true)); let (mut window, events) = glfw .create_window( 800, 600, "Hello, I am a window.", glfw::WindowMode::Windowed, ) .expect("Failed to create GLFW window."); window.set_sticky_keys(true); // Polling of events can be turned on and off by the specific event type window.set_pos_polling(true); window.set_all_polling(true); window.set_size_polling(true); window.set_close_polling(true); window.set_refresh_polling(true); window.set_focus_polling(true); window.set_iconify_polling(true); window.set_framebuffer_size_polling(true); window.set_key_polling(true); window.set_char_polling(true); window.set_char_mods_polling(true); window.set_mouse_button_polling(true); window.set_cursor_pos_polling(true); window.set_cursor_enter_polling(true); window.set_scroll_polling(true); window.set_maximize_polling(true); window.set_content_scale_polling(true); // Alternatively, all event types may be set to poll at once. Note that // in this example, this call is redundant as all events have been set // to poll in the above code. window.set_all_polling(true); window.make_current(); while!window.should_close() { glfw.poll_events(); for event in glfw::flush_messages(&events) { handle_window_event(&mut window, event); } } } fn
(window: &mut glfw::Window, (time, event): (f64, glfw::WindowEvent)) { match event { glfw::WindowEvent::Pos(x, y) => { window.set_title(&format!("Time: {:?}, Window pos: ({:?}, {:?})", time, x, y)) } glfw::WindowEvent::Size(w, h) => window.set_title(&format!( "Time: {:?}, Window size: ({:?}, {:?})", time, w, h )), glfw::WindowEvent::Close => println!("Time: {:?}, Window close requested.", time), glfw::WindowEvent::Refresh => { println!("Time: {:?}, Window refresh callback triggered.", time) } glfw::WindowEvent::Focus(true) => println!("Time: {:?}, Window focus gained.", time), glfw::WindowEvent::Focus(false) => println!("Time: {:?}, Window focus lost.", time), glfw::WindowEvent::Iconify(true) => println!("Time: {:?}, Window was minimised", time), glfw::WindowEvent::Iconify(false) => println!("Time: {:?}, Window was maximised.", time), glfw::WindowEvent::FramebufferSize(w, h) => { println!("Time: {:?}, Framebuffer size: ({:?}, {:?})", time, w, h) } glfw::WindowEvent::Char(character) => { println!("Time: {:?}, Character: {:?}", time, character) } glfw::WindowEvent::CharModifiers(character, mods) => println!( "Time: {:?}, Character: {:?}, Modifiers: [{:?}]", time, character, mods ), glfw::WindowEvent::MouseButton(btn, action, mods) => println!( "Time: {:?}, Button: {:?}, Action: {:?}, Modifiers: [{:?}]", time, glfw::DebugAliases(btn), action, mods ), glfw::WindowEvent::CursorPos(xpos, ypos) => window.set_title(&format!( "Time: {:?}, Cursor position: ({:?}, {:?})", time, xpos, ypos )), glfw::WindowEvent::CursorEnter(true) => { println!("Time: {:?}, Cursor entered window.", time) } glfw::WindowEvent::CursorEnter(false) => println!("Time: {:?}, Cursor left window.", time), glfw::WindowEvent::Scroll(x, y) => window.set_title(&format!( "Time: {:?}, Scroll offset: ({:?}, {:?})", time, x, y )), glfw::WindowEvent::Key(key, scancode, action, mods) => { println!( "Time: {:?}, Key: {:?}, ScanCode: {:?}, Action: {:?}, Modifiers: [{:?}]", time, key, scancode, action, mods ); match (key, action) { (Key::Escape, Action::Press) => window.set_should_close(true), (Key::R, Action::Press) => { // Resize should cause the window to "refresh" let (window_width, window_height) = window.get_size(); window.set_size(window_width + 1, window_height); window.set_size(window_width, window_height); } _ => {} } } glfw::WindowEvent::FileDrop(paths) => { println!("Time: {:?}, Files dropped: {:?}", time, paths) } glfw::WindowEvent::Maximize(maximized) => { println!("Time: {:?}, Window maximized: {:?}.", time, maximized) } glfw::WindowEvent::ContentScale(xscale, yscale) => println!( "Time: {:?}, Content scale x: {:?}, Content scale y: {:?}", time, xscale, yscale ), } }
handle_window_event
identifier_name
issue-23302.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Check that an enum with recursion in the discriminant throws // the appropriate error (rather than, say, blowing the stack). enum X { A = X::A as isize, //~ ERROR E0265 } // Since `Y::B` here defaults to `Y::A+1`, this is also a // recursive definition. enum Y { A = Y::B as isize, //~ ERROR E0265 B, } fn
() { }
main
identifier_name
issue-23302.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Check that an enum with recursion in the discriminant throws // the appropriate error (rather than, say, blowing the stack). enum X { A = X::A as isize, //~ ERROR E0265 }
enum Y { A = Y::B as isize, //~ ERROR E0265 B, } fn main() { }
// Since `Y::B` here defaults to `Y::A+1`, this is also a // recursive definition.
random_line_split
issue-23302.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Check that an enum with recursion in the discriminant throws // the appropriate error (rather than, say, blowing the stack). enum X { A = X::A as isize, //~ ERROR E0265 } // Since `Y::B` here defaults to `Y::A+1`, this is also a // recursive definition. enum Y { A = Y::B as isize, //~ ERROR E0265 B, } fn main()
{ }
identifier_body
scale_button.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with rgtk. If not, see <http://www.gnu.org/licenses/>. use libc::c_double; use gtk::cast::GTK_SCALEBUTTON; use gtk::{self, ffi}; pub trait ScaleButtonTrait: gtk::WidgetTrait + gtk::ContainerTrait + gtk::ButtonTrait { fn set_adjustment(&mut self, adjustment: &gtk::Adjustment) -> () { unsafe { ffi::gtk_scale_button_set_adjustment(GTK_SCALEBUTTON(self.unwrap_widget()), adjustment.unwrap_pointer()); } } fn set_value(&mut self, value: f64) -> () { unsafe { ffi::gtk_scale_button_set_value(GTK_SCALEBUTTON(self.unwrap_widget()), value as c_double); } } fn get_value(&self) -> f64 { unsafe { ffi::gtk_scale_button_get_value(GTK_SCALEBUTTON(self.unwrap_widget())) as f64 } } fn get_adjustment(&self) -> gtk::Adjustment
}
{ unsafe { gtk::Adjustment::wrap_pointer(ffi::gtk_scale_button_get_adjustment(GTK_SCALEBUTTON(self.unwrap_widget()))) } }
identifier_body
scale_button.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with rgtk. If not, see <http://www.gnu.org/licenses/>. use libc::c_double; use gtk::cast::GTK_SCALEBUTTON; use gtk::{self, ffi}; pub trait ScaleButtonTrait: gtk::WidgetTrait + gtk::ContainerTrait + gtk::ButtonTrait { fn set_adjustment(&mut self, adjustment: &gtk::Adjustment) -> () { unsafe { ffi::gtk_scale_button_set_adjustment(GTK_SCALEBUTTON(self.unwrap_widget()), adjustment.unwrap_pointer()); } } fn set_value(&mut self, value: f64) -> () { unsafe { ffi::gtk_scale_button_set_value(GTK_SCALEBUTTON(self.unwrap_widget()), value as c_double); } } fn get_value(&self) -> f64 { unsafe { ffi::gtk_scale_button_get_value(GTK_SCALEBUTTON(self.unwrap_widget())) as f64 } }
} }
fn get_adjustment(&self) -> gtk::Adjustment { unsafe { gtk::Adjustment::wrap_pointer(ffi::gtk_scale_button_get_adjustment(GTK_SCALEBUTTON(self.unwrap_widget()))) }
random_line_split
scale_button.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with rgtk. If not, see <http://www.gnu.org/licenses/>. use libc::c_double; use gtk::cast::GTK_SCALEBUTTON; use gtk::{self, ffi}; pub trait ScaleButtonTrait: gtk::WidgetTrait + gtk::ContainerTrait + gtk::ButtonTrait { fn set_adjustment(&mut self, adjustment: &gtk::Adjustment) -> () { unsafe { ffi::gtk_scale_button_set_adjustment(GTK_SCALEBUTTON(self.unwrap_widget()), adjustment.unwrap_pointer()); } } fn
(&mut self, value: f64) -> () { unsafe { ffi::gtk_scale_button_set_value(GTK_SCALEBUTTON(self.unwrap_widget()), value as c_double); } } fn get_value(&self) -> f64 { unsafe { ffi::gtk_scale_button_get_value(GTK_SCALEBUTTON(self.unwrap_widget())) as f64 } } fn get_adjustment(&self) -> gtk::Adjustment { unsafe { gtk::Adjustment::wrap_pointer(ffi::gtk_scale_button_get_adjustment(GTK_SCALEBUTTON(self.unwrap_widget()))) } } }
set_value
identifier_name
mod.rs
use std::default::Default; use std::str::FromStr; use std::string::ToString; mod tag; pub use self::tag::Tag; #[derive(Debug)] pub struct Playlist { tags: Vec<Tag> } impl Default for Playlist { fn default() -> Playlist { let mut tags: Vec<Tag> = Vec::new(); tags.push(Tag::M3U); tags.push(Tag::VERSION(3)); Playlist {tags: tags} } } impl ToString for Playlist { fn to_string(&self) -> String { self.tags.iter().map(|tag: &Tag| -> String { tag.to_string() }).collect::<Vec<String>>().join("\n") }
} impl FromStr for Playlist { type Err = (); fn from_str(s: &str) -> Result<Playlist, ()> { let mut lines: Vec<&str> = s.split("#").collect(); lines.remove(0); let mut tags: Vec<Tag> = Vec::new(); for line in lines.iter(){ match Tag::from_str(line.trim()) { Ok(tag) => tags.push(tag), Err(e) => println!("[Playlist] Parse fail ({:?})", e) }; } // TODO: verify tags if tags.len() == 0 { Err(()) } else { Ok(Playlist{tags: tags}) } } } impl Playlist { pub fn new () -> Playlist { let tags: Vec<Tag> = Vec::new(); Playlist{tags: tags} } pub fn append(&mut self, tag: Tag) { self.tags.push(tag); } pub fn tags(&self) -> &[Tag] { self.tags.as_slice() } }
random_line_split
mod.rs
use std::default::Default; use std::str::FromStr; use std::string::ToString; mod tag; pub use self::tag::Tag; #[derive(Debug)] pub struct Playlist { tags: Vec<Tag> } impl Default for Playlist { fn default() -> Playlist { let mut tags: Vec<Tag> = Vec::new(); tags.push(Tag::M3U); tags.push(Tag::VERSION(3)); Playlist {tags: tags} } } impl ToString for Playlist { fn
(&self) -> String { self.tags.iter().map(|tag: &Tag| -> String { tag.to_string() }).collect::<Vec<String>>().join("\n") } } impl FromStr for Playlist { type Err = (); fn from_str(s: &str) -> Result<Playlist, ()> { let mut lines: Vec<&str> = s.split("#").collect(); lines.remove(0); let mut tags: Vec<Tag> = Vec::new(); for line in lines.iter(){ match Tag::from_str(line.trim()) { Ok(tag) => tags.push(tag), Err(e) => println!("[Playlist] Parse fail ({:?})", e) }; } // TODO: verify tags if tags.len() == 0 { Err(()) } else { Ok(Playlist{tags: tags}) } } } impl Playlist { pub fn new () -> Playlist { let tags: Vec<Tag> = Vec::new(); Playlist{tags: tags} } pub fn append(&mut self, tag: Tag) { self.tags.push(tag); } pub fn tags(&self) -> &[Tag] { self.tags.as_slice() } }
to_string
identifier_name
mod.rs
use std::default::Default; use std::str::FromStr; use std::string::ToString; mod tag; pub use self::tag::Tag; #[derive(Debug)] pub struct Playlist { tags: Vec<Tag> } impl Default for Playlist { fn default() -> Playlist { let mut tags: Vec<Tag> = Vec::new(); tags.push(Tag::M3U); tags.push(Tag::VERSION(3)); Playlist {tags: tags} } } impl ToString for Playlist { fn to_string(&self) -> String { self.tags.iter().map(|tag: &Tag| -> String { tag.to_string() }).collect::<Vec<String>>().join("\n") } } impl FromStr for Playlist { type Err = (); fn from_str(s: &str) -> Result<Playlist, ()> { let mut lines: Vec<&str> = s.split("#").collect(); lines.remove(0); let mut tags: Vec<Tag> = Vec::new(); for line in lines.iter(){ match Tag::from_str(line.trim()) { Ok(tag) => tags.push(tag), Err(e) => println!("[Playlist] Parse fail ({:?})", e) }; } // TODO: verify tags if tags.len() == 0 { Err(()) } else { Ok(Playlist{tags: tags}) } } } impl Playlist { pub fn new () -> Playlist { let tags: Vec<Tag> = Vec::new(); Playlist{tags: tags} } pub fn append(&mut self, tag: Tag) { self.tags.push(tag); } pub fn tags(&self) -> &[Tag]
}
{ self.tags.as_slice() }
identifier_body
mod.rs
use std::default::Default; use std::str::FromStr; use std::string::ToString; mod tag; pub use self::tag::Tag; #[derive(Debug)] pub struct Playlist { tags: Vec<Tag> } impl Default for Playlist { fn default() -> Playlist { let mut tags: Vec<Tag> = Vec::new(); tags.push(Tag::M3U); tags.push(Tag::VERSION(3)); Playlist {tags: tags} } } impl ToString for Playlist { fn to_string(&self) -> String { self.tags.iter().map(|tag: &Tag| -> String { tag.to_string() }).collect::<Vec<String>>().join("\n") } } impl FromStr for Playlist { type Err = (); fn from_str(s: &str) -> Result<Playlist, ()> { let mut lines: Vec<&str> = s.split("#").collect(); lines.remove(0); let mut tags: Vec<Tag> = Vec::new(); for line in lines.iter(){ match Tag::from_str(line.trim()) { Ok(tag) => tags.push(tag), Err(e) => println!("[Playlist] Parse fail ({:?})", e) }; } // TODO: verify tags if tags.len() == 0 { Err(()) } else
} } impl Playlist { pub fn new () -> Playlist { let tags: Vec<Tag> = Vec::new(); Playlist{tags: tags} } pub fn append(&mut self, tag: Tag) { self.tags.push(tag); } pub fn tags(&self) -> &[Tag] { self.tags.as_slice() } }
{ Ok(Playlist{tags: tags}) }
conditional_block
testutil.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashSet; use std::str::FromStr; use quickcheck::Arbitrary; use quickcheck::Gen; use crate::hgid::HgId; use crate::key::Key; use crate::path::PathComponent; use crate::path::PathComponentBuf; use crate::path::RepoPath; use crate::path::RepoPathBuf; pub fn repo_path(s: &str) -> &RepoPath { if s == "" { panic!("the empty repo path is special, use RepoPath::empty() to build"); } RepoPath::from_str(s).unwrap() } pub fn repo_path_buf(s: &str) -> RepoPathBuf { if s == "" { panic!("the empty repo path is special, use RepoPathBuf::new() to build"); } RepoPathBuf::from_string(s.to_owned()).unwrap() } pub fn path_component(s: &str) -> &PathComponent { PathComponent::from_str(s).unwrap() } pub fn path_component_buf(s: &str) -> PathComponentBuf { PathComponentBuf::from_string(s.to_owned()).unwrap() } pub fn hgid(hex: &str) -> HgId { if hex.len() > HgId::hex_len() { panic!("invalid length for hex hgid: {}", hex); } if hex == "0" {
} let mut buffer = String::new(); for _i in 0..HgId::hex_len() - hex.len() { buffer.push('0'); } buffer.push_str(hex); HgId::from_str(&buffer).unwrap() } pub fn key(path: &str, hexnode: &str) -> Key { Key::new(repo_path_buf(path), hgid(hexnode)) } /// The null hgid id is special and it's semantics vary. A null key contains a null hgid id. pub fn null_key(path: &str) -> Key { Key::new(repo_path_buf(path), HgId::null_id().clone()) } pub fn generate_repo_paths(count: usize, qc_gen: &mut Gen) -> Vec<RepoPathBuf> { struct Generator<'a> { current_path: RepoPathBuf, current_component_length: usize, min_files_per_dir: usize, directory_component_min: usize, directory_component_max: usize, generated_paths: Vec<RepoPathBuf>, generate_paths_cnt: usize, qc_gen: &'a mut Gen, } impl<'a> Generator<'a> { fn generate_directory(&mut self) { let dir_components_cnt = if self.current_component_length == 0 { std::usize::MAX } else { self.directory_component_min + usize::arbitrary(&mut self.qc_gen) % (self.directory_component_max - self.directory_component_min) }; let mut component_hash = HashSet::new(); for i in 0..dir_components_cnt { if self.generate_paths_cnt <= self.generated_paths.len() { break; } let component = PathComponentBuf::arbitrary(self.qc_gen); if component_hash.contains(&component) { continue; } self.current_path.push(component.as_ref()); component_hash.insert(component); self.current_component_length += 1; // Decide if this is a directory. As we nest more and more directories, the // probabilty of having directories decreses. let u = self.current_component_length as u32; if i < self.min_files_per_dir || ((u64::arbitrary(self.qc_gen) % ((u + 2) as u64)) as u32) < u + 1 { self.generated_paths.push(self.current_path.clone()); } else { self.generate_directory(); } self.current_path.pop(); self.current_component_length -= 1; } } } let mut generator = Generator { current_path: RepoPathBuf::new(), current_component_length: 0, min_files_per_dir: 2, directory_component_min: 3, directory_component_max: 20, generated_paths: Vec::with_capacity(count), generate_paths_cnt: count, qc_gen, }; generator.generate_directory(); generator.generated_paths } #[cfg(test)] mod tests { use quickcheck::Gen; use super::*; #[test] fn test_generate_repo_paths() { let mut qc_gen = Gen::new(10); let count = 10000; let paths = generate_repo_paths(count, &mut qc_gen); assert_eq!(paths.len(), count); } }
panic!("hgid 0 is special, use HgId::null_id() to build");
random_line_split
testutil.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashSet; use std::str::FromStr; use quickcheck::Arbitrary; use quickcheck::Gen; use crate::hgid::HgId; use crate::key::Key; use crate::path::PathComponent; use crate::path::PathComponentBuf; use crate::path::RepoPath; use crate::path::RepoPathBuf; pub fn repo_path(s: &str) -> &RepoPath
pub fn repo_path_buf(s: &str) -> RepoPathBuf { if s == "" { panic!("the empty repo path is special, use RepoPathBuf::new() to build"); } RepoPathBuf::from_string(s.to_owned()).unwrap() } pub fn path_component(s: &str) -> &PathComponent { PathComponent::from_str(s).unwrap() } pub fn path_component_buf(s: &str) -> PathComponentBuf { PathComponentBuf::from_string(s.to_owned()).unwrap() } pub fn hgid(hex: &str) -> HgId { if hex.len() > HgId::hex_len() { panic!("invalid length for hex hgid: {}", hex); } if hex == "0" { panic!("hgid 0 is special, use HgId::null_id() to build"); } let mut buffer = String::new(); for _i in 0..HgId::hex_len() - hex.len() { buffer.push('0'); } buffer.push_str(hex); HgId::from_str(&buffer).unwrap() } pub fn key(path: &str, hexnode: &str) -> Key { Key::new(repo_path_buf(path), hgid(hexnode)) } /// The null hgid id is special and it's semantics vary. A null key contains a null hgid id. pub fn null_key(path: &str) -> Key { Key::new(repo_path_buf(path), HgId::null_id().clone()) } pub fn generate_repo_paths(count: usize, qc_gen: &mut Gen) -> Vec<RepoPathBuf> { struct Generator<'a> { current_path: RepoPathBuf, current_component_length: usize, min_files_per_dir: usize, directory_component_min: usize, directory_component_max: usize, generated_paths: Vec<RepoPathBuf>, generate_paths_cnt: usize, qc_gen: &'a mut Gen, } impl<'a> Generator<'a> { fn generate_directory(&mut self) { let dir_components_cnt = if self.current_component_length == 0 { std::usize::MAX } else { self.directory_component_min + usize::arbitrary(&mut self.qc_gen) % (self.directory_component_max - self.directory_component_min) }; let mut component_hash = HashSet::new(); for i in 0..dir_components_cnt { if self.generate_paths_cnt <= self.generated_paths.len() { break; } let component = PathComponentBuf::arbitrary(self.qc_gen); if component_hash.contains(&component) { continue; } self.current_path.push(component.as_ref()); component_hash.insert(component); self.current_component_length += 1; // Decide if this is a directory. As we nest more and more directories, the // probabilty of having directories decreses. let u = self.current_component_length as u32; if i < self.min_files_per_dir || ((u64::arbitrary(self.qc_gen) % ((u + 2) as u64)) as u32) < u + 1 { self.generated_paths.push(self.current_path.clone()); } else { self.generate_directory(); } self.current_path.pop(); self.current_component_length -= 1; } } } let mut generator = Generator { current_path: RepoPathBuf::new(), current_component_length: 0, min_files_per_dir: 2, directory_component_min: 3, directory_component_max: 20, generated_paths: Vec::with_capacity(count), generate_paths_cnt: count, qc_gen, }; generator.generate_directory(); generator.generated_paths } #[cfg(test)] mod tests { use quickcheck::Gen; use super::*; #[test] fn test_generate_repo_paths() { let mut qc_gen = Gen::new(10); let count = 10000; let paths = generate_repo_paths(count, &mut qc_gen); assert_eq!(paths.len(), count); } }
{ if s == "" { panic!("the empty repo path is special, use RepoPath::empty() to build"); } RepoPath::from_str(s).unwrap() }
identifier_body
testutil.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashSet; use std::str::FromStr; use quickcheck::Arbitrary; use quickcheck::Gen; use crate::hgid::HgId; use crate::key::Key; use crate::path::PathComponent; use crate::path::PathComponentBuf; use crate::path::RepoPath; use crate::path::RepoPathBuf; pub fn repo_path(s: &str) -> &RepoPath { if s == "" { panic!("the empty repo path is special, use RepoPath::empty() to build"); } RepoPath::from_str(s).unwrap() } pub fn repo_path_buf(s: &str) -> RepoPathBuf { if s == "" { panic!("the empty repo path is special, use RepoPathBuf::new() to build"); } RepoPathBuf::from_string(s.to_owned()).unwrap() } pub fn path_component(s: &str) -> &PathComponent { PathComponent::from_str(s).unwrap() } pub fn path_component_buf(s: &str) -> PathComponentBuf { PathComponentBuf::from_string(s.to_owned()).unwrap() } pub fn hgid(hex: &str) -> HgId { if hex.len() > HgId::hex_len()
if hex == "0" { panic!("hgid 0 is special, use HgId::null_id() to build"); } let mut buffer = String::new(); for _i in 0..HgId::hex_len() - hex.len() { buffer.push('0'); } buffer.push_str(hex); HgId::from_str(&buffer).unwrap() } pub fn key(path: &str, hexnode: &str) -> Key { Key::new(repo_path_buf(path), hgid(hexnode)) } /// The null hgid id is special and it's semantics vary. A null key contains a null hgid id. pub fn null_key(path: &str) -> Key { Key::new(repo_path_buf(path), HgId::null_id().clone()) } pub fn generate_repo_paths(count: usize, qc_gen: &mut Gen) -> Vec<RepoPathBuf> { struct Generator<'a> { current_path: RepoPathBuf, current_component_length: usize, min_files_per_dir: usize, directory_component_min: usize, directory_component_max: usize, generated_paths: Vec<RepoPathBuf>, generate_paths_cnt: usize, qc_gen: &'a mut Gen, } impl<'a> Generator<'a> { fn generate_directory(&mut self) { let dir_components_cnt = if self.current_component_length == 0 { std::usize::MAX } else { self.directory_component_min + usize::arbitrary(&mut self.qc_gen) % (self.directory_component_max - self.directory_component_min) }; let mut component_hash = HashSet::new(); for i in 0..dir_components_cnt { if self.generate_paths_cnt <= self.generated_paths.len() { break; } let component = PathComponentBuf::arbitrary(self.qc_gen); if component_hash.contains(&component) { continue; } self.current_path.push(component.as_ref()); component_hash.insert(component); self.current_component_length += 1; // Decide if this is a directory. As we nest more and more directories, the // probabilty of having directories decreses. let u = self.current_component_length as u32; if i < self.min_files_per_dir || ((u64::arbitrary(self.qc_gen) % ((u + 2) as u64)) as u32) < u + 1 { self.generated_paths.push(self.current_path.clone()); } else { self.generate_directory(); } self.current_path.pop(); self.current_component_length -= 1; } } } let mut generator = Generator { current_path: RepoPathBuf::new(), current_component_length: 0, min_files_per_dir: 2, directory_component_min: 3, directory_component_max: 20, generated_paths: Vec::with_capacity(count), generate_paths_cnt: count, qc_gen, }; generator.generate_directory(); generator.generated_paths } #[cfg(test)] mod tests { use quickcheck::Gen; use super::*; #[test] fn test_generate_repo_paths() { let mut qc_gen = Gen::new(10); let count = 10000; let paths = generate_repo_paths(count, &mut qc_gen); assert_eq!(paths.len(), count); } }
{ panic!("invalid length for hex hgid: {}", hex); }
conditional_block
testutil.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashSet; use std::str::FromStr; use quickcheck::Arbitrary; use quickcheck::Gen; use crate::hgid::HgId; use crate::key::Key; use crate::path::PathComponent; use crate::path::PathComponentBuf; use crate::path::RepoPath; use crate::path::RepoPathBuf; pub fn repo_path(s: &str) -> &RepoPath { if s == "" { panic!("the empty repo path is special, use RepoPath::empty() to build"); } RepoPath::from_str(s).unwrap() } pub fn repo_path_buf(s: &str) -> RepoPathBuf { if s == "" { panic!("the empty repo path is special, use RepoPathBuf::new() to build"); } RepoPathBuf::from_string(s.to_owned()).unwrap() } pub fn path_component(s: &str) -> &PathComponent { PathComponent::from_str(s).unwrap() } pub fn path_component_buf(s: &str) -> PathComponentBuf { PathComponentBuf::from_string(s.to_owned()).unwrap() } pub fn hgid(hex: &str) -> HgId { if hex.len() > HgId::hex_len() { panic!("invalid length for hex hgid: {}", hex); } if hex == "0" { panic!("hgid 0 is special, use HgId::null_id() to build"); } let mut buffer = String::new(); for _i in 0..HgId::hex_len() - hex.len() { buffer.push('0'); } buffer.push_str(hex); HgId::from_str(&buffer).unwrap() } pub fn key(path: &str, hexnode: &str) -> Key { Key::new(repo_path_buf(path), hgid(hexnode)) } /// The null hgid id is special and it's semantics vary. A null key contains a null hgid id. pub fn null_key(path: &str) -> Key { Key::new(repo_path_buf(path), HgId::null_id().clone()) } pub fn generate_repo_paths(count: usize, qc_gen: &mut Gen) -> Vec<RepoPathBuf> { struct Generator<'a> { current_path: RepoPathBuf, current_component_length: usize, min_files_per_dir: usize, directory_component_min: usize, directory_component_max: usize, generated_paths: Vec<RepoPathBuf>, generate_paths_cnt: usize, qc_gen: &'a mut Gen, } impl<'a> Generator<'a> { fn generate_directory(&mut self) { let dir_components_cnt = if self.current_component_length == 0 { std::usize::MAX } else { self.directory_component_min + usize::arbitrary(&mut self.qc_gen) % (self.directory_component_max - self.directory_component_min) }; let mut component_hash = HashSet::new(); for i in 0..dir_components_cnt { if self.generate_paths_cnt <= self.generated_paths.len() { break; } let component = PathComponentBuf::arbitrary(self.qc_gen); if component_hash.contains(&component) { continue; } self.current_path.push(component.as_ref()); component_hash.insert(component); self.current_component_length += 1; // Decide if this is a directory. As we nest more and more directories, the // probabilty of having directories decreses. let u = self.current_component_length as u32; if i < self.min_files_per_dir || ((u64::arbitrary(self.qc_gen) % ((u + 2) as u64)) as u32) < u + 1 { self.generated_paths.push(self.current_path.clone()); } else { self.generate_directory(); } self.current_path.pop(); self.current_component_length -= 1; } } } let mut generator = Generator { current_path: RepoPathBuf::new(), current_component_length: 0, min_files_per_dir: 2, directory_component_min: 3, directory_component_max: 20, generated_paths: Vec::with_capacity(count), generate_paths_cnt: count, qc_gen, }; generator.generate_directory(); generator.generated_paths } #[cfg(test)] mod tests { use quickcheck::Gen; use super::*; #[test] fn
() { let mut qc_gen = Gen::new(10); let count = 10000; let paths = generate_repo_paths(count, &mut qc_gen); assert_eq!(paths.len(), count); } }
test_generate_repo_paths
identifier_name
dtstats.rs
use std::io::Result; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use std::time::Duration; extern crate dtlib; fn main() { let log_result = parse_log(dtlib::constants::LOG_FILE); if!log_result.is_ok() { println!("Could not load log."); } else { let log = log_result.unwrap(); let stats_opt = calc_stats(log); if!stats_opt.is_some() { println!("Could not calculate stats."); } else { let stats = stats_opt.unwrap(); print!( " == DT Stats == \n\ \n\ Sectors written: {}\n\ GB written: {}\n\ \n\ Uptime (h): {}\n\ Uptime (d): {}\n\ Uptime (y): {}\n\ \n\ GB/h: {}\n\ GB/d: {}\n\ GB/y: {}\n\ \n\ Days until 100GB written: {}\n\ Days until 1TB written: {}\n\ Days until 100TB written: {} = {} years\n", stats.sectors_written, stats.gbytes_written, stats.uptime_hours, stats.uptime_days, stats.uptime_years, stats.gbytes_per_hour, stats.gbytes_per_day, stats.gbytes_per_year, stats.days_until_100_gb, stats.days_until_1_tb, stats.days_until_100_tb, stats.years_until_100_tb ); } } } struct DtStats { sectors_written : u64, gbytes_written : u64, uptime_hours : f64, uptime_days : f64, uptime_years : f32, gbytes_per_hour : f64, gbytes_per_day : f64, gbytes_per_year : f64, days_until_100_gb : u64, days_until_1_tb : u64, days_until_100_tb : u64, years_until_100_tb : u64 } struct LogEntry { sectors_written : usize, uptime : Duration } fn calc_stats(entries : LogIterator) -> Option<DtStats> { let (sectors, uptime_opt) = entries .map(|entry| (entry.sectors_written as u64, entry.uptime)) .fold( (0 as u64, Some(Duration::new(0, 0))), |(sectors, uptime), (new_sectors, new_uptime)| ( sectors + new_sectors, uptime.and_then( |uptime| uptime.checked_add(new_uptime) ) ) ); if uptime_opt.is_some() { let uptime = uptime_opt.unwrap(); let gbytes_written : u64 = (sectors * dtlib::constants::BLOCK_SIZE as u64) / (1024 * 1024 * 1024); let uptime_hours = uptime.as_secs() as f64 / (60 * 60) as f64; let uptime_days = uptime_hours / 24 as f64; let uptime_years = uptime_days / 365 as f64; let gbytes_per_hour = gbytes_written as f64 / uptime_hours; let gbytes_per_day = gbytes_written as f64 / uptime_days; let gbytes_per_year = gbytes_written as f64 / uptime_years; return Some( DtStats { sectors_written: sectors, gbytes_written: gbytes_written, uptime_hours: uptime_hours, uptime_days: uptime_days, uptime_years: uptime_years as f32, gbytes_per_hour: gbytes_per_hour, gbytes_per_day: gbytes_per_day, gbytes_per_year: gbytes_per_year, days_until_100_gb: (100.0 as f64 / gbytes_per_day) as u64, days_until_1_tb: (1024.0 as f64 / gbytes_per_day) as u64, days_until_100_tb: (102400.0 as f64 / gbytes_per_day) as u64, years_until_100_tb: (102400.0 as f64 / gbytes_per_day) as u64 / 365 } ); } else { return None; } } fn parse_log_line(line : &String) -> Option<LogEntry> { let mut split = line.split(':'); let sectors_opt = split.next() .and_then(|s| s.parse::<usize>().ok()); let utime_opt = split.next() .and_then(|s| s.parse::<u64>().ok()) .map(|t| Duration::from_secs(t)); return match (sectors_opt, utime_opt) { (Some(sectors), Some(uptime)) => Some( LogEntry{ sectors_written: sectors, uptime: uptime } ), _ => None } } type LogIterator = Box<Iterator<Item=LogEntry>>; fn parse_log(path : &str) -> Result<LogIterator> { let file = File::open(path); return file.map( |f| { let buf_file = BufReader::new(f); let it = buf_file .lines() .filter(|line| line.is_ok()) .map(|line| line.unwrap()) .map(|line| parse_log_line(&line)) .filter(|opt| opt.is_some()) .map(|opt| opt.unwrap());
return Box::new(it) as LogIterator; } ); }
random_line_split
dtstats.rs
use std::io::Result; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use std::time::Duration; extern crate dtlib; fn main() { let log_result = parse_log(dtlib::constants::LOG_FILE); if!log_result.is_ok() { println!("Could not load log."); } else { let log = log_result.unwrap(); let stats_opt = calc_stats(log); if!stats_opt.is_some() { println!("Could not calculate stats."); } else { let stats = stats_opt.unwrap(); print!( " == DT Stats == \n\ \n\ Sectors written: {}\n\ GB written: {}\n\ \n\ Uptime (h): {}\n\ Uptime (d): {}\n\ Uptime (y): {}\n\ \n\ GB/h: {}\n\ GB/d: {}\n\ GB/y: {}\n\ \n\ Days until 100GB written: {}\n\ Days until 1TB written: {}\n\ Days until 100TB written: {} = {} years\n", stats.sectors_written, stats.gbytes_written, stats.uptime_hours, stats.uptime_days, stats.uptime_years, stats.gbytes_per_hour, stats.gbytes_per_day, stats.gbytes_per_year, stats.days_until_100_gb, stats.days_until_1_tb, stats.days_until_100_tb, stats.years_until_100_tb ); } } } struct DtStats { sectors_written : u64, gbytes_written : u64, uptime_hours : f64, uptime_days : f64, uptime_years : f32, gbytes_per_hour : f64, gbytes_per_day : f64, gbytes_per_year : f64, days_until_100_gb : u64, days_until_1_tb : u64, days_until_100_tb : u64, years_until_100_tb : u64 } struct LogEntry { sectors_written : usize, uptime : Duration } fn calc_stats(entries : LogIterator) -> Option<DtStats> { let (sectors, uptime_opt) = entries .map(|entry| (entry.sectors_written as u64, entry.uptime)) .fold( (0 as u64, Some(Duration::new(0, 0))), |(sectors, uptime), (new_sectors, new_uptime)| ( sectors + new_sectors, uptime.and_then( |uptime| uptime.checked_add(new_uptime) ) ) ); if uptime_opt.is_some() { let uptime = uptime_opt.unwrap(); let gbytes_written : u64 = (sectors * dtlib::constants::BLOCK_SIZE as u64) / (1024 * 1024 * 1024); let uptime_hours = uptime.as_secs() as f64 / (60 * 60) as f64; let uptime_days = uptime_hours / 24 as f64; let uptime_years = uptime_days / 365 as f64; let gbytes_per_hour = gbytes_written as f64 / uptime_hours; let gbytes_per_day = gbytes_written as f64 / uptime_days; let gbytes_per_year = gbytes_written as f64 / uptime_years; return Some( DtStats { sectors_written: sectors, gbytes_written: gbytes_written, uptime_hours: uptime_hours, uptime_days: uptime_days, uptime_years: uptime_years as f32, gbytes_per_hour: gbytes_per_hour, gbytes_per_day: gbytes_per_day, gbytes_per_year: gbytes_per_year, days_until_100_gb: (100.0 as f64 / gbytes_per_day) as u64, days_until_1_tb: (1024.0 as f64 / gbytes_per_day) as u64, days_until_100_tb: (102400.0 as f64 / gbytes_per_day) as u64, years_until_100_tb: (102400.0 as f64 / gbytes_per_day) as u64 / 365 } ); } else { return None; } } fn parse_log_line(line : &String) -> Option<LogEntry> { let mut split = line.split(':'); let sectors_opt = split.next() .and_then(|s| s.parse::<usize>().ok()); let utime_opt = split.next() .and_then(|s| s.parse::<u64>().ok()) .map(|t| Duration::from_secs(t)); return match (sectors_opt, utime_opt) { (Some(sectors), Some(uptime)) => Some( LogEntry{ sectors_written: sectors, uptime: uptime } ), _ => None } } type LogIterator = Box<Iterator<Item=LogEntry>>; fn
(path : &str) -> Result<LogIterator> { let file = File::open(path); return file.map( |f| { let buf_file = BufReader::new(f); let it = buf_file .lines() .filter(|line| line.is_ok()) .map(|line| line.unwrap()) .map(|line| parse_log_line(&line)) .filter(|opt| opt.is_some()) .map(|opt| opt.unwrap()); return Box::new(it) as LogIterator; } ); }
parse_log
identifier_name
dtstats.rs
use std::io::Result; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use std::time::Duration; extern crate dtlib; fn main() { let log_result = parse_log(dtlib::constants::LOG_FILE); if!log_result.is_ok()
else { let log = log_result.unwrap(); let stats_opt = calc_stats(log); if!stats_opt.is_some() { println!("Could not calculate stats."); } else { let stats = stats_opt.unwrap(); print!( " == DT Stats == \n\ \n\ Sectors written: {}\n\ GB written: {}\n\ \n\ Uptime (h): {}\n\ Uptime (d): {}\n\ Uptime (y): {}\n\ \n\ GB/h: {}\n\ GB/d: {}\n\ GB/y: {}\n\ \n\ Days until 100GB written: {}\n\ Days until 1TB written: {}\n\ Days until 100TB written: {} = {} years\n", stats.sectors_written, stats.gbytes_written, stats.uptime_hours, stats.uptime_days, stats.uptime_years, stats.gbytes_per_hour, stats.gbytes_per_day, stats.gbytes_per_year, stats.days_until_100_gb, stats.days_until_1_tb, stats.days_until_100_tb, stats.years_until_100_tb ); } } } struct DtStats { sectors_written : u64, gbytes_written : u64, uptime_hours : f64, uptime_days : f64, uptime_years : f32, gbytes_per_hour : f64, gbytes_per_day : f64, gbytes_per_year : f64, days_until_100_gb : u64, days_until_1_tb : u64, days_until_100_tb : u64, years_until_100_tb : u64 } struct LogEntry { sectors_written : usize, uptime : Duration } fn calc_stats(entries : LogIterator) -> Option<DtStats> { let (sectors, uptime_opt) = entries .map(|entry| (entry.sectors_written as u64, entry.uptime)) .fold( (0 as u64, Some(Duration::new(0, 0))), |(sectors, uptime), (new_sectors, new_uptime)| ( sectors + new_sectors, uptime.and_then( |uptime| uptime.checked_add(new_uptime) ) ) ); if uptime_opt.is_some() { let uptime = uptime_opt.unwrap(); let gbytes_written : u64 = (sectors * dtlib::constants::BLOCK_SIZE as u64) / (1024 * 1024 * 1024); let uptime_hours = uptime.as_secs() as f64 / (60 * 60) as f64; let uptime_days = uptime_hours / 24 as f64; let uptime_years = uptime_days / 365 as f64; let gbytes_per_hour = gbytes_written as f64 / uptime_hours; let gbytes_per_day = gbytes_written as f64 / uptime_days; let gbytes_per_year = gbytes_written as f64 / uptime_years; return Some( DtStats { sectors_written: sectors, gbytes_written: gbytes_written, uptime_hours: uptime_hours, uptime_days: uptime_days, uptime_years: uptime_years as f32, gbytes_per_hour: gbytes_per_hour, gbytes_per_day: gbytes_per_day, gbytes_per_year: gbytes_per_year, days_until_100_gb: (100.0 as f64 / gbytes_per_day) as u64, days_until_1_tb: (1024.0 as f64 / gbytes_per_day) as u64, days_until_100_tb: (102400.0 as f64 / gbytes_per_day) as u64, years_until_100_tb: (102400.0 as f64 / gbytes_per_day) as u64 / 365 } ); } else { return None; } } fn parse_log_line(line : &String) -> Option<LogEntry> { let mut split = line.split(':'); let sectors_opt = split.next() .and_then(|s| s.parse::<usize>().ok()); let utime_opt = split.next() .and_then(|s| s.parse::<u64>().ok()) .map(|t| Duration::from_secs(t)); return match (sectors_opt, utime_opt) { (Some(sectors), Some(uptime)) => Some( LogEntry{ sectors_written: sectors, uptime: uptime } ), _ => None } } type LogIterator = Box<Iterator<Item=LogEntry>>; fn parse_log(path : &str) -> Result<LogIterator> { let file = File::open(path); return file.map( |f| { let buf_file = BufReader::new(f); let it = buf_file .lines() .filter(|line| line.is_ok()) .map(|line| line.unwrap()) .map(|line| parse_log_line(&line)) .filter(|opt| opt.is_some()) .map(|opt| opt.unwrap()); return Box::new(it) as LogIterator; } ); }
{ println!("Could not load log."); }
conditional_block
dtstats.rs
use std::io::Result; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use std::time::Duration; extern crate dtlib; fn main()
\n\ Sectors written: {}\n\ GB written: {}\n\ \n\ Uptime (h): {}\n\ Uptime (d): {}\n\ Uptime (y): {}\n\ \n\ GB/h: {}\n\ GB/d: {}\n\ GB/y: {}\n\ \n\ Days until 100GB written: {}\n\ Days until 1TB written: {}\n\ Days until 100TB written: {} = {} years\n", stats.sectors_written, stats.gbytes_written, stats.uptime_hours, stats.uptime_days, stats.uptime_years, stats.gbytes_per_hour, stats.gbytes_per_day, stats.gbytes_per_year, stats.days_until_100_gb, stats.days_until_1_tb, stats.days_until_100_tb, stats.years_until_100_tb ); } } } struct DtStats { sectors_written : u64, gbytes_written : u64, uptime_hours : f64, uptime_days : f64, uptime_years : f32, gbytes_per_hour : f64, gbytes_per_day : f64, gbytes_per_year : f64, days_until_100_gb : u64, days_until_1_tb : u64, days_until_100_tb : u64, years_until_100_tb : u64 } struct LogEntry { sectors_written : usize, uptime : Duration } fn calc_stats(entries : LogIterator) -> Option<DtStats> { let (sectors, uptime_opt) = entries .map(|entry| (entry.sectors_written as u64, entry.uptime)) .fold( (0 as u64, Some(Duration::new(0, 0))), |(sectors, uptime), (new_sectors, new_uptime)| ( sectors + new_sectors, uptime.and_then( |uptime| uptime.checked_add(new_uptime) ) ) ); if uptime_opt.is_some() { let uptime = uptime_opt.unwrap(); let gbytes_written : u64 = (sectors * dtlib::constants::BLOCK_SIZE as u64) / (1024 * 1024 * 1024); let uptime_hours = uptime.as_secs() as f64 / (60 * 60) as f64; let uptime_days = uptime_hours / 24 as f64; let uptime_years = uptime_days / 365 as f64; let gbytes_per_hour = gbytes_written as f64 / uptime_hours; let gbytes_per_day = gbytes_written as f64 / uptime_days; let gbytes_per_year = gbytes_written as f64 / uptime_years; return Some( DtStats { sectors_written: sectors, gbytes_written: gbytes_written, uptime_hours: uptime_hours, uptime_days: uptime_days, uptime_years: uptime_years as f32, gbytes_per_hour: gbytes_per_hour, gbytes_per_day: gbytes_per_day, gbytes_per_year: gbytes_per_year, days_until_100_gb: (100.0 as f64 / gbytes_per_day) as u64, days_until_1_tb: (1024.0 as f64 / gbytes_per_day) as u64, days_until_100_tb: (102400.0 as f64 / gbytes_per_day) as u64, years_until_100_tb: (102400.0 as f64 / gbytes_per_day) as u64 / 365 } ); } else { return None; } } fn parse_log_line(line : &String) -> Option<LogEntry> { let mut split = line.split(':'); let sectors_opt = split.next() .and_then(|s| s.parse::<usize>().ok()); let utime_opt = split.next() .and_then(|s| s.parse::<u64>().ok()) .map(|t| Duration::from_secs(t)); return match (sectors_opt, utime_opt) { (Some(sectors), Some(uptime)) => Some( LogEntry{ sectors_written: sectors, uptime: uptime } ), _ => None } } type LogIterator = Box<Iterator<Item=LogEntry>>; fn parse_log(path : &str) -> Result<LogIterator> { let file = File::open(path); return file.map( |f| { let buf_file = BufReader::new(f); let it = buf_file .lines() .filter(|line| line.is_ok()) .map(|line| line.unwrap()) .map(|line| parse_log_line(&line)) .filter(|opt| opt.is_some()) .map(|opt| opt.unwrap()); return Box::new(it) as LogIterator; } ); }
{ let log_result = parse_log(dtlib::constants::LOG_FILE); if !log_result.is_ok() { println!("Could not load log."); } else { let log = log_result.unwrap(); let stats_opt = calc_stats(log); if !stats_opt.is_some() { println!("Could not calculate stats."); } else { let stats = stats_opt.unwrap(); print!( " == DT Stats == \n\
identifier_body
day12.rs
extern crate serde_json; use std::ops::Add; use self::serde_json::value::Value; pub fn json_sum(value: &Value) -> i64 { match *value { Value::I64(n) => n, Value::U64(n) => n as i64, Value::Array(ref vec) => vec.iter().map(json_sum).fold(0, Add::add), Value::Object(ref o) => o.values().map(json_sum).fold(0, Add::add), _ => 0, } } pub fn json_sum_str(json: &str) -> i64 { match serde_json::from_str(json) { Ok(val) => json_sum(&val), Err(_) => 0, } } pub fn json_sum_unred(value: &Value) -> i64 { match *value { Value::I64(n) => n, Value::U64(n) => n as i64, Value::Array(ref vec) => { vec.iter() .map(json_sum_unred) .fold(0, Add::add) } Value::Object(ref o) => { if o.values().any(|v| v == &Value::String("red".to_owned())) { 0 } else { o.values().map(json_sum_unred).fold(0, Add::add) } } _ => 0, } } pub fn json_sum_unred_str(json: &str) -> i64 { match serde_json::from_str(json) { Ok(val) => json_sum_unred(&val), Err(_) => 0, } } pub fn process_file(path: &str) { use std::fs::File; use std::io::prelude::*; let mut file = File::open(path).unwrap(); let mut string = String::new(); file.read_to_string(&mut string).unwrap(); let json = serde_json::from_str(&string).unwrap();
#[cfg(test)] mod tests { use super::{json_sum_str, json_sum_unred_str}; #[test] fn test_json_sum() { assert_eq!(json_sum_str("[1,2,3]"), 6); assert_eq!(json_sum_str("{\"a\":2,\"b\":4}"), 6); assert_eq!(json_sum_str("[[[3]]]"), 3); assert_eq!(json_sum_str("{\"a\":{\"b\":4},\"c\":-1}"), 3); assert_eq!(json_sum_str("{\"a\":[-1,1]}"), 0); assert_eq!(json_sum_str("[-1,{\"a\":1}]"), 0); assert_eq!(json_sum_str("[]"), 0); assert_eq!(json_sum_str("[[]]"), 0); assert_eq!(json_sum_str("{}"), 0); } #[test] fn test_json_sum_unred() { assert_eq!(json_sum_unred_str("[1,2,3]"), 6); assert_eq!(json_sum_unred_str("[1,{\"c\":\"red\",\"b\":2},3]"), 4); assert_eq!(json_sum_unred_str("{\"d\":\"red\",\"e\":[1,2,3,4],\"f\":\ 5}"), 0); assert_eq!(json_sum_unred_str("[1,\"red\",5]"), 6); } }
println!("Part 1: {}", json_sum(&json)); println!("Part 2: {}", json_sum_unred(&json)); }
random_line_split
day12.rs
extern crate serde_json; use std::ops::Add; use self::serde_json::value::Value; pub fn json_sum(value: &Value) -> i64 { match *value { Value::I64(n) => n, Value::U64(n) => n as i64, Value::Array(ref vec) => vec.iter().map(json_sum).fold(0, Add::add), Value::Object(ref o) => o.values().map(json_sum).fold(0, Add::add), _ => 0, } } pub fn json_sum_str(json: &str) -> i64 { match serde_json::from_str(json) { Ok(val) => json_sum(&val), Err(_) => 0, } } pub fn json_sum_unred(value: &Value) -> i64 { match *value { Value::I64(n) => n, Value::U64(n) => n as i64, Value::Array(ref vec) => { vec.iter() .map(json_sum_unred) .fold(0, Add::add) } Value::Object(ref o) => { if o.values().any(|v| v == &Value::String("red".to_owned())) { 0 } else
} _ => 0, } } pub fn json_sum_unred_str(json: &str) -> i64 { match serde_json::from_str(json) { Ok(val) => json_sum_unred(&val), Err(_) => 0, } } pub fn process_file(path: &str) { use std::fs::File; use std::io::prelude::*; let mut file = File::open(path).unwrap(); let mut string = String::new(); file.read_to_string(&mut string).unwrap(); let json = serde_json::from_str(&string).unwrap(); println!("Part 1: {}", json_sum(&json)); println!("Part 2: {}", json_sum_unred(&json)); } #[cfg(test)] mod tests { use super::{json_sum_str, json_sum_unred_str}; #[test] fn test_json_sum() { assert_eq!(json_sum_str("[1,2,3]"), 6); assert_eq!(json_sum_str("{\"a\":2,\"b\":4}"), 6); assert_eq!(json_sum_str("[[[3]]]"), 3); assert_eq!(json_sum_str("{\"a\":{\"b\":4},\"c\":-1}"), 3); assert_eq!(json_sum_str("{\"a\":[-1,1]}"), 0); assert_eq!(json_sum_str("[-1,{\"a\":1}]"), 0); assert_eq!(json_sum_str("[]"), 0); assert_eq!(json_sum_str("[[]]"), 0); assert_eq!(json_sum_str("{}"), 0); } #[test] fn test_json_sum_unred() { assert_eq!(json_sum_unred_str("[1,2,3]"), 6); assert_eq!(json_sum_unred_str("[1,{\"c\":\"red\",\"b\":2},3]"), 4); assert_eq!(json_sum_unred_str("{\"d\":\"red\",\"e\":[1,2,3,4],\"f\":\ 5}"), 0); assert_eq!(json_sum_unred_str("[1,\"red\",5]"), 6); } }
{ o.values().map(json_sum_unred).fold(0, Add::add) }
conditional_block
day12.rs
extern crate serde_json; use std::ops::Add; use self::serde_json::value::Value; pub fn json_sum(value: &Value) -> i64 { match *value { Value::I64(n) => n, Value::U64(n) => n as i64, Value::Array(ref vec) => vec.iter().map(json_sum).fold(0, Add::add), Value::Object(ref o) => o.values().map(json_sum).fold(0, Add::add), _ => 0, } } pub fn json_sum_str(json: &str) -> i64 { match serde_json::from_str(json) { Ok(val) => json_sum(&val), Err(_) => 0, } } pub fn json_sum_unred(value: &Value) -> i64 { match *value { Value::I64(n) => n, Value::U64(n) => n as i64, Value::Array(ref vec) => { vec.iter() .map(json_sum_unred) .fold(0, Add::add) } Value::Object(ref o) => { if o.values().any(|v| v == &Value::String("red".to_owned())) { 0 } else { o.values().map(json_sum_unred).fold(0, Add::add) } } _ => 0, } } pub fn json_sum_unred_str(json: &str) -> i64 { match serde_json::from_str(json) { Ok(val) => json_sum_unred(&val), Err(_) => 0, } } pub fn
(path: &str) { use std::fs::File; use std::io::prelude::*; let mut file = File::open(path).unwrap(); let mut string = String::new(); file.read_to_string(&mut string).unwrap(); let json = serde_json::from_str(&string).unwrap(); println!("Part 1: {}", json_sum(&json)); println!("Part 2: {}", json_sum_unred(&json)); } #[cfg(test)] mod tests { use super::{json_sum_str, json_sum_unred_str}; #[test] fn test_json_sum() { assert_eq!(json_sum_str("[1,2,3]"), 6); assert_eq!(json_sum_str("{\"a\":2,\"b\":4}"), 6); assert_eq!(json_sum_str("[[[3]]]"), 3); assert_eq!(json_sum_str("{\"a\":{\"b\":4},\"c\":-1}"), 3); assert_eq!(json_sum_str("{\"a\":[-1,1]}"), 0); assert_eq!(json_sum_str("[-1,{\"a\":1}]"), 0); assert_eq!(json_sum_str("[]"), 0); assert_eq!(json_sum_str("[[]]"), 0); assert_eq!(json_sum_str("{}"), 0); } #[test] fn test_json_sum_unred() { assert_eq!(json_sum_unred_str("[1,2,3]"), 6); assert_eq!(json_sum_unred_str("[1,{\"c\":\"red\",\"b\":2},3]"), 4); assert_eq!(json_sum_unred_str("{\"d\":\"red\",\"e\":[1,2,3,4],\"f\":\ 5}"), 0); assert_eq!(json_sum_unred_str("[1,\"red\",5]"), 6); } }
process_file
identifier_name
day12.rs
extern crate serde_json; use std::ops::Add; use self::serde_json::value::Value; pub fn json_sum(value: &Value) -> i64 { match *value { Value::I64(n) => n, Value::U64(n) => n as i64, Value::Array(ref vec) => vec.iter().map(json_sum).fold(0, Add::add), Value::Object(ref o) => o.values().map(json_sum).fold(0, Add::add), _ => 0, } } pub fn json_sum_str(json: &str) -> i64 { match serde_json::from_str(json) { Ok(val) => json_sum(&val), Err(_) => 0, } } pub fn json_sum_unred(value: &Value) -> i64 { match *value { Value::I64(n) => n, Value::U64(n) => n as i64, Value::Array(ref vec) => { vec.iter() .map(json_sum_unred) .fold(0, Add::add) } Value::Object(ref o) => { if o.values().any(|v| v == &Value::String("red".to_owned())) { 0 } else { o.values().map(json_sum_unred).fold(0, Add::add) } } _ => 0, } } pub fn json_sum_unred_str(json: &str) -> i64
pub fn process_file(path: &str) { use std::fs::File; use std::io::prelude::*; let mut file = File::open(path).unwrap(); let mut string = String::new(); file.read_to_string(&mut string).unwrap(); let json = serde_json::from_str(&string).unwrap(); println!("Part 1: {}", json_sum(&json)); println!("Part 2: {}", json_sum_unred(&json)); } #[cfg(test)] mod tests { use super::{json_sum_str, json_sum_unred_str}; #[test] fn test_json_sum() { assert_eq!(json_sum_str("[1,2,3]"), 6); assert_eq!(json_sum_str("{\"a\":2,\"b\":4}"), 6); assert_eq!(json_sum_str("[[[3]]]"), 3); assert_eq!(json_sum_str("{\"a\":{\"b\":4},\"c\":-1}"), 3); assert_eq!(json_sum_str("{\"a\":[-1,1]}"), 0); assert_eq!(json_sum_str("[-1,{\"a\":1}]"), 0); assert_eq!(json_sum_str("[]"), 0); assert_eq!(json_sum_str("[[]]"), 0); assert_eq!(json_sum_str("{}"), 0); } #[test] fn test_json_sum_unred() { assert_eq!(json_sum_unred_str("[1,2,3]"), 6); assert_eq!(json_sum_unred_str("[1,{\"c\":\"red\",\"b\":2},3]"), 4); assert_eq!(json_sum_unred_str("{\"d\":\"red\",\"e\":[1,2,3,4],\"f\":\ 5}"), 0); assert_eq!(json_sum_unred_str("[1,\"red\",5]"), 6); } }
{ match serde_json::from_str(json) { Ok(val) => json_sum_unred(&val), Err(_) => 0, } }
identifier_body
lib.rs
//! A library for encoding/decoding Apple Icon Image (.icns) files. //! //! # ICNS concepts //! //! To understand this library, it helps to be familiar with the structure of //! an ICNS file; this section will give a high-level overview, or see //! [Wikipedia](https://en.wikipedia.org/wiki/Apple_Icon_Image_format) for more //! details about the file format. If you prefer to learn by example, you can //! just skip down to the [Example usage](#example-usage) section below. //! //! An ICNS file encodes a collection of images (typically different versions //! of the same icon at different resolutions) called an _icon family_. The //! file consists of a short header followed by a sequence of data blocks //! called _icon elements_. Each icon element consists of a header with an //! _OSType_ -- which is essentially a four-byte identifier indicating the type //! of data in the element -- and a blob of binary data. //! //! Each image in the ICNS file is encoded either as a single icon element, or //! as two elements -- one for the color data and one for the alpha mask. For //! example, 48x48 pixel icons are stored as two elements: an `ih32` element //! containing compressed 24-bit RGB data, and an `h8mk` element containing the //! 8-bit alpha mask. By contrast, 64x64 pixel icons are stored as a single //! `icp6` element, which contains either PNG or JPEG 2000 data for the whole //! 32-bit image. //! //! Some icon sizes have multiple possible encodings. For example, a 128x128 //! icon can be stored either as an `it32` and an `t8mk` element together //! (containing compressed RGB and alpha, respectively), or as a single `ic07` //! element (containing PNG or JPEG 2000 data). And for some icon sizes, there //! are separate OSTypes for single and double-pixel-density versions of the //! icon (for "retina" displays). For example, an `ic08` element encodes a //! single-density 256x256 image, while an `ic14` element encodes a //! double-density 256x256 image -- that is, the image data is actually 512x512 //! pixels, and is considered different from the single-density 512x512 pixel //! image encoded by an `ic09` element. //! //! Finally, there are some additional, optional element types that don't //! encode images at all. For example, the `TOC` element summarizes the //! contents of the ICNS file, and the `icnV` element stores version //! information. //! //! # API overview //! //! The API for this library is modelled loosely after that of //! [libicns](http://icns.sourceforge.net/apidocs.html). //! //! The icon family stored in an ICNS file is represeted by the //! [`IconFamily`](struct.IconFamily.html) struct, which provides methods for //! [reading](struct.IconFamily.html#method.read) and //! [writing](struct.IconFamily.html#method.write) ICNS files, as well as for //! high-level operations on the icon set, such as //! [adding](struct.IconFamily.html#method.add_icon_with_type), //! [extracting](struct.IconFamily.html#method.get_icon_with_type), and //! [listing](struct.IconFamily.html#method.available_icons) the encoded //! images. //! //! An `IconFamily` contains a vector of //! [`IconElement`](struct.IconElement.html) structs, which represent //! individual data blocks in the ICNS file. Each `IconElement` has an //! [`OSType`](struct.OSType.html) indicating the type of data in the element, //! as well as a `Vec<u8>` containing the data itself. Usually, you won't //! need to work with `IconElement`s directly, and can instead use the //! higher-level operations provided by `IconFamily`. //! //! Since raw OSTypes like `t8mk` and `icp4` can be hard to remember, the //! [`IconType`](enum.IconType.html) type enumerates all the icon element types //! that are supported by this library, with more mnemonic names (for example, //! `IconType::RGB24_48x48` indicates 24-bit RGB data for a 48x48 pixel icon, //! and is a bit more understandable than the corresponding OSType, `ih32`). //! The `IconType` enum also provides methods for getting the properties of //! each icon type, such as the size of the encoded image, or the associated //! mask type (for icons that are stored as two elements instead of one). //! //! Regardless of whether you use the higher-level `IconFamily` methods or the //! lower-level `IconElement` methods, icons from the ICNS file can be decoded //! into [`Image`](struct.Image.html) structs, which can be //! [converted](struct.Image.html#method.convert_to) to and from any of several //! [`PixelFormats`](enum.PixelFormat.html) to allow the raw pixel data to be //! easily transferred to another image library for further processing. Since //! this library already depends on the PNG codec anyway (since some ICNS icons //! are PNG-encoded), as a convenience, the [`Image`](struct.Image.html) struct //! also provides methods for [reading](struct.Image.html#method.read_png) and //! [writing](struct.Image.html#method.write_png) PNG files. //! //! # Limitations //! //! The ICNS format allows some icon types to be encoded either as PNG data or //! as JPEG 2000 data; however, when encoding icons, this library always uses //! PNG format, and when decoding icons, it cannot decode JPEG 2000 icons at //! all (it will detect the JPEG 2000 header and return an error). The reason //! for this is the apparent lack of JPEG 2000 libraries for Rust; if this ever //! changes, please feel free to file a bug or a send a pull request. //! //! Additionally, this library does not yet support many of the older icon //! types used by earlier versions of Mac OS (such as `ICN#`, a 32x32 black and //! white icon). Again, pull requests (with suitable tests) are welcome. //! //! # Example usage //! //! ```no_run //! use icns::{IconFamily, IconType, Image}; //! use std::fs::File; //! use std::io::{BufReader, BufWriter}; //! //! // Load an icon family from an ICNS file. //! let file = BufReader::new(File::open("16.icns").unwrap()); //! let mut icon_family = IconFamily::read(file).unwrap(); //! //! // Extract an icon from the family and save it as a PNG. //! let image = icon_family.get_icon_with_type(IconType::RGB24_16x16).unwrap(); //! let file = BufWriter::new(File::create("16.png").unwrap()); //! image.write_png(file).unwrap(); //! //! // Read in another icon from a PNG file, and add it to the icon family. //! let file = BufReader::new(File::open("32.png").unwrap()); //! let image = Image::read_png(file).unwrap(); //! icon_family.add_icon(&image).unwrap(); //! //! // Save the updated icon family to a new ICNS file. //! let file = BufWriter::new(File::create("16-and-32.icns").unwrap()); //! icon_family.write(file).unwrap(); //! ```
#[cfg(feature = "pngio")] extern crate png; #[cfg(feature = "pngio")] mod pngio; mod element; pub use self::element::IconElement; mod family; pub use self::family::IconFamily; mod icontype; pub use self::icontype::{Encoding, IconType, OSType}; mod image; pub use self::image::{Image, PixelFormat};
#![warn(missing_docs)] extern crate byteorder;
random_line_split
frag.rs
//! API for blowing strings into fragments and putting them back together. use regex::Regex; use eval::{self, Error, Value}; use eval::api::conv::str_; use eval::value::{ArrayRepr, StringRepr}; lazy_static!{ static ref WORD_SEP: Regex = Regex::new(r"\s+").unwrap(); static ref LINE_SEP: Regex = Regex::new("\r?\n").unwrap(); } /// Join an array of values into a single delimited string. pub fn join(delim: Value, array: Value) -> eval::Result { let delim_type = delim.typename(); let array_type = array.typename(); if let (Value::String(d), Value::Array(a)) = (delim, array) { let elem_count = a.len(); let strings: Vec<_> = a.into_iter() .map(str_).filter(Result::is_ok) .map(Result::unwrap).map(Value::unwrap_string) .collect(); let error_count = strings.len() - elem_count; if error_count == 0
else { // TODO: include the error message of the offending element's conversion return Err(Error::new(&format!( "join() failed to stringify {} element(s) of the input array", error_count))); } } Err(Error::new(&format!( "join() expects a string and an array, got: {}, {}", delim_type, array_type ))) } /// Split a string by given string delimiter. /// Returns an array of strings. // TODO(xion): introduce optional third parameter, maxsplit pub fn split(delim: Value, string: Value) -> eval::Result { eval2!((delim: &String, string: &String) -> Array { string.split(delim).map(StringRepr::from).map(Value::String).collect() }); eval2!((delim: &Regex, string: &String) -> Array { do_regex_split(delim, string) }); mismatch!("split"; ("string", "string") | ("regex", "string") => (delim, string)) } /// Split a string into array of words. pub fn words(string: Value) -> eval::Result { eval1!((string: &String) -> Array { do_regex_split(&WORD_SEP, string) }); mismatch!("words"; ("string") => (string)) } /// Split a string into array of lines. pub fn lines(string: Value) -> eval::Result { eval1!((string: &String) -> Array { do_regex_split(&LINE_SEP, string) }); mismatch!("lines"; ("string") => (string)) } // Utility functions #[inline] fn do_regex_split(delim: &Regex, string: &str) -> ArrayRepr { delim.split(string).map(StringRepr::from).map(Value::String).collect() }
{ return Ok(Value::String(strings.join(&d))); }
conditional_block
frag.rs
//! API for blowing strings into fragments and putting them back together. use regex::Regex;
lazy_static!{ static ref WORD_SEP: Regex = Regex::new(r"\s+").unwrap(); static ref LINE_SEP: Regex = Regex::new("\r?\n").unwrap(); } /// Join an array of values into a single delimited string. pub fn join(delim: Value, array: Value) -> eval::Result { let delim_type = delim.typename(); let array_type = array.typename(); if let (Value::String(d), Value::Array(a)) = (delim, array) { let elem_count = a.len(); let strings: Vec<_> = a.into_iter() .map(str_).filter(Result::is_ok) .map(Result::unwrap).map(Value::unwrap_string) .collect(); let error_count = strings.len() - elem_count; if error_count == 0 { return Ok(Value::String(strings.join(&d))); } else { // TODO: include the error message of the offending element's conversion return Err(Error::new(&format!( "join() failed to stringify {} element(s) of the input array", error_count))); } } Err(Error::new(&format!( "join() expects a string and an array, got: {}, {}", delim_type, array_type ))) } /// Split a string by given string delimiter. /// Returns an array of strings. // TODO(xion): introduce optional third parameter, maxsplit pub fn split(delim: Value, string: Value) -> eval::Result { eval2!((delim: &String, string: &String) -> Array { string.split(delim).map(StringRepr::from).map(Value::String).collect() }); eval2!((delim: &Regex, string: &String) -> Array { do_regex_split(delim, string) }); mismatch!("split"; ("string", "string") | ("regex", "string") => (delim, string)) } /// Split a string into array of words. pub fn words(string: Value) -> eval::Result { eval1!((string: &String) -> Array { do_regex_split(&WORD_SEP, string) }); mismatch!("words"; ("string") => (string)) } /// Split a string into array of lines. pub fn lines(string: Value) -> eval::Result { eval1!((string: &String) -> Array { do_regex_split(&LINE_SEP, string) }); mismatch!("lines"; ("string") => (string)) } // Utility functions #[inline] fn do_regex_split(delim: &Regex, string: &str) -> ArrayRepr { delim.split(string).map(StringRepr::from).map(Value::String).collect() }
use eval::{self, Error, Value}; use eval::api::conv::str_; use eval::value::{ArrayRepr, StringRepr};
random_line_split
frag.rs
//! API for blowing strings into fragments and putting them back together. use regex::Regex; use eval::{self, Error, Value}; use eval::api::conv::str_; use eval::value::{ArrayRepr, StringRepr}; lazy_static!{ static ref WORD_SEP: Regex = Regex::new(r"\s+").unwrap(); static ref LINE_SEP: Regex = Regex::new("\r?\n").unwrap(); } /// Join an array of values into a single delimited string. pub fn
(delim: Value, array: Value) -> eval::Result { let delim_type = delim.typename(); let array_type = array.typename(); if let (Value::String(d), Value::Array(a)) = (delim, array) { let elem_count = a.len(); let strings: Vec<_> = a.into_iter() .map(str_).filter(Result::is_ok) .map(Result::unwrap).map(Value::unwrap_string) .collect(); let error_count = strings.len() - elem_count; if error_count == 0 { return Ok(Value::String(strings.join(&d))); } else { // TODO: include the error message of the offending element's conversion return Err(Error::new(&format!( "join() failed to stringify {} element(s) of the input array", error_count))); } } Err(Error::new(&format!( "join() expects a string and an array, got: {}, {}", delim_type, array_type ))) } /// Split a string by given string delimiter. /// Returns an array of strings. // TODO(xion): introduce optional third parameter, maxsplit pub fn split(delim: Value, string: Value) -> eval::Result { eval2!((delim: &String, string: &String) -> Array { string.split(delim).map(StringRepr::from).map(Value::String).collect() }); eval2!((delim: &Regex, string: &String) -> Array { do_regex_split(delim, string) }); mismatch!("split"; ("string", "string") | ("regex", "string") => (delim, string)) } /// Split a string into array of words. pub fn words(string: Value) -> eval::Result { eval1!((string: &String) -> Array { do_regex_split(&WORD_SEP, string) }); mismatch!("words"; ("string") => (string)) } /// Split a string into array of lines. pub fn lines(string: Value) -> eval::Result { eval1!((string: &String) -> Array { do_regex_split(&LINE_SEP, string) }); mismatch!("lines"; ("string") => (string)) } // Utility functions #[inline] fn do_regex_split(delim: &Regex, string: &str) -> ArrayRepr { delim.split(string).map(StringRepr::from).map(Value::String).collect() }
join
identifier_name
frag.rs
//! API for blowing strings into fragments and putting them back together. use regex::Regex; use eval::{self, Error, Value}; use eval::api::conv::str_; use eval::value::{ArrayRepr, StringRepr}; lazy_static!{ static ref WORD_SEP: Regex = Regex::new(r"\s+").unwrap(); static ref LINE_SEP: Regex = Regex::new("\r?\n").unwrap(); } /// Join an array of values into a single delimited string. pub fn join(delim: Value, array: Value) -> eval::Result { let delim_type = delim.typename(); let array_type = array.typename(); if let (Value::String(d), Value::Array(a)) = (delim, array) { let elem_count = a.len(); let strings: Vec<_> = a.into_iter() .map(str_).filter(Result::is_ok) .map(Result::unwrap).map(Value::unwrap_string) .collect(); let error_count = strings.len() - elem_count; if error_count == 0 { return Ok(Value::String(strings.join(&d))); } else { // TODO: include the error message of the offending element's conversion return Err(Error::new(&format!( "join() failed to stringify {} element(s) of the input array", error_count))); } } Err(Error::new(&format!( "join() expects a string and an array, got: {}, {}", delim_type, array_type ))) } /// Split a string by given string delimiter. /// Returns an array of strings. // TODO(xion): introduce optional third parameter, maxsplit pub fn split(delim: Value, string: Value) -> eval::Result { eval2!((delim: &String, string: &String) -> Array { string.split(delim).map(StringRepr::from).map(Value::String).collect() }); eval2!((delim: &Regex, string: &String) -> Array { do_regex_split(delim, string) }); mismatch!("split"; ("string", "string") | ("regex", "string") => (delim, string)) } /// Split a string into array of words. pub fn words(string: Value) -> eval::Result { eval1!((string: &String) -> Array { do_regex_split(&WORD_SEP, string) }); mismatch!("words"; ("string") => (string)) } /// Split a string into array of lines. pub fn lines(string: Value) -> eval::Result
// Utility functions #[inline] fn do_regex_split(delim: &Regex, string: &str) -> ArrayRepr { delim.split(string).map(StringRepr::from).map(Value::String).collect() }
{ eval1!((string: &String) -> Array { do_regex_split(&LINE_SEP, string) }); mismatch!("lines"; ("string") => (string)) }
identifier_body
app.rs
use gtk; use gdk; use gio; use gtk::prelude::*; use gio::prelude::*; use std::cell::RefCell; use std::sync::mpsc::Receiver; use {NAME, TAGLINE}; use static_resources; use preferences; use headerbar; use sentinel_api::youtube; use views::trending; // Define thread local storage keys. thread_local! { pub static VPLAYER: RefCell<Option<(gtk:: Stack, gtk::Overlay)>> = RefCell::new(None); #[allow(unknown_lints, type_complexity)] pub static TRENDING: RefCell<Option<( gtk::Viewport,
)>> = RefCell::new(None); #[allow(unknown_lints, type_complexity)] pub static THUMBNAILS: RefCell<Option<( Vec<gtk::Image>, Receiver<Option<String>>, )>> = RefCell::new(None); } pub fn run_app() -> Result<(), String> { let application = match gtk::Application::new( Some("com.github.kil0meters.sentinel"), gio::ApplicationFlags::empty(), ) { Ok(app) => { app.connect_activate(move |app| { build_ui(app); }); app } Err(e) => { return Err(format!("Failed to create user interface: {:?}", e)); } }; application.run(&[]); Ok(()) } fn build_ui(app: &gtk::Application) { let builder = gtk::Builder::new_from_resource("/com/github/kil0meters/sentinel/gtk/interface.ui"); let win = gtk::ApplicationWindow::new(app); win.set_default_size(732, 500); win.set_gravity(gdk::Gravity::Center); let vbox: gtk::Box = builder.get_object("vbox").unwrap(); let revealer: gtk::Revealer = builder.get_object("search_revealer").unwrap(); let vplayer_stack: gtk::Stack = builder.get_object("vplayer_stack").unwrap(); let vplayer_overlay: gtk::Overlay = builder.get_object("vplayer_overlay").unwrap(); let stack: gtk::Stack = builder.get_object("stack").unwrap(); let viewport: gtk::Viewport = builder.get_object("trending_viewport").unwrap(); trending::refresh(&viewport); // move vplayer_stack and vplayer_overlay into a thread local storage // key to be used later VPLAYER.with(move |vplayer| { *vplayer.borrow_mut() = Some((vplayer_stack, vplayer_overlay)); }); let headerbar = headerbar::get_headerbar(&stack, &revealer, &viewport); win.add(&vbox); win.set_title(NAME); win.set_wmclass(NAME, NAME); win.set_titlebar(&headerbar); win.show_all(); win.activate(); }
Receiver<Option<Vec<youtube::Video>>>,
random_line_split
app.rs
use gtk; use gdk; use gio; use gtk::prelude::*; use gio::prelude::*; use std::cell::RefCell; use std::sync::mpsc::Receiver; use {NAME, TAGLINE}; use static_resources; use preferences; use headerbar; use sentinel_api::youtube; use views::trending; // Define thread local storage keys. thread_local! { pub static VPLAYER: RefCell<Option<(gtk:: Stack, gtk::Overlay)>> = RefCell::new(None); #[allow(unknown_lints, type_complexity)] pub static TRENDING: RefCell<Option<( gtk::Viewport, Receiver<Option<Vec<youtube::Video>>>, )>> = RefCell::new(None); #[allow(unknown_lints, type_complexity)] pub static THUMBNAILS: RefCell<Option<( Vec<gtk::Image>, Receiver<Option<String>>, )>> = RefCell::new(None); } pub fn run_app() -> Result<(), String> { let application = match gtk::Application::new( Some("com.github.kil0meters.sentinel"), gio::ApplicationFlags::empty(), ) { Ok(app) => { app.connect_activate(move |app| { build_ui(app); }); app } Err(e) => { return Err(format!("Failed to create user interface: {:?}", e)); } }; application.run(&[]); Ok(()) } fn build_ui(app: &gtk::Application)
}); let headerbar = headerbar::get_headerbar(&stack, &revealer, &viewport); win.add(&vbox); win.set_title(NAME); win.set_wmclass(NAME, NAME); win.set_titlebar(&headerbar); win.show_all(); win.activate(); }
{ let builder = gtk::Builder::new_from_resource("/com/github/kil0meters/sentinel/gtk/interface.ui"); let win = gtk::ApplicationWindow::new(app); win.set_default_size(732, 500); win.set_gravity(gdk::Gravity::Center); let vbox: gtk::Box = builder.get_object("vbox").unwrap(); let revealer: gtk::Revealer = builder.get_object("search_revealer").unwrap(); let vplayer_stack: gtk::Stack = builder.get_object("vplayer_stack").unwrap(); let vplayer_overlay: gtk::Overlay = builder.get_object("vplayer_overlay").unwrap(); let stack: gtk::Stack = builder.get_object("stack").unwrap(); let viewport: gtk::Viewport = builder.get_object("trending_viewport").unwrap(); trending::refresh(&viewport); // move vplayer_stack and vplayer_overlay into a thread local storage // key to be used later VPLAYER.with(move |vplayer| { *vplayer.borrow_mut() = Some((vplayer_stack, vplayer_overlay));
identifier_body
app.rs
use gtk; use gdk; use gio; use gtk::prelude::*; use gio::prelude::*; use std::cell::RefCell; use std::sync::mpsc::Receiver; use {NAME, TAGLINE}; use static_resources; use preferences; use headerbar; use sentinel_api::youtube; use views::trending; // Define thread local storage keys. thread_local! { pub static VPLAYER: RefCell<Option<(gtk:: Stack, gtk::Overlay)>> = RefCell::new(None); #[allow(unknown_lints, type_complexity)] pub static TRENDING: RefCell<Option<( gtk::Viewport, Receiver<Option<Vec<youtube::Video>>>, )>> = RefCell::new(None); #[allow(unknown_lints, type_complexity)] pub static THUMBNAILS: RefCell<Option<( Vec<gtk::Image>, Receiver<Option<String>>, )>> = RefCell::new(None); } pub fn
() -> Result<(), String> { let application = match gtk::Application::new( Some("com.github.kil0meters.sentinel"), gio::ApplicationFlags::empty(), ) { Ok(app) => { app.connect_activate(move |app| { build_ui(app); }); app } Err(e) => { return Err(format!("Failed to create user interface: {:?}", e)); } }; application.run(&[]); Ok(()) } fn build_ui(app: &gtk::Application) { let builder = gtk::Builder::new_from_resource("/com/github/kil0meters/sentinel/gtk/interface.ui"); let win = gtk::ApplicationWindow::new(app); win.set_default_size(732, 500); win.set_gravity(gdk::Gravity::Center); let vbox: gtk::Box = builder.get_object("vbox").unwrap(); let revealer: gtk::Revealer = builder.get_object("search_revealer").unwrap(); let vplayer_stack: gtk::Stack = builder.get_object("vplayer_stack").unwrap(); let vplayer_overlay: gtk::Overlay = builder.get_object("vplayer_overlay").unwrap(); let stack: gtk::Stack = builder.get_object("stack").unwrap(); let viewport: gtk::Viewport = builder.get_object("trending_viewport").unwrap(); trending::refresh(&viewport); // move vplayer_stack and vplayer_overlay into a thread local storage // key to be used later VPLAYER.with(move |vplayer| { *vplayer.borrow_mut() = Some((vplayer_stack, vplayer_overlay)); }); let headerbar = headerbar::get_headerbar(&stack, &revealer, &viewport); win.add(&vbox); win.set_title(NAME); win.set_wmclass(NAME, NAME); win.set_titlebar(&headerbar); win.show_all(); win.activate(); }
run_app
identifier_name
associated-type-projection-from-multiple-supertraits.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test equality constraints in a where clause where the type being // equated appears in a supertrait. pub trait Vehicle { type Color; fn go(&self) { } } pub trait Box { type Color; fn mail(&self) { } }
fn dent<C:BoxCar>(c: C, color: C::Color) { //~^ ERROR ambiguous associated type `Color` in bounds of `C` //~| NOTE could derive from `Vehicle` //~| NOTE could derive from `Box` } fn dent_object<COLOR>(c: BoxCar<Color=COLOR>) { //~^ ERROR ambiguous associated type } fn paint<C:BoxCar>(c: C, d: C::Color) { //~^ ERROR ambiguous associated type `Color` in bounds of `C` //~| NOTE could derive from `Vehicle` //~| NOTE could derive from `Box` } pub fn main() { }
pub trait BoxCar : Box + Vehicle { }
random_line_split
associated-type-projection-from-multiple-supertraits.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test equality constraints in a where clause where the type being // equated appears in a supertrait. pub trait Vehicle { type Color; fn go(&self) { } } pub trait Box { type Color; fn mail(&self) { } } pub trait BoxCar : Box + Vehicle { } fn dent<C:BoxCar>(c: C, color: C::Color) { //~^ ERROR ambiguous associated type `Color` in bounds of `C` //~| NOTE could derive from `Vehicle` //~| NOTE could derive from `Box` } fn dent_object<COLOR>(c: BoxCar<Color=COLOR>) { //~^ ERROR ambiguous associated type } fn paint<C:BoxCar>(c: C, d: C::Color)
pub fn main() { }
{ //~^ ERROR ambiguous associated type `Color` in bounds of `C` //~| NOTE could derive from `Vehicle` //~| NOTE could derive from `Box` }
identifier_body
associated-type-projection-from-multiple-supertraits.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test equality constraints in a where clause where the type being // equated appears in a supertrait. pub trait Vehicle { type Color; fn go(&self) { } } pub trait Box { type Color; fn mail(&self) { } } pub trait BoxCar : Box + Vehicle { } fn dent<C:BoxCar>(c: C, color: C::Color) { //~^ ERROR ambiguous associated type `Color` in bounds of `C` //~| NOTE could derive from `Vehicle` //~| NOTE could derive from `Box` } fn
<COLOR>(c: BoxCar<Color=COLOR>) { //~^ ERROR ambiguous associated type } fn paint<C:BoxCar>(c: C, d: C::Color) { //~^ ERROR ambiguous associated type `Color` in bounds of `C` //~| NOTE could derive from `Vehicle` //~| NOTE could derive from `Box` } pub fn main() { }
dent_object
identifier_name
issue-3979-generics.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 use std::ops::Add; trait Positioned<S> { fn SetX(&mut self, S); fn X(&self) -> S; } trait Movable<S: Add<Output=S>>: Positioned<S> { fn translate(&mut self, dx: S) { let x = self.X() + dx; self.SetX(x); } } struct
{ x: isize, y: isize } impl Positioned<isize> for Point { fn SetX(&mut self, x: isize) { self.x = x; } fn X(&self) -> isize { self.x } } impl Movable<isize> for Point {} pub fn main() { let mut p = Point{ x: 1, y: 2}; p.translate(3); assert_eq!(p.X(), 4); }
Point
identifier_name
issue-3979-generics.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
trait Positioned<S> { fn SetX(&mut self, S); fn X(&self) -> S; } trait Movable<S: Add<Output=S>>: Positioned<S> { fn translate(&mut self, dx: S) { let x = self.X() + dx; self.SetX(x); } } struct Point { x: isize, y: isize } impl Positioned<isize> for Point { fn SetX(&mut self, x: isize) { self.x = x; } fn X(&self) -> isize { self.x } } impl Movable<isize> for Point {} pub fn main() { let mut p = Point{ x: 1, y: 2}; p.translate(3); assert_eq!(p.X(), 4); }
// pretty-expanded FIXME #23616 use std::ops::Add;
random_line_split
issue-3979-generics.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 use std::ops::Add; trait Positioned<S> { fn SetX(&mut self, S); fn X(&self) -> S; } trait Movable<S: Add<Output=S>>: Positioned<S> { fn translate(&mut self, dx: S) { let x = self.X() + dx; self.SetX(x); } } struct Point { x: isize, y: isize } impl Positioned<isize> for Point { fn SetX(&mut self, x: isize) { self.x = x; } fn X(&self) -> isize
} impl Movable<isize> for Point {} pub fn main() { let mut p = Point{ x: 1, y: 2}; p.translate(3); assert_eq!(p.X(), 4); }
{ self.x }
identifier_body
assoc-type.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we do not yet support elision in associated types, even // when there is just one name we could take from the impl header. #![allow(warnings)] trait MyTrait { type Output; } impl MyTrait for &i32 { type Output = &i32; //~^ ERROR missing lifetime specifier } impl MyTrait for &u32 { type Output = &'_ i32; //~^ ERROR missing lifetime specifier } // This is what you have to do: impl<'a> MyTrait for &'a f32 { type Output = &'a f32; } fn
() { }
main
identifier_name
assoc-type.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we do not yet support elision in associated types, even // when there is just one name we could take from the impl header. #![allow(warnings)] trait MyTrait { type Output; } impl MyTrait for &i32 { type Output = &i32; //~^ ERROR missing lifetime specifier } impl MyTrait for &u32 { type Output = &'_ i32; //~^ ERROR missing lifetime specifier } // This is what you have to do: impl<'a> MyTrait for &'a f32 { type Output = &'a f32; } fn main() { }
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
assoc-type.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we do not yet support elision in associated types, even // when there is just one name we could take from the impl header. #![allow(warnings)] trait MyTrait { type Output; } impl MyTrait for &i32 { type Output = &i32; //~^ ERROR missing lifetime specifier } impl MyTrait for &u32 { type Output = &'_ i32; //~^ ERROR missing lifetime specifier } // This is what you have to do: impl<'a> MyTrait for &'a f32 { type Output = &'a f32; } fn main()
{ }
identifier_body
build.rs
use flapigen::{CppConfig, CppOptional, CppStrView, CppVariant, LanguageConfig}; use std::{env, path::Path}; fn
() { let out_dir = env::var("OUT_DIR").expect("no OUT_DIR, but cargo should provide it"); //ANCHOR: cpp_config let cpp_cfg = CppConfig::new( // ANCHOR: cpp_output Path::new("..").join("cpp-part").join("rust-api"), // ANCHOR_END: cpp_output "rust".into(), ) .cpp_optional(CppOptional::Boost) .cpp_variant(CppVariant::Boost) .cpp_str_view(CppStrView::Boost); //ANCHOR_END: cpp_config let swig_gen = flapigen::Generator::new(LanguageConfig::CppConfig(cpp_cfg)); swig_gen.expand( "c++-api-for-rust", // ANCHOR: rust_input Path::new("src/cpp_glue.rs.in"), // ANCHOR_END: rust_input // ANCHOR: rust_output &Path::new(&out_dir).join("cpp_glue.rs"), // ANCHOR_END: rust_output ); println!( "cargo:rerun-if-changed={}", Path::new("src").join("cpp_glue.rs.in").display() ); }
main
identifier_name
build.rs
use flapigen::{CppConfig, CppOptional, CppStrView, CppVariant, LanguageConfig}; use std::{env, path::Path}; fn main() { let out_dir = env::var("OUT_DIR").expect("no OUT_DIR, but cargo should provide it"); //ANCHOR: cpp_config let cpp_cfg = CppConfig::new( // ANCHOR: cpp_output Path::new("..").join("cpp-part").join("rust-api"),
"rust".into(), ) .cpp_optional(CppOptional::Boost) .cpp_variant(CppVariant::Boost) .cpp_str_view(CppStrView::Boost); //ANCHOR_END: cpp_config let swig_gen = flapigen::Generator::new(LanguageConfig::CppConfig(cpp_cfg)); swig_gen.expand( "c++-api-for-rust", // ANCHOR: rust_input Path::new("src/cpp_glue.rs.in"), // ANCHOR_END: rust_input // ANCHOR: rust_output &Path::new(&out_dir).join("cpp_glue.rs"), // ANCHOR_END: rust_output ); println!( "cargo:rerun-if-changed={}", Path::new("src").join("cpp_glue.rs.in").display() ); }
// ANCHOR_END: cpp_output
random_line_split
build.rs
use flapigen::{CppConfig, CppOptional, CppStrView, CppVariant, LanguageConfig}; use std::{env, path::Path}; fn main()
// ANCHOR: rust_output &Path::new(&out_dir).join("cpp_glue.rs"), // ANCHOR_END: rust_output ); println!( "cargo:rerun-if-changed={}", Path::new("src").join("cpp_glue.rs.in").display() ); }
{ let out_dir = env::var("OUT_DIR").expect("no OUT_DIR, but cargo should provide it"); //ANCHOR: cpp_config let cpp_cfg = CppConfig::new( // ANCHOR: cpp_output Path::new("..").join("cpp-part").join("rust-api"), // ANCHOR_END: cpp_output "rust".into(), ) .cpp_optional(CppOptional::Boost) .cpp_variant(CppVariant::Boost) .cpp_str_view(CppStrView::Boost); //ANCHOR_END: cpp_config let swig_gen = flapigen::Generator::new(LanguageConfig::CppConfig(cpp_cfg)); swig_gen.expand( "c++-api-for-rust", // ANCHOR: rust_input Path::new("src/cpp_glue.rs.in"), // ANCHOR_END: rust_input
identifier_body
vec_resize_to_zero.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_ast::LitKind; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Spanned; declare_clippy_lint! { /// ### What it does /// Finds occurrences of `Vec::resize(0, an_int)` /// /// ### Why is this bad? /// This is probably an argument inversion mistake. /// /// ### Example /// ```rust /// vec!(1, 2, 3, 4, 5).resize(0, 5) /// ``` pub VEC_RESIZE_TO_ZERO, correctness, "emptying a vector with `resize(0, an_int)` instead of `clear()` is probably an argument inversion mistake" } declare_lint_pass!(VecResizeToZero => [VEC_RESIZE_TO_ZERO]); impl<'tcx> LateLintPass<'tcx> for VecResizeToZero { fn
(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if_chain! { if let hir::ExprKind::MethodCall(path_segment, _, args, _) = expr.kind; if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, method_def_id, &paths::VEC_RESIZE) && args.len() == 3; if let ExprKind::Lit(Spanned { node: LitKind::Int(0, _),.. }) = args[1].kind; if let ExprKind::Lit(Spanned { node: LitKind::Int(..),.. }) = args[2].kind; then { let method_call_span = expr.span.with_lo(path_segment.ident.span.lo()); span_lint_and_then( cx, VEC_RESIZE_TO_ZERO, expr.span, "emptying a vector with `resize`", |db| { db.help("the arguments may be inverted..."); db.span_suggestion( method_call_span, "...or you can empty the vector with", "clear()".to_string(), Applicability::MaybeIncorrect, ); }, ); } } } }
check_expr
identifier_name
vec_resize_to_zero.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_ast::LitKind; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Spanned; declare_clippy_lint! { /// ### What it does /// Finds occurrences of `Vec::resize(0, an_int)` /// /// ### Why is this bad? /// This is probably an argument inversion mistake. /// /// ### Example /// ```rust /// vec!(1, 2, 3, 4, 5).resize(0, 5) /// ``` pub VEC_RESIZE_TO_ZERO, correctness, "emptying a vector with `resize(0, an_int)` instead of `clear()` is probably an argument inversion mistake" } declare_lint_pass!(VecResizeToZero => [VEC_RESIZE_TO_ZERO]); impl<'tcx> LateLintPass<'tcx> for VecResizeToZero { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>)
Applicability::MaybeIncorrect, ); }, ); } } } }
{ if_chain! { if let hir::ExprKind::MethodCall(path_segment, _, args, _) = expr.kind; if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, method_def_id, &paths::VEC_RESIZE) && args.len() == 3; if let ExprKind::Lit(Spanned { node: LitKind::Int(0, _), .. }) = args[1].kind; if let ExprKind::Lit(Spanned { node: LitKind::Int(..), .. }) = args[2].kind; then { let method_call_span = expr.span.with_lo(path_segment.ident.span.lo()); span_lint_and_then( cx, VEC_RESIZE_TO_ZERO, expr.span, "emptying a vector with `resize`", |db| { db.help("the arguments may be inverted..."); db.span_suggestion( method_call_span, "...or you can empty the vector with", "clear()".to_string(),
identifier_body
vec_resize_to_zero.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_ast::LitKind; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Spanned; declare_clippy_lint! { /// ### What it does /// Finds occurrences of `Vec::resize(0, an_int)` /// /// ### Why is this bad? /// This is probably an argument inversion mistake. /// /// ### Example /// ```rust /// vec!(1, 2, 3, 4, 5).resize(0, 5) /// ``` pub VEC_RESIZE_TO_ZERO, correctness, "emptying a vector with `resize(0, an_int)` instead of `clear()` is probably an argument inversion mistake" } declare_lint_pass!(VecResizeToZero => [VEC_RESIZE_TO_ZERO]); impl<'tcx> LateLintPass<'tcx> for VecResizeToZero { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if_chain! { if let hir::ExprKind::MethodCall(path_segment, _, args, _) = expr.kind; if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, method_def_id, &paths::VEC_RESIZE) && args.len() == 3; if let ExprKind::Lit(Spanned { node: LitKind::Int(0, _),.. }) = args[1].kind; if let ExprKind::Lit(Spanned { node: LitKind::Int(..),.. }) = args[2].kind; then { let method_call_span = expr.span.with_lo(path_segment.ident.span.lo()); span_lint_and_then( cx, VEC_RESIZE_TO_ZERO, expr.span, "emptying a vector with `resize`", |db| { db.help("the arguments may be inverted..."); db.span_suggestion(
"clear()".to_string(), Applicability::MaybeIncorrect, ); }, ); } } } }
method_call_span, "...or you can empty the vector with",
random_line_split
options.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. #[derive(Clone,Copy,PartialEq)] pub enum StyleJoinMode { None, Some, All, } // Documentation can be found in: docs/svgcleaner.adoc pub struct CleaningOptions { pub remove_unused_defs: bool, pub convert_shapes: bool, pub remove_title: bool, pub remove_desc: bool, pub remove_metadata: bool, pub remove_dupl_linear_gradients: bool, pub remove_dupl_radial_gradients: bool, pub remove_dupl_fe_gaussian_blur: bool, pub ungroup_groups: bool, pub ungroup_defs: bool, pub group_by_style: bool, pub merge_gradients: bool, pub regroup_gradient_stops: bool, pub remove_invalid_stops: bool, pub remove_invisible_elements: bool, pub resolve_use: bool, pub remove_version: bool, pub remove_unreferenced_ids: bool, pub trim_ids: bool, pub remove_text_attributes: bool, pub remove_unused_coordinates: bool, pub remove_default_attributes: bool, pub remove_xmlns_xlink_attribute: bool, pub remove_needless_attributes: bool, pub remove_gradient_attributes: bool, pub join_style_attributes: StyleJoinMode, pub apply_transform_to_gradients: bool, pub apply_transform_to_shapes: bool, pub paths_to_relative: bool, pub remove_unused_segments: bool, pub convert_segments: bool, pub append_newline: bool, pub apply_transform_to_paths: bool, // 1..12 pub coordinates_precision: u8, // 1..12 pub properties_precision: u8, // 1..12 pub paths_coordinates_precision: u8, // 1..12 pub transforms_precision: u8, } // Should all be 'false'. impl Default for CleaningOptions { fn default() -> CleaningOptions
remove_unreferenced_ids: false, trim_ids: false, remove_text_attributes: false, remove_unused_coordinates: false, remove_default_attributes: false, remove_xmlns_xlink_attribute: false, remove_needless_attributes: false, remove_gradient_attributes: false, join_style_attributes: StyleJoinMode::None, apply_transform_to_gradients: false, apply_transform_to_shapes: false, paths_to_relative: false, remove_unused_segments: false, convert_segments: false, append_newline: false, apply_transform_to_paths: false, coordinates_precision: 6, properties_precision: 6, paths_coordinates_precision: 8, transforms_precision: 8, } } }
{ CleaningOptions { remove_unused_defs: false, convert_shapes: false, remove_title: false, remove_desc: false, remove_metadata: false, remove_dupl_linear_gradients: false, remove_dupl_radial_gradients: false, remove_dupl_fe_gaussian_blur: false, ungroup_groups: false, ungroup_defs: false, group_by_style: false, merge_gradients: false, regroup_gradient_stops: false, remove_invalid_stops: false, remove_invisible_elements: false, resolve_use: false, remove_version: false,
identifier_body
options.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. #[derive(Clone,Copy,PartialEq)] pub enum StyleJoinMode { None, Some, All, } // Documentation can be found in: docs/svgcleaner.adoc pub struct CleaningOptions { pub remove_unused_defs: bool, pub convert_shapes: bool, pub remove_title: bool, pub remove_desc: bool, pub remove_metadata: bool, pub remove_dupl_linear_gradients: bool, pub remove_dupl_radial_gradients: bool, pub remove_dupl_fe_gaussian_blur: bool, pub ungroup_groups: bool, pub ungroup_defs: bool, pub group_by_style: bool, pub merge_gradients: bool, pub regroup_gradient_stops: bool, pub remove_invalid_stops: bool, pub remove_invisible_elements: bool, pub resolve_use: bool, pub remove_version: bool, pub remove_unreferenced_ids: bool, pub trim_ids: bool, pub remove_text_attributes: bool, pub remove_unused_coordinates: bool, pub remove_default_attributes: bool, pub remove_xmlns_xlink_attribute: bool, pub remove_needless_attributes: bool, pub remove_gradient_attributes: bool, pub join_style_attributes: StyleJoinMode, pub apply_transform_to_gradients: bool, pub apply_transform_to_shapes: bool, pub paths_to_relative: bool, pub remove_unused_segments: bool, pub convert_segments: bool, pub append_newline: bool, pub apply_transform_to_paths: bool, // 1..12 pub coordinates_precision: u8, // 1..12 pub properties_precision: u8, // 1..12 pub paths_coordinates_precision: u8, // 1..12 pub transforms_precision: u8, } // Should all be 'false'. impl Default for CleaningOptions { fn
() -> CleaningOptions { CleaningOptions { remove_unused_defs: false, convert_shapes: false, remove_title: false, remove_desc: false, remove_metadata: false, remove_dupl_linear_gradients: false, remove_dupl_radial_gradients: false, remove_dupl_fe_gaussian_blur: false, ungroup_groups: false, ungroup_defs: false, group_by_style: false, merge_gradients: false, regroup_gradient_stops: false, remove_invalid_stops: false, remove_invisible_elements: false, resolve_use: false, remove_version: false, remove_unreferenced_ids: false, trim_ids: false, remove_text_attributes: false, remove_unused_coordinates: false, remove_default_attributes: false, remove_xmlns_xlink_attribute: false, remove_needless_attributes: false, remove_gradient_attributes: false, join_style_attributes: StyleJoinMode::None, apply_transform_to_gradients: false, apply_transform_to_shapes: false, paths_to_relative: false, remove_unused_segments: false, convert_segments: false, append_newline: false, apply_transform_to_paths: false, coordinates_precision: 6, properties_precision: 6, paths_coordinates_precision: 8, transforms_precision: 8, } } }
default
identifier_name
options.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. #[derive(Clone,Copy,PartialEq)] pub enum StyleJoinMode { None, Some, All, } // Documentation can be found in: docs/svgcleaner.adoc pub struct CleaningOptions { pub remove_unused_defs: bool, pub convert_shapes: bool, pub remove_title: bool, pub remove_desc: bool, pub remove_metadata: bool, pub remove_dupl_linear_gradients: bool, pub remove_dupl_radial_gradients: bool, pub remove_dupl_fe_gaussian_blur: bool, pub ungroup_groups: bool, pub ungroup_defs: bool, pub group_by_style: bool, pub merge_gradients: bool, pub regroup_gradient_stops: bool, pub remove_invalid_stops: bool, pub remove_invisible_elements: bool, pub resolve_use: bool, pub remove_version: bool, pub remove_unreferenced_ids: bool, pub trim_ids: bool, pub remove_text_attributes: bool, pub remove_unused_coordinates: bool, pub remove_default_attributes: bool, pub remove_xmlns_xlink_attribute: bool, pub remove_needless_attributes: bool, pub remove_gradient_attributes: bool, pub join_style_attributes: StyleJoinMode, pub apply_transform_to_gradients: bool, pub apply_transform_to_shapes: bool, pub paths_to_relative: bool, pub remove_unused_segments: bool, pub convert_segments: bool, pub append_newline: bool, pub apply_transform_to_paths: bool, // 1..12 pub coordinates_precision: u8, // 1..12 pub properties_precision: u8, // 1..12
} // Should all be 'false'. impl Default for CleaningOptions { fn default() -> CleaningOptions { CleaningOptions { remove_unused_defs: false, convert_shapes: false, remove_title: false, remove_desc: false, remove_metadata: false, remove_dupl_linear_gradients: false, remove_dupl_radial_gradients: false, remove_dupl_fe_gaussian_blur: false, ungroup_groups: false, ungroup_defs: false, group_by_style: false, merge_gradients: false, regroup_gradient_stops: false, remove_invalid_stops: false, remove_invisible_elements: false, resolve_use: false, remove_version: false, remove_unreferenced_ids: false, trim_ids: false, remove_text_attributes: false, remove_unused_coordinates: false, remove_default_attributes: false, remove_xmlns_xlink_attribute: false, remove_needless_attributes: false, remove_gradient_attributes: false, join_style_attributes: StyleJoinMode::None, apply_transform_to_gradients: false, apply_transform_to_shapes: false, paths_to_relative: false, remove_unused_segments: false, convert_segments: false, append_newline: false, apply_transform_to_paths: false, coordinates_precision: 6, properties_precision: 6, paths_coordinates_precision: 8, transforms_precision: 8, } } }
pub paths_coordinates_precision: u8, // 1..12 pub transforms_precision: u8,
random_line_split
lossy.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use char; use str as core_str; use fmt; use fmt::Write; use mem; /// Lossy UTF-8 string. #[unstable(feature = "str_internals", issue = "0")] pub struct Utf8Lossy { bytes: [u8] } impl Utf8Lossy { pub fn from_str(s: &str) -> &Utf8Lossy { Utf8Lossy::from_bytes(s.as_bytes()) } pub fn from_bytes(bytes: &[u8]) -> &Utf8Lossy { unsafe { mem::transmute(bytes) } } pub fn chunks(&self) -> Utf8LossyChunksIter { Utf8LossyChunksIter { source: &self.bytes } } } /// Iterator over lossy UTF-8 string #[unstable(feature = "str_internals", issue = "0")] #[allow(missing_debug_implementations)] pub struct Utf8LossyChunksIter<'a> { source: &'a [u8], } #[unstable(feature = "str_internals", issue = "0")] #[derive(PartialEq, Eq, Debug)] pub struct Utf8LossyChunk<'a> { /// Sequence of valid chars. /// Can be empty between broken UTF-8 chars. pub valid: &'a str, /// Single broken char, empty if none. /// Empty iff iterator item is last. pub broken: &'a [u8], } impl<'a> Iterator for Utf8LossyChunksIter<'a> { type Item = Utf8LossyChunk<'a>; fn next(&mut self) -> Option<Utf8LossyChunk<'a>> { if self.source.len() == 0 { return None; } const TAG_CONT_U8: u8 = 128; fn safe_get(xs: &[u8], i: usize) -> u8 { *xs.get(i).unwrap_or(&0) } let mut i = 0; while i < self.source.len() { let i_ = i; let byte = unsafe { *self.source.get_unchecked(i) }; i += 1; if byte < 128 { } else { let w = core_str::utf8_char_width(byte); macro_rules! error { () => ({ unsafe { let r = Utf8LossyChunk { valid: core_str::from_utf8_unchecked(&self.source[0..i_]), broken: &self.source[i_..i], }; self.source = &self.source[i..]; return Some(r); } })} match w { 2 => { if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; } 3 => { match (byte, safe_get(self.source, i)) { (0xE0, 0xA0..= 0xBF) => (), (0xE1..= 0xEC, 0x80..= 0xBF) => (), (0xED, 0x80..= 0x9F) => (), (0xEE..= 0xEF, 0x80..= 0xBF) => (), _ => { error!(); } } i += 1; if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; } 4 => { match (byte, safe_get(self.source, i)) { (0xF0, 0x90..= 0xBF) => (), (0xF1..= 0xF3, 0x80..= 0xBF) => (), (0xF4, 0x80..= 0x8F) => (), _ => { error!(); } } i += 1; if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; } _ => { error!(); } } } } let r = Utf8LossyChunk { valid: unsafe { core_str::from_utf8_unchecked(self.source) }, broken: &[], }; self.source = &[]; Some(r) } } impl fmt::Display for Utf8Lossy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // If we're the empty string then our iterator won't actually yield // anything, so perform the formatting manually if self.bytes.len() == 0
for Utf8LossyChunk { valid, broken } in self.chunks() { // If we successfully decoded the whole chunk as a valid string then // we can return a direct formatting of the string which will also // respect various formatting flags if possible. if valid.len() == self.bytes.len() { assert!(broken.is_empty()); return valid.fmt(f) } f.write_str(valid)?; if!broken.is_empty() { f.write_char(char::REPLACEMENT_CHARACTER)?; } } Ok(()) } } impl fmt::Debug for Utf8Lossy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char('"')?; for Utf8LossyChunk { valid, broken } in self.chunks() { // Valid part. // Here we partially parse UTF-8 again which is suboptimal. { let mut from = 0; for (i, c) in valid.char_indices() { let esc = c.escape_debug(); // If char needs escaping, flush backlog so far and write, else skip if esc.len()!= 1 { f.write_str(&valid[from..i])?; for c in esc { f.write_char(c)?; } from = i + c.len_utf8(); } } f.write_str(&valid[from..])?; } // Broken parts of string as hex escape. for &b in broken { write!(f, "\\x{:02x}", b)?; } } f.write_char('"') } }
{ return "".fmt(f) }
conditional_block
lossy.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use char; use str as core_str; use fmt; use fmt::Write; use mem; /// Lossy UTF-8 string. #[unstable(feature = "str_internals", issue = "0")] pub struct Utf8Lossy { bytes: [u8] } impl Utf8Lossy { pub fn from_str(s: &str) -> &Utf8Lossy { Utf8Lossy::from_bytes(s.as_bytes()) } pub fn from_bytes(bytes: &[u8]) -> &Utf8Lossy { unsafe { mem::transmute(bytes) } } pub fn chunks(&self) -> Utf8LossyChunksIter { Utf8LossyChunksIter { source: &self.bytes } } } /// Iterator over lossy UTF-8 string #[unstable(feature = "str_internals", issue = "0")] #[allow(missing_debug_implementations)] pub struct Utf8LossyChunksIter<'a> { source: &'a [u8], } #[unstable(feature = "str_internals", issue = "0")] #[derive(PartialEq, Eq, Debug)] pub struct Utf8LossyChunk<'a> { /// Sequence of valid chars. /// Can be empty between broken UTF-8 chars. pub valid: &'a str, /// Single broken char, empty if none. /// Empty iff iterator item is last. pub broken: &'a [u8], } impl<'a> Iterator for Utf8LossyChunksIter<'a> { type Item = Utf8LossyChunk<'a>; fn next(&mut self) -> Option<Utf8LossyChunk<'a>> { if self.source.len() == 0 { return None; } const TAG_CONT_U8: u8 = 128; fn safe_get(xs: &[u8], i: usize) -> u8 { *xs.get(i).unwrap_or(&0) } let mut i = 0; while i < self.source.len() { let i_ = i; let byte = unsafe { *self.source.get_unchecked(i) }; i += 1;
macro_rules! error { () => ({ unsafe { let r = Utf8LossyChunk { valid: core_str::from_utf8_unchecked(&self.source[0..i_]), broken: &self.source[i_..i], }; self.source = &self.source[i..]; return Some(r); } })} match w { 2 => { if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; } 3 => { match (byte, safe_get(self.source, i)) { (0xE0, 0xA0..= 0xBF) => (), (0xE1..= 0xEC, 0x80..= 0xBF) => (), (0xED, 0x80..= 0x9F) => (), (0xEE..= 0xEF, 0x80..= 0xBF) => (), _ => { error!(); } } i += 1; if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; } 4 => { match (byte, safe_get(self.source, i)) { (0xF0, 0x90..= 0xBF) => (), (0xF1..= 0xF3, 0x80..= 0xBF) => (), (0xF4, 0x80..= 0x8F) => (), _ => { error!(); } } i += 1; if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; } _ => { error!(); } } } } let r = Utf8LossyChunk { valid: unsafe { core_str::from_utf8_unchecked(self.source) }, broken: &[], }; self.source = &[]; Some(r) } } impl fmt::Display for Utf8Lossy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // If we're the empty string then our iterator won't actually yield // anything, so perform the formatting manually if self.bytes.len() == 0 { return "".fmt(f) } for Utf8LossyChunk { valid, broken } in self.chunks() { // If we successfully decoded the whole chunk as a valid string then // we can return a direct formatting of the string which will also // respect various formatting flags if possible. if valid.len() == self.bytes.len() { assert!(broken.is_empty()); return valid.fmt(f) } f.write_str(valid)?; if!broken.is_empty() { f.write_char(char::REPLACEMENT_CHARACTER)?; } } Ok(()) } } impl fmt::Debug for Utf8Lossy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char('"')?; for Utf8LossyChunk { valid, broken } in self.chunks() { // Valid part. // Here we partially parse UTF-8 again which is suboptimal. { let mut from = 0; for (i, c) in valid.char_indices() { let esc = c.escape_debug(); // If char needs escaping, flush backlog so far and write, else skip if esc.len()!= 1 { f.write_str(&valid[from..i])?; for c in esc { f.write_char(c)?; } from = i + c.len_utf8(); } } f.write_str(&valid[from..])?; } // Broken parts of string as hex escape. for &b in broken { write!(f, "\\x{:02x}", b)?; } } f.write_char('"') } }
if byte < 128 { } else { let w = core_str::utf8_char_width(byte);
random_line_split
lossy.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use char; use str as core_str; use fmt; use fmt::Write; use mem; /// Lossy UTF-8 string. #[unstable(feature = "str_internals", issue = "0")] pub struct Utf8Lossy { bytes: [u8] } impl Utf8Lossy { pub fn from_str(s: &str) -> &Utf8Lossy { Utf8Lossy::from_bytes(s.as_bytes()) } pub fn from_bytes(bytes: &[u8]) -> &Utf8Lossy { unsafe { mem::transmute(bytes) } } pub fn chunks(&self) -> Utf8LossyChunksIter
} /// Iterator over lossy UTF-8 string #[unstable(feature = "str_internals", issue = "0")] #[allow(missing_debug_implementations)] pub struct Utf8LossyChunksIter<'a> { source: &'a [u8], } #[unstable(feature = "str_internals", issue = "0")] #[derive(PartialEq, Eq, Debug)] pub struct Utf8LossyChunk<'a> { /// Sequence of valid chars. /// Can be empty between broken UTF-8 chars. pub valid: &'a str, /// Single broken char, empty if none. /// Empty iff iterator item is last. pub broken: &'a [u8], } impl<'a> Iterator for Utf8LossyChunksIter<'a> { type Item = Utf8LossyChunk<'a>; fn next(&mut self) -> Option<Utf8LossyChunk<'a>> { if self.source.len() == 0 { return None; } const TAG_CONT_U8: u8 = 128; fn safe_get(xs: &[u8], i: usize) -> u8 { *xs.get(i).unwrap_or(&0) } let mut i = 0; while i < self.source.len() { let i_ = i; let byte = unsafe { *self.source.get_unchecked(i) }; i += 1; if byte < 128 { } else { let w = core_str::utf8_char_width(byte); macro_rules! error { () => ({ unsafe { let r = Utf8LossyChunk { valid: core_str::from_utf8_unchecked(&self.source[0..i_]), broken: &self.source[i_..i], }; self.source = &self.source[i..]; return Some(r); } })} match w { 2 => { if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; } 3 => { match (byte, safe_get(self.source, i)) { (0xE0, 0xA0..= 0xBF) => (), (0xE1..= 0xEC, 0x80..= 0xBF) => (), (0xED, 0x80..= 0x9F) => (), (0xEE..= 0xEF, 0x80..= 0xBF) => (), _ => { error!(); } } i += 1; if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; } 4 => { match (byte, safe_get(self.source, i)) { (0xF0, 0x90..= 0xBF) => (), (0xF1..= 0xF3, 0x80..= 0xBF) => (), (0xF4, 0x80..= 0x8F) => (), _ => { error!(); } } i += 1; if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; } _ => { error!(); } } } } let r = Utf8LossyChunk { valid: unsafe { core_str::from_utf8_unchecked(self.source) }, broken: &[], }; self.source = &[]; Some(r) } } impl fmt::Display for Utf8Lossy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // If we're the empty string then our iterator won't actually yield // anything, so perform the formatting manually if self.bytes.len() == 0 { return "".fmt(f) } for Utf8LossyChunk { valid, broken } in self.chunks() { // If we successfully decoded the whole chunk as a valid string then // we can return a direct formatting of the string which will also // respect various formatting flags if possible. if valid.len() == self.bytes.len() { assert!(broken.is_empty()); return valid.fmt(f) } f.write_str(valid)?; if!broken.is_empty() { f.write_char(char::REPLACEMENT_CHARACTER)?; } } Ok(()) } } impl fmt::Debug for Utf8Lossy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char('"')?; for Utf8LossyChunk { valid, broken } in self.chunks() { // Valid part. // Here we partially parse UTF-8 again which is suboptimal. { let mut from = 0; for (i, c) in valid.char_indices() { let esc = c.escape_debug(); // If char needs escaping, flush backlog so far and write, else skip if esc.len()!= 1 { f.write_str(&valid[from..i])?; for c in esc { f.write_char(c)?; } from = i + c.len_utf8(); } } f.write_str(&valid[from..])?; } // Broken parts of string as hex escape. for &b in broken { write!(f, "\\x{:02x}", b)?; } } f.write_char('"') } }
{ Utf8LossyChunksIter { source: &self.bytes } }
identifier_body
lossy.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use char; use str as core_str; use fmt; use fmt::Write; use mem; /// Lossy UTF-8 string. #[unstable(feature = "str_internals", issue = "0")] pub struct Utf8Lossy { bytes: [u8] } impl Utf8Lossy { pub fn from_str(s: &str) -> &Utf8Lossy { Utf8Lossy::from_bytes(s.as_bytes()) } pub fn from_bytes(bytes: &[u8]) -> &Utf8Lossy { unsafe { mem::transmute(bytes) } } pub fn chunks(&self) -> Utf8LossyChunksIter { Utf8LossyChunksIter { source: &self.bytes } } } /// Iterator over lossy UTF-8 string #[unstable(feature = "str_internals", issue = "0")] #[allow(missing_debug_implementations)] pub struct Utf8LossyChunksIter<'a> { source: &'a [u8], } #[unstable(feature = "str_internals", issue = "0")] #[derive(PartialEq, Eq, Debug)] pub struct Utf8LossyChunk<'a> { /// Sequence of valid chars. /// Can be empty between broken UTF-8 chars. pub valid: &'a str, /// Single broken char, empty if none. /// Empty iff iterator item is last. pub broken: &'a [u8], } impl<'a> Iterator for Utf8LossyChunksIter<'a> { type Item = Utf8LossyChunk<'a>; fn next(&mut self) -> Option<Utf8LossyChunk<'a>> { if self.source.len() == 0 { return None; } const TAG_CONT_U8: u8 = 128; fn
(xs: &[u8], i: usize) -> u8 { *xs.get(i).unwrap_or(&0) } let mut i = 0; while i < self.source.len() { let i_ = i; let byte = unsafe { *self.source.get_unchecked(i) }; i += 1; if byte < 128 { } else { let w = core_str::utf8_char_width(byte); macro_rules! error { () => ({ unsafe { let r = Utf8LossyChunk { valid: core_str::from_utf8_unchecked(&self.source[0..i_]), broken: &self.source[i_..i], }; self.source = &self.source[i..]; return Some(r); } })} match w { 2 => { if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; } 3 => { match (byte, safe_get(self.source, i)) { (0xE0, 0xA0..= 0xBF) => (), (0xE1..= 0xEC, 0x80..= 0xBF) => (), (0xED, 0x80..= 0x9F) => (), (0xEE..= 0xEF, 0x80..= 0xBF) => (), _ => { error!(); } } i += 1; if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; } 4 => { match (byte, safe_get(self.source, i)) { (0xF0, 0x90..= 0xBF) => (), (0xF1..= 0xF3, 0x80..= 0xBF) => (), (0xF4, 0x80..= 0x8F) => (), _ => { error!(); } } i += 1; if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; if safe_get(self.source, i) & 192!= TAG_CONT_U8 { error!(); } i += 1; } _ => { error!(); } } } } let r = Utf8LossyChunk { valid: unsafe { core_str::from_utf8_unchecked(self.source) }, broken: &[], }; self.source = &[]; Some(r) } } impl fmt::Display for Utf8Lossy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // If we're the empty string then our iterator won't actually yield // anything, so perform the formatting manually if self.bytes.len() == 0 { return "".fmt(f) } for Utf8LossyChunk { valid, broken } in self.chunks() { // If we successfully decoded the whole chunk as a valid string then // we can return a direct formatting of the string which will also // respect various formatting flags if possible. if valid.len() == self.bytes.len() { assert!(broken.is_empty()); return valid.fmt(f) } f.write_str(valid)?; if!broken.is_empty() { f.write_char(char::REPLACEMENT_CHARACTER)?; } } Ok(()) } } impl fmt::Debug for Utf8Lossy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char('"')?; for Utf8LossyChunk { valid, broken } in self.chunks() { // Valid part. // Here we partially parse UTF-8 again which is suboptimal. { let mut from = 0; for (i, c) in valid.char_indices() { let esc = c.escape_debug(); // If char needs escaping, flush backlog so far and write, else skip if esc.len()!= 1 { f.write_str(&valid[from..i])?; for c in esc { f.write_char(c)?; } from = i + c.len_utf8(); } } f.write_str(&valid[from..])?; } // Broken parts of string as hex escape. for &b in broken { write!(f, "\\x{:02x}", b)?; } } f.write_char('"') } }
safe_get
identifier_name
register.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Gamari <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::iter::FromIterator; use std::ops::Deref; use syntax::ast; use syntax::ptr::P; use syntax::ast_util::empty_generics; use syntax::codemap::{respan, mk_sp}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::ext::quote::rt::ToTokens; use super::Builder; use super::utils; use super::super::node; /// A visitor to build the struct for each register pub struct BuildRegStructs<'a> { builder: &'a mut Builder, cx: &'a ExtCtxt<'a>, } impl<'a> node::RegVisitor for BuildRegStructs<'a> { fn visit_prim_reg(&mut self, path: &Vec<String>, reg: &node::Reg, fields: &Vec<node::Field>) { let width = match reg.ty { node::RegType::RegPrim(ref width, _) => width.node, _ => panic!("visit_prim_reg called with non-primitive register"), }; for field in fields.iter() { for item in build_field_type(self.cx, path, reg, field).into_iter() { self.builder.push_item(item); } } for item in build_reg_struct(self.cx, path, reg, &width).into_iter() { self.builder.push_item(item); } } } impl<'a> BuildRegStructs<'a> { pub fn new(builder: &'a mut Builder, cx: &'a ExtCtxt<'a>) -> BuildRegStructs<'a> { BuildRegStructs {builder: builder, cx: cx} } } /// Build a field type if necessary (e.g. in the case of an `EnumField`) fn build_field_type(cx: &ExtCtxt, path: &Vec<String>, reg: &node::Reg, field: &node::Field) -> Vec<P<ast::Item>> { match field.ty.node { node::FieldType::EnumField { ref variants,.. } => { // FIXME(bgamari): We construct a path, then only take the last // segment, this could be more efficient let name: ast::Ident = utils::field_type_path(cx, path, reg, field) .segments.last().unwrap().identifier; let enum_def: ast::EnumDef = ast::EnumDef { variants: FromIterator::from_iter( variants.iter().map(|v| P(build_enum_variant(cx, v)))), }; let mut attrs: Vec<ast::Attribute> = vec!( utils::list_attribute(cx, "derive", vec!("PartialEq"), field.name.span), utils::list_attribute(cx, "allow", vec!("dead_code", "non_camel_case_types", "missing_docs"), field.name.span)); // setting the enum's repr to the width of the register // (unless there's only 1 variant; in which case we omit // the repr attribute due to E0083 if variants.len() > 1 { let enum_repr = utils::reg_primitive_type_name(reg) .expect("Unexpected non-primitive reg"); attrs.push(utils::list_attribute(cx, "repr", vec!(enum_repr), field.name.span)); } let ty_item: P<ast::Item> = P(ast::Item { ident: name, id: ast::DUMMY_NODE_ID, node: ast::ItemEnum(enum_def, empty_generics()), vis: ast::Public, attrs: attrs, span: field.ty.span, }); vec!(ty_item) }, _ => Vec::new() } } /// Produce a register struct if necessary (for primitive typed registers). /// In this case `None` indicates no struct is necessary, not failure. /// For instance, /// /// pub struct REG {_value: u32} fn build_reg_struct(cx: &ExtCtxt, path: &Vec<String>, reg: &node::Reg, _width: &node::RegWidth) -> Vec<P<ast::Item>> { let packed_ty = utils::reg_primitive_type(cx, reg) .expect("Unexpected non-primitive reg"); let reg_doc = match reg.docstring { Some(d) => d.node.name.to_string(), None => "no documentation".to_string(), }; let docstring = format!("Register `{}`: {}", reg.name.node, reg_doc); let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring)); let ty_name = utils::path_ident(cx, path); let item = quote_item!(cx, $doc_attr #[derive(Clone)] #[allow(non_camel_case_types)] #[repr(C)] pub struct $ty_name { value: VolatileCell<$packed_ty>, } ); let mut item: ast::Item = item.unwrap().deref().clone(); item.span = reg.name.span; let copy_impl = quote_item!(cx, impl ::core::marker::Copy for $ty_name {}).unwrap();
fn build_enum_variant(cx: &ExtCtxt, variant: &node::Variant) -> ast::Variant { let doc = match variant.docstring { Some(d) => d.node.name.to_string(), None => "no documentation".to_string(), }; let docstring = format!("`0x{:x}`. {}", variant.value.node, doc); let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring)); respan( mk_sp(variant.name.span.lo, variant.value.span.hi), ast::Variant_ { name: cx.ident_of(variant.name.node.as_str()), attrs: vec!(doc_attr), data: ast::VariantData::Unit(ast::DUMMY_NODE_ID), disr_expr: Some(utils::expr_int(cx, respan(variant.value.span, variant.value.node as i64))), } ) }
vec!(P(item), copy_impl) } /// Build a variant of an `EnumField`
random_line_split
register.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Gamari <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::iter::FromIterator; use std::ops::Deref; use syntax::ast; use syntax::ptr::P; use syntax::ast_util::empty_generics; use syntax::codemap::{respan, mk_sp}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::ext::quote::rt::ToTokens; use super::Builder; use super::utils; use super::super::node; /// A visitor to build the struct for each register pub struct
<'a> { builder: &'a mut Builder, cx: &'a ExtCtxt<'a>, } impl<'a> node::RegVisitor for BuildRegStructs<'a> { fn visit_prim_reg(&mut self, path: &Vec<String>, reg: &node::Reg, fields: &Vec<node::Field>) { let width = match reg.ty { node::RegType::RegPrim(ref width, _) => width.node, _ => panic!("visit_prim_reg called with non-primitive register"), }; for field in fields.iter() { for item in build_field_type(self.cx, path, reg, field).into_iter() { self.builder.push_item(item); } } for item in build_reg_struct(self.cx, path, reg, &width).into_iter() { self.builder.push_item(item); } } } impl<'a> BuildRegStructs<'a> { pub fn new(builder: &'a mut Builder, cx: &'a ExtCtxt<'a>) -> BuildRegStructs<'a> { BuildRegStructs {builder: builder, cx: cx} } } /// Build a field type if necessary (e.g. in the case of an `EnumField`) fn build_field_type(cx: &ExtCtxt, path: &Vec<String>, reg: &node::Reg, field: &node::Field) -> Vec<P<ast::Item>> { match field.ty.node { node::FieldType::EnumField { ref variants,.. } => { // FIXME(bgamari): We construct a path, then only take the last // segment, this could be more efficient let name: ast::Ident = utils::field_type_path(cx, path, reg, field) .segments.last().unwrap().identifier; let enum_def: ast::EnumDef = ast::EnumDef { variants: FromIterator::from_iter( variants.iter().map(|v| P(build_enum_variant(cx, v)))), }; let mut attrs: Vec<ast::Attribute> = vec!( utils::list_attribute(cx, "derive", vec!("PartialEq"), field.name.span), utils::list_attribute(cx, "allow", vec!("dead_code", "non_camel_case_types", "missing_docs"), field.name.span)); // setting the enum's repr to the width of the register // (unless there's only 1 variant; in which case we omit // the repr attribute due to E0083 if variants.len() > 1 { let enum_repr = utils::reg_primitive_type_name(reg) .expect("Unexpected non-primitive reg"); attrs.push(utils::list_attribute(cx, "repr", vec!(enum_repr), field.name.span)); } let ty_item: P<ast::Item> = P(ast::Item { ident: name, id: ast::DUMMY_NODE_ID, node: ast::ItemEnum(enum_def, empty_generics()), vis: ast::Public, attrs: attrs, span: field.ty.span, }); vec!(ty_item) }, _ => Vec::new() } } /// Produce a register struct if necessary (for primitive typed registers). /// In this case `None` indicates no struct is necessary, not failure. /// For instance, /// /// pub struct REG {_value: u32} fn build_reg_struct(cx: &ExtCtxt, path: &Vec<String>, reg: &node::Reg, _width: &node::RegWidth) -> Vec<P<ast::Item>> { let packed_ty = utils::reg_primitive_type(cx, reg) .expect("Unexpected non-primitive reg"); let reg_doc = match reg.docstring { Some(d) => d.node.name.to_string(), None => "no documentation".to_string(), }; let docstring = format!("Register `{}`: {}", reg.name.node, reg_doc); let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring)); let ty_name = utils::path_ident(cx, path); let item = quote_item!(cx, $doc_attr #[derive(Clone)] #[allow(non_camel_case_types)] #[repr(C)] pub struct $ty_name { value: VolatileCell<$packed_ty>, } ); let mut item: ast::Item = item.unwrap().deref().clone(); item.span = reg.name.span; let copy_impl = quote_item!(cx, impl ::core::marker::Copy for $ty_name {}).unwrap(); vec!(P(item), copy_impl) } /// Build a variant of an `EnumField` fn build_enum_variant(cx: &ExtCtxt, variant: &node::Variant) -> ast::Variant { let doc = match variant.docstring { Some(d) => d.node.name.to_string(), None => "no documentation".to_string(), }; let docstring = format!("`0x{:x}`. {}", variant.value.node, doc); let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring)); respan( mk_sp(variant.name.span.lo, variant.value.span.hi), ast::Variant_ { name: cx.ident_of(variant.name.node.as_str()), attrs: vec!(doc_attr), data: ast::VariantData::Unit(ast::DUMMY_NODE_ID), disr_expr: Some(utils::expr_int(cx, respan(variant.value.span, variant.value.node as i64))), } ) }
BuildRegStructs
identifier_name
register.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Gamari <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::iter::FromIterator; use std::ops::Deref; use syntax::ast; use syntax::ptr::P; use syntax::ast_util::empty_generics; use syntax::codemap::{respan, mk_sp}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::ext::quote::rt::ToTokens; use super::Builder; use super::utils; use super::super::node; /// A visitor to build the struct for each register pub struct BuildRegStructs<'a> { builder: &'a mut Builder, cx: &'a ExtCtxt<'a>, } impl<'a> node::RegVisitor for BuildRegStructs<'a> { fn visit_prim_reg(&mut self, path: &Vec<String>, reg: &node::Reg, fields: &Vec<node::Field>)
} impl<'a> BuildRegStructs<'a> { pub fn new(builder: &'a mut Builder, cx: &'a ExtCtxt<'a>) -> BuildRegStructs<'a> { BuildRegStructs {builder: builder, cx: cx} } } /// Build a field type if necessary (e.g. in the case of an `EnumField`) fn build_field_type(cx: &ExtCtxt, path: &Vec<String>, reg: &node::Reg, field: &node::Field) -> Vec<P<ast::Item>> { match field.ty.node { node::FieldType::EnumField { ref variants,.. } => { // FIXME(bgamari): We construct a path, then only take the last // segment, this could be more efficient let name: ast::Ident = utils::field_type_path(cx, path, reg, field) .segments.last().unwrap().identifier; let enum_def: ast::EnumDef = ast::EnumDef { variants: FromIterator::from_iter( variants.iter().map(|v| P(build_enum_variant(cx, v)))), }; let mut attrs: Vec<ast::Attribute> = vec!( utils::list_attribute(cx, "derive", vec!("PartialEq"), field.name.span), utils::list_attribute(cx, "allow", vec!("dead_code", "non_camel_case_types", "missing_docs"), field.name.span)); // setting the enum's repr to the width of the register // (unless there's only 1 variant; in which case we omit // the repr attribute due to E0083 if variants.len() > 1 { let enum_repr = utils::reg_primitive_type_name(reg) .expect("Unexpected non-primitive reg"); attrs.push(utils::list_attribute(cx, "repr", vec!(enum_repr), field.name.span)); } let ty_item: P<ast::Item> = P(ast::Item { ident: name, id: ast::DUMMY_NODE_ID, node: ast::ItemEnum(enum_def, empty_generics()), vis: ast::Public, attrs: attrs, span: field.ty.span, }); vec!(ty_item) }, _ => Vec::new() } } /// Produce a register struct if necessary (for primitive typed registers). /// In this case `None` indicates no struct is necessary, not failure. /// For instance, /// /// pub struct REG {_value: u32} fn build_reg_struct(cx: &ExtCtxt, path: &Vec<String>, reg: &node::Reg, _width: &node::RegWidth) -> Vec<P<ast::Item>> { let packed_ty = utils::reg_primitive_type(cx, reg) .expect("Unexpected non-primitive reg"); let reg_doc = match reg.docstring { Some(d) => d.node.name.to_string(), None => "no documentation".to_string(), }; let docstring = format!("Register `{}`: {}", reg.name.node, reg_doc); let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring)); let ty_name = utils::path_ident(cx, path); let item = quote_item!(cx, $doc_attr #[derive(Clone)] #[allow(non_camel_case_types)] #[repr(C)] pub struct $ty_name { value: VolatileCell<$packed_ty>, } ); let mut item: ast::Item = item.unwrap().deref().clone(); item.span = reg.name.span; let copy_impl = quote_item!(cx, impl ::core::marker::Copy for $ty_name {}).unwrap(); vec!(P(item), copy_impl) } /// Build a variant of an `EnumField` fn build_enum_variant(cx: &ExtCtxt, variant: &node::Variant) -> ast::Variant { let doc = match variant.docstring { Some(d) => d.node.name.to_string(), None => "no documentation".to_string(), }; let docstring = format!("`0x{:x}`. {}", variant.value.node, doc); let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring)); respan( mk_sp(variant.name.span.lo, variant.value.span.hi), ast::Variant_ { name: cx.ident_of(variant.name.node.as_str()), attrs: vec!(doc_attr), data: ast::VariantData::Unit(ast::DUMMY_NODE_ID), disr_expr: Some(utils::expr_int(cx, respan(variant.value.span, variant.value.node as i64))), } ) }
{ let width = match reg.ty { node::RegType::RegPrim(ref width, _) => width.node, _ => panic!("visit_prim_reg called with non-primitive register"), }; for field in fields.iter() { for item in build_field_type(self.cx, path, reg, field).into_iter() { self.builder.push_item(item); } } for item in build_reg_struct(self.cx, path, reg, &width).into_iter() { self.builder.push_item(item); } }
identifier_body
constant.rs
// Copyright (c) 2018 The predicates-rs Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/license/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Definition of a constant (always true or always false) `Predicate`. use std::fmt; use crate::reflection; use crate::utils; use crate::Predicate; /// Predicate that always returns a constant (boolean) result. /// /// This is created by the `predicate::always` and `predicate::never` functions. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct BooleanPredicate { retval: bool, } impl<Item:?Sized> Predicate<Item> for BooleanPredicate { fn eval(&self, _variable: &Item) -> bool
fn find_case<'a>(&'a self, expected: bool, variable: &Item) -> Option<reflection::Case<'a>> { utils::default_find_case(self, expected, variable) } } impl reflection::PredicateReflection for BooleanPredicate { fn parameters<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Parameter<'a>> + 'a> { let params = vec![reflection::Parameter::new("value", &self.retval)]; Box::new(params.into_iter()) } } impl fmt::Display for BooleanPredicate { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let palette = crate::Palette::current(); write!(f, "{}", palette.expected.paint(self.retval)) } } /// Creates a new `Predicate` that always returns `true`. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::always(); /// assert_eq!(true, predicate_fn.eval(&5)); /// assert_eq!(true, predicate_fn.eval(&10)); /// assert_eq!(true, predicate_fn.eval(&15)); /// // Won't work - Predicates can only operate on a single type /// // assert_eq!(true, predicate_fn.eval("hello")) /// ``` pub fn always() -> BooleanPredicate { BooleanPredicate { retval: true } } /// Creates a new `Predicate` that always returns `false`. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::never(); /// assert_eq!(false, predicate_fn.eval(&5)); /// assert_eq!(false, predicate_fn.eval(&10)); /// assert_eq!(false, predicate_fn.eval(&15)); /// // Won't work - Predicates can only operate on a single type /// // assert_eq!(false, predicate_fn.eval("hello")) /// ``` pub fn never() -> BooleanPredicate { BooleanPredicate { retval: false } }
{ self.retval }
identifier_body
constant.rs
// Copyright (c) 2018 The predicates-rs Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/license/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Definition of a constant (always true or always false) `Predicate`. use std::fmt;
use crate::utils; use crate::Predicate; /// Predicate that always returns a constant (boolean) result. /// /// This is created by the `predicate::always` and `predicate::never` functions. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct BooleanPredicate { retval: bool, } impl<Item:?Sized> Predicate<Item> for BooleanPredicate { fn eval(&self, _variable: &Item) -> bool { self.retval } fn find_case<'a>(&'a self, expected: bool, variable: &Item) -> Option<reflection::Case<'a>> { utils::default_find_case(self, expected, variable) } } impl reflection::PredicateReflection for BooleanPredicate { fn parameters<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Parameter<'a>> + 'a> { let params = vec![reflection::Parameter::new("value", &self.retval)]; Box::new(params.into_iter()) } } impl fmt::Display for BooleanPredicate { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let palette = crate::Palette::current(); write!(f, "{}", palette.expected.paint(self.retval)) } } /// Creates a new `Predicate` that always returns `true`. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::always(); /// assert_eq!(true, predicate_fn.eval(&5)); /// assert_eq!(true, predicate_fn.eval(&10)); /// assert_eq!(true, predicate_fn.eval(&15)); /// // Won't work - Predicates can only operate on a single type /// // assert_eq!(true, predicate_fn.eval("hello")) /// ``` pub fn always() -> BooleanPredicate { BooleanPredicate { retval: true } } /// Creates a new `Predicate` that always returns `false`. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::never(); /// assert_eq!(false, predicate_fn.eval(&5)); /// assert_eq!(false, predicate_fn.eval(&10)); /// assert_eq!(false, predicate_fn.eval(&15)); /// // Won't work - Predicates can only operate on a single type /// // assert_eq!(false, predicate_fn.eval("hello")) /// ``` pub fn never() -> BooleanPredicate { BooleanPredicate { retval: false } }
use crate::reflection;
random_line_split
constant.rs
// Copyright (c) 2018 The predicates-rs Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/license/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Definition of a constant (always true or always false) `Predicate`. use std::fmt; use crate::reflection; use crate::utils; use crate::Predicate; /// Predicate that always returns a constant (boolean) result. /// /// This is created by the `predicate::always` and `predicate::never` functions. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct BooleanPredicate { retval: bool, } impl<Item:?Sized> Predicate<Item> for BooleanPredicate { fn eval(&self, _variable: &Item) -> bool { self.retval } fn find_case<'a>(&'a self, expected: bool, variable: &Item) -> Option<reflection::Case<'a>> { utils::default_find_case(self, expected, variable) } } impl reflection::PredicateReflection for BooleanPredicate { fn parameters<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Parameter<'a>> + 'a> { let params = vec![reflection::Parameter::new("value", &self.retval)]; Box::new(params.into_iter()) } } impl fmt::Display for BooleanPredicate { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let palette = crate::Palette::current(); write!(f, "{}", palette.expected.paint(self.retval)) } } /// Creates a new `Predicate` that always returns `true`. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::always(); /// assert_eq!(true, predicate_fn.eval(&5)); /// assert_eq!(true, predicate_fn.eval(&10)); /// assert_eq!(true, predicate_fn.eval(&15)); /// // Won't work - Predicates can only operate on a single type /// // assert_eq!(true, predicate_fn.eval("hello")) /// ``` pub fn always() -> BooleanPredicate { BooleanPredicate { retval: true } } /// Creates a new `Predicate` that always returns `false`. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::never(); /// assert_eq!(false, predicate_fn.eval(&5)); /// assert_eq!(false, predicate_fn.eval(&10)); /// assert_eq!(false, predicate_fn.eval(&15)); /// // Won't work - Predicates can only operate on a single type /// // assert_eq!(false, predicate_fn.eval("hello")) /// ``` pub fn
() -> BooleanPredicate { BooleanPredicate { retval: false } }
never
identifier_name
objc_interface_type.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![cfg(target_os = "macos")] #[macro_use] extern crate objc; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; #[repr(transparent)] #[derive(Clone)] pub struct Foo(pub id); impl std::ops::Deref for Foo { type Target = objc::runtime::Object; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Foo {} impl Foo { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Foo), alloc) }) } } impl IFoo for Foo {} pub trait IFoo: Sized + std::ops::Deref {} #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct
{ pub foo: Foo, } #[test] fn bindgen_test_layout_FooStruct() { assert_eq!( ::std::mem::size_of::<FooStruct>(), 8usize, concat!("Size of: ", stringify!(FooStruct)) ); assert_eq!( ::std::mem::align_of::<FooStruct>(), 8usize, concat!("Alignment of ", stringify!(FooStruct)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<FooStruct>())).foo as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(FooStruct), "::", stringify!(foo) ) ); } impl Default for FooStruct { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } } extern "C" { pub fn fooFunc(foo: Foo); } extern "C" { pub static mut kFoo: Foo; }
FooStruct
identifier_name
objc_interface_type.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![cfg(target_os = "macos")] #[macro_use] extern crate objc; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; #[repr(transparent)] #[derive(Clone)] pub struct Foo(pub id); impl std::ops::Deref for Foo { type Target = objc::runtime::Object; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Foo {} impl Foo { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Foo), alloc) }) } } impl IFoo for Foo {} pub trait IFoo: Sized + std::ops::Deref {} #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct FooStruct { pub foo: Foo, } #[test] fn bindgen_test_layout_FooStruct() { assert_eq!( ::std::mem::size_of::<FooStruct>(), 8usize, concat!("Size of: ", stringify!(FooStruct)) ); assert_eq!( ::std::mem::align_of::<FooStruct>(), 8usize, concat!("Alignment of ", stringify!(FooStruct)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<FooStruct>())).foo as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(FooStruct), "::", stringify!(foo) )
); } impl Default for FooStruct { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } } extern "C" { pub fn fooFunc(foo: Foo); } extern "C" { pub static mut kFoo: Foo; }
random_line_split
od.rs
// Copyright 2016-2020 James Bostock. See the LICENSE file at the top-level // directory of this distribution. // An implementation of the od(1) command in Rust. // See http://man.cat-v.org/unix-6th/1/od use std::env; use std::io; use std::io::BufReader; use std::io::BufWriter; use std::io::Read; use std::io::Seek; use std::io::SeekFrom; use std::io::Stdout; use std::io::Write; use std::num::ParseIntError; mod util; type FmtFn = fn(&mut BufWriter<Stdout>, &[u8]) -> io::Result<usize>; /// Writes a chunk of output data as octal byte values. fn
(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> { for byte in data { write!(out, " {:03o}", byte)?; } writeln!(out)?; Ok(data.len()) } /// Writes a chunk of output data as octal (16 bit) word values. Words are /// assumed to be little endian. fn write_oct_words(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> { for word in data.chunks(2) { write!(out, " {:06o}", u16::from(word[1]) << 8 | u16::from(word[0]))?; } writeln!(out)?; Ok(data.len()) } /// Writes a chunk of output data as decimal (16 bit) word values. Words are /// assumed to be little endian. fn write_dec_words(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> { for word in data.chunks(2) { write!(out, " {:06}", u16::from(word[1]) << 8 | u16::from(word[0]))?; } writeln!(out)?; Ok(data.len()) } /// Writes a chunk of output data as hexadecimal (16 bit) word values. Words /// are assumed to be little endian. fn write_hex_words(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> { for word in data.chunks(2) { write!(out, " {:06x}", u16::from(word[1]) << 8 | u16::from(word[0]))?; } writeln!(out)?; Ok(data.len()) } /// Writes a chunk of data as ASCII, reverting to octal byte values for /// non-printable characters. Standard escape sequences are supported. fn write_ascii_chars(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> { for byte in data { match *byte { 7u8 => write!(out, " \\g")?, 8u8 => write!(out, " \\b")?, 9u8 => write!(out, " \\t")?, 10u8 => write!(out, " \\n")?, 11u8 => write!(out, " \\v")?, 12u8 => write!(out, " \\f")?, 13u8 => write!(out, " \\r")?, _ => if *byte < 32u8 || *byte > 126u8 { write!(out, " {:03o}", *byte)? } else { write!(out, " {}", *byte as char)? } } } writeln!(out)?; Ok(data.len()) } const CHUNK_SIZE: usize = 16; // The offset string is of the form [+]offset[.][b] // +100 => 0o100 // +100. => 100 // +100b => 0o100 * 512 // +100.b => 100 * 512 fn parse_offset(offstr: &str) -> Result<u64, ParseIntError> { let mut char_indices = offstr.char_indices().rev(); let mut mult = 1; let (s, r) = match char_indices.next() { Some((x, 'b')) => { mult = 512; match char_indices.next() { Some((y, '.')) => (&offstr[0..y], 10), Some((_, _)) => (&offstr[0..x], 8), None => (&offstr[0..0], 8) } }, Some((x, '.')) => (&offstr[0..x], 10), Some((_, _)) => (&offstr[..], 8), None => (&offstr[0..0], 8) }; match u64::from_str_radix(s, r) { Ok(n) => Ok(n * mult), Err(e) => Err(e) } } #[test] fn test_parse_offset() { match parse_offset("100") { Ok(off) => assert!(off == 0o100), Err(_) => assert!(false) } match parse_offset("100.") { Ok(off) => assert!(off == 100), Err(_) => assert!(false) } match parse_offset("100b") { Ok(off) => assert!(off == 0o100 * 512), Err(_) => assert!(false) } match parse_offset("100.b") { Ok(off) => assert!(off == 100 * 512), Err(_) => assert!(false) } } /// Dumps the data read from the named input source to the standard output. fn od(filename: &str, offset: u64, fmt_fns: &[FmtFn]) -> io::Result<u64> { let mut reader = BufReader::new(util::Input::open(filename)?); let mut writer = BufWriter::new(io::stdout()); let mut offset = offset; if offset > 0 { reader.seek(SeekFrom::Start(offset))?; } let mut chunk = [0; CHUNK_SIZE]; loop { let n = reader.read(&mut chunk)?; if n > 0 { let mut first = true; for fmt_fn in fmt_fns.iter() { if first { write!(writer, "{:07o}", offset)?; first = false; } else { write!(writer, " ")?; } fmt_fn(&mut writer, &chunk)?; offset += chunk.len() as u64; } } if n < CHUNK_SIZE { break } } writeln!(writer, "{:07o}", offset)?; Ok(offset) } fn main() { let mut args = env::args(); let prog = args.next().unwrap(); let mut offset : u64 = 0; let mut offstr = String::from("0"); let mut fmt_fns: Vec<FmtFn> = Vec::new(); let getopt = util::GetOpt::new("bcdho", args); // Default to reading from standard input. let mut filename = String::from("-"); for arg in getopt { match arg { Ok(util::Arg::Opt('b')) => fmt_fns.push(write_oct_bytes), Ok(util::Arg::Opt('c')) => fmt_fns.push(write_ascii_chars), Ok(util::Arg::Opt('d')) => fmt_fns.push(write_dec_words), Ok(util::Arg::Opt('h')) => fmt_fns.push(write_hex_words), Ok(util::Arg::Opt('o')) => fmt_fns.push(write_oct_words), Ok(util::Arg::Arg(val)) => { if val.starts_with('+') { offstr = val; } else { filename = val; } }, Ok(val) => { // Should never happen. eprintln!("{}: error: unexpected: {:?}", prog, val); std::process::exit(1); }, Err(e) => { eprintln!("{}: error: {}", prog, e); std::process::exit(1); } } } // If no output formats have been specified, default to octal words. if fmt_fns.is_empty() { fmt_fns.push(write_oct_words); } match parse_offset(&offstr) { Ok(off) => offset = off, Err(e) => println!("{}: {}", offstr, e) } match od(&filename, offset, &fmt_fns) { Ok(_) => std::process::exit(0), Err(e) => { eprintln!("Error: {}", e); std::process::exit(1) } } }
write_oct_bytes
identifier_name
od.rs
// Copyright 2016-2020 James Bostock. See the LICENSE file at the top-level // directory of this distribution. // An implementation of the od(1) command in Rust. // See http://man.cat-v.org/unix-6th/1/od use std::env; use std::io; use std::io::BufReader; use std::io::BufWriter; use std::io::Read; use std::io::Seek; use std::io::SeekFrom; use std::io::Stdout; use std::io::Write; use std::num::ParseIntError; mod util; type FmtFn = fn(&mut BufWriter<Stdout>, &[u8]) -> io::Result<usize>; /// Writes a chunk of output data as octal byte values. fn write_oct_bytes(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize>
/// Writes a chunk of output data as octal (16 bit) word values. Words are /// assumed to be little endian. fn write_oct_words(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> { for word in data.chunks(2) { write!(out, " {:06o}", u16::from(word[1]) << 8 | u16::from(word[0]))?; } writeln!(out)?; Ok(data.len()) } /// Writes a chunk of output data as decimal (16 bit) word values. Words are /// assumed to be little endian. fn write_dec_words(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> { for word in data.chunks(2) { write!(out, " {:06}", u16::from(word[1]) << 8 | u16::from(word[0]))?; } writeln!(out)?; Ok(data.len()) } /// Writes a chunk of output data as hexadecimal (16 bit) word values. Words /// are assumed to be little endian. fn write_hex_words(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> { for word in data.chunks(2) { write!(out, " {:06x}", u16::from(word[1]) << 8 | u16::from(word[0]))?; } writeln!(out)?; Ok(data.len()) } /// Writes a chunk of data as ASCII, reverting to octal byte values for /// non-printable characters. Standard escape sequences are supported. fn write_ascii_chars(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> { for byte in data { match *byte { 7u8 => write!(out, " \\g")?, 8u8 => write!(out, " \\b")?, 9u8 => write!(out, " \\t")?, 10u8 => write!(out, " \\n")?, 11u8 => write!(out, " \\v")?, 12u8 => write!(out, " \\f")?, 13u8 => write!(out, " \\r")?, _ => if *byte < 32u8 || *byte > 126u8 { write!(out, " {:03o}", *byte)? } else { write!(out, " {}", *byte as char)? } } } writeln!(out)?; Ok(data.len()) } const CHUNK_SIZE: usize = 16; // The offset string is of the form [+]offset[.][b] // +100 => 0o100 // +100. => 100 // +100b => 0o100 * 512 // +100.b => 100 * 512 fn parse_offset(offstr: &str) -> Result<u64, ParseIntError> { let mut char_indices = offstr.char_indices().rev(); let mut mult = 1; let (s, r) = match char_indices.next() { Some((x, 'b')) => { mult = 512; match char_indices.next() { Some((y, '.')) => (&offstr[0..y], 10), Some((_, _)) => (&offstr[0..x], 8), None => (&offstr[0..0], 8) } }, Some((x, '.')) => (&offstr[0..x], 10), Some((_, _)) => (&offstr[..], 8), None => (&offstr[0..0], 8) }; match u64::from_str_radix(s, r) { Ok(n) => Ok(n * mult), Err(e) => Err(e) } } #[test] fn test_parse_offset() { match parse_offset("100") { Ok(off) => assert!(off == 0o100), Err(_) => assert!(false) } match parse_offset("100.") { Ok(off) => assert!(off == 100), Err(_) => assert!(false) } match parse_offset("100b") { Ok(off) => assert!(off == 0o100 * 512), Err(_) => assert!(false) } match parse_offset("100.b") { Ok(off) => assert!(off == 100 * 512), Err(_) => assert!(false) } } /// Dumps the data read from the named input source to the standard output. fn od(filename: &str, offset: u64, fmt_fns: &[FmtFn]) -> io::Result<u64> { let mut reader = BufReader::new(util::Input::open(filename)?); let mut writer = BufWriter::new(io::stdout()); let mut offset = offset; if offset > 0 { reader.seek(SeekFrom::Start(offset))?; } let mut chunk = [0; CHUNK_SIZE]; loop { let n = reader.read(&mut chunk)?; if n > 0 { let mut first = true; for fmt_fn in fmt_fns.iter() { if first { write!(writer, "{:07o}", offset)?; first = false; } else { write!(writer, " ")?; } fmt_fn(&mut writer, &chunk)?; offset += chunk.len() as u64; } } if n < CHUNK_SIZE { break } } writeln!(writer, "{:07o}", offset)?; Ok(offset) } fn main() { let mut args = env::args(); let prog = args.next().unwrap(); let mut offset : u64 = 0; let mut offstr = String::from("0"); let mut fmt_fns: Vec<FmtFn> = Vec::new(); let getopt = util::GetOpt::new("bcdho", args); // Default to reading from standard input. let mut filename = String::from("-"); for arg in getopt { match arg { Ok(util::Arg::Opt('b')) => fmt_fns.push(write_oct_bytes), Ok(util::Arg::Opt('c')) => fmt_fns.push(write_ascii_chars), Ok(util::Arg::Opt('d')) => fmt_fns.push(write_dec_words), Ok(util::Arg::Opt('h')) => fmt_fns.push(write_hex_words), Ok(util::Arg::Opt('o')) => fmt_fns.push(write_oct_words), Ok(util::Arg::Arg(val)) => { if val.starts_with('+') { offstr = val; } else { filename = val; } }, Ok(val) => { // Should never happen. eprintln!("{}: error: unexpected: {:?}", prog, val); std::process::exit(1); }, Err(e) => { eprintln!("{}: error: {}", prog, e); std::process::exit(1); } } } // If no output formats have been specified, default to octal words. if fmt_fns.is_empty() { fmt_fns.push(write_oct_words); } match parse_offset(&offstr) { Ok(off) => offset = off, Err(e) => println!("{}: {}", offstr, e) } match od(&filename, offset, &fmt_fns) { Ok(_) => std::process::exit(0), Err(e) => { eprintln!("Error: {}", e); std::process::exit(1) } } }
{ for byte in data { write!(out, " {:03o}", byte)?; } writeln!(out)?; Ok(data.len()) }
identifier_body
od.rs
// Copyright 2016-2020 James Bostock. See the LICENSE file at the top-level // directory of this distribution. // An implementation of the od(1) command in Rust. // See http://man.cat-v.org/unix-6th/1/od use std::env; use std::io; use std::io::BufReader; use std::io::BufWriter; use std::io::Read; use std::io::Seek; use std::io::SeekFrom; use std::io::Stdout; use std::io::Write; use std::num::ParseIntError; mod util; type FmtFn = fn(&mut BufWriter<Stdout>, &[u8]) -> io::Result<usize>; /// Writes a chunk of output data as octal byte values. fn write_oct_bytes(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> { for byte in data { write!(out, " {:03o}", byte)?; } writeln!(out)?; Ok(data.len()) } /// Writes a chunk of output data as octal (16 bit) word values. Words are /// assumed to be little endian. fn write_oct_words(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> { for word in data.chunks(2) { write!(out, " {:06o}", u16::from(word[1]) << 8 | u16::from(word[0]))?; } writeln!(out)?; Ok(data.len()) } /// Writes a chunk of output data as decimal (16 bit) word values. Words are /// assumed to be little endian. fn write_dec_words(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> { for word in data.chunks(2) { write!(out, " {:06}", u16::from(word[1]) << 8 | u16::from(word[0]))?; } writeln!(out)?; Ok(data.len()) } /// Writes a chunk of output data as hexadecimal (16 bit) word values. Words /// are assumed to be little endian. fn write_hex_words(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> {
Ok(data.len()) } /// Writes a chunk of data as ASCII, reverting to octal byte values for /// non-printable characters. Standard escape sequences are supported. fn write_ascii_chars(out: &mut BufWriter<Stdout>, data: &[u8]) -> io::Result<usize> { for byte in data { match *byte { 7u8 => write!(out, " \\g")?, 8u8 => write!(out, " \\b")?, 9u8 => write!(out, " \\t")?, 10u8 => write!(out, " \\n")?, 11u8 => write!(out, " \\v")?, 12u8 => write!(out, " \\f")?, 13u8 => write!(out, " \\r")?, _ => if *byte < 32u8 || *byte > 126u8 { write!(out, " {:03o}", *byte)? } else { write!(out, " {}", *byte as char)? } } } writeln!(out)?; Ok(data.len()) } const CHUNK_SIZE: usize = 16; // The offset string is of the form [+]offset[.][b] // +100 => 0o100 // +100. => 100 // +100b => 0o100 * 512 // +100.b => 100 * 512 fn parse_offset(offstr: &str) -> Result<u64, ParseIntError> { let mut char_indices = offstr.char_indices().rev(); let mut mult = 1; let (s, r) = match char_indices.next() { Some((x, 'b')) => { mult = 512; match char_indices.next() { Some((y, '.')) => (&offstr[0..y], 10), Some((_, _)) => (&offstr[0..x], 8), None => (&offstr[0..0], 8) } }, Some((x, '.')) => (&offstr[0..x], 10), Some((_, _)) => (&offstr[..], 8), None => (&offstr[0..0], 8) }; match u64::from_str_radix(s, r) { Ok(n) => Ok(n * mult), Err(e) => Err(e) } } #[test] fn test_parse_offset() { match parse_offset("100") { Ok(off) => assert!(off == 0o100), Err(_) => assert!(false) } match parse_offset("100.") { Ok(off) => assert!(off == 100), Err(_) => assert!(false) } match parse_offset("100b") { Ok(off) => assert!(off == 0o100 * 512), Err(_) => assert!(false) } match parse_offset("100.b") { Ok(off) => assert!(off == 100 * 512), Err(_) => assert!(false) } } /// Dumps the data read from the named input source to the standard output. fn od(filename: &str, offset: u64, fmt_fns: &[FmtFn]) -> io::Result<u64> { let mut reader = BufReader::new(util::Input::open(filename)?); let mut writer = BufWriter::new(io::stdout()); let mut offset = offset; if offset > 0 { reader.seek(SeekFrom::Start(offset))?; } let mut chunk = [0; CHUNK_SIZE]; loop { let n = reader.read(&mut chunk)?; if n > 0 { let mut first = true; for fmt_fn in fmt_fns.iter() { if first { write!(writer, "{:07o}", offset)?; first = false; } else { write!(writer, " ")?; } fmt_fn(&mut writer, &chunk)?; offset += chunk.len() as u64; } } if n < CHUNK_SIZE { break } } writeln!(writer, "{:07o}", offset)?; Ok(offset) } fn main() { let mut args = env::args(); let prog = args.next().unwrap(); let mut offset : u64 = 0; let mut offstr = String::from("0"); let mut fmt_fns: Vec<FmtFn> = Vec::new(); let getopt = util::GetOpt::new("bcdho", args); // Default to reading from standard input. let mut filename = String::from("-"); for arg in getopt { match arg { Ok(util::Arg::Opt('b')) => fmt_fns.push(write_oct_bytes), Ok(util::Arg::Opt('c')) => fmt_fns.push(write_ascii_chars), Ok(util::Arg::Opt('d')) => fmt_fns.push(write_dec_words), Ok(util::Arg::Opt('h')) => fmt_fns.push(write_hex_words), Ok(util::Arg::Opt('o')) => fmt_fns.push(write_oct_words), Ok(util::Arg::Arg(val)) => { if val.starts_with('+') { offstr = val; } else { filename = val; } }, Ok(val) => { // Should never happen. eprintln!("{}: error: unexpected: {:?}", prog, val); std::process::exit(1); }, Err(e) => { eprintln!("{}: error: {}", prog, e); std::process::exit(1); } } } // If no output formats have been specified, default to octal words. if fmt_fns.is_empty() { fmt_fns.push(write_oct_words); } match parse_offset(&offstr) { Ok(off) => offset = off, Err(e) => println!("{}: {}", offstr, e) } match od(&filename, offset, &fmt_fns) { Ok(_) => std::process::exit(0), Err(e) => { eprintln!("Error: {}", e); std::process::exit(1) } } }
for word in data.chunks(2) { write!(out, " {:06x}", u16::from(word[1]) << 8 | u16::from(word[0]))?; } writeln!(out)?;
random_line_split
mod.rs
// Copyright © 2020 Cormac O'Brien // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pub mod particle; use crate::common::{ alloc::LinkedSlab, engine, net::{EntityEffects, EntityState, EntityUpdate}, }; use cgmath::{Deg, Vector3}; use chrono::Duration; // if this is changed, it must also be changed in deferred.frag pub const MAX_LIGHTS: usize = 32; pub const MAX_BEAMS: usize = 24; pub const MAX_TEMP_ENTITIES: usize = 64; pub const MAX_STATIC_ENTITIES: usize = 128; #[derive(Debug)] pub struct ClientEntity { pub force_link: bool, pub baseline: EntityState, pub msg_time: Duration, pub msg_origins: [Vector3<f32>; 2], pub origin: Vector3<f32>, pub msg_angles: [Vector3<Deg<f32>>; 2], pub angles: Vector3<Deg<f32>>, pub model_id: usize, model_changed: bool, pub frame_id: usize, pub skin_id: usize, colormap: Option<u8>, pub sync_base: Duration, pub effects: EntityEffects, pub light_id: Option<usize>, // vis_frame: usize, } impl ClientEntity { pub fn from_baseline(baseline: EntityState) -> ClientEntity { ClientEntity { force_link: false, baseline: baseline.clone(), msg_time: Duration::zero(), msg_origins: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)], origin: baseline.origin, msg_angles: [ Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), ], angles: baseline.angles, model_id: baseline.model_id, model_changed: false, frame_id: baseline.frame_id, skin_id: baseline.skin_id, colormap: None, sync_base: Duration::zero(), effects: baseline.effects, light_id: None, } } pub fn uninitialized() -> ClientEntity { ClientEntity { force_link: false, baseline: EntityState::uninitialized(), msg_time: Duration::zero(), msg_origins: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)], origin: Vector3::new(0.0, 0.0, 0.0), msg_angles: [ Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), ], angles: Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), model_id: 0, model_changed: false, frame_id: 0, skin_id: 0, colormap: None, sync_base: Duration::zero(), effects: EntityEffects::empty(), light_id: None, } } /// Update the entity with values from the server. /// /// `msg_times` specifies the last two message times from the server, where /// `msg_times[0]` is more recent. pub fn u
&mut self, msg_times: [Duration; 2], update: EntityUpdate) { // enable lerping self.force_link = false; if update.no_lerp || self.msg_time!= msg_times[1] { self.force_link = true; } self.msg_time = msg_times[0]; // fill in missing values from baseline let new_state = update.to_entity_state(&self.baseline); self.msg_origins[1] = self.msg_origins[0]; self.msg_origins[0] = new_state.origin; self.msg_angles[1] = self.msg_angles[0]; self.msg_angles[0] = new_state.angles; if self.model_id!= new_state.model_id { self.model_changed = true; self.force_link = true; self.model_id = new_state.model_id; } self.frame_id = new_state.frame_id; self.skin_id = new_state.skin_id; self.effects = new_state.effects; self.colormap = update.colormap; if self.force_link { self.msg_origins[1] = self.msg_origins[0]; self.origin = self.msg_origins[0]; self.msg_angles[1] = self.msg_angles[0]; self.angles = self.msg_angles[0]; } } /// Sets the entity's most recent message angles to the specified value. /// /// This is primarily useful for allowing interpolated view angles in demos. pub fn update_angles(&mut self, angles: Vector3<Deg<f32>>) { self.msg_angles[0] = angles; } /// Sets the entity's angles to the specified value, overwriting the message /// history. /// /// This causes the entity to "snap" to the correct angle rather than /// interpolating to it. pub fn set_angles(&mut self, angles: Vector3<Deg<f32>>) { self.msg_angles[0] = angles; self.msg_angles[1] = angles; self.angles = angles; } /// Returns the timestamp of the last message that updated this entity. pub fn msg_time(&self) -> Duration { self.msg_time } /// Returns true if the last update to this entity changed its model. pub fn model_changed(&self) -> bool { self.model_changed } pub fn colormap(&self) -> Option<u8> { self.colormap } pub fn get_origin(&self) -> Vector3<f32> { self.origin } pub fn get_angles(&self) -> Vector3<Deg<f32>> { self.angles } pub fn model_id(&self) -> usize { self.model_id } pub fn frame_id(&self) -> usize { self.frame_id } pub fn skin_id(&self) -> usize { self.skin_id } } /// A descriptor used to spawn dynamic lights. #[derive(Clone, Debug)] pub struct LightDesc { /// The origin of the light. pub origin: Vector3<f32>, /// The initial radius of the light. pub init_radius: f32, /// The rate of radius decay in units/second. pub decay_rate: f32, /// If the radius decays to this value, the light is ignored. pub min_radius: Option<f32>, /// Time-to-live of the light. pub ttl: Duration, } /// A dynamic point light. #[derive(Clone, Debug)] pub struct Light { origin: Vector3<f32>, init_radius: f32, decay_rate: f32, min_radius: Option<f32>, spawned: Duration, ttl: Duration, } impl Light { /// Create a light from a `LightDesc` at the specified time. pub fn from_desc(time: Duration, desc: LightDesc) -> Light { Light { origin: desc.origin, init_radius: desc.init_radius, decay_rate: desc.decay_rate, min_radius: desc.min_radius, spawned: time, ttl: desc.ttl, } } /// Return the origin of the light. pub fn origin(&self) -> Vector3<f32> { self.origin } /// Return the radius of the light for the given time. /// /// If the radius would decay to a negative value, returns 0. pub fn radius(&self, time: Duration) -> f32 { let lived = time - self.spawned; let decay = self.decay_rate * engine::duration_to_f32(lived); let radius = (self.init_radius - decay).max(0.0); if let Some(min) = self.min_radius { if radius < min { return 0.0; } } radius } /// Returns `true` if the light should be retained at the specified time. pub fn retain(&mut self, time: Duration) -> bool { self.spawned + self.ttl > time } } /// A set of active dynamic lights. pub struct Lights { slab: LinkedSlab<Light>, } impl Lights { /// Create an empty set of lights with the given capacity. pub fn with_capacity(capacity: usize) -> Lights { Lights { slab: LinkedSlab::with_capacity(capacity), } } /// Return a reference to the light with the given key, or `None` if no /// such light exists. pub fn get(&self, key: usize) -> Option<&Light> { self.slab.get(key) } /// Return a mutable reference to the light with the given key, or `None` /// if no such light exists. pub fn get_mut(&mut self, key: usize) -> Option<&mut Light> { self.slab.get_mut(key) } /// Insert a new light into the set of lights. /// /// Returns a key corresponding to the newly inserted light. /// /// If `key` is `Some` and there is an existing light with that key, then /// the light will be overwritten with the new value. pub fn insert(&mut self, time: Duration, desc: LightDesc, key: Option<usize>) -> usize { if let Some(k) = key { if let Some(key_light) = self.slab.get_mut(k) { *key_light = Light::from_desc(time, desc); return k; } } self.slab.insert(Light::from_desc(time, desc)) } /// Return an iterator over the active lights. pub fn iter(&self) -> impl Iterator<Item = &Light> { self.slab.iter() } /// Updates the set of dynamic lights for the specified time. /// /// This will deallocate any lights which have outlived their time-to-live. pub fn update(&mut self, time: Duration) { self.slab.retain(|_, light| light.retain(time)); } } #[derive(Copy, Clone, Debug)] pub struct Beam { pub entity_id: usize, pub model_id: usize, pub expire: Duration, pub start: Vector3<f32>, pub end: Vector3<f32>, }
pdate(
identifier_name
mod.rs
// Copyright © 2020 Cormac O'Brien // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pub mod particle; use crate::common::{ alloc::LinkedSlab, engine, net::{EntityEffects, EntityState, EntityUpdate}, }; use cgmath::{Deg, Vector3}; use chrono::Duration; // if this is changed, it must also be changed in deferred.frag pub const MAX_LIGHTS: usize = 32; pub const MAX_BEAMS: usize = 24; pub const MAX_TEMP_ENTITIES: usize = 64; pub const MAX_STATIC_ENTITIES: usize = 128; #[derive(Debug)] pub struct ClientEntity { pub force_link: bool, pub baseline: EntityState, pub msg_time: Duration, pub msg_origins: [Vector3<f32>; 2], pub origin: Vector3<f32>, pub msg_angles: [Vector3<Deg<f32>>; 2], pub angles: Vector3<Deg<f32>>, pub model_id: usize, model_changed: bool, pub frame_id: usize, pub skin_id: usize, colormap: Option<u8>, pub sync_base: Duration, pub effects: EntityEffects, pub light_id: Option<usize>, // vis_frame: usize, } impl ClientEntity { pub fn from_baseline(baseline: EntityState) -> ClientEntity {
} } pub fn uninitialized() -> ClientEntity { ClientEntity { force_link: false, baseline: EntityState::uninitialized(), msg_time: Duration::zero(), msg_origins: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)], origin: Vector3::new(0.0, 0.0, 0.0), msg_angles: [ Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), ], angles: Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), model_id: 0, model_changed: false, frame_id: 0, skin_id: 0, colormap: None, sync_base: Duration::zero(), effects: EntityEffects::empty(), light_id: None, } } /// Update the entity with values from the server. /// /// `msg_times` specifies the last two message times from the server, where /// `msg_times[0]` is more recent. pub fn update(&mut self, msg_times: [Duration; 2], update: EntityUpdate) { // enable lerping self.force_link = false; if update.no_lerp || self.msg_time!= msg_times[1] { self.force_link = true; } self.msg_time = msg_times[0]; // fill in missing values from baseline let new_state = update.to_entity_state(&self.baseline); self.msg_origins[1] = self.msg_origins[0]; self.msg_origins[0] = new_state.origin; self.msg_angles[1] = self.msg_angles[0]; self.msg_angles[0] = new_state.angles; if self.model_id!= new_state.model_id { self.model_changed = true; self.force_link = true; self.model_id = new_state.model_id; } self.frame_id = new_state.frame_id; self.skin_id = new_state.skin_id; self.effects = new_state.effects; self.colormap = update.colormap; if self.force_link { self.msg_origins[1] = self.msg_origins[0]; self.origin = self.msg_origins[0]; self.msg_angles[1] = self.msg_angles[0]; self.angles = self.msg_angles[0]; } } /// Sets the entity's most recent message angles to the specified value. /// /// This is primarily useful for allowing interpolated view angles in demos. pub fn update_angles(&mut self, angles: Vector3<Deg<f32>>) { self.msg_angles[0] = angles; } /// Sets the entity's angles to the specified value, overwriting the message /// history. /// /// This causes the entity to "snap" to the correct angle rather than /// interpolating to it. pub fn set_angles(&mut self, angles: Vector3<Deg<f32>>) { self.msg_angles[0] = angles; self.msg_angles[1] = angles; self.angles = angles; } /// Returns the timestamp of the last message that updated this entity. pub fn msg_time(&self) -> Duration { self.msg_time } /// Returns true if the last update to this entity changed its model. pub fn model_changed(&self) -> bool { self.model_changed } pub fn colormap(&self) -> Option<u8> { self.colormap } pub fn get_origin(&self) -> Vector3<f32> { self.origin } pub fn get_angles(&self) -> Vector3<Deg<f32>> { self.angles } pub fn model_id(&self) -> usize { self.model_id } pub fn frame_id(&self) -> usize { self.frame_id } pub fn skin_id(&self) -> usize { self.skin_id } } /// A descriptor used to spawn dynamic lights. #[derive(Clone, Debug)] pub struct LightDesc { /// The origin of the light. pub origin: Vector3<f32>, /// The initial radius of the light. pub init_radius: f32, /// The rate of radius decay in units/second. pub decay_rate: f32, /// If the radius decays to this value, the light is ignored. pub min_radius: Option<f32>, /// Time-to-live of the light. pub ttl: Duration, } /// A dynamic point light. #[derive(Clone, Debug)] pub struct Light { origin: Vector3<f32>, init_radius: f32, decay_rate: f32, min_radius: Option<f32>, spawned: Duration, ttl: Duration, } impl Light { /// Create a light from a `LightDesc` at the specified time. pub fn from_desc(time: Duration, desc: LightDesc) -> Light { Light { origin: desc.origin, init_radius: desc.init_radius, decay_rate: desc.decay_rate, min_radius: desc.min_radius, spawned: time, ttl: desc.ttl, } } /// Return the origin of the light. pub fn origin(&self) -> Vector3<f32> { self.origin } /// Return the radius of the light for the given time. /// /// If the radius would decay to a negative value, returns 0. pub fn radius(&self, time: Duration) -> f32 { let lived = time - self.spawned; let decay = self.decay_rate * engine::duration_to_f32(lived); let radius = (self.init_radius - decay).max(0.0); if let Some(min) = self.min_radius { if radius < min { return 0.0; } } radius } /// Returns `true` if the light should be retained at the specified time. pub fn retain(&mut self, time: Duration) -> bool { self.spawned + self.ttl > time } } /// A set of active dynamic lights. pub struct Lights { slab: LinkedSlab<Light>, } impl Lights { /// Create an empty set of lights with the given capacity. pub fn with_capacity(capacity: usize) -> Lights { Lights { slab: LinkedSlab::with_capacity(capacity), } } /// Return a reference to the light with the given key, or `None` if no /// such light exists. pub fn get(&self, key: usize) -> Option<&Light> { self.slab.get(key) } /// Return a mutable reference to the light with the given key, or `None` /// if no such light exists. pub fn get_mut(&mut self, key: usize) -> Option<&mut Light> { self.slab.get_mut(key) } /// Insert a new light into the set of lights. /// /// Returns a key corresponding to the newly inserted light. /// /// If `key` is `Some` and there is an existing light with that key, then /// the light will be overwritten with the new value. pub fn insert(&mut self, time: Duration, desc: LightDesc, key: Option<usize>) -> usize { if let Some(k) = key { if let Some(key_light) = self.slab.get_mut(k) { *key_light = Light::from_desc(time, desc); return k; } } self.slab.insert(Light::from_desc(time, desc)) } /// Return an iterator over the active lights. pub fn iter(&self) -> impl Iterator<Item = &Light> { self.slab.iter() } /// Updates the set of dynamic lights for the specified time. /// /// This will deallocate any lights which have outlived their time-to-live. pub fn update(&mut self, time: Duration) { self.slab.retain(|_, light| light.retain(time)); } } #[derive(Copy, Clone, Debug)] pub struct Beam { pub entity_id: usize, pub model_id: usize, pub expire: Duration, pub start: Vector3<f32>, pub end: Vector3<f32>, }
ClientEntity { force_link: false, baseline: baseline.clone(), msg_time: Duration::zero(), msg_origins: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)], origin: baseline.origin, msg_angles: [ Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), ], angles: baseline.angles, model_id: baseline.model_id, model_changed: false, frame_id: baseline.frame_id, skin_id: baseline.skin_id, colormap: None, sync_base: Duration::zero(), effects: baseline.effects, light_id: None,
identifier_body
mod.rs
// Copyright © 2020 Cormac O'Brien // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pub mod particle; use crate::common::{ alloc::LinkedSlab, engine, net::{EntityEffects, EntityState, EntityUpdate}, }; use cgmath::{Deg, Vector3}; use chrono::Duration; // if this is changed, it must also be changed in deferred.frag pub const MAX_LIGHTS: usize = 32; pub const MAX_BEAMS: usize = 24; pub const MAX_TEMP_ENTITIES: usize = 64; pub const MAX_STATIC_ENTITIES: usize = 128; #[derive(Debug)] pub struct ClientEntity { pub force_link: bool, pub baseline: EntityState, pub msg_time: Duration, pub msg_origins: [Vector3<f32>; 2], pub origin: Vector3<f32>, pub msg_angles: [Vector3<Deg<f32>>; 2], pub angles: Vector3<Deg<f32>>, pub model_id: usize, model_changed: bool, pub frame_id: usize, pub skin_id: usize, colormap: Option<u8>, pub sync_base: Duration, pub effects: EntityEffects, pub light_id: Option<usize>, // vis_frame: usize,
pub fn from_baseline(baseline: EntityState) -> ClientEntity { ClientEntity { force_link: false, baseline: baseline.clone(), msg_time: Duration::zero(), msg_origins: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)], origin: baseline.origin, msg_angles: [ Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), ], angles: baseline.angles, model_id: baseline.model_id, model_changed: false, frame_id: baseline.frame_id, skin_id: baseline.skin_id, colormap: None, sync_base: Duration::zero(), effects: baseline.effects, light_id: None, } } pub fn uninitialized() -> ClientEntity { ClientEntity { force_link: false, baseline: EntityState::uninitialized(), msg_time: Duration::zero(), msg_origins: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)], origin: Vector3::new(0.0, 0.0, 0.0), msg_angles: [ Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), ], angles: Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), model_id: 0, model_changed: false, frame_id: 0, skin_id: 0, colormap: None, sync_base: Duration::zero(), effects: EntityEffects::empty(), light_id: None, } } /// Update the entity with values from the server. /// /// `msg_times` specifies the last two message times from the server, where /// `msg_times[0]` is more recent. pub fn update(&mut self, msg_times: [Duration; 2], update: EntityUpdate) { // enable lerping self.force_link = false; if update.no_lerp || self.msg_time!= msg_times[1] { self.force_link = true; } self.msg_time = msg_times[0]; // fill in missing values from baseline let new_state = update.to_entity_state(&self.baseline); self.msg_origins[1] = self.msg_origins[0]; self.msg_origins[0] = new_state.origin; self.msg_angles[1] = self.msg_angles[0]; self.msg_angles[0] = new_state.angles; if self.model_id!= new_state.model_id { self.model_changed = true; self.force_link = true; self.model_id = new_state.model_id; } self.frame_id = new_state.frame_id; self.skin_id = new_state.skin_id; self.effects = new_state.effects; self.colormap = update.colormap; if self.force_link { self.msg_origins[1] = self.msg_origins[0]; self.origin = self.msg_origins[0]; self.msg_angles[1] = self.msg_angles[0]; self.angles = self.msg_angles[0]; } } /// Sets the entity's most recent message angles to the specified value. /// /// This is primarily useful for allowing interpolated view angles in demos. pub fn update_angles(&mut self, angles: Vector3<Deg<f32>>) { self.msg_angles[0] = angles; } /// Sets the entity's angles to the specified value, overwriting the message /// history. /// /// This causes the entity to "snap" to the correct angle rather than /// interpolating to it. pub fn set_angles(&mut self, angles: Vector3<Deg<f32>>) { self.msg_angles[0] = angles; self.msg_angles[1] = angles; self.angles = angles; } /// Returns the timestamp of the last message that updated this entity. pub fn msg_time(&self) -> Duration { self.msg_time } /// Returns true if the last update to this entity changed its model. pub fn model_changed(&self) -> bool { self.model_changed } pub fn colormap(&self) -> Option<u8> { self.colormap } pub fn get_origin(&self) -> Vector3<f32> { self.origin } pub fn get_angles(&self) -> Vector3<Deg<f32>> { self.angles } pub fn model_id(&self) -> usize { self.model_id } pub fn frame_id(&self) -> usize { self.frame_id } pub fn skin_id(&self) -> usize { self.skin_id } } /// A descriptor used to spawn dynamic lights. #[derive(Clone, Debug)] pub struct LightDesc { /// The origin of the light. pub origin: Vector3<f32>, /// The initial radius of the light. pub init_radius: f32, /// The rate of radius decay in units/second. pub decay_rate: f32, /// If the radius decays to this value, the light is ignored. pub min_radius: Option<f32>, /// Time-to-live of the light. pub ttl: Duration, } /// A dynamic point light. #[derive(Clone, Debug)] pub struct Light { origin: Vector3<f32>, init_radius: f32, decay_rate: f32, min_radius: Option<f32>, spawned: Duration, ttl: Duration, } impl Light { /// Create a light from a `LightDesc` at the specified time. pub fn from_desc(time: Duration, desc: LightDesc) -> Light { Light { origin: desc.origin, init_radius: desc.init_radius, decay_rate: desc.decay_rate, min_radius: desc.min_radius, spawned: time, ttl: desc.ttl, } } /// Return the origin of the light. pub fn origin(&self) -> Vector3<f32> { self.origin } /// Return the radius of the light for the given time. /// /// If the radius would decay to a negative value, returns 0. pub fn radius(&self, time: Duration) -> f32 { let lived = time - self.spawned; let decay = self.decay_rate * engine::duration_to_f32(lived); let radius = (self.init_radius - decay).max(0.0); if let Some(min) = self.min_radius { if radius < min { return 0.0; } } radius } /// Returns `true` if the light should be retained at the specified time. pub fn retain(&mut self, time: Duration) -> bool { self.spawned + self.ttl > time } } /// A set of active dynamic lights. pub struct Lights { slab: LinkedSlab<Light>, } impl Lights { /// Create an empty set of lights with the given capacity. pub fn with_capacity(capacity: usize) -> Lights { Lights { slab: LinkedSlab::with_capacity(capacity), } } /// Return a reference to the light with the given key, or `None` if no /// such light exists. pub fn get(&self, key: usize) -> Option<&Light> { self.slab.get(key) } /// Return a mutable reference to the light with the given key, or `None` /// if no such light exists. pub fn get_mut(&mut self, key: usize) -> Option<&mut Light> { self.slab.get_mut(key) } /// Insert a new light into the set of lights. /// /// Returns a key corresponding to the newly inserted light. /// /// If `key` is `Some` and there is an existing light with that key, then /// the light will be overwritten with the new value. pub fn insert(&mut self, time: Duration, desc: LightDesc, key: Option<usize>) -> usize { if let Some(k) = key { if let Some(key_light) = self.slab.get_mut(k) { *key_light = Light::from_desc(time, desc); return k; } } self.slab.insert(Light::from_desc(time, desc)) } /// Return an iterator over the active lights. pub fn iter(&self) -> impl Iterator<Item = &Light> { self.slab.iter() } /// Updates the set of dynamic lights for the specified time. /// /// This will deallocate any lights which have outlived their time-to-live. pub fn update(&mut self, time: Duration) { self.slab.retain(|_, light| light.retain(time)); } } #[derive(Copy, Clone, Debug)] pub struct Beam { pub entity_id: usize, pub model_id: usize, pub expire: Duration, pub start: Vector3<f32>, pub end: Vector3<f32>, }
} impl ClientEntity {
random_line_split
mod.rs
// Copyright © 2020 Cormac O'Brien // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pub mod particle; use crate::common::{ alloc::LinkedSlab, engine, net::{EntityEffects, EntityState, EntityUpdate}, }; use cgmath::{Deg, Vector3}; use chrono::Duration; // if this is changed, it must also be changed in deferred.frag pub const MAX_LIGHTS: usize = 32; pub const MAX_BEAMS: usize = 24; pub const MAX_TEMP_ENTITIES: usize = 64; pub const MAX_STATIC_ENTITIES: usize = 128; #[derive(Debug)] pub struct ClientEntity { pub force_link: bool, pub baseline: EntityState, pub msg_time: Duration, pub msg_origins: [Vector3<f32>; 2], pub origin: Vector3<f32>, pub msg_angles: [Vector3<Deg<f32>>; 2], pub angles: Vector3<Deg<f32>>, pub model_id: usize, model_changed: bool, pub frame_id: usize, pub skin_id: usize, colormap: Option<u8>, pub sync_base: Duration, pub effects: EntityEffects, pub light_id: Option<usize>, // vis_frame: usize, } impl ClientEntity { pub fn from_baseline(baseline: EntityState) -> ClientEntity { ClientEntity { force_link: false, baseline: baseline.clone(), msg_time: Duration::zero(), msg_origins: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)], origin: baseline.origin, msg_angles: [ Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), ], angles: baseline.angles, model_id: baseline.model_id, model_changed: false, frame_id: baseline.frame_id, skin_id: baseline.skin_id, colormap: None, sync_base: Duration::zero(), effects: baseline.effects, light_id: None, } } pub fn uninitialized() -> ClientEntity { ClientEntity { force_link: false, baseline: EntityState::uninitialized(), msg_time: Duration::zero(), msg_origins: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)], origin: Vector3::new(0.0, 0.0, 0.0), msg_angles: [ Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), ], angles: Vector3::new(Deg(0.0), Deg(0.0), Deg(0.0)), model_id: 0, model_changed: false, frame_id: 0, skin_id: 0, colormap: None, sync_base: Duration::zero(), effects: EntityEffects::empty(), light_id: None, } } /// Update the entity with values from the server. /// /// `msg_times` specifies the last two message times from the server, where /// `msg_times[0]` is more recent. pub fn update(&mut self, msg_times: [Duration; 2], update: EntityUpdate) { // enable lerping self.force_link = false; if update.no_lerp || self.msg_time!= msg_times[1] { self.force_link = true; } self.msg_time = msg_times[0]; // fill in missing values from baseline let new_state = update.to_entity_state(&self.baseline); self.msg_origins[1] = self.msg_origins[0]; self.msg_origins[0] = new_state.origin; self.msg_angles[1] = self.msg_angles[0]; self.msg_angles[0] = new_state.angles; if self.model_id!= new_state.model_id { self.model_changed = true; self.force_link = true; self.model_id = new_state.model_id; } self.frame_id = new_state.frame_id; self.skin_id = new_state.skin_id; self.effects = new_state.effects; self.colormap = update.colormap; if self.force_link { self.msg_origins[1] = self.msg_origins[0]; self.origin = self.msg_origins[0]; self.msg_angles[1] = self.msg_angles[0]; self.angles = self.msg_angles[0]; } } /// Sets the entity's most recent message angles to the specified value. /// /// This is primarily useful for allowing interpolated view angles in demos. pub fn update_angles(&mut self, angles: Vector3<Deg<f32>>) { self.msg_angles[0] = angles; } /// Sets the entity's angles to the specified value, overwriting the message /// history. /// /// This causes the entity to "snap" to the correct angle rather than /// interpolating to it. pub fn set_angles(&mut self, angles: Vector3<Deg<f32>>) { self.msg_angles[0] = angles; self.msg_angles[1] = angles; self.angles = angles; } /// Returns the timestamp of the last message that updated this entity. pub fn msg_time(&self) -> Duration { self.msg_time } /// Returns true if the last update to this entity changed its model. pub fn model_changed(&self) -> bool { self.model_changed } pub fn colormap(&self) -> Option<u8> { self.colormap } pub fn get_origin(&self) -> Vector3<f32> { self.origin } pub fn get_angles(&self) -> Vector3<Deg<f32>> { self.angles } pub fn model_id(&self) -> usize { self.model_id } pub fn frame_id(&self) -> usize { self.frame_id } pub fn skin_id(&self) -> usize { self.skin_id } } /// A descriptor used to spawn dynamic lights. #[derive(Clone, Debug)] pub struct LightDesc { /// The origin of the light. pub origin: Vector3<f32>, /// The initial radius of the light. pub init_radius: f32, /// The rate of radius decay in units/second. pub decay_rate: f32, /// If the radius decays to this value, the light is ignored. pub min_radius: Option<f32>, /// Time-to-live of the light. pub ttl: Duration, } /// A dynamic point light. #[derive(Clone, Debug)] pub struct Light { origin: Vector3<f32>, init_radius: f32, decay_rate: f32, min_radius: Option<f32>, spawned: Duration, ttl: Duration, } impl Light { /// Create a light from a `LightDesc` at the specified time. pub fn from_desc(time: Duration, desc: LightDesc) -> Light { Light { origin: desc.origin, init_radius: desc.init_radius, decay_rate: desc.decay_rate, min_radius: desc.min_radius, spawned: time, ttl: desc.ttl, } } /// Return the origin of the light. pub fn origin(&self) -> Vector3<f32> { self.origin } /// Return the radius of the light for the given time. /// /// If the radius would decay to a negative value, returns 0. pub fn radius(&self, time: Duration) -> f32 { let lived = time - self.spawned; let decay = self.decay_rate * engine::duration_to_f32(lived); let radius = (self.init_radius - decay).max(0.0); if let Some(min) = self.min_radius { if radius < min {
} radius } /// Returns `true` if the light should be retained at the specified time. pub fn retain(&mut self, time: Duration) -> bool { self.spawned + self.ttl > time } } /// A set of active dynamic lights. pub struct Lights { slab: LinkedSlab<Light>, } impl Lights { /// Create an empty set of lights with the given capacity. pub fn with_capacity(capacity: usize) -> Lights { Lights { slab: LinkedSlab::with_capacity(capacity), } } /// Return a reference to the light with the given key, or `None` if no /// such light exists. pub fn get(&self, key: usize) -> Option<&Light> { self.slab.get(key) } /// Return a mutable reference to the light with the given key, or `None` /// if no such light exists. pub fn get_mut(&mut self, key: usize) -> Option<&mut Light> { self.slab.get_mut(key) } /// Insert a new light into the set of lights. /// /// Returns a key corresponding to the newly inserted light. /// /// If `key` is `Some` and there is an existing light with that key, then /// the light will be overwritten with the new value. pub fn insert(&mut self, time: Duration, desc: LightDesc, key: Option<usize>) -> usize { if let Some(k) = key { if let Some(key_light) = self.slab.get_mut(k) { *key_light = Light::from_desc(time, desc); return k; } } self.slab.insert(Light::from_desc(time, desc)) } /// Return an iterator over the active lights. pub fn iter(&self) -> impl Iterator<Item = &Light> { self.slab.iter() } /// Updates the set of dynamic lights for the specified time. /// /// This will deallocate any lights which have outlived their time-to-live. pub fn update(&mut self, time: Duration) { self.slab.retain(|_, light| light.retain(time)); } } #[derive(Copy, Clone, Debug)] pub struct Beam { pub entity_id: usize, pub model_id: usize, pub expire: Duration, pub start: Vector3<f32>, pub end: Vector3<f32>, }
return 0.0; }
conditional_block
arcvec.rs
use std::sync::Arc; use std::fmt; use std::ops::Deref; #[derive(Clone)] pub struct ArcVec<T> { data: Arc<Vec<T>>, offset: usize, length: usize, } impl <T> ArcVec<T> { pub fn new(data: Vec<T>) -> ArcVec<T> {
ArcVec { data: Arc::new(data), offset: 0, length: length } } pub fn offset(mut self, offset: usize) -> ArcVec<T> { assert!(offset <= self.length); self.offset += offset; self.length -= offset; self } pub fn limit(mut self, length: usize) -> ArcVec<T> { assert!(length <= self.length); self.length = length; self } } impl<T> Deref for ArcVec<T> { type Target = [T]; fn deref(&self) -> &[T] { &self.data[self.offset..self.offset+self.length] } } impl<T : fmt::Debug> fmt::Debug for ArcVec<T> { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { self.deref().fmt(formatter) } }
let length = data.len();
random_line_split
arcvec.rs
use std::sync::Arc; use std::fmt; use std::ops::Deref; #[derive(Clone)] pub struct
<T> { data: Arc<Vec<T>>, offset: usize, length: usize, } impl <T> ArcVec<T> { pub fn new(data: Vec<T>) -> ArcVec<T> { let length = data.len(); ArcVec { data: Arc::new(data), offset: 0, length: length } } pub fn offset(mut self, offset: usize) -> ArcVec<T> { assert!(offset <= self.length); self.offset += offset; self.length -= offset; self } pub fn limit(mut self, length: usize) -> ArcVec<T> { assert!(length <= self.length); self.length = length; self } } impl<T> Deref for ArcVec<T> { type Target = [T]; fn deref(&self) -> &[T] { &self.data[self.offset..self.offset+self.length] } } impl<T : fmt::Debug> fmt::Debug for ArcVec<T> { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { self.deref().fmt(formatter) } }
ArcVec
identifier_name
sieve.rs
extern crate sieve; #[test] fn limit_lower_than_the_first_prime() { assert_eq!(sieve::primes_up_to(1), []); } #[test] fn limit_is_the_first_prime() { assert_eq!(sieve::primes_up_to(2), [2]); } #[test] fn primes_up_to_10() { assert_eq!(sieve::primes_up_to(10), [2, 3, 5, 7]); } #[test] fn limit_of_1000() { let expected = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,
701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; assert_eq!(sieve::primes_up_to(1000), expected); }
random_line_split
sieve.rs
extern crate sieve; #[test] fn limit_lower_than_the_first_prime() { assert_eq!(sieve::primes_up_to(1), []); } #[test] fn limit_is_the_first_prime()
#[test] fn primes_up_to_10() { assert_eq!(sieve::primes_up_to(10), [2, 3, 5, 7]); } #[test] fn limit_of_1000() { let expected = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; assert_eq!(sieve::primes_up_to(1000), expected); }
{ assert_eq!(sieve::primes_up_to(2), [2]); }
identifier_body
sieve.rs
extern crate sieve; #[test] fn
() { assert_eq!(sieve::primes_up_to(1), []); } #[test] fn limit_is_the_first_prime() { assert_eq!(sieve::primes_up_to(2), [2]); } #[test] fn primes_up_to_10() { assert_eq!(sieve::primes_up_to(10), [2, 3, 5, 7]); } #[test] fn limit_of_1000() { let expected = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; assert_eq!(sieve::primes_up_to(1000), expected); }
limit_lower_than_the_first_prime
identifier_name
shim.rs
use std::marker::PhantomData; // FIXME: remove this and use std::ptr::NonNull when Firefox requires Rust 1.25+ pub struct NonZeroPtr<T:'static>(&'static T); impl<T:'static> NonZeroPtr<T> { pub unsafe fn new_unchecked(ptr: *mut T) -> Self { NonZeroPtr(&*ptr) } pub fn as_ptr(&self) -> *mut T { self.0 as *const T as *mut T } } pub struct Unique<T:'static> { ptr: NonZeroPtr<T>, _marker: PhantomData<T>, } impl<T:'static> Unique<T> { pub unsafe fn new_unchecked(ptr: *mut T) -> Self { Unique { ptr: NonZeroPtr::new_unchecked(ptr), _marker: PhantomData, } } pub fn as_ptr(&self) -> *mut T { self.ptr.as_ptr() } } unsafe impl<T: Send +'static> Send for Unique<T> {} unsafe impl<T: Sync +'static> Sync for Unique<T> {} pub struct Shared<T:'static> { ptr: NonZeroPtr<T>, _marker: PhantomData<T>, // force it to be!Send/!Sync _marker2: PhantomData<*const u8>, } impl<T:'static> Shared<T> { pub unsafe fn new_unchecked(ptr: *mut T) -> Self { Shared { ptr: NonZeroPtr::new_unchecked(ptr), _marker: PhantomData, _marker2: PhantomData, } } pub unsafe fn
(&self) -> &mut T { &mut *self.ptr.as_ptr() } } impl<'a, T> From<&'a mut T> for Shared<T> { fn from(reference: &'a mut T) -> Self { unsafe { Shared::new_unchecked(reference) } } }
as_mut
identifier_name
shim.rs
use std::marker::PhantomData;
impl<T:'static> NonZeroPtr<T> { pub unsafe fn new_unchecked(ptr: *mut T) -> Self { NonZeroPtr(&*ptr) } pub fn as_ptr(&self) -> *mut T { self.0 as *const T as *mut T } } pub struct Unique<T:'static> { ptr: NonZeroPtr<T>, _marker: PhantomData<T>, } impl<T:'static> Unique<T> { pub unsafe fn new_unchecked(ptr: *mut T) -> Self { Unique { ptr: NonZeroPtr::new_unchecked(ptr), _marker: PhantomData, } } pub fn as_ptr(&self) -> *mut T { self.ptr.as_ptr() } } unsafe impl<T: Send +'static> Send for Unique<T> {} unsafe impl<T: Sync +'static> Sync for Unique<T> {} pub struct Shared<T:'static> { ptr: NonZeroPtr<T>, _marker: PhantomData<T>, // force it to be!Send/!Sync _marker2: PhantomData<*const u8>, } impl<T:'static> Shared<T> { pub unsafe fn new_unchecked(ptr: *mut T) -> Self { Shared { ptr: NonZeroPtr::new_unchecked(ptr), _marker: PhantomData, _marker2: PhantomData, } } pub unsafe fn as_mut(&self) -> &mut T { &mut *self.ptr.as_ptr() } } impl<'a, T> From<&'a mut T> for Shared<T> { fn from(reference: &'a mut T) -> Self { unsafe { Shared::new_unchecked(reference) } } }
// FIXME: remove this and use std::ptr::NonNull when Firefox requires Rust 1.25+ pub struct NonZeroPtr<T: 'static>(&'static T);
random_line_split
wrong-mul-method-signature.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // This test is to make sure we don't just ICE if the trait // method for an operator is not implemented properly. // (In this case the mul method should take &f64 and not f64) // See: #11450 use std::ops::Mul; struct Vec1 { x: f64 } // Expecting value in input signature impl Mul<f64> for Vec1 { type Output = Vec1; fn
(self, s: &f64) -> Vec1 { //~^ ERROR method `mul` has an incompatible type for trait Vec1 { x: self.x * *s } } } struct Vec2 { x: f64, y: f64 } // Wrong type parameter ordering impl Mul<Vec2> for Vec2 { type Output = f64; fn mul(self, s: f64) -> Vec2 { //~^ ERROR method `mul` has an incompatible type for trait Vec2 { x: self.x * s, y: self.y * s } } } struct Vec3 { x: f64, y: f64, z: f64 } // Unexpected return type impl Mul<f64> for Vec3 { type Output = i32; fn mul(self, s: f64) -> f64 { //~^ ERROR method `mul` has an incompatible type for trait s } } pub fn main() { // Check that the usage goes from the trait declaration: let x: Vec1 = Vec1 { x: 1.0 } * 2.0; // this is OK let x: Vec2 = Vec2 { x: 1.0, y: 2.0 } * 2.0; // trait had reversed order //~^ ERROR mismatched types //~| expected `Vec2` //~| found `_` //~| expected struct `Vec2` //~| found floating-point variable //~| ERROR mismatched types //~| expected `Vec2` //~| found `f64` //~| expected struct `Vec2` //~| found f64 let x: i32 = Vec3 { x: 1.0, y: 2.0, z: 3.0 } * 2.0; }
mul
identifier_name
wrong-mul-method-signature.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // This test is to make sure we don't just ICE if the trait
struct Vec1 { x: f64 } // Expecting value in input signature impl Mul<f64> for Vec1 { type Output = Vec1; fn mul(self, s: &f64) -> Vec1 { //~^ ERROR method `mul` has an incompatible type for trait Vec1 { x: self.x * *s } } } struct Vec2 { x: f64, y: f64 } // Wrong type parameter ordering impl Mul<Vec2> for Vec2 { type Output = f64; fn mul(self, s: f64) -> Vec2 { //~^ ERROR method `mul` has an incompatible type for trait Vec2 { x: self.x * s, y: self.y * s } } } struct Vec3 { x: f64, y: f64, z: f64 } // Unexpected return type impl Mul<f64> for Vec3 { type Output = i32; fn mul(self, s: f64) -> f64 { //~^ ERROR method `mul` has an incompatible type for trait s } } pub fn main() { // Check that the usage goes from the trait declaration: let x: Vec1 = Vec1 { x: 1.0 } * 2.0; // this is OK let x: Vec2 = Vec2 { x: 1.0, y: 2.0 } * 2.0; // trait had reversed order //~^ ERROR mismatched types //~| expected `Vec2` //~| found `_` //~| expected struct `Vec2` //~| found floating-point variable //~| ERROR mismatched types //~| expected `Vec2` //~| found `f64` //~| expected struct `Vec2` //~| found f64 let x: i32 = Vec3 { x: 1.0, y: 2.0, z: 3.0 } * 2.0; }
// method for an operator is not implemented properly. // (In this case the mul method should take &f64 and not f64) // See: #11450 use std::ops::Mul;
random_line_split
wrong-mul-method-signature.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // This test is to make sure we don't just ICE if the trait // method for an operator is not implemented properly. // (In this case the mul method should take &f64 and not f64) // See: #11450 use std::ops::Mul; struct Vec1 { x: f64 } // Expecting value in input signature impl Mul<f64> for Vec1 { type Output = Vec1; fn mul(self, s: &f64) -> Vec1 { //~^ ERROR method `mul` has an incompatible type for trait Vec1 { x: self.x * *s } } } struct Vec2 { x: f64, y: f64 } // Wrong type parameter ordering impl Mul<Vec2> for Vec2 { type Output = f64; fn mul(self, s: f64) -> Vec2
} struct Vec3 { x: f64, y: f64, z: f64 } // Unexpected return type impl Mul<f64> for Vec3 { type Output = i32; fn mul(self, s: f64) -> f64 { //~^ ERROR method `mul` has an incompatible type for trait s } } pub fn main() { // Check that the usage goes from the trait declaration: let x: Vec1 = Vec1 { x: 1.0 } * 2.0; // this is OK let x: Vec2 = Vec2 { x: 1.0, y: 2.0 } * 2.0; // trait had reversed order //~^ ERROR mismatched types //~| expected `Vec2` //~| found `_` //~| expected struct `Vec2` //~| found floating-point variable //~| ERROR mismatched types //~| expected `Vec2` //~| found `f64` //~| expected struct `Vec2` //~| found f64 let x: i32 = Vec3 { x: 1.0, y: 2.0, z: 3.0 } * 2.0; }
{ //~^ ERROR method `mul` has an incompatible type for trait Vec2 { x: self.x * s, y: self.y * s } }
identifier_body
car_factory.rs
use super::car_type::{Body, CarType, Colour}; pub struct
{ car_types: Vec<CarType>, } impl CarFactory { pub fn new() -> CarFactory { CarFactory { car_types: Vec::new(), } } pub fn get_car_type_id(&mut self, body: Body, colour: Colour) -> u8 { let position = self.car_types .iter() .position(|ref r| r.body == body && r.colour == colour); match position { Some(x) => x as u8, None => { let car_type = CarType::new(body, colour); self.car_types.push(car_type); (self.car_types.len() - 1) as u8 } } } pub fn get_car_type(&mut self, id: u8) -> Option<&CarType> { self.car_types.get(id as usize) } pub fn print(&self) { println!("Number of car types: {}", self.car_types.len()); } }
CarFactory
identifier_name
car_factory.rs
use super::car_type::{Body, CarType, Colour}; pub struct CarFactory { car_types: Vec<CarType>, } impl CarFactory { pub fn new() -> CarFactory { CarFactory { car_types: Vec::new(), } } pub fn get_car_type_id(&mut self, body: Body, colour: Colour) -> u8 { let position = self.car_types .iter() .position(|ref r| r.body == body && r.colour == colour); match position { Some(x) => x as u8, None => { let car_type = CarType::new(body, colour); self.car_types.push(car_type); (self.car_types.len() - 1) as u8 } } } pub fn get_car_type(&mut self, id: u8) -> Option<&CarType> { self.car_types.get(id as usize) }
println!("Number of car types: {}", self.car_types.len()); } }
pub fn print(&self) {
random_line_split
car_factory.rs
use super::car_type::{Body, CarType, Colour}; pub struct CarFactory { car_types: Vec<CarType>, } impl CarFactory { pub fn new() -> CarFactory { CarFactory { car_types: Vec::new(), } } pub fn get_car_type_id(&mut self, body: Body, colour: Colour) -> u8 { let position = self.car_types .iter() .position(|ref r| r.body == body && r.colour == colour); match position { Some(x) => x as u8, None => { let car_type = CarType::new(body, colour); self.car_types.push(car_type); (self.car_types.len() - 1) as u8 } } } pub fn get_car_type(&mut self, id: u8) -> Option<&CarType>
pub fn print(&self) { println!("Number of car types: {}", self.car_types.len()); } }
{ self.car_types.get(id as usize) }
identifier_body
test.rs
use std::path::PathBuf; use crate::app::{config, ddns, index::Index, lastfm, playlist, settings, thumbnail, user, vfs}; use crate::db::DB; use crate::test::*; pub struct Context { pub db: DB, pub index: Index, pub config_manager: config::Manager, pub ddns_manager: ddns::Manager, pub lastfm_manager: lastfm::Manager, pub playlist_manager: playlist::Manager, pub settings_manager: settings::Manager, pub thumbnail_manager: thumbnail::Manager, pub user_manager: user::Manager, pub vfs_manager: vfs::Manager, pub test_directory: PathBuf, } pub struct ContextBuilder { config: config::Config, pub test_directory: PathBuf, } impl ContextBuilder { pub fn new(test_name: String) -> Self { Self { test_directory: prepare_test_directory(&test_name), config: config::Config::default(), } } pub fn user(mut self, name: &str, password: &str, is_admin: bool) -> Self { self.config .users .get_or_insert(Vec::new()) .push(user::NewUser { name: name.to_owned(), password: password.to_owned(), admin: is_admin, }); self } pub fn
(mut self, name: &str, source: &str) -> Self { self.config .mount_dirs .get_or_insert(Vec::new()) .push(vfs::MountDir { name: name.to_owned(), source: source.to_owned(), }); self } pub fn build(self) -> Context { let cache_output_dir = self.test_directory.join("cache"); let db_path = self.test_directory.join("db.sqlite"); let db = DB::new(&db_path).unwrap(); let settings_manager = settings::Manager::new(db.clone()); let auth_secret = settings_manager.get_auth_secret().unwrap(); let user_manager = user::Manager::new(db.clone(), auth_secret); let vfs_manager = vfs::Manager::new(db.clone()); let ddns_manager = ddns::Manager::new(db.clone()); let config_manager = config::Manager::new( settings_manager.clone(), user_manager.clone(), vfs_manager.clone(), ddns_manager.clone(), ); let index = Index::new(db.clone(), vfs_manager.clone(), settings_manager.clone()); let playlist_manager = playlist::Manager::new(db.clone(), vfs_manager.clone()); let thumbnail_manager = thumbnail::Manager::new(cache_output_dir); let lastfm_manager = lastfm::Manager::new(index.clone(), user_manager.clone()); config_manager.apply(&self.config).unwrap(); Context { db, index, config_manager, ddns_manager, lastfm_manager, playlist_manager, settings_manager, thumbnail_manager, user_manager, vfs_manager, test_directory: self.test_directory, } } }
mount
identifier_name
test.rs
use std::path::PathBuf; use crate::app::{config, ddns, index::Index, lastfm, playlist, settings, thumbnail, user, vfs}; use crate::db::DB; use crate::test::*; pub struct Context { pub db: DB, pub index: Index, pub config_manager: config::Manager, pub ddns_manager: ddns::Manager, pub lastfm_manager: lastfm::Manager, pub playlist_manager: playlist::Manager, pub settings_manager: settings::Manager, pub thumbnail_manager: thumbnail::Manager, pub user_manager: user::Manager, pub vfs_manager: vfs::Manager, pub test_directory: PathBuf, } pub struct ContextBuilder { config: config::Config, pub test_directory: PathBuf, } impl ContextBuilder { pub fn new(test_name: String) -> Self { Self { test_directory: prepare_test_directory(&test_name), config: config::Config::default(), } } pub fn user(mut self, name: &str, password: &str, is_admin: bool) -> Self { self.config .users .get_or_insert(Vec::new()) .push(user::NewUser { name: name.to_owned(), password: password.to_owned(), admin: is_admin, }); self } pub fn mount(mut self, name: &str, source: &str) -> Self { self.config .mount_dirs .get_or_insert(Vec::new()) .push(vfs::MountDir { name: name.to_owned(), source: source.to_owned(), }); self } pub fn build(self) -> Context { let cache_output_dir = self.test_directory.join("cache"); let db_path = self.test_directory.join("db.sqlite"); let db = DB::new(&db_path).unwrap(); let settings_manager = settings::Manager::new(db.clone());
let user_manager = user::Manager::new(db.clone(), auth_secret); let vfs_manager = vfs::Manager::new(db.clone()); let ddns_manager = ddns::Manager::new(db.clone()); let config_manager = config::Manager::new( settings_manager.clone(), user_manager.clone(), vfs_manager.clone(), ddns_manager.clone(), ); let index = Index::new(db.clone(), vfs_manager.clone(), settings_manager.clone()); let playlist_manager = playlist::Manager::new(db.clone(), vfs_manager.clone()); let thumbnail_manager = thumbnail::Manager::new(cache_output_dir); let lastfm_manager = lastfm::Manager::new(index.clone(), user_manager.clone()); config_manager.apply(&self.config).unwrap(); Context { db, index, config_manager, ddns_manager, lastfm_manager, playlist_manager, settings_manager, thumbnail_manager, user_manager, vfs_manager, test_directory: self.test_directory, } } }
let auth_secret = settings_manager.get_auth_secret().unwrap();
random_line_split
test.rs
use std::path::PathBuf; use crate::app::{config, ddns, index::Index, lastfm, playlist, settings, thumbnail, user, vfs}; use crate::db::DB; use crate::test::*; pub struct Context { pub db: DB, pub index: Index, pub config_manager: config::Manager, pub ddns_manager: ddns::Manager, pub lastfm_manager: lastfm::Manager, pub playlist_manager: playlist::Manager, pub settings_manager: settings::Manager, pub thumbnail_manager: thumbnail::Manager, pub user_manager: user::Manager, pub vfs_manager: vfs::Manager, pub test_directory: PathBuf, } pub struct ContextBuilder { config: config::Config, pub test_directory: PathBuf, } impl ContextBuilder { pub fn new(test_name: String) -> Self { Self { test_directory: prepare_test_directory(&test_name), config: config::Config::default(), } } pub fn user(mut self, name: &str, password: &str, is_admin: bool) -> Self { self.config .users .get_or_insert(Vec::new()) .push(user::NewUser { name: name.to_owned(), password: password.to_owned(), admin: is_admin, }); self } pub fn mount(mut self, name: &str, source: &str) -> Self { self.config .mount_dirs .get_or_insert(Vec::new()) .push(vfs::MountDir { name: name.to_owned(), source: source.to_owned(), }); self } pub fn build(self) -> Context
config_manager.apply(&self.config).unwrap(); Context { db, index, config_manager, ddns_manager, lastfm_manager, playlist_manager, settings_manager, thumbnail_manager, user_manager, vfs_manager, test_directory: self.test_directory, } } }
{ let cache_output_dir = self.test_directory.join("cache"); let db_path = self.test_directory.join("db.sqlite"); let db = DB::new(&db_path).unwrap(); let settings_manager = settings::Manager::new(db.clone()); let auth_secret = settings_manager.get_auth_secret().unwrap(); let user_manager = user::Manager::new(db.clone(), auth_secret); let vfs_manager = vfs::Manager::new(db.clone()); let ddns_manager = ddns::Manager::new(db.clone()); let config_manager = config::Manager::new( settings_manager.clone(), user_manager.clone(), vfs_manager.clone(), ddns_manager.clone(), ); let index = Index::new(db.clone(), vfs_manager.clone(), settings_manager.clone()); let playlist_manager = playlist::Manager::new(db.clone(), vfs_manager.clone()); let thumbnail_manager = thumbnail::Manager::new(cache_output_dir); let lastfm_manager = lastfm::Manager::new(index.clone(), user_manager.clone());
identifier_body
base.rs
//! Base helper routines for a code generator. use collections::Set; use grammar::free_variables::FreeVariables; use grammar::repr::*; use lr1::core::*; use rust::RustWrite; use std::io::{self, Write}; use util::Sep; /// Base struct for various kinds of code generator. The flavor of /// code generator is customized by supplying distinct types for `C` /// (e.g., `self::ascent::RecursiveAscent`). pub struct CodeGenerator<'codegen, 'grammar: 'codegen, W: Write + 'codegen, C> { /// the complete grammar pub grammar: &'grammar Grammar, /// some suitable prefix to separate our identifiers from the user's pub prefix: &'grammar str, /// types from the grammar pub types: &'grammar Types, /// the start symbol S the user specified pub user_start_symbol: NonterminalString, /// the synthetic start symbol S' that we specified pub start_symbol: NonterminalString, /// the vector of states pub states: &'codegen [LR1State<'grammar>], /// where we write output pub out: &'codegen mut RustWrite<W>, /// where to find the action routines (typically `super`) pub action_module: String, /// custom fields for the specific kind of codegenerator /// (recursive ascent, table-driven, etc) pub custom: C, pub repeatable: bool, } impl<'codegen, 'grammar, W: Write, C> CodeGenerator<'codegen, 'grammar, W, C> { pub fn new( grammar: &'grammar Grammar, user_start_symbol: NonterminalString, start_symbol: NonterminalString, states: &'codegen [LR1State<'grammar>], out: &'codegen mut RustWrite<W>, repeatable: bool, action_module: &str, custom: C, ) -> Self { CodeGenerator { grammar: grammar, prefix: &grammar.prefix, types: &grammar.types, states: states, user_start_symbol: user_start_symbol, start_symbol: start_symbol, out: out, custom: custom, repeatable: repeatable, action_module: action_module.to_string(), } } /// We often create meta types that pull together a bunch of /// user-given types -- basically describing (e.g.) the full set /// of return values from any nonterminal (and, in some cases, /// terminals). These types need to carry generic parameters from /// the grammar, since the nonterminals may include generic /// parameters -- but we don't want them to carry *all* the /// generic parameters, since that can be unnecessarily /// restrictive. /// /// In particular, consider something like this: /// /// ```notrust /// grammar<'a>(buffer: &'a mut Vec<u32>); /// ``` /// /// Here, we likely do not want the `'a` in the type of `buffer` to appear /// in the nonterminal result. That's because, if it did, then the /// action functions will have a signature like: /// /// ```ignore /// fn foo<'a, T>(x: &'a mut Vec<T>) -> Result<'a> {... } /// ``` /// /// In that case, we would only be able to call one action fn and /// will in fact get borrowck errors, because Rust would think we /// were potentially returning this `&'a mut Vec<T>`. /// /// Therefore, we take the full list of type parameters and we /// filter them down to those that appear in the types that we /// need to include (those that appear in the `tys` parameter). /// /// In some cases, we need to include a few more than just that /// obviously appear textually: for example, if we have `T::Foo`, /// and we see a where-clause `T: Bar<'a>`, then we need to /// include both `T` and `'a`, since that bound may be important /// for resolving `T::Foo` (in other words, `T::Foo` may expand to /// `<T as Bar<'a>>::Foo`). pub fn filter_type_parameters_and_where_clauses( grammar: &Grammar, tys: impl IntoIterator<Item = TypeRepr>, ) -> (Vec<TypeParameter>, Vec<WhereClause>) { let referenced_ty_params: Set<_> = tys .into_iter() .flat_map(|t| t.free_variables(&grammar.type_parameters)) .collect(); let filtered_type_params: Vec<_> = grammar .type_parameters .iter() .filter(|t| referenced_ty_params.contains(t)) .cloned() .collect(); // If `T` is referenced in the types we need to keep, then // include any bounds like `T: Foo`. This may be needed for // the well-formedness conditions on `T` (e.g., maybe we have // `T: Hash` and a `HashSet<T>` or something) but it may also // be needed because of `T::Foo`-like types. // // Do not however include a bound like `T: 'a` unless both `T` // **and** `'a` are referenced -- same with bounds like `T: // Foo<U>`. If those were needed, then `'a` or `U` would also // have to appear in the types. debug!("filtered_type_params = {:?}", filtered_type_params); let filtered_where_clauses: Vec<_> = grammar .where_clauses .iter() .filter(|wc| { debug!( "wc = {:?} free_variables = {:?}", wc, wc.free_variables(&grammar.type_parameters) ); wc.free_variables(&grammar.type_parameters) .iter() .all(|p| referenced_ty_params.contains(p)) }).cloned() .collect(); debug!("filtered_where_clauses = {:?}", filtered_where_clauses); (filtered_type_params, filtered_where_clauses) } pub fn
<F>(&mut self, body: F) -> io::Result<()> where F: FnOnce(&mut Self) -> io::Result<()>, { rust!(self.out, ""); rust!(self.out, "#[cfg_attr(rustfmt, rustfmt_skip)]"); rust!(self.out, "mod {}parse{} {{", self.prefix, self.start_symbol); // these stylistic lints are annoying for the generated code, // which doesn't follow conventions: rust!( self.out, "#![allow(non_snake_case, non_camel_case_types, unused_mut, unused_variables, \ unused_imports, unused_parens)]" ); rust!(self.out, ""); try!(self.write_uses()); try!(body(self)); rust!(self.out, "}}"); Ok(()) } pub fn write_uses(&mut self) -> io::Result<()> { try!( self.out .write_uses(&format!("{}::", self.action_module), &self.grammar) ); if self.grammar.intern_token.is_some() { rust!( self.out, "use {}::{}intern_token::Token;", self.action_module, self.prefix ); } else { rust!( self.out, "use {}::{}ToTriple;", self.action_module, self.prefix ); } Ok(()) } pub fn start_parser_fn(&mut self) -> io::Result<()> { let parse_error_type = self.types.parse_error_type(); let (type_parameters, parameters, mut where_clauses); let intern_token = self.grammar.intern_token.is_some(); if intern_token { // if we are generating the tokenizer, we just need the // input, and that has already been added as one of the // user parameters type_parameters = vec![]; parameters = vec![]; where_clauses = vec![]; } else { // otherwise, we need an iterator of type `TOKENS` let mut user_type_parameters = String::new(); for type_parameter in &self.grammar.type_parameters { user_type_parameters.push_str(&format!("{}, ", type_parameter)); } type_parameters = vec![ format!( "{}TOKEN: {}ToTriple<{}>", self.prefix, self.prefix, user_type_parameters, ), format!( "{}TOKENS: IntoIterator<Item={}TOKEN>", self.prefix, self.prefix ), ]; parameters = vec![format!("{}tokens0: {}TOKENS", self.prefix, self.prefix)]; where_clauses = vec![]; if self.repeatable { where_clauses.push(format!("{}TOKENS: Clone", self.prefix)); } } rust!( self.out, "{}struct {}Parser {{", self.grammar.nonterminals[&self.start_symbol].visibility, self.user_start_symbol ); if intern_token { rust!( self.out, "builder: {1}::{0}intern_token::{0}MatcherBuilder,", self.prefix, self.action_module ); } rust!(self.out, "_priv: (),"); rust!(self.out, "}}"); rust!(self.out, ""); rust!(self.out, "impl {}Parser {{", self.user_start_symbol); rust!( self.out, "{}fn new() -> {}Parser {{", self.grammar.nonterminals[&self.start_symbol].visibility, self.user_start_symbol ); if intern_token { rust!( self.out, "let {0}builder = {1}::{0}intern_token::{0}MatcherBuilder::new();", self.prefix, self.action_module ); } rust!(self.out, "{}Parser {{", self.user_start_symbol); if intern_token { rust!(self.out, "builder: {}builder,", self.prefix); } rust!(self.out, "_priv: (),"); rust!(self.out, "}}"); // Parser rust!(self.out, "}}"); // new() rust!(self.out, ""); rust!(self.out, "#[allow(dead_code)]"); try!( self.out .fn_header( &self.grammar.nonterminals[&self.start_symbol].visibility, "parse".to_owned(), ).with_parameters(Some("&self".to_owned())) .with_grammar(self.grammar) .with_type_parameters(type_parameters) .with_parameters(parameters) .with_return_type(format!( "Result<{}, {}>", self.types.nonterminal_type(&self.start_symbol), parse_error_type )).with_where_clauses(where_clauses) .emit() ); rust!(self.out, "{{"); Ok(()) } pub fn define_tokens(&mut self) -> io::Result<()> { if self.grammar.intern_token.is_some() { // if we are generating the tokenizer, create a matcher as our input iterator rust!( self.out, "let mut {}tokens = self.builder.matcher(input);", self.prefix ); } else { // otherwise, convert one from the `IntoIterator` // supplied, using the `ToTriple` trait which inserts // errors/locations etc if none are given let clone_call = if self.repeatable { ".clone()" } else { "" }; rust!( self.out, "let {}tokens = {}tokens0{}.into_iter();", self.prefix, self.prefix, clone_call ); rust!( self.out, "let mut {}tokens = {}tokens.map(|t| {}ToTriple::to_triple(t));", self.prefix, self.prefix, self.prefix ); } Ok(()) } pub fn end_parser_fn(&mut self) -> io::Result<()> { rust!(self.out, "}}"); // fn rust!(self.out, "}}"); // impl Ok(()) } /// Returns phantom data type that captures the user-declared type /// parameters in a phantom-data. This helps with ensuring that /// all type parameters are constrained, even if they are not /// used. pub fn phantom_data_type(&self) -> String { let phantom_bits: Vec<_> = self .grammar .type_parameters .iter() .map(|tp| match *tp { TypeParameter::Lifetime(ref l) => format!("&{} ()", l), TypeParameter::Id(ref id) => id.to_string(), }) .collect(); format!("::std::marker::PhantomData<({})>", Sep(", ", &phantom_bits),) } /// Returns expression that captures the user-declared type /// parameters in a phantom-data. This helps with ensuring that /// all type parameters are constrained, even if they are not /// used. pub fn phantom_data_expr(&self) -> String { let phantom_bits: Vec<_> = self .grammar .type_parameters .iter() .map(|tp| match *tp { TypeParameter::Lifetime(_) => format!("&()"), TypeParameter::Id(ref id) => id.to_string(), }) .collect(); format!( "::std::marker::PhantomData::<({})>", Sep(", ", &phantom_bits), ) } }
write_parse_mod
identifier_name
base.rs
//! Base helper routines for a code generator. use collections::Set; use grammar::free_variables::FreeVariables; use grammar::repr::*; use lr1::core::*; use rust::RustWrite; use std::io::{self, Write}; use util::Sep; /// Base struct for various kinds of code generator. The flavor of /// code generator is customized by supplying distinct types for `C` /// (e.g., `self::ascent::RecursiveAscent`). pub struct CodeGenerator<'codegen, 'grammar: 'codegen, W: Write + 'codegen, C> { /// the complete grammar pub grammar: &'grammar Grammar, /// some suitable prefix to separate our identifiers from the user's pub prefix: &'grammar str, /// types from the grammar pub types: &'grammar Types, /// the start symbol S the user specified pub user_start_symbol: NonterminalString, /// the synthetic start symbol S' that we specified pub start_symbol: NonterminalString, /// the vector of states pub states: &'codegen [LR1State<'grammar>], /// where we write output pub out: &'codegen mut RustWrite<W>, /// where to find the action routines (typically `super`) pub action_module: String, /// custom fields for the specific kind of codegenerator /// (recursive ascent, table-driven, etc) pub custom: C, pub repeatable: bool, } impl<'codegen, 'grammar, W: Write, C> CodeGenerator<'codegen, 'grammar, W, C> { pub fn new( grammar: &'grammar Grammar, user_start_symbol: NonterminalString, start_symbol: NonterminalString, states: &'codegen [LR1State<'grammar>], out: &'codegen mut RustWrite<W>, repeatable: bool, action_module: &str, custom: C, ) -> Self { CodeGenerator { grammar: grammar, prefix: &grammar.prefix, types: &grammar.types, states: states, user_start_symbol: user_start_symbol, start_symbol: start_symbol, out: out, custom: custom, repeatable: repeatable, action_module: action_module.to_string(), } } /// We often create meta types that pull together a bunch of /// user-given types -- basically describing (e.g.) the full set /// of return values from any nonterminal (and, in some cases, /// terminals). These types need to carry generic parameters from /// the grammar, since the nonterminals may include generic /// parameters -- but we don't want them to carry *all* the /// generic parameters, since that can be unnecessarily /// restrictive. /// /// In particular, consider something like this: /// /// ```notrust /// grammar<'a>(buffer: &'a mut Vec<u32>); /// ``` /// /// Here, we likely do not want the `'a` in the type of `buffer` to appear /// in the nonterminal result. That's because, if it did, then the /// action functions will have a signature like: /// /// ```ignore /// fn foo<'a, T>(x: &'a mut Vec<T>) -> Result<'a> {... } /// ``` /// /// In that case, we would only be able to call one action fn and /// will in fact get borrowck errors, because Rust would think we /// were potentially returning this `&'a mut Vec<T>`. /// /// Therefore, we take the full list of type parameters and we /// filter them down to those that appear in the types that we /// need to include (those that appear in the `tys` parameter). /// /// In some cases, we need to include a few more than just that /// obviously appear textually: for example, if we have `T::Foo`, /// and we see a where-clause `T: Bar<'a>`, then we need to /// include both `T` and `'a`, since that bound may be important /// for resolving `T::Foo` (in other words, `T::Foo` may expand to /// `<T as Bar<'a>>::Foo`). pub fn filter_type_parameters_and_where_clauses( grammar: &Grammar, tys: impl IntoIterator<Item = TypeRepr>, ) -> (Vec<TypeParameter>, Vec<WhereClause>) { let referenced_ty_params: Set<_> = tys .into_iter() .flat_map(|t| t.free_variables(&grammar.type_parameters)) .collect(); let filtered_type_params: Vec<_> = grammar .type_parameters .iter() .filter(|t| referenced_ty_params.contains(t)) .cloned() .collect(); // If `T` is referenced in the types we need to keep, then // include any bounds like `T: Foo`. This may be needed for // the well-formedness conditions on `T` (e.g., maybe we have // `T: Hash` and a `HashSet<T>` or something) but it may also // be needed because of `T::Foo`-like types. // // Do not however include a bound like `T: 'a` unless both `T` // **and** `'a` are referenced -- same with bounds like `T: // Foo<U>`. If those were needed, then `'a` or `U` would also // have to appear in the types. debug!("filtered_type_params = {:?}", filtered_type_params); let filtered_where_clauses: Vec<_> = grammar .where_clauses .iter() .filter(|wc| { debug!( "wc = {:?} free_variables = {:?}", wc, wc.free_variables(&grammar.type_parameters) ); wc.free_variables(&grammar.type_parameters) .iter() .all(|p| referenced_ty_params.contains(p)) }).cloned() .collect(); debug!("filtered_where_clauses = {:?}", filtered_where_clauses); (filtered_type_params, filtered_where_clauses) } pub fn write_parse_mod<F>(&mut self, body: F) -> io::Result<()> where F: FnOnce(&mut Self) -> io::Result<()>, { rust!(self.out, ""); rust!(self.out, "#[cfg_attr(rustfmt, rustfmt_skip)]"); rust!(self.out, "mod {}parse{} {{", self.prefix, self.start_symbol); // these stylistic lints are annoying for the generated code, // which doesn't follow conventions: rust!( self.out, "#![allow(non_snake_case, non_camel_case_types, unused_mut, unused_variables, \ unused_imports, unused_parens)]" ); rust!(self.out, ""); try!(self.write_uses()); try!(body(self)); rust!(self.out, "}}"); Ok(()) } pub fn write_uses(&mut self) -> io::Result<()> { try!( self.out .write_uses(&format!("{}::", self.action_module), &self.grammar) ); if self.grammar.intern_token.is_some() { rust!( self.out, "use {}::{}intern_token::Token;", self.action_module, self.prefix ); } else { rust!( self.out, "use {}::{}ToTriple;", self.action_module, self.prefix ); } Ok(()) } pub fn start_parser_fn(&mut self) -> io::Result<()> { let parse_error_type = self.types.parse_error_type(); let (type_parameters, parameters, mut where_clauses); let intern_token = self.grammar.intern_token.is_some(); if intern_token { // if we are generating the tokenizer, we just need the // input, and that has already been added as one of the // user parameters type_parameters = vec![]; parameters = vec![]; where_clauses = vec![]; } else { // otherwise, we need an iterator of type `TOKENS` let mut user_type_parameters = String::new(); for type_parameter in &self.grammar.type_parameters { user_type_parameters.push_str(&format!("{}, ", type_parameter)); } type_parameters = vec![ format!( "{}TOKEN: {}ToTriple<{}>", self.prefix, self.prefix, user_type_parameters, ), format!( "{}TOKENS: IntoIterator<Item={}TOKEN>", self.prefix, self.prefix ), ]; parameters = vec![format!("{}tokens0: {}TOKENS", self.prefix, self.prefix)]; where_clauses = vec![]; if self.repeatable { where_clauses.push(format!("{}TOKENS: Clone", self.prefix)); } } rust!( self.out, "{}struct {}Parser {{", self.grammar.nonterminals[&self.start_symbol].visibility, self.user_start_symbol ); if intern_token { rust!( self.out, "builder: {1}::{0}intern_token::{0}MatcherBuilder,", self.prefix, self.action_module ); } rust!(self.out, "_priv: (),"); rust!(self.out, "}}"); rust!(self.out, ""); rust!(self.out, "impl {}Parser {{", self.user_start_symbol); rust!( self.out, "{}fn new() -> {}Parser {{", self.grammar.nonterminals[&self.start_symbol].visibility, self.user_start_symbol ); if intern_token { rust!( self.out, "let {0}builder = {1}::{0}intern_token::{0}MatcherBuilder::new();", self.prefix, self.action_module ); } rust!(self.out, "{}Parser {{", self.user_start_symbol); if intern_token { rust!(self.out, "builder: {}builder,", self.prefix); } rust!(self.out, "_priv: (),"); rust!(self.out, "}}"); // Parser rust!(self.out, "}}"); // new() rust!(self.out, ""); rust!(self.out, "#[allow(dead_code)]"); try!( self.out .fn_header( &self.grammar.nonterminals[&self.start_symbol].visibility, "parse".to_owned(), ).with_parameters(Some("&self".to_owned())) .with_grammar(self.grammar) .with_type_parameters(type_parameters) .with_parameters(parameters) .with_return_type(format!( "Result<{}, {}>", self.types.nonterminal_type(&self.start_symbol), parse_error_type )).with_where_clauses(where_clauses) .emit() ); rust!(self.out, "{{"); Ok(()) } pub fn define_tokens(&mut self) -> io::Result<()> { if self.grammar.intern_token.is_some() { // if we are generating the tokenizer, create a matcher as our input iterator rust!( self.out, "let mut {}tokens = self.builder.matcher(input);", self.prefix ); } else
} Ok(()) } pub fn end_parser_fn(&mut self) -> io::Result<()> { rust!(self.out, "}}"); // fn rust!(self.out, "}}"); // impl Ok(()) } /// Returns phantom data type that captures the user-declared type /// parameters in a phantom-data. This helps with ensuring that /// all type parameters are constrained, even if they are not /// used. pub fn phantom_data_type(&self) -> String { let phantom_bits: Vec<_> = self .grammar .type_parameters .iter() .map(|tp| match *tp { TypeParameter::Lifetime(ref l) => format!("&{} ()", l), TypeParameter::Id(ref id) => id.to_string(), }) .collect(); format!("::std::marker::PhantomData<({})>", Sep(", ", &phantom_bits),) } /// Returns expression that captures the user-declared type /// parameters in a phantom-data. This helps with ensuring that /// all type parameters are constrained, even if they are not /// used. pub fn phantom_data_expr(&self) -> String { let phantom_bits: Vec<_> = self .grammar .type_parameters .iter() .map(|tp| match *tp { TypeParameter::Lifetime(_) => format!("&()"), TypeParameter::Id(ref id) => id.to_string(), }) .collect(); format!( "::std::marker::PhantomData::<({})>", Sep(", ", &phantom_bits), ) } }
{ // otherwise, convert one from the `IntoIterator` // supplied, using the `ToTriple` trait which inserts // errors/locations etc if none are given let clone_call = if self.repeatable { ".clone()" } else { "" }; rust!( self.out, "let {}tokens = {}tokens0{}.into_iter();", self.prefix, self.prefix, clone_call ); rust!( self.out, "let mut {}tokens = {}tokens.map(|t| {}ToTriple::to_triple(t));", self.prefix, self.prefix, self.prefix );
conditional_block
base.rs
//! Base helper routines for a code generator. use collections::Set; use grammar::free_variables::FreeVariables; use grammar::repr::*; use lr1::core::*; use rust::RustWrite; use std::io::{self, Write}; use util::Sep; /// Base struct for various kinds of code generator. The flavor of /// code generator is customized by supplying distinct types for `C` /// (e.g., `self::ascent::RecursiveAscent`). pub struct CodeGenerator<'codegen, 'grammar: 'codegen, W: Write + 'codegen, C> { /// the complete grammar pub grammar: &'grammar Grammar, /// some suitable prefix to separate our identifiers from the user's pub prefix: &'grammar str, /// types from the grammar pub types: &'grammar Types, /// the start symbol S the user specified pub user_start_symbol: NonterminalString, /// the synthetic start symbol S' that we specified pub start_symbol: NonterminalString, /// the vector of states pub states: &'codegen [LR1State<'grammar>], /// where we write output pub out: &'codegen mut RustWrite<W>, /// where to find the action routines (typically `super`) pub action_module: String, /// custom fields for the specific kind of codegenerator /// (recursive ascent, table-driven, etc) pub custom: C, pub repeatable: bool, } impl<'codegen, 'grammar, W: Write, C> CodeGenerator<'codegen, 'grammar, W, C> { pub fn new( grammar: &'grammar Grammar, user_start_symbol: NonterminalString, start_symbol: NonterminalString, states: &'codegen [LR1State<'grammar>], out: &'codegen mut RustWrite<W>, repeatable: bool, action_module: &str, custom: C, ) -> Self { CodeGenerator { grammar: grammar, prefix: &grammar.prefix, types: &grammar.types, states: states, user_start_symbol: user_start_symbol, start_symbol: start_symbol, out: out, custom: custom, repeatable: repeatable, action_module: action_module.to_string(), } } /// We often create meta types that pull together a bunch of /// user-given types -- basically describing (e.g.) the full set /// of return values from any nonterminal (and, in some cases, /// terminals). These types need to carry generic parameters from /// the grammar, since the nonterminals may include generic /// parameters -- but we don't want them to carry *all* the /// generic parameters, since that can be unnecessarily /// restrictive. /// /// In particular, consider something like this: /// /// ```notrust /// grammar<'a>(buffer: &'a mut Vec<u32>); /// ``` /// /// Here, we likely do not want the `'a` in the type of `buffer` to appear /// in the nonterminal result. That's because, if it did, then the /// action functions will have a signature like: /// /// ```ignore /// fn foo<'a, T>(x: &'a mut Vec<T>) -> Result<'a> {... } /// ``` /// /// In that case, we would only be able to call one action fn and /// will in fact get borrowck errors, because Rust would think we /// were potentially returning this `&'a mut Vec<T>`. /// /// Therefore, we take the full list of type parameters and we /// filter them down to those that appear in the types that we /// need to include (those that appear in the `tys` parameter). /// /// In some cases, we need to include a few more than just that /// obviously appear textually: for example, if we have `T::Foo`, /// and we see a where-clause `T: Bar<'a>`, then we need to /// include both `T` and `'a`, since that bound may be important /// for resolving `T::Foo` (in other words, `T::Foo` may expand to /// `<T as Bar<'a>>::Foo`). pub fn filter_type_parameters_and_where_clauses( grammar: &Grammar, tys: impl IntoIterator<Item = TypeRepr>, ) -> (Vec<TypeParameter>, Vec<WhereClause>) { let referenced_ty_params: Set<_> = tys .into_iter() .flat_map(|t| t.free_variables(&grammar.type_parameters)) .collect(); let filtered_type_params: Vec<_> = grammar .type_parameters .iter() .filter(|t| referenced_ty_params.contains(t)) .cloned() .collect(); // If `T` is referenced in the types we need to keep, then // include any bounds like `T: Foo`. This may be needed for // the well-formedness conditions on `T` (e.g., maybe we have // `T: Hash` and a `HashSet<T>` or something) but it may also // be needed because of `T::Foo`-like types. // // Do not however include a bound like `T: 'a` unless both `T` // **and** `'a` are referenced -- same with bounds like `T: // Foo<U>`. If those were needed, then `'a` or `U` would also // have to appear in the types. debug!("filtered_type_params = {:?}", filtered_type_params); let filtered_where_clauses: Vec<_> = grammar .where_clauses .iter() .filter(|wc| { debug!( "wc = {:?} free_variables = {:?}", wc, wc.free_variables(&grammar.type_parameters) ); wc.free_variables(&grammar.type_parameters) .iter() .all(|p| referenced_ty_params.contains(p)) }).cloned() .collect(); debug!("filtered_where_clauses = {:?}", filtered_where_clauses); (filtered_type_params, filtered_where_clauses) } pub fn write_parse_mod<F>(&mut self, body: F) -> io::Result<()> where F: FnOnce(&mut Self) -> io::Result<()>,
{ rust!(self.out, ""); rust!(self.out, "#[cfg_attr(rustfmt, rustfmt_skip)]"); rust!(self.out, "mod {}parse{} {{", self.prefix, self.start_symbol); // these stylistic lints are annoying for the generated code, // which doesn't follow conventions: rust!( self.out, "#![allow(non_snake_case, non_camel_case_types, unused_mut, unused_variables, \ unused_imports, unused_parens)]" ); rust!(self.out, ""); try!(self.write_uses()); try!(body(self)); rust!(self.out, "}}"); Ok(()) } pub fn write_uses(&mut self) -> io::Result<()> { try!( self.out .write_uses(&format!("{}::", self.action_module), &self.grammar) ); if self.grammar.intern_token.is_some() { rust!( self.out, "use {}::{}intern_token::Token;", self.action_module, self.prefix ); } else { rust!( self.out, "use {}::{}ToTriple;", self.action_module, self.prefix ); } Ok(()) } pub fn start_parser_fn(&mut self) -> io::Result<()> { let parse_error_type = self.types.parse_error_type(); let (type_parameters, parameters, mut where_clauses); let intern_token = self.grammar.intern_token.is_some(); if intern_token { // if we are generating the tokenizer, we just need the // input, and that has already been added as one of the // user parameters type_parameters = vec![]; parameters = vec![]; where_clauses = vec![]; } else { // otherwise, we need an iterator of type `TOKENS` let mut user_type_parameters = String::new(); for type_parameter in &self.grammar.type_parameters { user_type_parameters.push_str(&format!("{}, ", type_parameter)); } type_parameters = vec![ format!( "{}TOKEN: {}ToTriple<{}>", self.prefix, self.prefix, user_type_parameters, ), format!( "{}TOKENS: IntoIterator<Item={}TOKEN>", self.prefix, self.prefix ), ]; parameters = vec![format!("{}tokens0: {}TOKENS", self.prefix, self.prefix)]; where_clauses = vec![]; if self.repeatable { where_clauses.push(format!("{}TOKENS: Clone", self.prefix)); } } rust!( self.out, "{}struct {}Parser {{", self.grammar.nonterminals[&self.start_symbol].visibility, self.user_start_symbol ); if intern_token { rust!( self.out, "builder: {1}::{0}intern_token::{0}MatcherBuilder,", self.prefix, self.action_module ); } rust!(self.out, "_priv: (),"); rust!(self.out, "}}"); rust!(self.out, ""); rust!(self.out, "impl {}Parser {{", self.user_start_symbol); rust!( self.out, "{}fn new() -> {}Parser {{", self.grammar.nonterminals[&self.start_symbol].visibility, self.user_start_symbol ); if intern_token { rust!( self.out, "let {0}builder = {1}::{0}intern_token::{0}MatcherBuilder::new();", self.prefix, self.action_module ); } rust!(self.out, "{}Parser {{", self.user_start_symbol); if intern_token { rust!(self.out, "builder: {}builder,", self.prefix); } rust!(self.out, "_priv: (),"); rust!(self.out, "}}"); // Parser rust!(self.out, "}}"); // new() rust!(self.out, ""); rust!(self.out, "#[allow(dead_code)]"); try!( self.out .fn_header( &self.grammar.nonterminals[&self.start_symbol].visibility, "parse".to_owned(), ).with_parameters(Some("&self".to_owned())) .with_grammar(self.grammar) .with_type_parameters(type_parameters) .with_parameters(parameters) .with_return_type(format!( "Result<{}, {}>", self.types.nonterminal_type(&self.start_symbol), parse_error_type )).with_where_clauses(where_clauses) .emit() ); rust!(self.out, "{{"); Ok(()) } pub fn define_tokens(&mut self) -> io::Result<()> { if self.grammar.intern_token.is_some() { // if we are generating the tokenizer, create a matcher as our input iterator rust!( self.out, "let mut {}tokens = self.builder.matcher(input);", self.prefix ); } else { // otherwise, convert one from the `IntoIterator` // supplied, using the `ToTriple` trait which inserts // errors/locations etc if none are given let clone_call = if self.repeatable { ".clone()" } else { "" }; rust!( self.out, "let {}tokens = {}tokens0{}.into_iter();", self.prefix, self.prefix, clone_call ); rust!( self.out, "let mut {}tokens = {}tokens.map(|t| {}ToTriple::to_triple(t));", self.prefix, self.prefix, self.prefix ); } Ok(()) } pub fn end_parser_fn(&mut self) -> io::Result<()> { rust!(self.out, "}}"); // fn rust!(self.out, "}}"); // impl Ok(()) } /// Returns phantom data type that captures the user-declared type /// parameters in a phantom-data. This helps with ensuring that /// all type parameters are constrained, even if they are not /// used. pub fn phantom_data_type(&self) -> String { let phantom_bits: Vec<_> = self .grammar .type_parameters .iter() .map(|tp| match *tp { TypeParameter::Lifetime(ref l) => format!("&{} ()", l), TypeParameter::Id(ref id) => id.to_string(), }) .collect(); format!("::std::marker::PhantomData<({})>", Sep(", ", &phantom_bits),) } /// Returns expression that captures the user-declared type /// parameters in a phantom-data. This helps with ensuring that /// all type parameters are constrained, even if they are not /// used. pub fn phantom_data_expr(&self) -> String { let phantom_bits: Vec<_> = self .grammar .type_parameters .iter() .map(|tp| match *tp { TypeParameter::Lifetime(_) => format!("&()"), TypeParameter::Id(ref id) => id.to_string(), }) .collect(); format!( "::std::marker::PhantomData::<({})>", Sep(", ", &phantom_bits), ) } }
random_line_split
base.rs
//! Base helper routines for a code generator. use collections::Set; use grammar::free_variables::FreeVariables; use grammar::repr::*; use lr1::core::*; use rust::RustWrite; use std::io::{self, Write}; use util::Sep; /// Base struct for various kinds of code generator. The flavor of /// code generator is customized by supplying distinct types for `C` /// (e.g., `self::ascent::RecursiveAscent`). pub struct CodeGenerator<'codegen, 'grammar: 'codegen, W: Write + 'codegen, C> { /// the complete grammar pub grammar: &'grammar Grammar, /// some suitable prefix to separate our identifiers from the user's pub prefix: &'grammar str, /// types from the grammar pub types: &'grammar Types, /// the start symbol S the user specified pub user_start_symbol: NonterminalString, /// the synthetic start symbol S' that we specified pub start_symbol: NonterminalString, /// the vector of states pub states: &'codegen [LR1State<'grammar>], /// where we write output pub out: &'codegen mut RustWrite<W>, /// where to find the action routines (typically `super`) pub action_module: String, /// custom fields for the specific kind of codegenerator /// (recursive ascent, table-driven, etc) pub custom: C, pub repeatable: bool, } impl<'codegen, 'grammar, W: Write, C> CodeGenerator<'codegen, 'grammar, W, C> { pub fn new( grammar: &'grammar Grammar, user_start_symbol: NonterminalString, start_symbol: NonterminalString, states: &'codegen [LR1State<'grammar>], out: &'codegen mut RustWrite<W>, repeatable: bool, action_module: &str, custom: C, ) -> Self { CodeGenerator { grammar: grammar, prefix: &grammar.prefix, types: &grammar.types, states: states, user_start_symbol: user_start_symbol, start_symbol: start_symbol, out: out, custom: custom, repeatable: repeatable, action_module: action_module.to_string(), } } /// We often create meta types that pull together a bunch of /// user-given types -- basically describing (e.g.) the full set /// of return values from any nonterminal (and, in some cases, /// terminals). These types need to carry generic parameters from /// the grammar, since the nonterminals may include generic /// parameters -- but we don't want them to carry *all* the /// generic parameters, since that can be unnecessarily /// restrictive. /// /// In particular, consider something like this: /// /// ```notrust /// grammar<'a>(buffer: &'a mut Vec<u32>); /// ``` /// /// Here, we likely do not want the `'a` in the type of `buffer` to appear /// in the nonterminal result. That's because, if it did, then the /// action functions will have a signature like: /// /// ```ignore /// fn foo<'a, T>(x: &'a mut Vec<T>) -> Result<'a> {... } /// ``` /// /// In that case, we would only be able to call one action fn and /// will in fact get borrowck errors, because Rust would think we /// were potentially returning this `&'a mut Vec<T>`. /// /// Therefore, we take the full list of type parameters and we /// filter them down to those that appear in the types that we /// need to include (those that appear in the `tys` parameter). /// /// In some cases, we need to include a few more than just that /// obviously appear textually: for example, if we have `T::Foo`, /// and we see a where-clause `T: Bar<'a>`, then we need to /// include both `T` and `'a`, since that bound may be important /// for resolving `T::Foo` (in other words, `T::Foo` may expand to /// `<T as Bar<'a>>::Foo`). pub fn filter_type_parameters_and_where_clauses( grammar: &Grammar, tys: impl IntoIterator<Item = TypeRepr>, ) -> (Vec<TypeParameter>, Vec<WhereClause>)
// **and** `'a` are referenced -- same with bounds like `T: // Foo<U>`. If those were needed, then `'a` or `U` would also // have to appear in the types. debug!("filtered_type_params = {:?}", filtered_type_params); let filtered_where_clauses: Vec<_> = grammar .where_clauses .iter() .filter(|wc| { debug!( "wc = {:?} free_variables = {:?}", wc, wc.free_variables(&grammar.type_parameters) ); wc.free_variables(&grammar.type_parameters) .iter() .all(|p| referenced_ty_params.contains(p)) }).cloned() .collect(); debug!("filtered_where_clauses = {:?}", filtered_where_clauses); (filtered_type_params, filtered_where_clauses) } pub fn write_parse_mod<F>(&mut self, body: F) -> io::Result<()> where F: FnOnce(&mut Self) -> io::Result<()>, { rust!(self.out, ""); rust!(self.out, "#[cfg_attr(rustfmt, rustfmt_skip)]"); rust!(self.out, "mod {}parse{} {{", self.prefix, self.start_symbol); // these stylistic lints are annoying for the generated code, // which doesn't follow conventions: rust!( self.out, "#![allow(non_snake_case, non_camel_case_types, unused_mut, unused_variables, \ unused_imports, unused_parens)]" ); rust!(self.out, ""); try!(self.write_uses()); try!(body(self)); rust!(self.out, "}}"); Ok(()) } pub fn write_uses(&mut self) -> io::Result<()> { try!( self.out .write_uses(&format!("{}::", self.action_module), &self.grammar) ); if self.grammar.intern_token.is_some() { rust!( self.out, "use {}::{}intern_token::Token;", self.action_module, self.prefix ); } else { rust!( self.out, "use {}::{}ToTriple;", self.action_module, self.prefix ); } Ok(()) } pub fn start_parser_fn(&mut self) -> io::Result<()> { let parse_error_type = self.types.parse_error_type(); let (type_parameters, parameters, mut where_clauses); let intern_token = self.grammar.intern_token.is_some(); if intern_token { // if we are generating the tokenizer, we just need the // input, and that has already been added as one of the // user parameters type_parameters = vec![]; parameters = vec![]; where_clauses = vec![]; } else { // otherwise, we need an iterator of type `TOKENS` let mut user_type_parameters = String::new(); for type_parameter in &self.grammar.type_parameters { user_type_parameters.push_str(&format!("{}, ", type_parameter)); } type_parameters = vec![ format!( "{}TOKEN: {}ToTriple<{}>", self.prefix, self.prefix, user_type_parameters, ), format!( "{}TOKENS: IntoIterator<Item={}TOKEN>", self.prefix, self.prefix ), ]; parameters = vec![format!("{}tokens0: {}TOKENS", self.prefix, self.prefix)]; where_clauses = vec![]; if self.repeatable { where_clauses.push(format!("{}TOKENS: Clone", self.prefix)); } } rust!( self.out, "{}struct {}Parser {{", self.grammar.nonterminals[&self.start_symbol].visibility, self.user_start_symbol ); if intern_token { rust!( self.out, "builder: {1}::{0}intern_token::{0}MatcherBuilder,", self.prefix, self.action_module ); } rust!(self.out, "_priv: (),"); rust!(self.out, "}}"); rust!(self.out, ""); rust!(self.out, "impl {}Parser {{", self.user_start_symbol); rust!( self.out, "{}fn new() -> {}Parser {{", self.grammar.nonterminals[&self.start_symbol].visibility, self.user_start_symbol ); if intern_token { rust!( self.out, "let {0}builder = {1}::{0}intern_token::{0}MatcherBuilder::new();", self.prefix, self.action_module ); } rust!(self.out, "{}Parser {{", self.user_start_symbol); if intern_token { rust!(self.out, "builder: {}builder,", self.prefix); } rust!(self.out, "_priv: (),"); rust!(self.out, "}}"); // Parser rust!(self.out, "}}"); // new() rust!(self.out, ""); rust!(self.out, "#[allow(dead_code)]"); try!( self.out .fn_header( &self.grammar.nonterminals[&self.start_symbol].visibility, "parse".to_owned(), ).with_parameters(Some("&self".to_owned())) .with_grammar(self.grammar) .with_type_parameters(type_parameters) .with_parameters(parameters) .with_return_type(format!( "Result<{}, {}>", self.types.nonterminal_type(&self.start_symbol), parse_error_type )).with_where_clauses(where_clauses) .emit() ); rust!(self.out, "{{"); Ok(()) } pub fn define_tokens(&mut self) -> io::Result<()> { if self.grammar.intern_token.is_some() { // if we are generating the tokenizer, create a matcher as our input iterator rust!( self.out, "let mut {}tokens = self.builder.matcher(input);", self.prefix ); } else { // otherwise, convert one from the `IntoIterator` // supplied, using the `ToTriple` trait which inserts // errors/locations etc if none are given let clone_call = if self.repeatable { ".clone()" } else { "" }; rust!( self.out, "let {}tokens = {}tokens0{}.into_iter();", self.prefix, self.prefix, clone_call ); rust!( self.out, "let mut {}tokens = {}tokens.map(|t| {}ToTriple::to_triple(t));", self.prefix, self.prefix, self.prefix ); } Ok(()) } pub fn end_parser_fn(&mut self) -> io::Result<()> { rust!(self.out, "}}"); // fn rust!(self.out, "}}"); // impl Ok(()) } /// Returns phantom data type that captures the user-declared type /// parameters in a phantom-data. This helps with ensuring that /// all type parameters are constrained, even if they are not /// used. pub fn phantom_data_type(&self) -> String { let phantom_bits: Vec<_> = self .grammar .type_parameters .iter() .map(|tp| match *tp { TypeParameter::Lifetime(ref l) => format!("&{} ()", l), TypeParameter::Id(ref id) => id.to_string(), }) .collect(); format!("::std::marker::PhantomData<({})>", Sep(", ", &phantom_bits),) } /// Returns expression that captures the user-declared type /// parameters in a phantom-data. This helps with ensuring that /// all type parameters are constrained, even if they are not /// used. pub fn phantom_data_expr(&self) -> String { let phantom_bits: Vec<_> = self .grammar .type_parameters .iter() .map(|tp| match *tp { TypeParameter::Lifetime(_) => format!("&()"), TypeParameter::Id(ref id) => id.to_string(), }) .collect(); format!( "::std::marker::PhantomData::<({})>", Sep(", ", &phantom_bits), ) } }
{ let referenced_ty_params: Set<_> = tys .into_iter() .flat_map(|t| t.free_variables(&grammar.type_parameters)) .collect(); let filtered_type_params: Vec<_> = grammar .type_parameters .iter() .filter(|t| referenced_ty_params.contains(t)) .cloned() .collect(); // If `T` is referenced in the types we need to keep, then // include any bounds like `T: Foo`. This may be needed for // the well-formedness conditions on `T` (e.g., maybe we have // `T: Hash` and a `HashSet<T>` or something) but it may also // be needed because of `T::Foo`-like types. // // Do not however include a bound like `T: 'a` unless both `T`
identifier_body
bluetoothremotegattserver.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutHeap, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bluetoothdevice::BluetoothDevice; use dom::bluetoothremotegattservice::BluetoothRemoteGATTService; use std::cell::Cell; // https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattserver #[dom_struct] pub struct BluetoothRemoteGATTServer { reflector_: Reflector, device: MutHeap<JS<BluetoothDevice>>, connected: Cell<bool>, } impl BluetoothRemoteGATTServer { pub fn new_inherited(device: &BluetoothDevice, is_connected: bool) -> BluetoothRemoteGATTServer { BluetoothRemoteGATTServer { reflector_: Reflector::new(), device: MutHeap::new(device), connected: Cell::new(is_connected), } } pub fn new(global: GlobalRef, device: &BluetoothDevice, connected: bool) -> Root<BluetoothRemoteGATTServer> { reflect_dom_object(box BluetoothRemoteGATTServer::new_inherited( device, connected), global, BluetoothRemoteGATTServerBinding::Wrap) } } impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-device fn Device(&self) -> Root<BluetoothDevice> { self.device.get() } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connected fn Connected(&self) -> bool { self.connected.get() } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connect fn Connect(&self) -> Root<BluetoothRemoteGATTServer> { if!self.connected.get()
Root::from_ref(self) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-disconnect fn Disconnect(&self) { self.connected.set(false); } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-getprimaryservice fn GetPrimaryService(&self) -> Option<Root<BluetoothRemoteGATTService>> { //UNIMPLEMENTED None } }
{ self.connected.set(true); }
conditional_block
bluetoothremotegattserver.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutHeap, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bluetoothdevice::BluetoothDevice; use dom::bluetoothremotegattservice::BluetoothRemoteGATTService; use std::cell::Cell; // https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattserver #[dom_struct] pub struct BluetoothRemoteGATTServer { reflector_: Reflector, device: MutHeap<JS<BluetoothDevice>>, connected: Cell<bool>, } impl BluetoothRemoteGATTServer { pub fn new_inherited(device: &BluetoothDevice, is_connected: bool) -> BluetoothRemoteGATTServer { BluetoothRemoteGATTServer { reflector_: Reflector::new(), device: MutHeap::new(device), connected: Cell::new(is_connected), } } pub fn new(global: GlobalRef, device: &BluetoothDevice, connected: bool) -> Root<BluetoothRemoteGATTServer> { reflect_dom_object(box BluetoothRemoteGATTServer::new_inherited( device, connected), global, BluetoothRemoteGATTServerBinding::Wrap) } } impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-device fn
(&self) -> Root<BluetoothDevice> { self.device.get() } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connected fn Connected(&self) -> bool { self.connected.get() } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connect fn Connect(&self) -> Root<BluetoothRemoteGATTServer> { if!self.connected.get() { self.connected.set(true); } Root::from_ref(self) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-disconnect fn Disconnect(&self) { self.connected.set(false); } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-getprimaryservice fn GetPrimaryService(&self) -> Option<Root<BluetoothRemoteGATTService>> { //UNIMPLEMENTED None } }
Device
identifier_name
bluetoothremotegattserver.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutHeap, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bluetoothdevice::BluetoothDevice; use dom::bluetoothremotegattservice::BluetoothRemoteGATTService; use std::cell::Cell; // https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattserver #[dom_struct] pub struct BluetoothRemoteGATTServer { reflector_: Reflector, device: MutHeap<JS<BluetoothDevice>>, connected: Cell<bool>, } impl BluetoothRemoteGATTServer { pub fn new_inherited(device: &BluetoothDevice, is_connected: bool) -> BluetoothRemoteGATTServer { BluetoothRemoteGATTServer { reflector_: Reflector::new(), device: MutHeap::new(device), connected: Cell::new(is_connected), } } pub fn new(global: GlobalRef, device: &BluetoothDevice, connected: bool) -> Root<BluetoothRemoteGATTServer> { reflect_dom_object(box BluetoothRemoteGATTServer::new_inherited( device, connected), global, BluetoothRemoteGATTServerBinding::Wrap) } } impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer {
} // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connected fn Connected(&self) -> bool { self.connected.get() } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connect fn Connect(&self) -> Root<BluetoothRemoteGATTServer> { if!self.connected.get() { self.connected.set(true); } Root::from_ref(self) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-disconnect fn Disconnect(&self) { self.connected.set(false); } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-getprimaryservice fn GetPrimaryService(&self) -> Option<Root<BluetoothRemoteGATTService>> { //UNIMPLEMENTED None } }
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-device fn Device(&self) -> Root<BluetoothDevice> { self.device.get()
random_line_split
bluetoothremotegattserver.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutHeap, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bluetoothdevice::BluetoothDevice; use dom::bluetoothremotegattservice::BluetoothRemoteGATTService; use std::cell::Cell; // https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattserver #[dom_struct] pub struct BluetoothRemoteGATTServer { reflector_: Reflector, device: MutHeap<JS<BluetoothDevice>>, connected: Cell<bool>, } impl BluetoothRemoteGATTServer { pub fn new_inherited(device: &BluetoothDevice, is_connected: bool) -> BluetoothRemoteGATTServer { BluetoothRemoteGATTServer { reflector_: Reflector::new(), device: MutHeap::new(device), connected: Cell::new(is_connected), } } pub fn new(global: GlobalRef, device: &BluetoothDevice, connected: bool) -> Root<BluetoothRemoteGATTServer> { reflect_dom_object(box BluetoothRemoteGATTServer::new_inherited( device, connected), global, BluetoothRemoteGATTServerBinding::Wrap) } } impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-device fn Device(&self) -> Root<BluetoothDevice> { self.device.get() } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connected fn Connected(&self) -> bool { self.connected.get() } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connect fn Connect(&self) -> Root<BluetoothRemoteGATTServer> { if!self.connected.get() { self.connected.set(true); } Root::from_ref(self) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-disconnect fn Disconnect(&self) { self.connected.set(false); } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-getprimaryservice fn GetPrimaryService(&self) -> Option<Root<BluetoothRemoteGATTService>>
}
{ //UNIMPLEMENTED None }
identifier_body
slice-panic-1.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that is a slicing expr[..] fails, the correct cleanups happen. #![feature(slicing_syntax)] use std::task; struct Foo; static mut DTOR_COUNT: int = 0; impl Drop for Foo { fn drop(&mut self) { unsafe { DTOR_COUNT += 1; } } } fn
() { let x: &[_] = &[Foo, Foo]; x[3..4]; } fn main() { let _ = task::try(proc() foo()); unsafe { assert!(DTOR_COUNT == 2); } }
foo
identifier_name
slice-panic-1.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that is a slicing expr[..] fails, the correct cleanups happen. #![feature(slicing_syntax)] use std::task; struct Foo; static mut DTOR_COUNT: int = 0; impl Drop for Foo { fn drop(&mut self) { unsafe { DTOR_COUNT += 1; } } } fn foo() { let x: &[_] = &[Foo, Foo]; x[3..4]; } fn main() { let _ = task::try(proc() foo());
unsafe { assert!(DTOR_COUNT == 2); } }
random_line_split
slice-panic-1.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that is a slicing expr[..] fails, the correct cleanups happen. #![feature(slicing_syntax)] use std::task; struct Foo; static mut DTOR_COUNT: int = 0; impl Drop for Foo { fn drop(&mut self) { unsafe { DTOR_COUNT += 1; } } } fn foo() { let x: &[_] = &[Foo, Foo]; x[3..4]; } fn main()
{ let _ = task::try(proc() foo()); unsafe { assert!(DTOR_COUNT == 2); } }
identifier_body
c_str.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![unstable(feature = "std_misc")] use convert::{Into, From}; use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering}; use error::Error; use fmt; use io; use iter::Iterator; use libc; use mem; #[allow(deprecated)] use old_io; use ops::Deref; use option::Option::{self, Some, None}; use result::Result::{self, Ok, Err}; use slice; use string::String; use vec::Vec; /// A type representing an owned C-compatible string /// /// This type serves the primary purpose of being able to safely generate a /// C-compatible string from a Rust byte slice or vector. An instance of this /// type is a static guarantee that the underlying bytes contain no interior 0 /// bytes and the final byte is 0. /// /// A `CString` is created from either a byte slice or a byte vector. After /// being created, a `CString` predominately inherits all of its methods from /// the `Deref` implementation to `[libc::c_char]`. Note that the underlying /// array is represented as an array of `libc::c_char` as opposed to `u8`. A /// `u8` slice can be obtained with the `as_bytes` method. Slices produced from /// a `CString` do *not* contain the trailing nul terminator unless otherwise /// specified. /// /// # Examples /// /// ```no_run /// # #![feature(libc)] /// # extern crate libc; /// # fn main() { /// use std::ffi::CString; /// use libc; /// /// extern { /// fn my_printer(s: *const libc::c_char); /// } /// /// let to_print = &b"Hello, world!"[..]; /// let c_to_print = CString::new(to_print).unwrap(); /// unsafe { /// my_printer(c_to_print.as_ptr()); /// } /// # } /// ``` #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] #[stable(feature = "rust1", since = "1.0.0")] pub struct CString { inner: Vec<u8>, } /// Representation of a borrowed C string. /// /// This dynamically sized type is only safely constructed via a borrowed /// version of an instance of `CString`. This type can be constructed from a raw /// C string as well and represents a C string borrowed from another location. /// /// Note that this structure is **not** `repr(C)` and is not recommended to be /// placed in the signatures of FFI functions. Instead safe wrappers of FFI /// functions may leverage the unsafe `from_ptr` constructor to provide a safe /// interface to other consumers. /// /// # Examples /// /// Inspecting a foreign C string /// /// ```no_run /// # #![feature(libc)] /// extern crate libc; /// use std::ffi::CStr; /// /// extern { fn my_string() -> *const libc::c_char; } /// /// fn main() { /// unsafe { /// let slice = CStr::from_ptr(my_string()); /// println!("string length: {}", slice.to_bytes().len()); /// } /// } /// ``` /// /// Passing a Rust-originating C string /// /// ```no_run /// # #![feature(libc)] /// extern crate libc; /// use std::ffi::{CString, CStr}; /// /// fn work(data: &CStr) { /// extern { fn work_with(data: *const libc::c_char); } /// /// unsafe { work_with(data.as_ptr()) } /// } /// /// fn main() { /// let s = CString::new("data data data data").unwrap(); /// work(&s); /// } /// ``` #[derive(Hash)] #[stable(feature = "rust1", since = "1.0.0")] pub struct CStr { // FIXME: this should not be represented with a DST slice but rather with // just a raw `libc::c_char` along with some form of marker to make // this an unsized type. Essentially `sizeof(&CStr)` should be the // same as `sizeof(&c_char)` but `CStr` should be an unsized type. inner: [libc::c_char] } /// An error returned from `CString::new` to indicate that a nul byte was found /// in the vector provided. #[derive(Clone, PartialEq, Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub struct NulError(usize, Vec<u8>); impl CString { /// Create a new C-compatible string from a container of bytes. /// /// This method will consume the provided data and use the underlying bytes /// to construct a new string, ensuring that there is a trailing 0 byte. /// /// # Examples /// /// ```no_run /// # #![feature(libc)] /// extern crate libc; /// use std::ffi::CString; /// /// extern { fn puts(s: *const libc::c_char); } /// /// fn main() { /// let to_print = CString::new("Hello!").unwrap(); /// unsafe { /// puts(to_print.as_ptr()); /// } /// } /// ``` /// /// # Errors /// /// This function will return an error if the bytes yielded contain an /// internal 0 byte. The error returned will contain the bytes as well as /// the position of the nul byte. #[stable(feature = "rust1", since = "1.0.0")] pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> { let bytes = t.into(); match bytes.iter().position(|x| *x == 0) { Some(i) => Err(NulError(i, bytes)), None => Ok(unsafe { CString::from_vec_unchecked(bytes) }), } } /// Create a C-compatible string from a byte vector without checking for /// interior 0 bytes. /// /// This method is equivalent to `from_vec` except that no runtime assertion /// is made that `v` contains no 0 bytes. #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString { v.push(0); CString { inner: v } } /// Returns the contents of this `CString` as a slice of bytes. /// /// The returned slice does **not** contain the trailing nul separator and /// it is guaranteed to not have any interior nul bytes. #[stable(feature = "rust1", since = "1.0.0")] pub fn as_bytes(&self) -> &[u8] { &self.inner[..self.inner.len() - 1] } /// Equivalent to the `as_bytes` function except that the returned slice /// includes the trailing nul byte. #[stable(feature = "rust1", since = "1.0.0")] pub fn as_bytes_with_nul(&self) -> &[u8] { &self.inner } } #[stable(feature = "rust1", since = "1.0.0")] impl Deref for CString { type Target = CStr; fn deref(&self) -> &CStr { unsafe { mem::transmute(self.as_bytes_with_nul()) } } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for CString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&String::from_utf8_lossy(self.as_bytes()), f) } } impl NulError { /// Returns the position of the nul byte in the slice that was provided to /// `CString::from_vec`. #[stable(feature = "rust1", since = "1.0.0")] pub fn nul_position(&self) -> usize { self.0 } /// Consumes this error, returning the underlying vector of bytes which /// generated the error in the first place. #[stable(feature = "rust1", since = "1.0.0")] pub fn into_vec(self) -> Vec<u8> { self.1 } } #[stable(feature = "rust1", since = "1.0.0")] impl Error for NulError { fn description(&self) -> &str { "nul byte found in data" } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for NulError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "nul byte found in provided data at position: {}", self.0) } } #[stable(feature = "rust1", since = "1.0.0")] impl From<NulError> for io::Error { fn from(_: NulError) -> io::Error { io::Error::new(io::ErrorKind::InvalidInput, "data provided contains a nul byte") } } #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] impl From<NulError> for old_io::IoError { fn from(_: NulError) -> old_io::IoError { old_io::IoError { kind: old_io::IoErrorKind::InvalidInput, desc: "data provided contains a nul byte", detail: None } } } impl CStr { /// Cast a raw C string to a safe C string wrapper. /// /// This function will cast the provided `ptr` to the `CStr` wrapper which /// allows inspection and interoperation of non-owned C strings. This method /// is unsafe for a number of reasons: /// /// * There is no guarantee to the validity of `ptr` /// * The returned lifetime is not guaranteed to be the actual lifetime of /// `ptr` /// * There is no guarantee that the memory pointed to by `ptr` contains a /// valid nul terminator byte at the end of the string. /// /// > **Note**: This operation is intended to be a 0-cost cast but it is /// > currently implemented with an up-front calculation of the length of /// > the string. This is not guaranteed to always be the case. /// /// # Examples /// /// ```no_run /// # #![feature(libc)] /// # extern crate libc; /// # fn main() { /// use std::ffi::CStr; /// use std::str; /// use libc; /// /// extern { /// fn my_string() -> *const libc::c_char; /// } /// /// unsafe { /// let slice = CStr::from_ptr(my_string()); /// println!("string returned: {}", /// str::from_utf8(slice.to_bytes()).unwrap()); /// } /// # } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_ptr<'a>(ptr: *const libc::c_char) -> &'a CStr { let len = libc::strlen(ptr); mem::transmute(slice::from_raw_parts(ptr, len as usize + 1)) } /// Return the inner pointer to this C string. /// /// The returned pointer will be valid for as long as `self` is and points /// to a contiguous region of memory terminated with a 0 byte to represent /// the end of the string. #[stable(feature = "rust1", since = "1.0.0")] pub fn
(&self) -> *const libc::c_char { self.inner.as_ptr() } /// Convert this C string to a byte slice. /// /// This function will calculate the length of this string (which normally /// requires a linear amount of work to be done) and then return the /// resulting slice of `u8` elements. /// /// The returned slice will **not** contain the trailing nul that this C /// string has. /// /// > **Note**: This method is currently implemented as a 0-cost cast, but /// > it is planned to alter its definition in the future to perform the /// > length calculation whenever this method is called. #[stable(feature = "rust1", since = "1.0.0")] pub fn to_bytes(&self) -> &[u8] { let bytes = self.to_bytes_with_nul(); &bytes[..bytes.len() - 1] } /// Convert this C string to a byte slice containing the trailing 0 byte. /// /// This function is the equivalent of `to_bytes` except that it will retain /// the trailing nul instead of chopping it off. /// /// > **Note**: This method is currently implemented as a 0-cost cast, but /// > it is planned to alter its definition in the future to perform the /// > length calculation whenever this method is called. #[stable(feature = "rust1", since = "1.0.0")] pub fn to_bytes_with_nul(&self) -> &[u8] { unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&self.inner) } } } #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for CStr { fn eq(&self, other: &CStr) -> bool { self.to_bytes().eq(other.to_bytes()) } } #[stable(feature = "rust1", since = "1.0.0")] impl Eq for CStr {} #[stable(feature = "rust1", since = "1.0.0")] impl PartialOrd for CStr { fn partial_cmp(&self, other: &CStr) -> Option<Ordering> { self.to_bytes().partial_cmp(&other.to_bytes()) } } #[stable(feature = "rust1", since = "1.0.0")] impl Ord for CStr { fn cmp(&self, other: &CStr) -> Ordering { self.to_bytes().cmp(&other.to_bytes()) } } #[cfg(test)] mod tests { use prelude::v1::*; use super::*; use libc; #[test] fn c_to_rust() { let data = b"123\0"; let ptr = data.as_ptr() as *const libc::c_char; unsafe { assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123"); assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0"); } } #[test] fn simple() { let s = CString::new("1234").unwrap(); assert_eq!(s.as_bytes(), b"1234"); assert_eq!(s.as_bytes_with_nul(), b"1234\0"); } #[test] fn build_with_zero1() { assert!(CString::new(&b"\0"[..]).is_err()); } #[test] fn build_with_zero2() { assert!(CString::new(vec![0]).is_err()); } #[test] fn build_with_zero3() { unsafe { let s = CString::from_vec_unchecked(vec![0]); assert_eq!(s.as_bytes(), b"\0"); } } #[test] fn formatted() { let s = CString::new(&b"12"[..]).unwrap(); assert_eq!(format!("{:?}", s), "\"12\""); } #[test] fn borrowed() { unsafe { let s = CStr::from_ptr(b"12\0".as_ptr() as *const _); assert_eq!(s.to_bytes(), b"12"); assert_eq!(s.to_bytes_with_nul(), b"12\0"); } } }
as_ptr
identifier_name
c_str.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![unstable(feature = "std_misc")] use convert::{Into, From}; use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering}; use error::Error; use fmt; use io; use iter::Iterator; use libc; use mem; #[allow(deprecated)] use old_io;
use slice; use string::String; use vec::Vec; /// A type representing an owned C-compatible string /// /// This type serves the primary purpose of being able to safely generate a /// C-compatible string from a Rust byte slice or vector. An instance of this /// type is a static guarantee that the underlying bytes contain no interior 0 /// bytes and the final byte is 0. /// /// A `CString` is created from either a byte slice or a byte vector. After /// being created, a `CString` predominately inherits all of its methods from /// the `Deref` implementation to `[libc::c_char]`. Note that the underlying /// array is represented as an array of `libc::c_char` as opposed to `u8`. A /// `u8` slice can be obtained with the `as_bytes` method. Slices produced from /// a `CString` do *not* contain the trailing nul terminator unless otherwise /// specified. /// /// # Examples /// /// ```no_run /// # #![feature(libc)] /// # extern crate libc; /// # fn main() { /// use std::ffi::CString; /// use libc; /// /// extern { /// fn my_printer(s: *const libc::c_char); /// } /// /// let to_print = &b"Hello, world!"[..]; /// let c_to_print = CString::new(to_print).unwrap(); /// unsafe { /// my_printer(c_to_print.as_ptr()); /// } /// # } /// ``` #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] #[stable(feature = "rust1", since = "1.0.0")] pub struct CString { inner: Vec<u8>, } /// Representation of a borrowed C string. /// /// This dynamically sized type is only safely constructed via a borrowed /// version of an instance of `CString`. This type can be constructed from a raw /// C string as well and represents a C string borrowed from another location. /// /// Note that this structure is **not** `repr(C)` and is not recommended to be /// placed in the signatures of FFI functions. Instead safe wrappers of FFI /// functions may leverage the unsafe `from_ptr` constructor to provide a safe /// interface to other consumers. /// /// # Examples /// /// Inspecting a foreign C string /// /// ```no_run /// # #![feature(libc)] /// extern crate libc; /// use std::ffi::CStr; /// /// extern { fn my_string() -> *const libc::c_char; } /// /// fn main() { /// unsafe { /// let slice = CStr::from_ptr(my_string()); /// println!("string length: {}", slice.to_bytes().len()); /// } /// } /// ``` /// /// Passing a Rust-originating C string /// /// ```no_run /// # #![feature(libc)] /// extern crate libc; /// use std::ffi::{CString, CStr}; /// /// fn work(data: &CStr) { /// extern { fn work_with(data: *const libc::c_char); } /// /// unsafe { work_with(data.as_ptr()) } /// } /// /// fn main() { /// let s = CString::new("data data data data").unwrap(); /// work(&s); /// } /// ``` #[derive(Hash)] #[stable(feature = "rust1", since = "1.0.0")] pub struct CStr { // FIXME: this should not be represented with a DST slice but rather with // just a raw `libc::c_char` along with some form of marker to make // this an unsized type. Essentially `sizeof(&CStr)` should be the // same as `sizeof(&c_char)` but `CStr` should be an unsized type. inner: [libc::c_char] } /// An error returned from `CString::new` to indicate that a nul byte was found /// in the vector provided. #[derive(Clone, PartialEq, Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub struct NulError(usize, Vec<u8>); impl CString { /// Create a new C-compatible string from a container of bytes. /// /// This method will consume the provided data and use the underlying bytes /// to construct a new string, ensuring that there is a trailing 0 byte. /// /// # Examples /// /// ```no_run /// # #![feature(libc)] /// extern crate libc; /// use std::ffi::CString; /// /// extern { fn puts(s: *const libc::c_char); } /// /// fn main() { /// let to_print = CString::new("Hello!").unwrap(); /// unsafe { /// puts(to_print.as_ptr()); /// } /// } /// ``` /// /// # Errors /// /// This function will return an error if the bytes yielded contain an /// internal 0 byte. The error returned will contain the bytes as well as /// the position of the nul byte. #[stable(feature = "rust1", since = "1.0.0")] pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> { let bytes = t.into(); match bytes.iter().position(|x| *x == 0) { Some(i) => Err(NulError(i, bytes)), None => Ok(unsafe { CString::from_vec_unchecked(bytes) }), } } /// Create a C-compatible string from a byte vector without checking for /// interior 0 bytes. /// /// This method is equivalent to `from_vec` except that no runtime assertion /// is made that `v` contains no 0 bytes. #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString { v.push(0); CString { inner: v } } /// Returns the contents of this `CString` as a slice of bytes. /// /// The returned slice does **not** contain the trailing nul separator and /// it is guaranteed to not have any interior nul bytes. #[stable(feature = "rust1", since = "1.0.0")] pub fn as_bytes(&self) -> &[u8] { &self.inner[..self.inner.len() - 1] } /// Equivalent to the `as_bytes` function except that the returned slice /// includes the trailing nul byte. #[stable(feature = "rust1", since = "1.0.0")] pub fn as_bytes_with_nul(&self) -> &[u8] { &self.inner } } #[stable(feature = "rust1", since = "1.0.0")] impl Deref for CString { type Target = CStr; fn deref(&self) -> &CStr { unsafe { mem::transmute(self.as_bytes_with_nul()) } } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for CString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&String::from_utf8_lossy(self.as_bytes()), f) } } impl NulError { /// Returns the position of the nul byte in the slice that was provided to /// `CString::from_vec`. #[stable(feature = "rust1", since = "1.0.0")] pub fn nul_position(&self) -> usize { self.0 } /// Consumes this error, returning the underlying vector of bytes which /// generated the error in the first place. #[stable(feature = "rust1", since = "1.0.0")] pub fn into_vec(self) -> Vec<u8> { self.1 } } #[stable(feature = "rust1", since = "1.0.0")] impl Error for NulError { fn description(&self) -> &str { "nul byte found in data" } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for NulError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "nul byte found in provided data at position: {}", self.0) } } #[stable(feature = "rust1", since = "1.0.0")] impl From<NulError> for io::Error { fn from(_: NulError) -> io::Error { io::Error::new(io::ErrorKind::InvalidInput, "data provided contains a nul byte") } } #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] impl From<NulError> for old_io::IoError { fn from(_: NulError) -> old_io::IoError { old_io::IoError { kind: old_io::IoErrorKind::InvalidInput, desc: "data provided contains a nul byte", detail: None } } } impl CStr { /// Cast a raw C string to a safe C string wrapper. /// /// This function will cast the provided `ptr` to the `CStr` wrapper which /// allows inspection and interoperation of non-owned C strings. This method /// is unsafe for a number of reasons: /// /// * There is no guarantee to the validity of `ptr` /// * The returned lifetime is not guaranteed to be the actual lifetime of /// `ptr` /// * There is no guarantee that the memory pointed to by `ptr` contains a /// valid nul terminator byte at the end of the string. /// /// > **Note**: This operation is intended to be a 0-cost cast but it is /// > currently implemented with an up-front calculation of the length of /// > the string. This is not guaranteed to always be the case. /// /// # Examples /// /// ```no_run /// # #![feature(libc)] /// # extern crate libc; /// # fn main() { /// use std::ffi::CStr; /// use std::str; /// use libc; /// /// extern { /// fn my_string() -> *const libc::c_char; /// } /// /// unsafe { /// let slice = CStr::from_ptr(my_string()); /// println!("string returned: {}", /// str::from_utf8(slice.to_bytes()).unwrap()); /// } /// # } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_ptr<'a>(ptr: *const libc::c_char) -> &'a CStr { let len = libc::strlen(ptr); mem::transmute(slice::from_raw_parts(ptr, len as usize + 1)) } /// Return the inner pointer to this C string. /// /// The returned pointer will be valid for as long as `self` is and points /// to a contiguous region of memory terminated with a 0 byte to represent /// the end of the string. #[stable(feature = "rust1", since = "1.0.0")] pub fn as_ptr(&self) -> *const libc::c_char { self.inner.as_ptr() } /// Convert this C string to a byte slice. /// /// This function will calculate the length of this string (which normally /// requires a linear amount of work to be done) and then return the /// resulting slice of `u8` elements. /// /// The returned slice will **not** contain the trailing nul that this C /// string has. /// /// > **Note**: This method is currently implemented as a 0-cost cast, but /// > it is planned to alter its definition in the future to perform the /// > length calculation whenever this method is called. #[stable(feature = "rust1", since = "1.0.0")] pub fn to_bytes(&self) -> &[u8] { let bytes = self.to_bytes_with_nul(); &bytes[..bytes.len() - 1] } /// Convert this C string to a byte slice containing the trailing 0 byte. /// /// This function is the equivalent of `to_bytes` except that it will retain /// the trailing nul instead of chopping it off. /// /// > **Note**: This method is currently implemented as a 0-cost cast, but /// > it is planned to alter its definition in the future to perform the /// > length calculation whenever this method is called. #[stable(feature = "rust1", since = "1.0.0")] pub fn to_bytes_with_nul(&self) -> &[u8] { unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&self.inner) } } } #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for CStr { fn eq(&self, other: &CStr) -> bool { self.to_bytes().eq(other.to_bytes()) } } #[stable(feature = "rust1", since = "1.0.0")] impl Eq for CStr {} #[stable(feature = "rust1", since = "1.0.0")] impl PartialOrd for CStr { fn partial_cmp(&self, other: &CStr) -> Option<Ordering> { self.to_bytes().partial_cmp(&other.to_bytes()) } } #[stable(feature = "rust1", since = "1.0.0")] impl Ord for CStr { fn cmp(&self, other: &CStr) -> Ordering { self.to_bytes().cmp(&other.to_bytes()) } } #[cfg(test)] mod tests { use prelude::v1::*; use super::*; use libc; #[test] fn c_to_rust() { let data = b"123\0"; let ptr = data.as_ptr() as *const libc::c_char; unsafe { assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123"); assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0"); } } #[test] fn simple() { let s = CString::new("1234").unwrap(); assert_eq!(s.as_bytes(), b"1234"); assert_eq!(s.as_bytes_with_nul(), b"1234\0"); } #[test] fn build_with_zero1() { assert!(CString::new(&b"\0"[..]).is_err()); } #[test] fn build_with_zero2() { assert!(CString::new(vec![0]).is_err()); } #[test] fn build_with_zero3() { unsafe { let s = CString::from_vec_unchecked(vec![0]); assert_eq!(s.as_bytes(), b"\0"); } } #[test] fn formatted() { let s = CString::new(&b"12"[..]).unwrap(); assert_eq!(format!("{:?}", s), "\"12\""); } #[test] fn borrowed() { unsafe { let s = CStr::from_ptr(b"12\0".as_ptr() as *const _); assert_eq!(s.to_bytes(), b"12"); assert_eq!(s.to_bytes_with_nul(), b"12\0"); } } }
use ops::Deref; use option::Option::{self, Some, None}; use result::Result::{self, Ok, Err};
random_line_split