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
graphic.rs
use cursive::theme::{BaseColor, Color, ColorStyle}; use cursive::traits::*; use cursive::vec::Vec2; use cursive::Printer; use tutor::{Label, LabeledChord, PrevCharStatus}; pub struct Graphic { switches: Vec<Switch>, } #[derive(Clone, Copy)] pub enum ChordType { Next, Error, Backspace, Persistent, } struct Switch { position: (usize, usize), next: Option<Label>, error: Option<Label>, persistent: Vec<Label>, backspace: Option<Label>, } //////////////////////////////////////////////////////////////////////////////// impl Graphic { pub fn new(persistent: Vec<LabeledChord>) -> Self { let switches: Vec<_> = get_switch_positions() .into_iter() .map(Switch::new) .collect(); let mut graphic = Self { switches }; for labeled_chord in persistent { graphic.apply_chord(labeled_chord, ChordType::Persistent); } graphic } pub fn update( &mut self, next: Option<LabeledChord>, prev: &PrevCharStatus, ) { for switch in &mut self.switches { switch.clear() } if let Some(c) = next { self.apply_chord(c, ChordType::Next) } if let Some(c) = prev.backspace() { self.apply_chord(c, ChordType::Backspace) } if let Some(c) = prev.error() { self.apply_chord(c, ChordType::Error) } } fn apply_chord(&mut self, lc: LabeledChord, chord_type: ChordType) { let (label, chord) = (lc.label, lc.chord); for (bit, switch) in chord.iter().zip(self.switches.iter_mut()) { if bit { switch.set_label(chord_type, label.clone()); } } } pub fn size(&self) -> Vec2 { Vec2::new(78, 12) } } impl View for Graphic { fn required_size(&mut self, _constraint: Vec2) -> Vec2 { self.size() } fn draw(&self, printer: &Printer) { for switch in &self.switches { switch.draw(printer); } } } impl Switch { fn new(position: (usize, usize)) -> Self { Self { next: None, error: None, backspace: None, persistent: Vec::new(), position, } } fn set_label(&mut self, chord_type: ChordType, label: Label) { match chord_type { ChordType::Next => self.next = Some(label), ChordType::Error => self.error = Some(label), ChordType::Backspace => self.backspace = Some(label), ChordType::Persistent => self.persistent.push(label), } } /// Clear all labels except the `persistent` label, since that one stays for /// the whole lesson fn clear(&mut self) { self.next = None; self.error = None; self.backspace = None; } /// Pick 1 label to show, according to their priority order fn label(&self) -> Label { self.next .as_ref() .or_else(|| self.error.as_ref()) .or_else(|| self.backspace.as_ref()) .cloned() .or_else(|| Label::join(&self.persistent)) .unwrap_or_else(Label::default) } /// Pick a style for the switch, based on which labeled chords include it fn styles(&self) -> (ColorStyle, ColorStyle) { let next = Self::next_style(); let error = Self::error_style(); let backspace = Self::backspace_style(); let default = Self::default_style(); match ( self.next.is_some(), self.error.is_some(), self.backspace.is_some(), ) { (true, false, false) => (next, next), (false, true, false) => (error, error), (false, false, true) => (backspace, backspace), (true, true, false) => (next, error), (true, false, true) => (next, backspace), _ => (default, default), } } fn next_style() -> ColorStyle { ColorStyle::tertiary() } fn backspace_style() -> ColorStyle { // TODO the background color is hardcoded, instead of inheriting from // the theme! ColorStyle::new( Color::Dark(BaseColor::Yellow), Color::Dark(BaseColor::Black), ) } fn error_style() -> ColorStyle { ColorStyle::secondary() }
fn draw(&self, printer: &Printer) { let (x, y) = self.position; let row2_left = format!("│{}", self.label()); let (left, right) = self.styles(); printer.with_color(left, |printer| { printer.print((x, y), "╭───"); printer.print((x, y + 1), &row2_left); printer.print((x, y + 2), "╰"); }); printer.with_color(right, |printer| { printer.print((x + 4, y), "╮"); printer.print((x + 4, y + 1), "│"); printer.print((x + 1, y + 2), "───╯"); }); } } fn get_switch_positions() -> Vec<(usize, usize)> { vec![ (0, 2), (6, 1), (12, 1), (18, 1), (54, 1), (60, 1), (66, 1), (72, 2), (0, 5), (6, 4), (12, 4), (18, 4), (54, 4), (60, 4), (66, 4), (72, 5), (60, 7), (12, 7), (20, 8), (26, 8), (32, 9), (40, 9), (46, 8), (52, 8), ] }
fn default_style() -> ColorStyle { ColorStyle::title_secondary() }
random_line_split
headers.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::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HeadersBinding; use dom::bindings::codegen::Bindings::HeadersBinding::HeadersMethods; use dom::bindings::error::Error; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{ByteString, is_token}; use hyper; use std::result::Result; #[dom_struct] pub struct Headers { reflector_: Reflector, guard: Guard, #[ignore_heap_size_of = "Defined in hyper"] header_list: DOMRefCell<hyper::header::Headers> } // https://fetch.spec.whatwg.org/#concept-headers-guard #[derive(JSTraceable, HeapSizeOf, PartialEq)] pub enum Guard { Immutable, Request, RequestNoCors, Response, None, } impl Headers { pub fn new_inherited() -> Headers { Headers { reflector_: Reflector::new(), guard: Guard::None, header_list: DOMRefCell::new(hyper::header::Headers::new()), } } pub fn new(global: GlobalRef) -> Root<Headers> { reflect_dom_object(box Headers::new_inherited(), global, HeadersBinding::Wrap) } } impl HeadersMethods for Headers { // https://fetch.spec.whatwg.org/#concept-headers-append fn Append(&self, name: ByteString, value: ByteString) -> Result<(), Error> { // Step 1 let value = normalize_value(value); // Step 2 let (valid_name, valid_value) = try!(validate_name_and_value(name, value)); // Step 3 if self.guard == Guard::Immutable { return Err(Error::Type("Guard is immutable".to_string())); } // Step 4 if self.guard == Guard::Request && is_forbidden_header_name(&valid_name) { return Ok(()); } // Step 5 if self.guard == Guard::RequestNoCors &&!is_cors_safelisted_request_header(&valid_name) { return Ok(()); } // Step 6 if self.guard == Guard::Response && is_forbidden_response_header(&valid_name) { return Ok(()); } // Step 7 self.header_list.borrow_mut().set_raw(valid_name, vec![valid_value]); return Ok(()); } } // TODO // "Content-Type" once parsed, the value should be // `application/x-www-form-urlencoded`, `multipart/form-data`, // or `text/plain`. // "DPR", "Downlink", "Save-Data", "Viewport-Width", "Width": // once parsed, the value should not be failure. // https://fetch.spec.whatwg.org/#cors-safelisted-request-header fn is_cors_safelisted_request_header(name: &str) -> bool { match name { "accept" | "accept-language" | "content-language" => true, _ => false, } } // https://fetch.spec.whatwg.org/#forbidden-response-header-name fn is_forbidden_response_header(name: &str) -> bool { match name { "set-cookie" | "set-cookie2" => true, _ => false, } } // https://fetch.spec.whatwg.org/#forbidden-header-name pub fn is_forbidden_header_name(name: &str) -> bool { let disallowed_headers = ["accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "date", "dnt", "expect", "host", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding", "upgrade", "via"]; let disallowed_header_prefixes = ["sec-", "proxy-"]; disallowed_headers.iter().any(|header| *header == name) || disallowed_header_prefixes.iter().any(|prefix| name.starts_with(prefix)) } // There is some unresolved confusion over the definition of a name and a value. // The fetch spec [1] defines a name as "a case-insensitive byte // sequence that matches the field-name token production. The token // productions are viewable in [2]." A field-name is defined as a // token, which is defined in [3]. // ISSUE 1: // It defines a value as "a byte sequence that matches the field-content token production." // To note, there is a difference between field-content and // field-value (which is made up of fied-content and obs-fold). The // current definition does not allow for obs-fold (which are white // space and newlines) in values. So perhaps a value should be defined // as "a byte sequence that matches the field-value token production." // However, this would then allow values made up entirely of white space and newlines. // RELATED ISSUE 2: // According to a previously filed Errata ID: 4189 in [4], "the // specified field-value rule does not allow single field-vchar // surrounded by whitespace anywhere". They provided a fix for the // field-content production, but ISSUE 1 has still not been resolved. // The production definitions likely need to be re-written. // [1] https://fetch.spec.whatwg.org/#concept-header-value // [2] https://tools.ietf.org/html/rfc7230#section-3.2 // [3] https://tools.ietf.org/html/rfc7230#section-3.2.6 // [4] https://www.rfc-editor.org/errata_search.php?rfc=7230 fn validate_name_and_value(name: ByteString, value: ByteString) -> Result<(String, Vec<u8>), Error> { if!is_field_name(&name) { return Err(Error::Type("Name is not valid".to_string())); } if!is_field_content(&value) { return Err(Error::Type("Value is not valid".to_string())); } match String::from_utf8(name.into()) { Ok(ns) => Ok((ns, value.into())), _ => Err(Error::Type("Non-UTF8 header name found".to_string())), } } // Removes trailing and leading HTTP whitespace bytes. // https://fetch.spec.whatwg.org/#concept-header-value-normalize pub fn normalize_value(value: ByteString) -> ByteString { match (index_of_first_non_whitespace(&value), index_of_last_non_whitespace(&value)) { (Some(begin), Some(end)) => ByteString::new(value[begin..end + 1].to_owned()), _ => ByteString::new(vec![]), } } fn is_HTTP_whitespace(byte: u8) -> bool { byte == b'\t' || byte == b'\n' || byte == b'\r' || byte == b' ' } fn index_of_first_non_whitespace(value: &ByteString) -> Option<usize> { for (index, &byte) in value.iter().enumerate() { if!is_HTTP_whitespace(byte) { return Some(index); } } None }
for (index, &byte) in value.iter().enumerate().rev() { if!is_HTTP_whitespace(byte) { return Some(index); } } None } // http://tools.ietf.org/html/rfc7230#section-3.2 fn is_field_name(name: &ByteString) -> bool { is_token(&*name) } // https://tools.ietf.org/html/rfc7230#section-3.2 // http://www.rfc-editor.org/errata_search.php?rfc=7230 // Errata ID: 4189 // field-content = field-vchar [ 1*( SP / HTAB / field-vchar ) // field-vchar ] fn is_field_content(value: &ByteString) -> bool { if value.len() == 0 { return false; } if!is_field_vchar(value[0]) { return false; } for &ch in &value[1..value.len() - 1] { if!is_field_vchar(ch) ||!is_space(ch) ||!is_htab(ch) { return false; } } if!is_field_vchar(value[value.len() - 1]) { return false; } return true; } fn is_space(x: u8) -> bool { x == b' ' } fn is_htab(x: u8) -> bool { x == b'\t' } // https://tools.ietf.org/html/rfc7230#section-3.2 fn is_field_vchar(x: u8) -> bool { is_vchar(x) || is_obs_text(x) } // https://tools.ietf.org/html/rfc5234#appendix-B.1 fn is_vchar(x: u8) -> bool { match x { 0x21...0x7E => true, _ => false, } } // http://tools.ietf.org/html/rfc7230#section-3.2.6 fn is_obs_text(x: u8) -> bool { match x { 0x80...0xFF => true, _ => false, } }
fn index_of_last_non_whitespace(value: &ByteString) -> Option<usize> {
random_line_split
headers.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::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HeadersBinding; use dom::bindings::codegen::Bindings::HeadersBinding::HeadersMethods; use dom::bindings::error::Error; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{ByteString, is_token}; use hyper; use std::result::Result; #[dom_struct] pub struct Headers { reflector_: Reflector, guard: Guard, #[ignore_heap_size_of = "Defined in hyper"] header_list: DOMRefCell<hyper::header::Headers> } // https://fetch.spec.whatwg.org/#concept-headers-guard #[derive(JSTraceable, HeapSizeOf, PartialEq)] pub enum Guard { Immutable, Request, RequestNoCors, Response, None, } impl Headers { pub fn new_inherited() -> Headers { Headers { reflector_: Reflector::new(), guard: Guard::None, header_list: DOMRefCell::new(hyper::header::Headers::new()), } } pub fn new(global: GlobalRef) -> Root<Headers> { reflect_dom_object(box Headers::new_inherited(), global, HeadersBinding::Wrap) } } impl HeadersMethods for Headers { // https://fetch.spec.whatwg.org/#concept-headers-append fn Append(&self, name: ByteString, value: ByteString) -> Result<(), Error> { // Step 1 let value = normalize_value(value); // Step 2 let (valid_name, valid_value) = try!(validate_name_and_value(name, value)); // Step 3 if self.guard == Guard::Immutable { return Err(Error::Type("Guard is immutable".to_string())); } // Step 4 if self.guard == Guard::Request && is_forbidden_header_name(&valid_name) { return Ok(()); } // Step 5 if self.guard == Guard::RequestNoCors &&!is_cors_safelisted_request_header(&valid_name) { return Ok(()); } // Step 6 if self.guard == Guard::Response && is_forbidden_response_header(&valid_name) { return Ok(()); } // Step 7 self.header_list.borrow_mut().set_raw(valid_name, vec![valid_value]); return Ok(()); } } // TODO // "Content-Type" once parsed, the value should be // `application/x-www-form-urlencoded`, `multipart/form-data`, // or `text/plain`. // "DPR", "Downlink", "Save-Data", "Viewport-Width", "Width": // once parsed, the value should not be failure. // https://fetch.spec.whatwg.org/#cors-safelisted-request-header fn is_cors_safelisted_request_header(name: &str) -> bool { match name { "accept" | "accept-language" | "content-language" => true, _ => false, } } // https://fetch.spec.whatwg.org/#forbidden-response-header-name fn is_forbidden_response_header(name: &str) -> bool { match name { "set-cookie" | "set-cookie2" => true, _ => false, } } // https://fetch.spec.whatwg.org/#forbidden-header-name pub fn is_forbidden_header_name(name: &str) -> bool { let disallowed_headers = ["accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "date", "dnt", "expect", "host", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding", "upgrade", "via"]; let disallowed_header_prefixes = ["sec-", "proxy-"]; disallowed_headers.iter().any(|header| *header == name) || disallowed_header_prefixes.iter().any(|prefix| name.starts_with(prefix)) } // There is some unresolved confusion over the definition of a name and a value. // The fetch spec [1] defines a name as "a case-insensitive byte // sequence that matches the field-name token production. The token // productions are viewable in [2]." A field-name is defined as a // token, which is defined in [3]. // ISSUE 1: // It defines a value as "a byte sequence that matches the field-content token production." // To note, there is a difference between field-content and // field-value (which is made up of fied-content and obs-fold). The // current definition does not allow for obs-fold (which are white // space and newlines) in values. So perhaps a value should be defined // as "a byte sequence that matches the field-value token production." // However, this would then allow values made up entirely of white space and newlines. // RELATED ISSUE 2: // According to a previously filed Errata ID: 4189 in [4], "the // specified field-value rule does not allow single field-vchar // surrounded by whitespace anywhere". They provided a fix for the // field-content production, but ISSUE 1 has still not been resolved. // The production definitions likely need to be re-written. // [1] https://fetch.spec.whatwg.org/#concept-header-value // [2] https://tools.ietf.org/html/rfc7230#section-3.2 // [3] https://tools.ietf.org/html/rfc7230#section-3.2.6 // [4] https://www.rfc-editor.org/errata_search.php?rfc=7230 fn validate_name_and_value(name: ByteString, value: ByteString) -> Result<(String, Vec<u8>), Error> { if!is_field_name(&name) { return Err(Error::Type("Name is not valid".to_string())); } if!is_field_content(&value) { return Err(Error::Type("Value is not valid".to_string())); } match String::from_utf8(name.into()) { Ok(ns) => Ok((ns, value.into())), _ => Err(Error::Type("Non-UTF8 header name found".to_string())), } } // Removes trailing and leading HTTP whitespace bytes. // https://fetch.spec.whatwg.org/#concept-header-value-normalize pub fn normalize_value(value: ByteString) -> ByteString { match (index_of_first_non_whitespace(&value), index_of_last_non_whitespace(&value)) { (Some(begin), Some(end)) => ByteString::new(value[begin..end + 1].to_owned()), _ => ByteString::new(vec![]), } } fn is_HTTP_whitespace(byte: u8) -> bool { byte == b'\t' || byte == b'\n' || byte == b'\r' || byte == b' ' } fn index_of_first_non_whitespace(value: &ByteString) -> Option<usize> { for (index, &byte) in value.iter().enumerate() { if!is_HTTP_whitespace(byte) { return Some(index); } } None } fn index_of_last_non_whitespace(value: &ByteString) -> Option<usize> { for (index, &byte) in value.iter().enumerate().rev() { if!is_HTTP_whitespace(byte) { return Some(index); } } None } // http://tools.ietf.org/html/rfc7230#section-3.2 fn is_field_name(name: &ByteString) -> bool { is_token(&*name) } // https://tools.ietf.org/html/rfc7230#section-3.2 // http://www.rfc-editor.org/errata_search.php?rfc=7230 // Errata ID: 4189 // field-content = field-vchar [ 1*( SP / HTAB / field-vchar ) // field-vchar ] fn is_field_content(value: &ByteString) -> bool { if value.len() == 0 { return false; } if!is_field_vchar(value[0]) { return false; } for &ch in &value[1..value.len() - 1] { if!is_field_vchar(ch) ||!is_space(ch) ||!is_htab(ch) { return false; } } if!is_field_vchar(value[value.len() - 1]) { return false; } return true; } fn is_space(x: u8) -> bool { x == b' ' } fn is_htab(x: u8) -> bool
// https://tools.ietf.org/html/rfc7230#section-3.2 fn is_field_vchar(x: u8) -> bool { is_vchar(x) || is_obs_text(x) } // https://tools.ietf.org/html/rfc5234#appendix-B.1 fn is_vchar(x: u8) -> bool { match x { 0x21...0x7E => true, _ => false, } } // http://tools.ietf.org/html/rfc7230#section-3.2.6 fn is_obs_text(x: u8) -> bool { match x { 0x80...0xFF => true, _ => false, } }
{ x == b'\t' }
identifier_body
headers.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::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HeadersBinding; use dom::bindings::codegen::Bindings::HeadersBinding::HeadersMethods; use dom::bindings::error::Error; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{ByteString, is_token}; use hyper; use std::result::Result; #[dom_struct] pub struct Headers { reflector_: Reflector, guard: Guard, #[ignore_heap_size_of = "Defined in hyper"] header_list: DOMRefCell<hyper::header::Headers> } // https://fetch.spec.whatwg.org/#concept-headers-guard #[derive(JSTraceable, HeapSizeOf, PartialEq)] pub enum Guard { Immutable, Request, RequestNoCors, Response, None, } impl Headers { pub fn new_inherited() -> Headers { Headers { reflector_: Reflector::new(), guard: Guard::None, header_list: DOMRefCell::new(hyper::header::Headers::new()), } } pub fn new(global: GlobalRef) -> Root<Headers> { reflect_dom_object(box Headers::new_inherited(), global, HeadersBinding::Wrap) } } impl HeadersMethods for Headers { // https://fetch.spec.whatwg.org/#concept-headers-append fn
(&self, name: ByteString, value: ByteString) -> Result<(), Error> { // Step 1 let value = normalize_value(value); // Step 2 let (valid_name, valid_value) = try!(validate_name_and_value(name, value)); // Step 3 if self.guard == Guard::Immutable { return Err(Error::Type("Guard is immutable".to_string())); } // Step 4 if self.guard == Guard::Request && is_forbidden_header_name(&valid_name) { return Ok(()); } // Step 5 if self.guard == Guard::RequestNoCors &&!is_cors_safelisted_request_header(&valid_name) { return Ok(()); } // Step 6 if self.guard == Guard::Response && is_forbidden_response_header(&valid_name) { return Ok(()); } // Step 7 self.header_list.borrow_mut().set_raw(valid_name, vec![valid_value]); return Ok(()); } } // TODO // "Content-Type" once parsed, the value should be // `application/x-www-form-urlencoded`, `multipart/form-data`, // or `text/plain`. // "DPR", "Downlink", "Save-Data", "Viewport-Width", "Width": // once parsed, the value should not be failure. // https://fetch.spec.whatwg.org/#cors-safelisted-request-header fn is_cors_safelisted_request_header(name: &str) -> bool { match name { "accept" | "accept-language" | "content-language" => true, _ => false, } } // https://fetch.spec.whatwg.org/#forbidden-response-header-name fn is_forbidden_response_header(name: &str) -> bool { match name { "set-cookie" | "set-cookie2" => true, _ => false, } } // https://fetch.spec.whatwg.org/#forbidden-header-name pub fn is_forbidden_header_name(name: &str) -> bool { let disallowed_headers = ["accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "date", "dnt", "expect", "host", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding", "upgrade", "via"]; let disallowed_header_prefixes = ["sec-", "proxy-"]; disallowed_headers.iter().any(|header| *header == name) || disallowed_header_prefixes.iter().any(|prefix| name.starts_with(prefix)) } // There is some unresolved confusion over the definition of a name and a value. // The fetch spec [1] defines a name as "a case-insensitive byte // sequence that matches the field-name token production. The token // productions are viewable in [2]." A field-name is defined as a // token, which is defined in [3]. // ISSUE 1: // It defines a value as "a byte sequence that matches the field-content token production." // To note, there is a difference between field-content and // field-value (which is made up of fied-content and obs-fold). The // current definition does not allow for obs-fold (which are white // space and newlines) in values. So perhaps a value should be defined // as "a byte sequence that matches the field-value token production." // However, this would then allow values made up entirely of white space and newlines. // RELATED ISSUE 2: // According to a previously filed Errata ID: 4189 in [4], "the // specified field-value rule does not allow single field-vchar // surrounded by whitespace anywhere". They provided a fix for the // field-content production, but ISSUE 1 has still not been resolved. // The production definitions likely need to be re-written. // [1] https://fetch.spec.whatwg.org/#concept-header-value // [2] https://tools.ietf.org/html/rfc7230#section-3.2 // [3] https://tools.ietf.org/html/rfc7230#section-3.2.6 // [4] https://www.rfc-editor.org/errata_search.php?rfc=7230 fn validate_name_and_value(name: ByteString, value: ByteString) -> Result<(String, Vec<u8>), Error> { if!is_field_name(&name) { return Err(Error::Type("Name is not valid".to_string())); } if!is_field_content(&value) { return Err(Error::Type("Value is not valid".to_string())); } match String::from_utf8(name.into()) { Ok(ns) => Ok((ns, value.into())), _ => Err(Error::Type("Non-UTF8 header name found".to_string())), } } // Removes trailing and leading HTTP whitespace bytes. // https://fetch.spec.whatwg.org/#concept-header-value-normalize pub fn normalize_value(value: ByteString) -> ByteString { match (index_of_first_non_whitespace(&value), index_of_last_non_whitespace(&value)) { (Some(begin), Some(end)) => ByteString::new(value[begin..end + 1].to_owned()), _ => ByteString::new(vec![]), } } fn is_HTTP_whitespace(byte: u8) -> bool { byte == b'\t' || byte == b'\n' || byte == b'\r' || byte == b' ' } fn index_of_first_non_whitespace(value: &ByteString) -> Option<usize> { for (index, &byte) in value.iter().enumerate() { if!is_HTTP_whitespace(byte) { return Some(index); } } None } fn index_of_last_non_whitespace(value: &ByteString) -> Option<usize> { for (index, &byte) in value.iter().enumerate().rev() { if!is_HTTP_whitespace(byte) { return Some(index); } } None } // http://tools.ietf.org/html/rfc7230#section-3.2 fn is_field_name(name: &ByteString) -> bool { is_token(&*name) } // https://tools.ietf.org/html/rfc7230#section-3.2 // http://www.rfc-editor.org/errata_search.php?rfc=7230 // Errata ID: 4189 // field-content = field-vchar [ 1*( SP / HTAB / field-vchar ) // field-vchar ] fn is_field_content(value: &ByteString) -> bool { if value.len() == 0 { return false; } if!is_field_vchar(value[0]) { return false; } for &ch in &value[1..value.len() - 1] { if!is_field_vchar(ch) ||!is_space(ch) ||!is_htab(ch) { return false; } } if!is_field_vchar(value[value.len() - 1]) { return false; } return true; } fn is_space(x: u8) -> bool { x == b' ' } fn is_htab(x: u8) -> bool { x == b'\t' } // https://tools.ietf.org/html/rfc7230#section-3.2 fn is_field_vchar(x: u8) -> bool { is_vchar(x) || is_obs_text(x) } // https://tools.ietf.org/html/rfc5234#appendix-B.1 fn is_vchar(x: u8) -> bool { match x { 0x21...0x7E => true, _ => false, } } // http://tools.ietf.org/html/rfc7230#section-3.2.6 fn is_obs_text(x: u8) -> bool { match x { 0x80...0xFF => true, _ => false, } }
Append
identifier_name
promisenativehandler.rs
/* This Source Code Form is subject to the terms of the Mozilla Public
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::bindings::trace::JSTraceable; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{JSContext, HandleValue}; use malloc_size_of::MallocSizeOf; pub trait Callback: JSTraceable + MallocSizeOf { fn callback(&self, cx: *mut JSContext, v: HandleValue); } #[dom_struct] pub struct PromiseNativeHandler { reflector: Reflector, resolve: Option<Box<Callback>>, reject: Option<Box<Callback>>, } impl PromiseNativeHandler { pub fn new(global: &GlobalScope, resolve: Option<Box<Callback>>, reject: Option<Box<Callback>>) -> DomRoot<PromiseNativeHandler> { reflect_dom_object(Box::new(PromiseNativeHandler { reflector: Reflector::new(), resolve: resolve, reject: reject, }), global, PromiseNativeHandlerBinding::Wrap) } fn callback(callback: &Option<Box<Callback>>, cx: *mut JSContext, v: HandleValue) { if let Some(ref callback) = *callback { callback.callback(cx, v) } } pub fn resolved_callback(&self, cx: *mut JSContext, v: HandleValue) { PromiseNativeHandler::callback(&self.resolve, cx, v) } pub fn rejected_callback(&self, cx: *mut JSContext, v: HandleValue) { PromiseNativeHandler::callback(&self.reject, cx, v) } }
* 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::PromiseNativeHandlerBinding;
random_line_split
promisenativehandler.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::PromiseNativeHandlerBinding; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::bindings::trace::JSTraceable; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{JSContext, HandleValue}; use malloc_size_of::MallocSizeOf; pub trait Callback: JSTraceable + MallocSizeOf { fn callback(&self, cx: *mut JSContext, v: HandleValue); } #[dom_struct] pub struct PromiseNativeHandler { reflector: Reflector, resolve: Option<Box<Callback>>, reject: Option<Box<Callback>>, } impl PromiseNativeHandler { pub fn new(global: &GlobalScope, resolve: Option<Box<Callback>>, reject: Option<Box<Callback>>) -> DomRoot<PromiseNativeHandler>
fn callback(callback: &Option<Box<Callback>>, cx: *mut JSContext, v: HandleValue) { if let Some(ref callback) = *callback { callback.callback(cx, v) } } pub fn resolved_callback(&self, cx: *mut JSContext, v: HandleValue) { PromiseNativeHandler::callback(&self.resolve, cx, v) } pub fn rejected_callback(&self, cx: *mut JSContext, v: HandleValue) { PromiseNativeHandler::callback(&self.reject, cx, v) } }
{ reflect_dom_object(Box::new(PromiseNativeHandler { reflector: Reflector::new(), resolve: resolve, reject: reject, }), global, PromiseNativeHandlerBinding::Wrap) }
identifier_body
promisenativehandler.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::PromiseNativeHandlerBinding; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::bindings::trace::JSTraceable; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{JSContext, HandleValue}; use malloc_size_of::MallocSizeOf; pub trait Callback: JSTraceable + MallocSizeOf { fn callback(&self, cx: *mut JSContext, v: HandleValue); } #[dom_struct] pub struct
{ reflector: Reflector, resolve: Option<Box<Callback>>, reject: Option<Box<Callback>>, } impl PromiseNativeHandler { pub fn new(global: &GlobalScope, resolve: Option<Box<Callback>>, reject: Option<Box<Callback>>) -> DomRoot<PromiseNativeHandler> { reflect_dom_object(Box::new(PromiseNativeHandler { reflector: Reflector::new(), resolve: resolve, reject: reject, }), global, PromiseNativeHandlerBinding::Wrap) } fn callback(callback: &Option<Box<Callback>>, cx: *mut JSContext, v: HandleValue) { if let Some(ref callback) = *callback { callback.callback(cx, v) } } pub fn resolved_callback(&self, cx: *mut JSContext, v: HandleValue) { PromiseNativeHandler::callback(&self.resolve, cx, v) } pub fn rejected_callback(&self, cx: *mut JSContext, v: HandleValue) { PromiseNativeHandler::callback(&self.reject, cx, v) } }
PromiseNativeHandler
identifier_name
promisenativehandler.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::PromiseNativeHandlerBinding; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::bindings::trace::JSTraceable; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{JSContext, HandleValue}; use malloc_size_of::MallocSizeOf; pub trait Callback: JSTraceable + MallocSizeOf { fn callback(&self, cx: *mut JSContext, v: HandleValue); } #[dom_struct] pub struct PromiseNativeHandler { reflector: Reflector, resolve: Option<Box<Callback>>, reject: Option<Box<Callback>>, } impl PromiseNativeHandler { pub fn new(global: &GlobalScope, resolve: Option<Box<Callback>>, reject: Option<Box<Callback>>) -> DomRoot<PromiseNativeHandler> { reflect_dom_object(Box::new(PromiseNativeHandler { reflector: Reflector::new(), resolve: resolve, reject: reject, }), global, PromiseNativeHandlerBinding::Wrap) } fn callback(callback: &Option<Box<Callback>>, cx: *mut JSContext, v: HandleValue) { if let Some(ref callback) = *callback
} pub fn resolved_callback(&self, cx: *mut JSContext, v: HandleValue) { PromiseNativeHandler::callback(&self.resolve, cx, v) } pub fn rejected_callback(&self, cx: *mut JSContext, v: HandleValue) { PromiseNativeHandler::callback(&self.reject, cx, v) } }
{ callback.callback(cx, v) }
conditional_block
grid.rs
use colours::Colours; use file::File; use filetype::file_colour; use term_grid as grid; #[derive(PartialEq, Debug, Copy, Clone)] pub struct Grid { pub across: bool, pub console_width: usize, pub colours: Colours, } impl Grid { pub fn view(&self, files: &[File]) { let direction = if self.across { grid::Direction::LeftToRight } else { grid::Direction::TopToBottom }; let mut grid = grid::Grid::new(grid::GridOptions { direction: direction, filling: grid::Filling::Spaces(2), }); grid.reserve(files.len()); for file in files.iter() { grid.add(grid::Cell { contents: file_colour(&self.colours, file).paint(&file.name).to_string(), width: file.file_name_width(), }); } if let Some(display) = grid.fit_into_width(self.console_width) { print!("{}", display); } else
} }
{ // File names too long for a grid - drop down to just listing them! for file in files.iter() { println!("{}", file_colour(&self.colours, file).paint(&file.name)); } }
conditional_block
grid.rs
use colours::Colours; use file::File; use filetype::file_colour; use term_grid as grid; #[derive(PartialEq, Debug, Copy, Clone)] pub struct
{ pub across: bool, pub console_width: usize, pub colours: Colours, } impl Grid { pub fn view(&self, files: &[File]) { let direction = if self.across { grid::Direction::LeftToRight } else { grid::Direction::TopToBottom }; let mut grid = grid::Grid::new(grid::GridOptions { direction: direction, filling: grid::Filling::Spaces(2), }); grid.reserve(files.len()); for file in files.iter() { grid.add(grid::Cell { contents: file_colour(&self.colours, file).paint(&file.name).to_string(), width: file.file_name_width(), }); } if let Some(display) = grid.fit_into_width(self.console_width) { print!("{}", display); } else { // File names too long for a grid - drop down to just listing them! for file in files.iter() { println!("{}", file_colour(&self.colours, file).paint(&file.name)); } } } }
Grid
identifier_name
grid.rs
use colours::Colours; use file::File; use filetype::file_colour; use term_grid as grid; #[derive(PartialEq, Debug, Copy, Clone)] pub struct Grid { pub across: bool, pub console_width: usize, pub colours: Colours, } impl Grid { pub fn view(&self, files: &[File]) { let direction = if self.across { grid::Direction::LeftToRight } else { grid::Direction::TopToBottom }; let mut grid = grid::Grid::new(grid::GridOptions { direction: direction, filling: grid::Filling::Spaces(2), }); grid.reserve(files.len()); for file in files.iter() { grid.add(grid::Cell { contents: file_colour(&self.colours, file).paint(&file.name).to_string(), width: file.file_name_width(), }); }
if let Some(display) = grid.fit_into_width(self.console_width) { print!("{}", display); } else { // File names too long for a grid - drop down to just listing them! for file in files.iter() { println!("{}", file_colour(&self.colours, file).paint(&file.name)); } } } }
random_line_split
grid.rs
use colours::Colours; use file::File; use filetype::file_colour; use term_grid as grid; #[derive(PartialEq, Debug, Copy, Clone)] pub struct Grid { pub across: bool, pub console_width: usize, pub colours: Colours, } impl Grid { pub fn view(&self, files: &[File])
} else { // File names too long for a grid - drop down to just listing them! for file in files.iter() { println!("{}", file_colour(&self.colours, file).paint(&file.name)); } } } }
{ let direction = if self.across { grid::Direction::LeftToRight } else { grid::Direction::TopToBottom }; let mut grid = grid::Grid::new(grid::GridOptions { direction: direction, filling: grid::Filling::Spaces(2), }); grid.reserve(files.len()); for file in files.iter() { grid.add(grid::Cell { contents: file_colour(&self.colours, file).paint(&file.name).to_string(), width: file.file_name_width(), }); } if let Some(display) = grid.fit_into_width(self.console_width) { print!("{}", display);
identifier_body
lib.rs
// ================================================================= // // * WARNING * // // This file is generated! // // Changes made to this file will be overwritten. If changes are // required to the generated code, the service_crategen project // must be updated to generate the changes. // // ================================================================= #![doc(html_logo_url = "https://raw.githubusercontent.com/rusoto/rusoto/master/assets/logo-square.png")] //! <p>AWS X-Ray provides APIs for managing debug traces and retrieving service maps and other data created by processing those traces.</p> //! //! If you're using the service, you're probably looking for [XRayClient](struct.XRayClient.html) and [XRay](trait.XRay.html). extern crate futures; #[macro_use] extern crate log; extern crate rusoto_core;
extern crate serde_json; mod generated; mod custom; pub use generated::*; pub use custom::*;
extern crate serde; #[macro_use] extern crate serde_derive;
random_line_split
reg_status.rs
#[derive(Debug, Clone)] pub struct RegStatus { pub carry: bool, pub zero: bool, pub interrupt_disable: bool, pub decimal: bool, pub break_command: bool, expansion: bool, pub overflow: bool, pub negative: bool, } impl From<u8> for RegStatus { fn from(value: u8) -> Self { RegStatus{ carry: (value & 1)!= 0, zero: (value & (1 << 1))!= 0, interrupt_disable: (value & (1 << 2))!= 0, decimal: (value & (1 << 3))!= 0, break_command: (value & (1 << 4))!= 0, expansion: true, overflow: (value & (1 << 6))!= 0, negative: (value & (1 << 7))!= 0, } } } impl Into<u8> for RegStatus { fn into(self) -> u8 { let mut ret = 0; if self.carry { ret |= 1; } if self.zero { ret |= 1 << 1; } if self.interrupt_disable { ret |= 1 << 2; } if self.decimal { ret |= 1 << 3; } if self.break_command { ret |= 1 << 4; } if self.expansion { ret |= 1 << 5; } if self.overflow
if self.negative { ret |= 1 << 7; } ret } }
{ ret |= 1 << 6; }
conditional_block
reg_status.rs
#[derive(Debug, Clone)] pub struct
{ pub carry: bool, pub zero: bool, pub interrupt_disable: bool, pub decimal: bool, pub break_command: bool, expansion: bool, pub overflow: bool, pub negative: bool, } impl From<u8> for RegStatus { fn from(value: u8) -> Self { RegStatus{ carry: (value & 1)!= 0, zero: (value & (1 << 1))!= 0, interrupt_disable: (value & (1 << 2))!= 0, decimal: (value & (1 << 3))!= 0, break_command: (value & (1 << 4))!= 0, expansion: true, overflow: (value & (1 << 6))!= 0, negative: (value & (1 << 7))!= 0, } } } impl Into<u8> for RegStatus { fn into(self) -> u8 { let mut ret = 0; if self.carry { ret |= 1; } if self.zero { ret |= 1 << 1; } if self.interrupt_disable { ret |= 1 << 2; } if self.decimal { ret |= 1 << 3; } if self.break_command { ret |= 1 << 4; } if self.expansion { ret |= 1 << 5; } if self.overflow { ret |= 1 << 6; } if self.negative { ret |= 1 << 7; } ret } }
RegStatus
identifier_name
reg_status.rs
#[derive(Debug, Clone)] pub struct RegStatus { pub carry: bool,
pub decimal: bool, pub break_command: bool, expansion: bool, pub overflow: bool, pub negative: bool, } impl From<u8> for RegStatus { fn from(value: u8) -> Self { RegStatus{ carry: (value & 1)!= 0, zero: (value & (1 << 1))!= 0, interrupt_disable: (value & (1 << 2))!= 0, decimal: (value & (1 << 3))!= 0, break_command: (value & (1 << 4))!= 0, expansion: true, overflow: (value & (1 << 6))!= 0, negative: (value & (1 << 7))!= 0, } } } impl Into<u8> for RegStatus { fn into(self) -> u8 { let mut ret = 0; if self.carry { ret |= 1; } if self.zero { ret |= 1 << 1; } if self.interrupt_disable { ret |= 1 << 2; } if self.decimal { ret |= 1 << 3; } if self.break_command { ret |= 1 << 4; } if self.expansion { ret |= 1 << 5; } if self.overflow { ret |= 1 << 6; } if self.negative { ret |= 1 << 7; } ret } }
pub zero: bool, pub interrupt_disable: bool,
random_line_split
fs2.rs
// Copyright 2013-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. use core::prelude::*; use io::prelude::*; use os::unix::prelude::*; use ffi::{self, CString, OsString, AsOsStr, OsStr}; use io::{self, Error, Seek, SeekFrom}; use libc::{self, c_int, c_void, size_t, off_t, c_char, mode_t}; use mem; use path::{Path, PathBuf}; use ptr; use rc::Rc; use sys::fd::FileDesc; use sys::{c, cvt, cvt_r}; use sys_common::FromInner; use vec::Vec; pub struct File(FileDesc); pub struct FileAttr { stat: libc::stat, } pub struct ReadDir { dirp: *mut libc::DIR, root: Rc<PathBuf>, } pub struct DirEntry { buf: Vec<u8>, dirent: *mut libc::dirent_t, root: Rc<PathBuf>, } #[derive(Clone)] pub struct OpenOptions { flags: c_int, read: bool, write: bool, mode: mode_t, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct FilePermissions { mode: mode_t } impl FileAttr { pub fn is_dir(&self) -> bool { (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFDIR } pub fn is_file(&self) -> bool { (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFREG } pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 } } pub fn accessed(&self) -> u64 { self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64) } pub fn modified(&self) -> u64 { self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64) } // times are in milliseconds (currently) fn mktime(&self, secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 } } impl FilePermissions { pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 } pub fn set_readonly(&mut self, readonly: bool) { if readonly { self.mode &=!0o222; } else { self.mode |= 0o222; } } } impl FromInner<i32> for FilePermissions { fn from_inner(mode: i32) -> FilePermissions { FilePermissions { mode: mode as mode_t } } } impl Iterator for ReadDir { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<io::Result<DirEntry>> { extern { fn rust_dirent_t_size() -> c_int; } let mut buf: Vec<u8> = Vec::with_capacity(unsafe { rust_dirent_t_size() as usize }); let ptr = buf.as_mut_ptr() as *mut libc::dirent_t; let mut entry_ptr = ptr::null_mut(); loop { if unsafe { libc::readdir_r(self.dirp, ptr, &mut entry_ptr)!= 0 } { return Some(Err(Error::last_os_error())) } if entry_ptr.is_null() { return None } let entry = DirEntry { buf: buf, dirent: entry_ptr, root: self.root.clone() }; if entry.name_bytes() == b"." || entry.name_bytes() == b".." { buf = entry.buf; } else { return Some(Ok(entry)) } } } } impl Drop for ReadDir { fn drop(&mut self) { let r = unsafe { libc::closedir(self.dirp) }; debug_assert_eq!(r, 0); } } impl DirEntry { pub fn path(&self) -> PathBuf
fn name_bytes(&self) -> &[u8] { extern { fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char; } unsafe { let ptr = rust_list_dir_val(self.dirent); ffi::c_str_to_bytes(mem::copy_lifetime(self, &ptr)) } } } impl OpenOptions { pub fn new() -> OpenOptions { OpenOptions { flags: 0, read: false, write: false, mode: 0o666, } } pub fn read(&mut self, read: bool) { self.read = read; } pub fn write(&mut self, write: bool) { self.write = write; } pub fn append(&mut self, append: bool) { self.flag(libc::O_APPEND, append); } pub fn truncate(&mut self, truncate: bool) { self.flag(libc::O_TRUNC, truncate); } pub fn create(&mut self, create: bool) { self.flag(libc::O_CREAT, create); } pub fn mode(&mut self, mode: i32) { self.mode = mode as mode_t; } fn flag(&mut self, bit: c_int, on: bool) { if on { self.flags |= bit; } else { self.flags &=!bit; } } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let flags = opts.flags | match (opts.read, opts.write) { (true, true) => libc::O_RDWR, (false, true) => libc::O_WRONLY, (true, false) | (false, false) => libc::O_RDONLY, }; let path = cstr(path); let fd = try!(cvt_r(|| unsafe { libc::open(path.as_ptr(), flags, opts.mode) })); Ok(File(FileDesc::new(fd))) } pub fn file_attr(&self) -> io::Result<FileAttr> { let mut stat: libc::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat) })); Ok(FileAttr { stat: stat }) } pub fn fsync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) })); Ok(()) } pub fn datasync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) })); return Ok(()); #[cfg(any(target_os = "macos", target_os = "ios"))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(target_os = "linux")] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) } #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } } pub fn truncate(&self, size: u64) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::ftruncate(self.0.raw(), size as libc::off_t) })); Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t), SeekFrom::End(off) => (libc::SEEK_END, off as off_t), SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t), }; let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) })); Ok(n as u64) } pub fn fd(&self) -> &FileDesc { &self.0 } } fn cstr(path: &Path) -> CString { CString::from_slice(path.as_os_str().as_bytes()) } pub fn mkdir(p: &Path) -> io::Result<()> { let p = cstr(p); try!(cvt(unsafe { libc::mkdir(p.as_ptr(), 0o777) })); Ok(()) } pub fn readdir(p: &Path) -> io::Result<ReadDir> { let root = Rc::new(p.to_path_buf()); let p = cstr(p); unsafe { let ptr = libc::opendir(p.as_ptr()); if ptr.is_null() { Err(Error::last_os_error()) } else { Ok(ReadDir { dirp: ptr, root: root }) } } } pub fn unlink(p: &Path) -> io::Result<()> { let p = cstr(p); try!(cvt(unsafe { libc::unlink(p.as_ptr()) })); Ok(()) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let old = cstr(old); let new = cstr(new); try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })); Ok(()) } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { let p = cstr(p); try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })); Ok(()) } pub fn rmdir(p: &Path) -> io::Result<()> { let p = cstr(p); try!(cvt(unsafe { libc::rmdir(p.as_ptr()) })); Ok(()) } pub fn chown(p: &Path, uid: isize, gid: isize) -> io::Result<()> { let p = cstr(p); try!(cvt_r(|| unsafe { libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })); Ok(()) } pub fn readlink(p: &Path) -> io::Result<PathBuf> { let c_path = cstr(p); let p = c_path.as_ptr(); let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) }; if len < 0 { len = 1024; // FIXME: read PATH_MAX from C ffi? } let mut buf: Vec<u8> = Vec::with_capacity(len as usize); unsafe { let n = try!(cvt({ libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t) })); buf.set_len(n as usize); } let s: OsString = OsStringExt::from_vec(buf); Ok(PathBuf::new(&s)) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { let src = cstr(src); let dst = cstr(dst); try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn link(src: &Path, dst: &Path) -> io::Result<()> { let src = cstr(src); let dst = cstr(dst); try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn stat(p: &Path) -> io::Result<FileAttr> { let p = cstr(p); let mut stat: libc::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat) })); Ok(FileAttr { stat: stat }) } pub fn lstat(p: &Path) -> io::Result<FileAttr> { let p = cstr(p); let mut stat: libc::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat) })); Ok(FileAttr { stat: stat }) } pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> { let p = cstr(p); let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)]; try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) })); Ok(()) }
{ self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes())) }
identifier_body
fs2.rs
// Copyright 2013-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. use core::prelude::*; use io::prelude::*; use os::unix::prelude::*; use ffi::{self, CString, OsString, AsOsStr, OsStr}; use io::{self, Error, Seek, SeekFrom}; use libc::{self, c_int, c_void, size_t, off_t, c_char, mode_t}; use mem; use path::{Path, PathBuf};
use sys_common::FromInner; use vec::Vec; pub struct File(FileDesc); pub struct FileAttr { stat: libc::stat, } pub struct ReadDir { dirp: *mut libc::DIR, root: Rc<PathBuf>, } pub struct DirEntry { buf: Vec<u8>, dirent: *mut libc::dirent_t, root: Rc<PathBuf>, } #[derive(Clone)] pub struct OpenOptions { flags: c_int, read: bool, write: bool, mode: mode_t, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct FilePermissions { mode: mode_t } impl FileAttr { pub fn is_dir(&self) -> bool { (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFDIR } pub fn is_file(&self) -> bool { (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFREG } pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 } } pub fn accessed(&self) -> u64 { self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64) } pub fn modified(&self) -> u64 { self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64) } // times are in milliseconds (currently) fn mktime(&self, secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 } } impl FilePermissions { pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 } pub fn set_readonly(&mut self, readonly: bool) { if readonly { self.mode &=!0o222; } else { self.mode |= 0o222; } } } impl FromInner<i32> for FilePermissions { fn from_inner(mode: i32) -> FilePermissions { FilePermissions { mode: mode as mode_t } } } impl Iterator for ReadDir { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<io::Result<DirEntry>> { extern { fn rust_dirent_t_size() -> c_int; } let mut buf: Vec<u8> = Vec::with_capacity(unsafe { rust_dirent_t_size() as usize }); let ptr = buf.as_mut_ptr() as *mut libc::dirent_t; let mut entry_ptr = ptr::null_mut(); loop { if unsafe { libc::readdir_r(self.dirp, ptr, &mut entry_ptr)!= 0 } { return Some(Err(Error::last_os_error())) } if entry_ptr.is_null() { return None } let entry = DirEntry { buf: buf, dirent: entry_ptr, root: self.root.clone() }; if entry.name_bytes() == b"." || entry.name_bytes() == b".." { buf = entry.buf; } else { return Some(Ok(entry)) } } } } impl Drop for ReadDir { fn drop(&mut self) { let r = unsafe { libc::closedir(self.dirp) }; debug_assert_eq!(r, 0); } } impl DirEntry { pub fn path(&self) -> PathBuf { self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes())) } fn name_bytes(&self) -> &[u8] { extern { fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char; } unsafe { let ptr = rust_list_dir_val(self.dirent); ffi::c_str_to_bytes(mem::copy_lifetime(self, &ptr)) } } } impl OpenOptions { pub fn new() -> OpenOptions { OpenOptions { flags: 0, read: false, write: false, mode: 0o666, } } pub fn read(&mut self, read: bool) { self.read = read; } pub fn write(&mut self, write: bool) { self.write = write; } pub fn append(&mut self, append: bool) { self.flag(libc::O_APPEND, append); } pub fn truncate(&mut self, truncate: bool) { self.flag(libc::O_TRUNC, truncate); } pub fn create(&mut self, create: bool) { self.flag(libc::O_CREAT, create); } pub fn mode(&mut self, mode: i32) { self.mode = mode as mode_t; } fn flag(&mut self, bit: c_int, on: bool) { if on { self.flags |= bit; } else { self.flags &=!bit; } } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let flags = opts.flags | match (opts.read, opts.write) { (true, true) => libc::O_RDWR, (false, true) => libc::O_WRONLY, (true, false) | (false, false) => libc::O_RDONLY, }; let path = cstr(path); let fd = try!(cvt_r(|| unsafe { libc::open(path.as_ptr(), flags, opts.mode) })); Ok(File(FileDesc::new(fd))) } pub fn file_attr(&self) -> io::Result<FileAttr> { let mut stat: libc::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat) })); Ok(FileAttr { stat: stat }) } pub fn fsync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) })); Ok(()) } pub fn datasync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) })); return Ok(()); #[cfg(any(target_os = "macos", target_os = "ios"))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(target_os = "linux")] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) } #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } } pub fn truncate(&self, size: u64) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::ftruncate(self.0.raw(), size as libc::off_t) })); Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t), SeekFrom::End(off) => (libc::SEEK_END, off as off_t), SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t), }; let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) })); Ok(n as u64) } pub fn fd(&self) -> &FileDesc { &self.0 } } fn cstr(path: &Path) -> CString { CString::from_slice(path.as_os_str().as_bytes()) } pub fn mkdir(p: &Path) -> io::Result<()> { let p = cstr(p); try!(cvt(unsafe { libc::mkdir(p.as_ptr(), 0o777) })); Ok(()) } pub fn readdir(p: &Path) -> io::Result<ReadDir> { let root = Rc::new(p.to_path_buf()); let p = cstr(p); unsafe { let ptr = libc::opendir(p.as_ptr()); if ptr.is_null() { Err(Error::last_os_error()) } else { Ok(ReadDir { dirp: ptr, root: root }) } } } pub fn unlink(p: &Path) -> io::Result<()> { let p = cstr(p); try!(cvt(unsafe { libc::unlink(p.as_ptr()) })); Ok(()) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let old = cstr(old); let new = cstr(new); try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })); Ok(()) } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { let p = cstr(p); try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })); Ok(()) } pub fn rmdir(p: &Path) -> io::Result<()> { let p = cstr(p); try!(cvt(unsafe { libc::rmdir(p.as_ptr()) })); Ok(()) } pub fn chown(p: &Path, uid: isize, gid: isize) -> io::Result<()> { let p = cstr(p); try!(cvt_r(|| unsafe { libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })); Ok(()) } pub fn readlink(p: &Path) -> io::Result<PathBuf> { let c_path = cstr(p); let p = c_path.as_ptr(); let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) }; if len < 0 { len = 1024; // FIXME: read PATH_MAX from C ffi? } let mut buf: Vec<u8> = Vec::with_capacity(len as usize); unsafe { let n = try!(cvt({ libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t) })); buf.set_len(n as usize); } let s: OsString = OsStringExt::from_vec(buf); Ok(PathBuf::new(&s)) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { let src = cstr(src); let dst = cstr(dst); try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn link(src: &Path, dst: &Path) -> io::Result<()> { let src = cstr(src); let dst = cstr(dst); try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn stat(p: &Path) -> io::Result<FileAttr> { let p = cstr(p); let mut stat: libc::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat) })); Ok(FileAttr { stat: stat }) } pub fn lstat(p: &Path) -> io::Result<FileAttr> { let p = cstr(p); let mut stat: libc::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat) })); Ok(FileAttr { stat: stat }) } pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> { let p = cstr(p); let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)]; try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) })); Ok(()) }
use ptr; use rc::Rc; use sys::fd::FileDesc; use sys::{c, cvt, cvt_r};
random_line_split
fs2.rs
// Copyright 2013-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. use core::prelude::*; use io::prelude::*; use os::unix::prelude::*; use ffi::{self, CString, OsString, AsOsStr, OsStr}; use io::{self, Error, Seek, SeekFrom}; use libc::{self, c_int, c_void, size_t, off_t, c_char, mode_t}; use mem; use path::{Path, PathBuf}; use ptr; use rc::Rc; use sys::fd::FileDesc; use sys::{c, cvt, cvt_r}; use sys_common::FromInner; use vec::Vec; pub struct File(FileDesc); pub struct FileAttr { stat: libc::stat, } pub struct ReadDir { dirp: *mut libc::DIR, root: Rc<PathBuf>, } pub struct DirEntry { buf: Vec<u8>, dirent: *mut libc::dirent_t, root: Rc<PathBuf>, } #[derive(Clone)] pub struct OpenOptions { flags: c_int, read: bool, write: bool, mode: mode_t, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct
{ mode: mode_t } impl FileAttr { pub fn is_dir(&self) -> bool { (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFDIR } pub fn is_file(&self) -> bool { (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFREG } pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 } } pub fn accessed(&self) -> u64 { self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64) } pub fn modified(&self) -> u64 { self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64) } // times are in milliseconds (currently) fn mktime(&self, secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 } } impl FilePermissions { pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 } pub fn set_readonly(&mut self, readonly: bool) { if readonly { self.mode &=!0o222; } else { self.mode |= 0o222; } } } impl FromInner<i32> for FilePermissions { fn from_inner(mode: i32) -> FilePermissions { FilePermissions { mode: mode as mode_t } } } impl Iterator for ReadDir { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<io::Result<DirEntry>> { extern { fn rust_dirent_t_size() -> c_int; } let mut buf: Vec<u8> = Vec::with_capacity(unsafe { rust_dirent_t_size() as usize }); let ptr = buf.as_mut_ptr() as *mut libc::dirent_t; let mut entry_ptr = ptr::null_mut(); loop { if unsafe { libc::readdir_r(self.dirp, ptr, &mut entry_ptr)!= 0 } { return Some(Err(Error::last_os_error())) } if entry_ptr.is_null() { return None } let entry = DirEntry { buf: buf, dirent: entry_ptr, root: self.root.clone() }; if entry.name_bytes() == b"." || entry.name_bytes() == b".." { buf = entry.buf; } else { return Some(Ok(entry)) } } } } impl Drop for ReadDir { fn drop(&mut self) { let r = unsafe { libc::closedir(self.dirp) }; debug_assert_eq!(r, 0); } } impl DirEntry { pub fn path(&self) -> PathBuf { self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes())) } fn name_bytes(&self) -> &[u8] { extern { fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char; } unsafe { let ptr = rust_list_dir_val(self.dirent); ffi::c_str_to_bytes(mem::copy_lifetime(self, &ptr)) } } } impl OpenOptions { pub fn new() -> OpenOptions { OpenOptions { flags: 0, read: false, write: false, mode: 0o666, } } pub fn read(&mut self, read: bool) { self.read = read; } pub fn write(&mut self, write: bool) { self.write = write; } pub fn append(&mut self, append: bool) { self.flag(libc::O_APPEND, append); } pub fn truncate(&mut self, truncate: bool) { self.flag(libc::O_TRUNC, truncate); } pub fn create(&mut self, create: bool) { self.flag(libc::O_CREAT, create); } pub fn mode(&mut self, mode: i32) { self.mode = mode as mode_t; } fn flag(&mut self, bit: c_int, on: bool) { if on { self.flags |= bit; } else { self.flags &=!bit; } } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let flags = opts.flags | match (opts.read, opts.write) { (true, true) => libc::O_RDWR, (false, true) => libc::O_WRONLY, (true, false) | (false, false) => libc::O_RDONLY, }; let path = cstr(path); let fd = try!(cvt_r(|| unsafe { libc::open(path.as_ptr(), flags, opts.mode) })); Ok(File(FileDesc::new(fd))) } pub fn file_attr(&self) -> io::Result<FileAttr> { let mut stat: libc::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat) })); Ok(FileAttr { stat: stat }) } pub fn fsync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) })); Ok(()) } pub fn datasync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) })); return Ok(()); #[cfg(any(target_os = "macos", target_os = "ios"))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(target_os = "linux")] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) } #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } } pub fn truncate(&self, size: u64) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::ftruncate(self.0.raw(), size as libc::off_t) })); Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t), SeekFrom::End(off) => (libc::SEEK_END, off as off_t), SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t), }; let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) })); Ok(n as u64) } pub fn fd(&self) -> &FileDesc { &self.0 } } fn cstr(path: &Path) -> CString { CString::from_slice(path.as_os_str().as_bytes()) } pub fn mkdir(p: &Path) -> io::Result<()> { let p = cstr(p); try!(cvt(unsafe { libc::mkdir(p.as_ptr(), 0o777) })); Ok(()) } pub fn readdir(p: &Path) -> io::Result<ReadDir> { let root = Rc::new(p.to_path_buf()); let p = cstr(p); unsafe { let ptr = libc::opendir(p.as_ptr()); if ptr.is_null() { Err(Error::last_os_error()) } else { Ok(ReadDir { dirp: ptr, root: root }) } } } pub fn unlink(p: &Path) -> io::Result<()> { let p = cstr(p); try!(cvt(unsafe { libc::unlink(p.as_ptr()) })); Ok(()) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let old = cstr(old); let new = cstr(new); try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })); Ok(()) } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { let p = cstr(p); try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })); Ok(()) } pub fn rmdir(p: &Path) -> io::Result<()> { let p = cstr(p); try!(cvt(unsafe { libc::rmdir(p.as_ptr()) })); Ok(()) } pub fn chown(p: &Path, uid: isize, gid: isize) -> io::Result<()> { let p = cstr(p); try!(cvt_r(|| unsafe { libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })); Ok(()) } pub fn readlink(p: &Path) -> io::Result<PathBuf> { let c_path = cstr(p); let p = c_path.as_ptr(); let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) }; if len < 0 { len = 1024; // FIXME: read PATH_MAX from C ffi? } let mut buf: Vec<u8> = Vec::with_capacity(len as usize); unsafe { let n = try!(cvt({ libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t) })); buf.set_len(n as usize); } let s: OsString = OsStringExt::from_vec(buf); Ok(PathBuf::new(&s)) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { let src = cstr(src); let dst = cstr(dst); try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn link(src: &Path, dst: &Path) -> io::Result<()> { let src = cstr(src); let dst = cstr(dst); try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn stat(p: &Path) -> io::Result<FileAttr> { let p = cstr(p); let mut stat: libc::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat) })); Ok(FileAttr { stat: stat }) } pub fn lstat(p: &Path) -> io::Result<FileAttr> { let p = cstr(p); let mut stat: libc::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat) })); Ok(FileAttr { stat: stat }) } pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> { let p = cstr(p); let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)]; try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) })); Ok(()) }
FilePermissions
identifier_name
lib.rs
// Copyright 2012-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. //! # The Unicode Library //! //! Unicode-intensive functions for `char` and `str` types. //! //! This crate provides a collection of Unicode-related functionality, //! including decompositions, conversions, etc., and provides traits //! implementing these functions for the `char` and `str` types. //! //! The functionality included here is only that which is necessary to //! provide for basic string-related manipulations. This crate does not //! (yet) aim to provide a full set of Unicode tables. #![crate_name = "unicode"] #![unstable(feature = "unicode")] #![feature(staged_api)] #![staged_api] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
#![feature(no_std)] #![no_std] #![feature(core)] extern crate core; // regex module pub use tables::regex; mod normalize; mod tables; mod u_char; mod u_str; // re-export char so that std et al see it correctly /// Character manipulation (`char` type, Unicode Scalar Value) /// /// This module provides the `CharExt` trait, as well as its /// implementation for the primitive `char` type, in order to allow /// basic character manipulation. /// /// A `char` actually represents a /// *[Unicode Scalar Value](http://www.unicode.org/glossary/#unicode_scalar_value)*, /// as it can contain any Unicode code point except high-surrogate and /// low-surrogate code points. /// /// As such, only values in the ranges \[0x0,0xD7FF\] and \[0xE000,0x10FFFF\] /// (inclusive) are allowed. A `char` can always be safely cast to a `u32`; /// however the converse is not always true due to the above range limits /// and, as such, should be performed via the `from_u32` function. #[stable(feature = "rust1", since = "1.0.0")] #[doc(primitive = "char")] pub mod char { pub use core::char::{MAX, from_u32, from_digit}; pub use normalize::{decompose_canonical, decompose_compatible, compose}; pub use tables::normalization::canonical_combining_class; pub use tables::UNICODE_VERSION; pub use u_char::CharExt; } pub mod str { pub use u_str::{UnicodeStr, Words, Graphemes, GraphemeIndices}; pub use u_str::{utf8_char_width, is_utf16, Utf16Items, Utf16Item}; pub use u_str::{utf16_items, Utf16Encoder}; }
html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")]
random_line_split
mod.rs
// This file is part of rust-web/twig // // For the copyright and license information, please view the LICENSE // file that was distributed with this source code. //! Twig Template API. use engine::TwigError; use runtime::Runtime;
use api::error::Traced; pub const _ANY_CALL: &'static str = "any"; pub const _ARRAY_CALL: &'static str = "array"; pub const _METHOD_CALL: &'static str = "method"; pub trait Template { /// Renders the template with the given context and returns it as string. fn render(&self, runtime: &Runtime) -> Result<String, Traced<TwigError>>; /// Displays the template with the given context. /// /// context is an array of parameters to pass to the template /// blocks is an array of blocks to pass to the template fn display(&self, runtime: &Runtime, blocks: Option<Vec<()>>); // TODO: error handling // /** // * Get the bound engine for this template. // */ // fn engine(&self) -> &Engine; }
random_line_split
basic_search.rs
// # Basic Example // // This example covers the basic functionalities of // tantivy. // // We will : // - define our schema // - create an index in a directory // - index a few documents into our index // - search for the best document matching a basic query // - retrieve the best document's original content. // --- // Importing tantivy... use tantivy::collector::TopDocs; use tantivy::query::QueryParser; use tantivy::schema::*; use tantivy::{doc, Index, ReloadPolicy}; use tempfile::TempDir; fn main() -> tantivy::Result<()>
// that. // // `TEXT` means the field should be tokenized and indexed, // along with its term frequency and term positions. // // `STORED` means that the field will also be saved // in a compressed, row-oriented key-value store. // This store is useful for reconstructing the // documents that were selected during the search phase. schema_builder.add_text_field("title", TEXT | STORED); // Our second field is body. // We want full-text search for it, but we do not // need to be able to be able to retrieve it // for our application. // // We can make our index lighter by omitting the `STORED` flag. schema_builder.add_text_field("body", TEXT); let schema = schema_builder.build(); // # Indexing documents // // Let's create a brand new index. // // This will actually just save a meta.json // with our schema in the directory. let index = Index::create_in_dir(&index_path, schema.clone())?; // To insert a document we will need an index writer. // There must be only one writer at a time. // This single `IndexWriter` is already // multithreaded. // // Here we give tantivy a budget of `50MB`. // Using a bigger heap for the indexer may increase // throughput, but 50 MB is already plenty. let mut index_writer = index.writer(50_000_000)?; // Let's index our documents! // We first need a handle on the title and the body field. // ### Adding documents // // We can create a document manually, by setting the fields // one by one in a Document object. let title = schema.get_field("title").unwrap(); let body = schema.get_field("body").unwrap(); let mut old_man_doc = Document::default(); old_man_doc.add_text(title, "The Old Man and the Sea"); old_man_doc.add_text( body, "He was an old man who fished alone in a skiff in the Gulf Stream and \ he had gone eighty-four days now without taking a fish.", ); //... and add it to the `IndexWriter`. index_writer.add_document(old_man_doc)?; // For convenience, tantivy also comes with a macro to // reduce the boilerplate above. index_writer.add_document(doc!( title => "Of Mice and Men", body => "A few miles south of Soledad, the Salinas River drops in close to the hillside \ bank and runs deep and green. The water is warm too, for it has slipped twinkling \ over the yellow sands in the sunlight before reaching the narrow pool. On one \ side of the river the golden foothill slopes curve up to the strong and rocky \ Gabilan Mountains, but on the valley side the water is lined with trees—willows \ fresh and green with every spring, carrying in their lower leaf junctures the \ debris of the winter’s flooding; and sycamores with mottled, white, recumbent \ limbs and branches that arch over the pool" ))?; // Multivalued field just need to be repeated. index_writer.add_document(doc!( title => "Frankenstein", title => "The Modern Prometheus", body => "You will rejoice to hear that no disaster has accompanied the commencement of an \ enterprise which you have regarded with such evil forebodings. I arrived here \ yesterday, and my first task is to assure my dear sister of my welfare and \ increasing confidence in the success of my undertaking." ))?; // This is an example, so we will only index 3 documents // here. You can check out tantivy's tutorial to index // the English wikipedia. Tantivy's indexing is rather fast. // Indexing 5 million articles of the English wikipedia takes // around 3 minutes on my computer! // ### Committing // // At this point our documents are not searchable. // // // We need to call `.commit()` explicitly to force the // `index_writer` to finish processing the documents in the queue, // flush the current index to the disk, and advertise // the existence of new documents. // // This call is blocking. index_writer.commit()?; // If `.commit()` returns correctly, then all of the // documents that have been added are guaranteed to be // persistently indexed. // // In the scenario of a crash or a power failure, // tantivy behaves as if it has rolled back to its last // commit. // # Searching // // ### Searcher // // A reader is required first in order to search an index. // It acts as a `Searcher` pool that reloads itself, // depending on a `ReloadPolicy`. // // For a search server you will typically create one reader for the entire lifetime of your // program, and acquire a new searcher for every single request. // // In the code below, we rely on the 'ON_COMMIT' policy: the reader // will reload the index automatically after each commit. let reader = index .reader_builder() .reload_policy(ReloadPolicy::OnCommit) .try_into()?; // We now need to acquire a searcher. // // A searcher points to a snapshotted, immutable version of the index. // // Some search experience might require more than // one query. Using the same searcher ensures that all of these queries will run on the // same version of the index. // // Acquiring a `searcher` is very cheap. // // You should acquire a searcher every time you start processing a request and // and release it right after your query is finished. let searcher = reader.searcher(); // ### Query // The query parser can interpret human queries. // Here, if the user does not specify which // field they want to search, tantivy will search // in both title and body. let query_parser = QueryParser::for_index(&index, vec![title, body]); // `QueryParser` may fail if the query is not in the right // format. For user facing applications, this can be a problem. // A ticket has been opened regarding this problem. let query = query_parser.parse_query("sea whale")?; // A query defines a set of documents, as // well as the way they should be scored. // // A query created by the query parser is scored according // to a metric called Tf-Idf, and will consider // any document matching at least one of our terms. // ### Collectors // // We are not interested in all of the documents but // only in the top 10. Keeping track of our top 10 best documents // is the role of the `TopDocs` collector. // We can now perform our query. let top_docs = searcher.search(&query, &TopDocs::with_limit(10))?; // The actual documents still need to be // retrieved from Tantivy's store. // // Since the body field was not configured as stored, // the document returned will only contain // a title. for (_score, doc_address) in top_docs { let retrieved_doc = searcher.doc(doc_address)?; println!("{}", schema.to_json(&retrieved_doc)); } Ok(()) }
{ // Let's create a temporary directory for the // sake of this example let index_path = TempDir::new()?; // # Defining the schema // // The Tantivy index requires a very strict schema. // The schema declares which fields are in the index, // and for each field, its type and "the way it should // be indexed". // First we need to define a schema ... let mut schema_builder = Schema::builder(); // Our first field is title. // We want full-text search for it, and we also want // to be able to retrieve the document after the search. // // `TEXT | STORED` is some syntactic sugar to describe
identifier_body
basic_search.rs
// # Basic Example // // This example covers the basic functionalities of // tantivy. // // We will : // - define our schema // - create an index in a directory // - index a few documents into our index // - search for the best document matching a basic query // - retrieve the best document's original content. // --- // Importing tantivy... use tantivy::collector::TopDocs; use tantivy::query::QueryParser; use tantivy::schema::*; use tantivy::{doc, Index, ReloadPolicy}; use tempfile::TempDir; fn
() -> tantivy::Result<()> { // Let's create a temporary directory for the // sake of this example let index_path = TempDir::new()?; // # Defining the schema // // The Tantivy index requires a very strict schema. // The schema declares which fields are in the index, // and for each field, its type and "the way it should // be indexed". // First we need to define a schema... let mut schema_builder = Schema::builder(); // Our first field is title. // We want full-text search for it, and we also want // to be able to retrieve the document after the search. // // `TEXT | STORED` is some syntactic sugar to describe // that. // // `TEXT` means the field should be tokenized and indexed, // along with its term frequency and term positions. // // `STORED` means that the field will also be saved // in a compressed, row-oriented key-value store. // This store is useful for reconstructing the // documents that were selected during the search phase. schema_builder.add_text_field("title", TEXT | STORED); // Our second field is body. // We want full-text search for it, but we do not // need to be able to be able to retrieve it // for our application. // // We can make our index lighter by omitting the `STORED` flag. schema_builder.add_text_field("body", TEXT); let schema = schema_builder.build(); // # Indexing documents // // Let's create a brand new index. // // This will actually just save a meta.json // with our schema in the directory. let index = Index::create_in_dir(&index_path, schema.clone())?; // To insert a document we will need an index writer. // There must be only one writer at a time. // This single `IndexWriter` is already // multithreaded. // // Here we give tantivy a budget of `50MB`. // Using a bigger heap for the indexer may increase // throughput, but 50 MB is already plenty. let mut index_writer = index.writer(50_000_000)?; // Let's index our documents! // We first need a handle on the title and the body field. // ### Adding documents // // We can create a document manually, by setting the fields // one by one in a Document object. let title = schema.get_field("title").unwrap(); let body = schema.get_field("body").unwrap(); let mut old_man_doc = Document::default(); old_man_doc.add_text(title, "The Old Man and the Sea"); old_man_doc.add_text( body, "He was an old man who fished alone in a skiff in the Gulf Stream and \ he had gone eighty-four days now without taking a fish.", ); //... and add it to the `IndexWriter`. index_writer.add_document(old_man_doc)?; // For convenience, tantivy also comes with a macro to // reduce the boilerplate above. index_writer.add_document(doc!( title => "Of Mice and Men", body => "A few miles south of Soledad, the Salinas River drops in close to the hillside \ bank and runs deep and green. The water is warm too, for it has slipped twinkling \ over the yellow sands in the sunlight before reaching the narrow pool. On one \ side of the river the golden foothill slopes curve up to the strong and rocky \ Gabilan Mountains, but on the valley side the water is lined with trees—willows \ fresh and green with every spring, carrying in their lower leaf junctures the \ debris of the winter’s flooding; and sycamores with mottled, white, recumbent \ limbs and branches that arch over the pool" ))?; // Multivalued field just need to be repeated. index_writer.add_document(doc!( title => "Frankenstein", title => "The Modern Prometheus", body => "You will rejoice to hear that no disaster has accompanied the commencement of an \ enterprise which you have regarded with such evil forebodings. I arrived here \ yesterday, and my first task is to assure my dear sister of my welfare and \ increasing confidence in the success of my undertaking." ))?; // This is an example, so we will only index 3 documents // here. You can check out tantivy's tutorial to index // the English wikipedia. Tantivy's indexing is rather fast. // Indexing 5 million articles of the English wikipedia takes // around 3 minutes on my computer! // ### Committing // // At this point our documents are not searchable. // // // We need to call `.commit()` explicitly to force the // `index_writer` to finish processing the documents in the queue, // flush the current index to the disk, and advertise // the existence of new documents. // // This call is blocking. index_writer.commit()?; // If `.commit()` returns correctly, then all of the // documents that have been added are guaranteed to be // persistently indexed. // // In the scenario of a crash or a power failure, // tantivy behaves as if it has rolled back to its last // commit. // # Searching // // ### Searcher // // A reader is required first in order to search an index. // It acts as a `Searcher` pool that reloads itself, // depending on a `ReloadPolicy`. // // For a search server you will typically create one reader for the entire lifetime of your // program, and acquire a new searcher for every single request. // // In the code below, we rely on the 'ON_COMMIT' policy: the reader // will reload the index automatically after each commit. let reader = index .reader_builder() .reload_policy(ReloadPolicy::OnCommit) .try_into()?; // We now need to acquire a searcher. // // A searcher points to a snapshotted, immutable version of the index. // // Some search experience might require more than // one query. Using the same searcher ensures that all of these queries will run on the // same version of the index. // // Acquiring a `searcher` is very cheap. // // You should acquire a searcher every time you start processing a request and // and release it right after your query is finished. let searcher = reader.searcher(); // ### Query // The query parser can interpret human queries. // Here, if the user does not specify which // field they want to search, tantivy will search // in both title and body. let query_parser = QueryParser::for_index(&index, vec![title, body]); // `QueryParser` may fail if the query is not in the right // format. For user facing applications, this can be a problem. // A ticket has been opened regarding this problem. let query = query_parser.parse_query("sea whale")?; // A query defines a set of documents, as // well as the way they should be scored. // // A query created by the query parser is scored according // to a metric called Tf-Idf, and will consider // any document matching at least one of our terms. // ### Collectors // // We are not interested in all of the documents but // only in the top 10. Keeping track of our top 10 best documents // is the role of the `TopDocs` collector. // We can now perform our query. let top_docs = searcher.search(&query, &TopDocs::with_limit(10))?; // The actual documents still need to be // retrieved from Tantivy's store. // // Since the body field was not configured as stored, // the document returned will only contain // a title. for (_score, doc_address) in top_docs { let retrieved_doc = searcher.doc(doc_address)?; println!("{}", schema.to_json(&retrieved_doc)); } Ok(()) }
main
identifier_name
basic_search.rs
// # Basic Example // // This example covers the basic functionalities of // tantivy. // // We will : // - define our schema // - create an index in a directory // - index a few documents into our index // - search for the best document matching a basic query // - retrieve the best document's original content. // --- // Importing tantivy... use tantivy::collector::TopDocs; use tantivy::query::QueryParser; use tantivy::schema::*; use tantivy::{doc, Index, ReloadPolicy}; use tempfile::TempDir; fn main() -> tantivy::Result<()> { // Let's create a temporary directory for the // sake of this example let index_path = TempDir::new()?; // # Defining the schema // // The Tantivy index requires a very strict schema. // The schema declares which fields are in the index, // and for each field, its type and "the way it should // be indexed". // First we need to define a schema... let mut schema_builder = Schema::builder(); // Our first field is title. // We want full-text search for it, and we also want // to be able to retrieve the document after the search. // // `TEXT | STORED` is some syntactic sugar to describe // that. // // `TEXT` means the field should be tokenized and indexed, // along with its term frequency and term positions. // // `STORED` means that the field will also be saved // in a compressed, row-oriented key-value store. // This store is useful for reconstructing the // documents that were selected during the search phase. schema_builder.add_text_field("title", TEXT | STORED); // Our second field is body. // We want full-text search for it, but we do not // need to be able to be able to retrieve it // for our application. // // We can make our index lighter by omitting the `STORED` flag. schema_builder.add_text_field("body", TEXT); let schema = schema_builder.build(); // # Indexing documents // // Let's create a brand new index. // // This will actually just save a meta.json // with our schema in the directory. let index = Index::create_in_dir(&index_path, schema.clone())?; // To insert a document we will need an index writer. // There must be only one writer at a time. // This single `IndexWriter` is already // multithreaded. // // Here we give tantivy a budget of `50MB`. // Using a bigger heap for the indexer may increase // throughput, but 50 MB is already plenty. let mut index_writer = index.writer(50_000_000)?; // Let's index our documents! // We first need a handle on the title and the body field. // ### Adding documents // // We can create a document manually, by setting the fields // one by one in a Document object. let title = schema.get_field("title").unwrap(); let body = schema.get_field("body").unwrap(); let mut old_man_doc = Document::default(); old_man_doc.add_text(title, "The Old Man and the Sea"); old_man_doc.add_text( body, "He was an old man who fished alone in a skiff in the Gulf Stream and \ he had gone eighty-four days now without taking a fish.", ); //... and add it to the `IndexWriter`. index_writer.add_document(old_man_doc)?; // For convenience, tantivy also comes with a macro to // reduce the boilerplate above. index_writer.add_document(doc!( title => "Of Mice and Men", body => "A few miles south of Soledad, the Salinas River drops in close to the hillside \ bank and runs deep and green. The water is warm too, for it has slipped twinkling \ over the yellow sands in the sunlight before reaching the narrow pool. On one \ side of the river the golden foothill slopes curve up to the strong and rocky \ Gabilan Mountains, but on the valley side the water is lined with trees—willows \ fresh and green with every spring, carrying in their lower leaf junctures the \ debris of the winter’s flooding; and sycamores with mottled, white, recumbent \ limbs and branches that arch over the pool" ))?; // Multivalued field just need to be repeated. index_writer.add_document(doc!( title => "Frankenstein", title => "The Modern Prometheus", body => "You will rejoice to hear that no disaster has accompanied the commencement of an \ enterprise which you have regarded with such evil forebodings. I arrived here \ yesterday, and my first task is to assure my dear sister of my welfare and \ increasing confidence in the success of my undertaking." ))?; // This is an example, so we will only index 3 documents // here. You can check out tantivy's tutorial to index // the English wikipedia. Tantivy's indexing is rather fast. // Indexing 5 million articles of the English wikipedia takes // around 3 minutes on my computer! // ### Committing // // At this point our documents are not searchable. // // // We need to call `.commit()` explicitly to force the // `index_writer` to finish processing the documents in the queue, // flush the current index to the disk, and advertise // the existence of new documents. // // This call is blocking. index_writer.commit()?; // If `.commit()` returns correctly, then all of the // documents that have been added are guaranteed to be // persistently indexed. // // In the scenario of a crash or a power failure, // tantivy behaves as if it has rolled back to its last // commit. // # Searching // // ### Searcher // // A reader is required first in order to search an index. // It acts as a `Searcher` pool that reloads itself, // depending on a `ReloadPolicy`. // // For a search server you will typically create one reader for the entire lifetime of your // program, and acquire a new searcher for every single request. // // In the code below, we rely on the 'ON_COMMIT' policy: the reader // will reload the index automatically after each commit. let reader = index .reader_builder() .reload_policy(ReloadPolicy::OnCommit) .try_into()?; // We now need to acquire a searcher. // // A searcher points to a snapshotted, immutable version of the index. // // Some search experience might require more than // one query. Using the same searcher ensures that all of these queries will run on the // same version of the index. // // Acquiring a `searcher` is very cheap. // // You should acquire a searcher every time you start processing a request and // and release it right after your query is finished. let searcher = reader.searcher(); // ### Query // The query parser can interpret human queries. // Here, if the user does not specify which // field they want to search, tantivy will search // in both title and body. let query_parser = QueryParser::for_index(&index, vec![title, body]); // `QueryParser` may fail if the query is not in the right // format. For user facing applications, this can be a problem. // A ticket has been opened regarding this problem. let query = query_parser.parse_query("sea whale")?; // A query defines a set of documents, as // well as the way they should be scored. // // A query created by the query parser is scored according // to a metric called Tf-Idf, and will consider // any document matching at least one of our terms. // ### Collectors // // We are not interested in all of the documents but // only in the top 10. Keeping track of our top 10 best documents // is the role of the `TopDocs` collector. // We can now perform our query. let top_docs = searcher.search(&query, &TopDocs::with_limit(10))?; // The actual documents still need to be
// // Since the body field was not configured as stored, // the document returned will only contain // a title. for (_score, doc_address) in top_docs { let retrieved_doc = searcher.doc(doc_address)?; println!("{}", schema.to_json(&retrieved_doc)); } Ok(()) }
// retrieved from Tantivy's store.
random_line_split
script.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/. */ #[crate_id = "github.com/mozilla/servo#script:0.1"]; #[crate_type = "lib"]; #[crate_type = "dylib"]; #[crate_type = "rlib"]; #[comment = "The Servo Parallel Browser Project"]; #[license = "MPL"]; #[feature(globs, macro_rules, struct_variant, phase)]; #[feature(phase)]; #[phase(syntax, link)] extern crate log; extern crate collections; extern crate geom; extern crate hubbub; extern crate encoding; extern crate js; extern crate native; extern crate serialize; #[phase(syntax)] extern crate servo_macros = "macros"; extern crate servo_net = "net"; extern crate servo_util = "util"; extern crate style; extern crate servo_msg = "msg"; extern crate url; pub mod dom { pub mod bindings { pub mod js; pub mod element; pub mod utils; pub mod callback; pub mod error; pub mod conversions; pub mod proxyhandler; pub mod trace; pub mod codegen { pub use self::BindingDeclarations::*; pub mod InterfaceTypes; pub mod InheritTypes; pub mod PrototypeList; pub mod RegisterBindings; pub mod BindingDeclarations; pub mod UnionTypes; } } pub mod types { pub use super::bindings::codegen::InterfaceTypes::*; } pub mod attr; pub mod attrlist; pub mod blob; pub mod characterdata; pub mod clientrect; pub mod clientrectlist; pub mod comment; pub mod console; pub mod document; pub mod documentfragment; pub mod documenttype; pub mod domexception; pub mod domimplementation; pub mod domparser; pub mod element; pub mod event; pub mod eventdispatcher; pub mod eventtarget; pub mod formdata; pub mod htmlanchorelement; pub mod htmlappletelement; pub mod htmlareaelement; pub mod htmlaudioelement; pub mod htmlbaseelement; pub mod htmlbodyelement; pub mod htmlbrelement; pub mod htmlbuttonelement; pub mod htmlcanvaselement; pub mod htmlcollection; pub mod htmldataelement; pub mod htmldatalistelement; pub mod htmldirectoryelement; pub mod htmldivelement; pub mod htmldlistelement; pub mod htmlelement; pub mod htmlembedelement; pub mod htmlfieldsetelement; pub mod htmlfontelement; pub mod htmlformelement; pub mod htmlframeelement; pub mod htmlframesetelement; pub mod htmlheadelement; pub mod htmlheadingelement; pub mod htmlhrelement; pub mod htmlhtmlelement; pub mod htmliframeelement;
pub mod htmlimageelement; pub mod htmlinputelement; pub mod htmllabelelement; pub mod htmllegendelement; pub mod htmllielement; pub mod htmllinkelement; pub mod htmlmainelement; pub mod htmlmapelement; pub mod htmlmediaelement; pub mod htmlmetaelement; pub mod htmlmeterelement; pub mod htmlmodelement; pub mod htmlobjectelement; pub mod htmlolistelement; pub mod htmloptgroupelement; pub mod htmloptionelement; pub mod htmloutputelement; pub mod htmlparagraphelement; pub mod htmlparamelement; pub mod htmlpreelement; pub mod htmlprogresselement; pub mod htmlquoteelement; pub mod htmlscriptelement; pub mod htmlselectelement; pub mod htmlserializer; pub mod htmlspanelement; pub mod htmlsourceelement; pub mod htmlstyleelement; pub mod htmltableelement; pub mod htmltablecaptionelement; pub mod htmltablecellelement; pub mod htmltabledatacellelement; pub mod htmltableheadercellelement; pub mod htmltablecolelement; pub mod htmltablerowelement; pub mod htmltablesectionelement; pub mod htmltemplateelement; pub mod htmltextareaelement; pub mod htmltimeelement; pub mod htmltitleelement; pub mod htmltrackelement; pub mod htmlulistelement; pub mod htmlvideoelement; pub mod htmlunknownelement; pub mod location; pub mod mouseevent; pub mod navigator; pub mod node; pub mod nodelist; pub mod processinginstruction; pub mod uievent; pub mod text; pub mod validitystate; pub mod virtualmethods; pub mod window; pub mod windowproxy; pub mod testbinding; } pub mod html { pub mod cssparse; pub mod hubbub_html_parser; } pub mod layout_interface; pub mod script_task;
random_line_split
audio_talker.rs
use crate::data::Data; use crate::talker::{Talker, TalkerBase}; use crate::voice; pub const MODEL: &str = "AudioTalker"; pub struct AudioTalker { base: TalkerBase, } impl AudioTalker { pub fn new(def_value: f32, hidden: Option<bool>) -> AudioTalker { let value = if def_value.is_nan() { 0. } else
; let mut base = TalkerBase::new_data("", MODEL, Data::f(value)); let voice = voice::audio(None, value, None); base.add_voice(voice); base.set_hidden(hidden.unwrap_or(false)); Self { base } } } impl Talker for AudioTalker { fn base<'a>(&'a self) -> &'a TalkerBase { &self.base } fn model(&self) -> &str { MODEL } fn talk(&mut self, _port: usize, tick: i64, len: usize) -> usize { for voice in self.voices() { let mut vc = voice.borrow_mut(); vc.set_len(len); vc.set_tick(tick); } len } fn voice_value(&self, port: usize) -> Option<f32> { if self.is_hidden() { if let Some(voice) = self.voices().get(port) { return voice.borrow().audio_value(0); } } None } }
{ def_value }
conditional_block
audio_talker.rs
use crate::data::Data; use crate::talker::{Talker, TalkerBase}; use crate::voice; pub const MODEL: &str = "AudioTalker"; pub struct AudioTalker { base: TalkerBase, } impl AudioTalker { pub fn new(def_value: f32, hidden: Option<bool>) -> AudioTalker { let value = if def_value.is_nan() { 0. } else { def_value }; let mut base = TalkerBase::new_data("", MODEL, Data::f(value)); let voice = voice::audio(None, value, None); base.add_voice(voice); base.set_hidden(hidden.unwrap_or(false)); Self { base } } } impl Talker for AudioTalker { fn base<'a>(&'a self) -> &'a TalkerBase { &self.base } fn model(&self) -> &str { MODEL } fn talk(&mut self, _port: usize, tick: i64, len: usize) -> usize { for voice in self.voices() { let mut vc = voice.borrow_mut(); vc.set_len(len); vc.set_tick(tick); } len } fn voice_value(&self, port: usize) -> Option<f32> { if self.is_hidden() { if let Some(voice) = self.voices().get(port) {
None } }
return voice.borrow().audio_value(0); } }
random_line_split
audio_talker.rs
use crate::data::Data; use crate::talker::{Talker, TalkerBase}; use crate::voice; pub const MODEL: &str = "AudioTalker"; pub struct AudioTalker { base: TalkerBase, } impl AudioTalker { pub fn new(def_value: f32, hidden: Option<bool>) -> AudioTalker { let value = if def_value.is_nan() { 0. } else { def_value }; let mut base = TalkerBase::new_data("", MODEL, Data::f(value)); let voice = voice::audio(None, value, None); base.add_voice(voice); base.set_hidden(hidden.unwrap_or(false)); Self { base } } } impl Talker for AudioTalker { fn base<'a>(&'a self) -> &'a TalkerBase { &self.base } fn
(&self) -> &str { MODEL } fn talk(&mut self, _port: usize, tick: i64, len: usize) -> usize { for voice in self.voices() { let mut vc = voice.borrow_mut(); vc.set_len(len); vc.set_tick(tick); } len } fn voice_value(&self, port: usize) -> Option<f32> { if self.is_hidden() { if let Some(voice) = self.voices().get(port) { return voice.borrow().audio_value(0); } } None } }
model
identifier_name
dtable.rs
// // SOS: the Stupid Operating System // by Eliza Weisman ([email protected]) // // Copyright (c) 2015-2017 Eliza Weisman // Released under the terms of the MIT license. See `LICENSE` in the root // directory of this repository for more information. //! `x86` and `x86_64` descriptor tables (IDT, GDT, or LDT) //! //! For more information, refer to the _Intel® 64 and IA-32 Architectures //! Software Developer’s Manual_, Vol. 3A, section 3.2, "Using Segments", and //! section 6.10, "Interrupt Descriptor Table (IDT)". #![deny(missing_docs)] // use memory::PAddr; use core::mem::size_of; /// A pointer to a descriptor table. /// This is a format suitable #[repr(C, packed)] pub struct Pointer<T: DTable> { /// the length of the descriptor table pub limit: u16 , /// pointer to the region in memory /// containing the descriptor table. pub base: *const T } unsafe impl<T: DTable> Sync for Pointer<T> { } /// A descriptor table (IDT or GDT). /// /// The IA32 architecture uses two descriptor table structures, the GDT /// (Global Descriptor Table), which is used for configuring segmentation, /// and the IDT (Interrupt Descriptor Table), which tells the CPU where /// interrupt service routines are located. /// /// As SOS relies on paging rather than segmentation for memory protection on /// both 32-bit and 64-bit systems, we use the GDT only minimally. However, the /// CPU still requires a correctly configured GDT to run in protected mode, even /// if it is not actually used. /// /// This trait specifies base functionality common to both types of descriptor /// table. pub trait DTable: Sized { /// The type of an entry in this descriptor table. /// /// For an IDT, these are /// interrupt [`Gate`](../interrupts/idt/gate/struct.Gate.html)s, /// while for a GDT or LDT, they are segment /// [`Descriptor`](../segment/struct.Descriptor.html)s. // TODO: can there be a trait for DTable entries? // - eliza, 10/06/2016 type Entry: Sized; /// Get the IDT pointer struct to pass to `lidt` or `lgdt` /// /// This expects that the object implementing `DTable` not contain /// additional data before or after the actual `DTable`, if you wish /// to attach information to a descriptor table besides the array of /// entries that it consists of, it will be necessary to encose the /// descriptor table in another `struct` or `enum` type. // TODO: can we have an associated `Entry` type + a function to get the // number of entries in the DTable, instead? that way, we could // calculate the limit using that information, allowing Rust code
// If we wanted to be really clever, we could probably also have a // method to get a pointer to a first entry (or enforce that the // DTable supports indexing?) and then we could get a pointer only // to the array segment of the DTable, while still allowing variables // to be placed before/after the array. // // I'm not sure if we actually want to support this – is there really // a use-case for it? I suppose it would also make our size calc. // more correct in case Rust ever puts additional data around a // DTable rray, but I imagine it will probably never do that... // – eliza, 06/03/2016 // #[inline] fn get_ptr(&self) -> Pointer<Self> { Pointer { limit: (size_of::<Self::Entry>() * self.entry_count()) as u16 , base: self as *const _ } } /// Returns the number of Entries in the `DTable`. /// /// This is used for calculating the limit. fn entry_count(&self) -> usize; /// Load the descriptor table with the appropriate load instruction fn load(&'static self); }
// to place more variables after the array in the DTable structure. //
random_line_split
dtable.rs
// // SOS: the Stupid Operating System // by Eliza Weisman ([email protected]) // // Copyright (c) 2015-2017 Eliza Weisman // Released under the terms of the MIT license. See `LICENSE` in the root // directory of this repository for more information. //! `x86` and `x86_64` descriptor tables (IDT, GDT, or LDT) //! //! For more information, refer to the _Intel® 64 and IA-32 Architectures //! Software Developer’s Manual_, Vol. 3A, section 3.2, "Using Segments", and //! section 6.10, "Interrupt Descriptor Table (IDT)". #![deny(missing_docs)] // use memory::PAddr; use core::mem::size_of; /// A pointer to a descriptor table. /// This is a format suitable #[repr(C, packed)] pub struct Pointer<T: DTable> { /// the length of the descriptor table pub limit: u16 , /// pointer to the region in memory /// containing the descriptor table. pub base: *const T } unsafe impl<T: DTable> Sync for Pointer<T> { } /// A descriptor table (IDT or GDT). /// /// The IA32 architecture uses two descriptor table structures, the GDT /// (Global Descriptor Table), which is used for configuring segmentation, /// and the IDT (Interrupt Descriptor Table), which tells the CPU where /// interrupt service routines are located. /// /// As SOS relies on paging rather than segmentation for memory protection on /// both 32-bit and 64-bit systems, we use the GDT only minimally. However, the /// CPU still requires a correctly configured GDT to run in protected mode, even /// if it is not actually used. /// /// This trait specifies base functionality common to both types of descriptor /// table. pub trait DTable: Sized { /// The type of an entry in this descriptor table. /// /// For an IDT, these are /// interrupt [`Gate`](../interrupts/idt/gate/struct.Gate.html)s, /// while for a GDT or LDT, they are segment /// [`Descriptor`](../segment/struct.Descriptor.html)s. // TODO: can there be a trait for DTable entries? // - eliza, 10/06/2016 type Entry: Sized; /// Get the IDT pointer struct to pass to `lidt` or `lgdt` /// /// This expects that the object implementing `DTable` not contain /// additional data before or after the actual `DTable`, if you wish /// to attach information to a descriptor table besides the array of /// entries that it consists of, it will be necessary to encose the /// descriptor table in another `struct` or `enum` type. // TODO: can we have an associated `Entry` type + a function to get the // number of entries in the DTable, instead? that way, we could // calculate the limit using that information, allowing Rust code // to place more variables after the array in the DTable structure. // // If we wanted to be really clever, we could probably also have a // method to get a pointer to a first entry (or enforce that the // DTable supports indexing?) and then we could get a pointer only // to the array segment of the DTable, while still allowing variables // to be placed before/after the array. // // I'm not sure if we actually want to support this – is there really // a use-case for it? I suppose it would also make our size calc. // more correct in case Rust ever puts additional data around a // DTable rray, but I imagine it will probably never do that... // – eliza, 06/03/2016 // #[inline] fn get_ptr
-> Pointer<Self> { Pointer { limit: (size_of::<Self::Entry>() * self.entry_count()) as u16 , base: self as *const _ } } /// Returns the number of Entries in the `DTable`. /// /// This is used for calculating the limit. fn entry_count(&self) -> usize; /// Load the descriptor table with the appropriate load instruction fn load(&'static self); }
(&self)
identifier_name
msgsend-ring-mutex-arcs.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. // This test creates a bunch of tasks that simultaneously send to each // other in a ring. The messages should all be basically // independent. // This is like msgsend-ring-pipes but adapted to use Arcs. // This also serves as a pipes test, because Arcs are implemented with pipes. // no-pretty-expanded FIXME #15189 // ignore-lexer-test FIXME #15679 use std::os; use std::sync::{Arc, Future, Mutex, Condvar}; use std::time::Duration; use std::uint; // A poor man's pipe. type pipe = Arc<(Mutex<Vec<uint>>, Condvar)>; fn send(p: &pipe, msg: uint) { let &(ref lock, ref cond) = &**p; let mut arr = lock.lock(); arr.push(msg); cond.notify_one(); } fn recv(p: &pipe) -> uint
fn init() -> (pipe,pipe) { let m = Arc::new((Mutex::new(Vec::new()), Condvar::new())); ((&m).clone(), m) } fn thread_ring(i: uint, count: uint, num_chan: pipe, num_port: pipe) { let mut num_chan = Some(num_chan); let mut num_port = Some(num_port); // Send/Receive lots of messages. for j in range(0u, count) { //println!("task %?, iter %?", i, j); let num_chan2 = num_chan.take().unwrap(); let num_port2 = num_port.take().unwrap(); send(&num_chan2, i * j); num_chan = Some(num_chan2); let _n = recv(&num_port2); //log(error, _n); num_port = Some(num_port2); }; } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_string(), "100".to_string(), "10000".to_string()) } else if args.len() <= 1u { vec!("".to_string(), "10".to_string(), "100".to_string()) } else { args.clone().into_iter().collect() }; let num_tasks = from_str::<uint>(args[1].as_slice()).unwrap(); let msg_per_task = from_str::<uint>(args[2].as_slice()).unwrap(); let (mut num_chan, num_port) = init(); let mut p = Some((num_chan, num_port)); let dur = Duration::span(|| { let (mut num_chan, num_port) = p.take().unwrap(); // create the ring let mut futures = Vec::new(); for i in range(1u, num_tasks) { //println!("spawning %?", i); let (new_chan, num_port) = init(); let num_chan_2 = num_chan.clone(); let new_future = Future::spawn(proc() { thread_ring(i, msg_per_task, num_chan_2, num_port) }); futures.push(new_future); num_chan = new_chan; }; // do our iteration thread_ring(0, msg_per_task, num_chan, num_port); // synchronize for f in futures.iter_mut() { f.get() } }); // all done, report stats. let num_msgs = num_tasks * msg_per_task; let rate = (num_msgs as f64) / (dur.num_milliseconds() as f64); println!("Sent {} messages in {} ms", num_msgs, dur.num_milliseconds()); println!(" {} messages / second", rate / 1000.0); println!(" {} μs / message", 1000000. / rate / 1000.0); }
{ let &(ref lock, ref cond) = &**p; let mut arr = lock.lock(); while arr.is_empty() { cond.wait(&arr); } arr.pop().unwrap() }
identifier_body
msgsend-ring-mutex-arcs.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. // This test creates a bunch of tasks that simultaneously send to each // other in a ring. The messages should all be basically // independent. // This is like msgsend-ring-pipes but adapted to use Arcs. // This also serves as a pipes test, because Arcs are implemented with pipes. // no-pretty-expanded FIXME #15189 // ignore-lexer-test FIXME #15679 use std::os; use std::sync::{Arc, Future, Mutex, Condvar}; use std::time::Duration; use std::uint; // A poor man's pipe. type pipe = Arc<(Mutex<Vec<uint>>, Condvar)>; fn send(p: &pipe, msg: uint) { let &(ref lock, ref cond) = &**p; let mut arr = lock.lock(); arr.push(msg); cond.notify_one(); } fn
(p: &pipe) -> uint { let &(ref lock, ref cond) = &**p; let mut arr = lock.lock(); while arr.is_empty() { cond.wait(&arr); } arr.pop().unwrap() } fn init() -> (pipe,pipe) { let m = Arc::new((Mutex::new(Vec::new()), Condvar::new())); ((&m).clone(), m) } fn thread_ring(i: uint, count: uint, num_chan: pipe, num_port: pipe) { let mut num_chan = Some(num_chan); let mut num_port = Some(num_port); // Send/Receive lots of messages. for j in range(0u, count) { //println!("task %?, iter %?", i, j); let num_chan2 = num_chan.take().unwrap(); let num_port2 = num_port.take().unwrap(); send(&num_chan2, i * j); num_chan = Some(num_chan2); let _n = recv(&num_port2); //log(error, _n); num_port = Some(num_port2); }; } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_string(), "100".to_string(), "10000".to_string()) } else if args.len() <= 1u { vec!("".to_string(), "10".to_string(), "100".to_string()) } else { args.clone().into_iter().collect() }; let num_tasks = from_str::<uint>(args[1].as_slice()).unwrap(); let msg_per_task = from_str::<uint>(args[2].as_slice()).unwrap(); let (mut num_chan, num_port) = init(); let mut p = Some((num_chan, num_port)); let dur = Duration::span(|| { let (mut num_chan, num_port) = p.take().unwrap(); // create the ring let mut futures = Vec::new(); for i in range(1u, num_tasks) { //println!("spawning %?", i); let (new_chan, num_port) = init(); let num_chan_2 = num_chan.clone(); let new_future = Future::spawn(proc() { thread_ring(i, msg_per_task, num_chan_2, num_port) }); futures.push(new_future); num_chan = new_chan; }; // do our iteration thread_ring(0, msg_per_task, num_chan, num_port); // synchronize for f in futures.iter_mut() { f.get() } }); // all done, report stats. let num_msgs = num_tasks * msg_per_task; let rate = (num_msgs as f64) / (dur.num_milliseconds() as f64); println!("Sent {} messages in {} ms", num_msgs, dur.num_milliseconds()); println!(" {} messages / second", rate / 1000.0); println!(" {} μs / message", 1000000. / rate / 1000.0); }
recv
identifier_name
msgsend-ring-mutex-arcs.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. // This test creates a bunch of tasks that simultaneously send to each // other in a ring. The messages should all be basically // independent. // This is like msgsend-ring-pipes but adapted to use Arcs. // This also serves as a pipes test, because Arcs are implemented with pipes. // no-pretty-expanded FIXME #15189 // ignore-lexer-test FIXME #15679 use std::os; use std::sync::{Arc, Future, Mutex, Condvar}; use std::time::Duration; use std::uint; // A poor man's pipe. type pipe = Arc<(Mutex<Vec<uint>>, Condvar)>; fn send(p: &pipe, msg: uint) { let &(ref lock, ref cond) = &**p; let mut arr = lock.lock(); arr.push(msg); cond.notify_one(); } fn recv(p: &pipe) -> uint { let &(ref lock, ref cond) = &**p; let mut arr = lock.lock(); while arr.is_empty() { cond.wait(&arr); } arr.pop().unwrap() } fn init() -> (pipe,pipe) { let m = Arc::new((Mutex::new(Vec::new()), Condvar::new())); ((&m).clone(), m) } fn thread_ring(i: uint, count: uint, num_chan: pipe, num_port: pipe) { let mut num_chan = Some(num_chan); let mut num_port = Some(num_port); // Send/Receive lots of messages. for j in range(0u, count) { //println!("task %?, iter %?", i, j); let num_chan2 = num_chan.take().unwrap(); let num_port2 = num_port.take().unwrap(); send(&num_chan2, i * j); num_chan = Some(num_chan2); let _n = recv(&num_port2); //log(error, _n); num_port = Some(num_port2); }; } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some()
else if args.len() <= 1u { vec!("".to_string(), "10".to_string(), "100".to_string()) } else { args.clone().into_iter().collect() }; let num_tasks = from_str::<uint>(args[1].as_slice()).unwrap(); let msg_per_task = from_str::<uint>(args[2].as_slice()).unwrap(); let (mut num_chan, num_port) = init(); let mut p = Some((num_chan, num_port)); let dur = Duration::span(|| { let (mut num_chan, num_port) = p.take().unwrap(); // create the ring let mut futures = Vec::new(); for i in range(1u, num_tasks) { //println!("spawning %?", i); let (new_chan, num_port) = init(); let num_chan_2 = num_chan.clone(); let new_future = Future::spawn(proc() { thread_ring(i, msg_per_task, num_chan_2, num_port) }); futures.push(new_future); num_chan = new_chan; }; // do our iteration thread_ring(0, msg_per_task, num_chan, num_port); // synchronize for f in futures.iter_mut() { f.get() } }); // all done, report stats. let num_msgs = num_tasks * msg_per_task; let rate = (num_msgs as f64) / (dur.num_milliseconds() as f64); println!("Sent {} messages in {} ms", num_msgs, dur.num_milliseconds()); println!(" {} messages / second", rate / 1000.0); println!(" {} μs / message", 1000000. / rate / 1000.0); }
{ vec!("".to_string(), "100".to_string(), "10000".to_string()) }
conditional_block
msgsend-ring-mutex-arcs.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. // This test creates a bunch of tasks that simultaneously send to each // other in a ring. The messages should all be basically // independent. // This is like msgsend-ring-pipes but adapted to use Arcs. // This also serves as a pipes test, because Arcs are implemented with pipes. // no-pretty-expanded FIXME #15189 // ignore-lexer-test FIXME #15679 use std::os; use std::sync::{Arc, Future, Mutex, Condvar}; use std::time::Duration; use std::uint; // A poor man's pipe. type pipe = Arc<(Mutex<Vec<uint>>, Condvar)>; fn send(p: &pipe, msg: uint) { let &(ref lock, ref cond) = &**p; let mut arr = lock.lock(); arr.push(msg); cond.notify_one(); } fn recv(p: &pipe) -> uint { let &(ref lock, ref cond) = &**p; let mut arr = lock.lock(); while arr.is_empty() { cond.wait(&arr); }
fn init() -> (pipe,pipe) { let m = Arc::new((Mutex::new(Vec::new()), Condvar::new())); ((&m).clone(), m) } fn thread_ring(i: uint, count: uint, num_chan: pipe, num_port: pipe) { let mut num_chan = Some(num_chan); let mut num_port = Some(num_port); // Send/Receive lots of messages. for j in range(0u, count) { //println!("task %?, iter %?", i, j); let num_chan2 = num_chan.take().unwrap(); let num_port2 = num_port.take().unwrap(); send(&num_chan2, i * j); num_chan = Some(num_chan2); let _n = recv(&num_port2); //log(error, _n); num_port = Some(num_port2); }; } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_string(), "100".to_string(), "10000".to_string()) } else if args.len() <= 1u { vec!("".to_string(), "10".to_string(), "100".to_string()) } else { args.clone().into_iter().collect() }; let num_tasks = from_str::<uint>(args[1].as_slice()).unwrap(); let msg_per_task = from_str::<uint>(args[2].as_slice()).unwrap(); let (mut num_chan, num_port) = init(); let mut p = Some((num_chan, num_port)); let dur = Duration::span(|| { let (mut num_chan, num_port) = p.take().unwrap(); // create the ring let mut futures = Vec::new(); for i in range(1u, num_tasks) { //println!("spawning %?", i); let (new_chan, num_port) = init(); let num_chan_2 = num_chan.clone(); let new_future = Future::spawn(proc() { thread_ring(i, msg_per_task, num_chan_2, num_port) }); futures.push(new_future); num_chan = new_chan; }; // do our iteration thread_ring(0, msg_per_task, num_chan, num_port); // synchronize for f in futures.iter_mut() { f.get() } }); // all done, report stats. let num_msgs = num_tasks * msg_per_task; let rate = (num_msgs as f64) / (dur.num_milliseconds() as f64); println!("Sent {} messages in {} ms", num_msgs, dur.num_milliseconds()); println!(" {} messages / second", rate / 1000.0); println!(" {} μs / message", 1000000. / rate / 1000.0); }
arr.pop().unwrap() }
random_line_split
mem.rs
// Copyright 2012-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. //! Basic functions for dealing with memory //! //! This module contains functions for querying the size and alignment of //! types, initializing and manipulating memory. #![stable(feature = "rust1", since = "1.0.0")] use marker::Sized; use intrinsics; use ptr; #[stable(feature = "rust1", since = "1.0.0")] pub use intrinsics::transmute; /// Leaks a value into the void, consuming ownership and never running its /// destructor. /// /// This function will take ownership of its argument, but is distinct from the /// `mem::drop` function in that it **does not run the destructor**, leaking the /// value and any resources that it owns. /// /// # Safety /// /// This function is not marked as `unsafe` as Rust does not guarantee that the /// `Drop` implementation for a value will always run. Note, however, that /// leaking resources such as memory or I/O objects is likely not desired, so /// this function is only recommended for specialized use cases. /// /// The safety of this function implies that when writing `unsafe` code /// yourself care must be taken when leveraging a destructor that is required to /// run to preserve memory safety. There are known situations where the /// destructor may not run (such as if ownership of the object with the /// destructor is returned) which must be taken into account. /// /// # Other forms of Leakage /// /// It's important to point out that this function is not the only method by /// which a value can be leaked in safe Rust code. Other known sources of /// leakage are: /// /// * `Rc` and `Arc` cycles /// * `mpsc::{Sender, Receiver}` cycles (they use `Arc` internally) /// * Panicking destructors are likely to leak local resources /// /// # When To Use /// /// There's only a few reasons to use this function. They mainly come /// up in unsafe code or FFI code. /// /// * You have an uninitialized value, perhaps for performance reasons, and /// need to prevent the destructor from running on it. /// * You have two copies of a value (like `std::mem::swap`), but need the /// destructor to only run once to prevent a double free. /// * Transferring resources across FFI boundries. /// /// # Example /// /// Leak some heap memory by never deallocating it. /// /// ```rust /// use std::mem; /// /// let heap_memory = Box::new(3); /// mem::forget(heap_memory); /// ``` /// /// Leak an I/O object, never closing the file. /// /// ```rust,no_run /// use std::mem; /// use std::fs::File; /// /// let file = File::open("foo.txt").unwrap(); /// mem::forget(file); /// ``` /// /// The swap function uses forget to good effect. /// /// ```rust /// use std::mem; /// use std::ptr; /// /// fn swap<T>(x: &mut T, y: &mut T) { /// unsafe { /// // Give ourselves some scratch space to work with /// let mut t: T = mem::uninitialized(); /// /// // Perform the swap, `&mut` pointers never alias /// ptr::copy_nonoverlapping(&*x, &mut t, 1); /// ptr::copy_nonoverlapping(&*y, x, 1); /// ptr::copy_nonoverlapping(&t, y, 1); /// /// // y and t now point to the same thing, but we need to completely /// // forget `t` because we do not want to run the destructor for `T` /// // on its value, which is still owned somewhere outside this function. /// mem::forget(t); /// } /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn forget<T>(t: T) { unsafe { intrinsics::forget(t) } } /// Returns the size of a type in bytes. /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::size_of::<i32>()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn size_of<T>() -> usize { unsafe { intrinsics::size_of::<T>() } } /// Returns the size of the type that `val` points to in bytes. /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::size_of_val(&5i32)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn size_of_val<T:?Sized>(val: &T) -> usize { unsafe { intrinsics::size_of_val(val) } } /// Returns the ABI-required minimum alignment of a type /// /// This is the alignment used for struct fields. It may be smaller than the preferred alignment. /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::min_align_of::<i32>()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[deprecated(reason = "use `align_of` instead", since = "1.2.0")] pub fn min_align_of<T>() -> usize { unsafe { intrinsics::min_align_of::<T>() } } /// Returns the ABI-required minimum alignment of the type of the value that `val` points to /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::min_align_of_val(&5i32)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[deprecated(reason = "use `align_of_val` instead", since = "1.2.0")] pub fn min_align_of_val<T:?Sized>(val: &T) -> usize { unsafe { intrinsics::min_align_of_val(val) } } /// Returns the alignment in memory for a type. /// /// This is the alignment used for struct fields. It may be smaller than the preferred alignment. /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::align_of::<i32>()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn align_of<T>() -> usize { unsafe { intrinsics::min_align_of::<T>() } } /// Returns the ABI-required minimum alignment of the type of the value that `val` points to /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::align_of_val(&5i32)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn align_of_val<T:?Sized>(val: &T) -> usize { unsafe { intrinsics::min_align_of_val(val) } } /// Creates a value initialized to zero. /// /// This function is similar to allocating space for a local variable and zeroing it out (an unsafe /// operation). /// /// Care must be taken when using this function, if the type `T` has a destructor and the value /// falls out of scope (due to unwinding or returning) before being initialized, then the /// destructor will run on zeroed data, likely leading to crashes. /// /// This is useful for FFI functions sometimes, but should generally be avoided. /// /// # Examples /// /// ``` /// use std::mem; /// /// let x: i32 = unsafe { mem::zeroed() }; /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn zeroed<T>() -> T { intrinsics::init() } /// Creates a value initialized to an unspecified series of bytes. /// /// The byte sequence usually indicates that the value at the memory /// in question has been dropped. Thus, *if* T carries a drop flag, /// any associated destructor will not be run when the value falls out /// of scope. /// /// Some code at one time used the `zeroed` function above to /// accomplish this goal. /// /// This function is expected to be deprecated with the transition /// to non-zeroing drop. #[inline] #[unstable(feature = "filling_drop")] pub unsafe fn dropped<T>() -> T { #[inline(always)] unsafe fn dropped_impl<T>() -> T { intrinsics::init_dropped() } dropped_impl() } /// Creates an uninitialized value. /// /// Care must be taken when using this function, if the type `T` has a destructor and the value /// falls out of scope (due to unwinding or returning) before being initialized, then the /// destructor will run on uninitialized data, likely leading to crashes. /// /// This is useful for FFI functions sometimes, but should generally be avoided. /// /// # Examples /// /// ``` /// use std::mem; /// /// let x: i32 = unsafe { mem::uninitialized() }; /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn uninitialized<T>() -> T { intrinsics::uninit() } /// Swap the values at two mutable locations of the same type, without deinitialising or copying /// either one. /// /// # Examples /// /// ``` /// use std::mem; /// /// let x = &mut 5; /// let y = &mut 42; /// /// mem::swap(x, y); /// /// assert_eq!(42, *x); /// assert_eq!(5, *y); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn
<T>(x: &mut T, y: &mut T) { unsafe { // Give ourselves some scratch space to work with let mut t: T = uninitialized(); // Perform the swap, `&mut` pointers never alias ptr::copy_nonoverlapping(&*x, &mut t, 1); ptr::copy_nonoverlapping(&*y, x, 1); ptr::copy_nonoverlapping(&t, y, 1); // y and t now point to the same thing, but we need to completely // forget `t` because we do not want to run the destructor for `T` // on its value, which is still owned somewhere outside this function. forget(t); } } /// Replaces the value at a mutable location with a new one, returning the old value, without /// deinitialising or copying either one. /// /// This is primarily used for transferring and swapping ownership of a value in a mutable /// location. /// /// # Examples /// /// A simple example: /// /// ``` /// use std::mem; /// /// let mut v: Vec<i32> = Vec::new(); /// /// mem::replace(&mut v, Vec::new()); /// ``` /// /// This function allows consumption of one field of a struct by replacing it with another value. /// The normal approach doesn't always work: /// /// ```rust,ignore /// struct Buffer<T> { buf: Vec<T> } /// /// impl<T> Buffer<T> { /// fn get_and_reset(&mut self) -> Vec<T> { /// // error: cannot move out of dereference of `&mut`-pointer /// let buf = self.buf; /// self.buf = Vec::new(); /// buf /// } /// } /// ``` /// /// Note that `T` does not necessarily implement `Clone`, so it can't even clone and reset /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from /// `self`, allowing it to be returned: /// /// ``` /// use std::mem; /// # struct Buffer<T> { buf: Vec<T> } /// impl<T> Buffer<T> { /// fn get_and_reset(&mut self) -> Vec<T> { /// mem::replace(&mut self.buf, Vec::new()) /// } /// } /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn replace<T>(dest: &mut T, mut src: T) -> T { swap(dest, &mut src); src } /// Disposes of a value. /// /// This function can be used to destroy any value by allowing `drop` to take ownership of its /// argument. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let x = RefCell::new(1); /// /// let mut mutable_borrow = x.borrow_mut(); /// *mutable_borrow = 1; /// /// drop(mutable_borrow); // relinquish the mutable borrow on this slot /// /// let borrow = x.borrow(); /// println!("{}", *borrow); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn drop<T>(_x: T) { } macro_rules! repeat_u8_as_u32 { ($name:expr) => { (($name as u32) << 24 | ($name as u32) << 16 | ($name as u32) << 8 | ($name as u32)) } } macro_rules! repeat_u8_as_u64 { ($name:expr) => { ((repeat_u8_as_u32!($name) as u64) << 32 | (repeat_u8_as_u32!($name) as u64)) } } // NOTE: Keep synchronized with values used in librustc_trans::trans::adt. // // In particular, the POST_DROP_U8 marker must never equal the // DTOR_NEEDED_U8 marker. // // For a while pnkfelix was using 0xc1 here. // But having the sign bit set is a pain, so 0x1d is probably better. // // And of course, 0x00 brings back the old world of zero'ing on drop. #[unstable(feature = "filling_drop")] pub const POST_DROP_U8: u8 = 0x1d; #[unstable(feature = "filling_drop")] pub const POST_DROP_U32: u32 = repeat_u8_as_u32!(POST_DROP_U8); #[unstable(feature = "filling_drop")] pub const POST_DROP_U64: u64 = repeat_u8_as_u64!(POST_DROP_U8); #[cfg(target_pointer_width = "32")] #[unstable(feature = "filling_drop")] pub const POST_DROP_USIZE: usize = POST_DROP_U32 as usize; #[cfg(target_pointer_width = "64")] #[unstable(feature = "filling_drop")] pub const POST_DROP_USIZE: usize = POST_DROP_U64 as usize; /// Interprets `src` as `&U`, and then reads `src` without moving the contained /// value. /// /// This function will unsafely assume the pointer `src` is valid for /// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It /// will also unsafely create a copy of the contained value instead of moving /// out of `src`. /// /// It is not a compile-time error if `T` and `U` have different sizes, but it /// is highly encouraged to only invoke this function where `T` and `U` have the /// same size. This function triggers undefined behavior if `U` is larger than /// `T`. /// /// # Examples /// /// ``` /// use std::mem; /// /// let one = unsafe { mem::transmute_copy(&1) }; /// /// assert_eq!(1, one); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn transmute_copy<T, U>(src: &T) -> U { // FIXME(#23542) Replace with type ascription. #![allow(trivial_casts)] ptr::read(src as *const T as *const U) } /// Transforms lifetime of the second pointer to match the first. #[inline] #[unstable(feature = "copy_lifetime", reason = "this function may be removed in the future due to its \ questionable utility")] #[deprecated(since = "1.2.0", reason = "unclear that this function buys more safety and \ lifetimes are generally not handled as such in unsafe \ code today")] pub unsafe fn copy_lifetime<'a, S:?Sized, T:?Sized + 'a>(_ptr: &'a S, ptr: &T) -> &'a T { transmute(ptr) } /// Transforms lifetime of the second mutable pointer to match the first. #[inline] #[unstable(feature = "copy_lifetime", reason = "this function may be removed in the future due to its \ questionable utility")] #[deprecated(since = "1.2.0", reason = "unclear that this function buys more safety and \ lifetimes are generally not handled as such in unsafe \ code today")] pub unsafe fn copy_mut_lifetime<'a, S:?Sized, T:?Sized + 'a>(_ptr: &'a S, ptr: &mut T) -> &'a mut T { transmute(ptr) }
swap
identifier_name
mem.rs
// Copyright 2012-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. //! Basic functions for dealing with memory //! //! This module contains functions for querying the size and alignment of //! types, initializing and manipulating memory. #![stable(feature = "rust1", since = "1.0.0")] use marker::Sized; use intrinsics; use ptr; #[stable(feature = "rust1", since = "1.0.0")] pub use intrinsics::transmute; /// Leaks a value into the void, consuming ownership and never running its /// destructor. /// /// This function will take ownership of its argument, but is distinct from the /// `mem::drop` function in that it **does not run the destructor**, leaking the
/// This function is not marked as `unsafe` as Rust does not guarantee that the /// `Drop` implementation for a value will always run. Note, however, that /// leaking resources such as memory or I/O objects is likely not desired, so /// this function is only recommended for specialized use cases. /// /// The safety of this function implies that when writing `unsafe` code /// yourself care must be taken when leveraging a destructor that is required to /// run to preserve memory safety. There are known situations where the /// destructor may not run (such as if ownership of the object with the /// destructor is returned) which must be taken into account. /// /// # Other forms of Leakage /// /// It's important to point out that this function is not the only method by /// which a value can be leaked in safe Rust code. Other known sources of /// leakage are: /// /// * `Rc` and `Arc` cycles /// * `mpsc::{Sender, Receiver}` cycles (they use `Arc` internally) /// * Panicking destructors are likely to leak local resources /// /// # When To Use /// /// There's only a few reasons to use this function. They mainly come /// up in unsafe code or FFI code. /// /// * You have an uninitialized value, perhaps for performance reasons, and /// need to prevent the destructor from running on it. /// * You have two copies of a value (like `std::mem::swap`), but need the /// destructor to only run once to prevent a double free. /// * Transferring resources across FFI boundries. /// /// # Example /// /// Leak some heap memory by never deallocating it. /// /// ```rust /// use std::mem; /// /// let heap_memory = Box::new(3); /// mem::forget(heap_memory); /// ``` /// /// Leak an I/O object, never closing the file. /// /// ```rust,no_run /// use std::mem; /// use std::fs::File; /// /// let file = File::open("foo.txt").unwrap(); /// mem::forget(file); /// ``` /// /// The swap function uses forget to good effect. /// /// ```rust /// use std::mem; /// use std::ptr; /// /// fn swap<T>(x: &mut T, y: &mut T) { /// unsafe { /// // Give ourselves some scratch space to work with /// let mut t: T = mem::uninitialized(); /// /// // Perform the swap, `&mut` pointers never alias /// ptr::copy_nonoverlapping(&*x, &mut t, 1); /// ptr::copy_nonoverlapping(&*y, x, 1); /// ptr::copy_nonoverlapping(&t, y, 1); /// /// // y and t now point to the same thing, but we need to completely /// // forget `t` because we do not want to run the destructor for `T` /// // on its value, which is still owned somewhere outside this function. /// mem::forget(t); /// } /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn forget<T>(t: T) { unsafe { intrinsics::forget(t) } } /// Returns the size of a type in bytes. /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::size_of::<i32>()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn size_of<T>() -> usize { unsafe { intrinsics::size_of::<T>() } } /// Returns the size of the type that `val` points to in bytes. /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::size_of_val(&5i32)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn size_of_val<T:?Sized>(val: &T) -> usize { unsafe { intrinsics::size_of_val(val) } } /// Returns the ABI-required minimum alignment of a type /// /// This is the alignment used for struct fields. It may be smaller than the preferred alignment. /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::min_align_of::<i32>()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[deprecated(reason = "use `align_of` instead", since = "1.2.0")] pub fn min_align_of<T>() -> usize { unsafe { intrinsics::min_align_of::<T>() } } /// Returns the ABI-required minimum alignment of the type of the value that `val` points to /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::min_align_of_val(&5i32)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[deprecated(reason = "use `align_of_val` instead", since = "1.2.0")] pub fn min_align_of_val<T:?Sized>(val: &T) -> usize { unsafe { intrinsics::min_align_of_val(val) } } /// Returns the alignment in memory for a type. /// /// This is the alignment used for struct fields. It may be smaller than the preferred alignment. /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::align_of::<i32>()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn align_of<T>() -> usize { unsafe { intrinsics::min_align_of::<T>() } } /// Returns the ABI-required minimum alignment of the type of the value that `val` points to /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::align_of_val(&5i32)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn align_of_val<T:?Sized>(val: &T) -> usize { unsafe { intrinsics::min_align_of_val(val) } } /// Creates a value initialized to zero. /// /// This function is similar to allocating space for a local variable and zeroing it out (an unsafe /// operation). /// /// Care must be taken when using this function, if the type `T` has a destructor and the value /// falls out of scope (due to unwinding or returning) before being initialized, then the /// destructor will run on zeroed data, likely leading to crashes. /// /// This is useful for FFI functions sometimes, but should generally be avoided. /// /// # Examples /// /// ``` /// use std::mem; /// /// let x: i32 = unsafe { mem::zeroed() }; /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn zeroed<T>() -> T { intrinsics::init() } /// Creates a value initialized to an unspecified series of bytes. /// /// The byte sequence usually indicates that the value at the memory /// in question has been dropped. Thus, *if* T carries a drop flag, /// any associated destructor will not be run when the value falls out /// of scope. /// /// Some code at one time used the `zeroed` function above to /// accomplish this goal. /// /// This function is expected to be deprecated with the transition /// to non-zeroing drop. #[inline] #[unstable(feature = "filling_drop")] pub unsafe fn dropped<T>() -> T { #[inline(always)] unsafe fn dropped_impl<T>() -> T { intrinsics::init_dropped() } dropped_impl() } /// Creates an uninitialized value. /// /// Care must be taken when using this function, if the type `T` has a destructor and the value /// falls out of scope (due to unwinding or returning) before being initialized, then the /// destructor will run on uninitialized data, likely leading to crashes. /// /// This is useful for FFI functions sometimes, but should generally be avoided. /// /// # Examples /// /// ``` /// use std::mem; /// /// let x: i32 = unsafe { mem::uninitialized() }; /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn uninitialized<T>() -> T { intrinsics::uninit() } /// Swap the values at two mutable locations of the same type, without deinitialising or copying /// either one. /// /// # Examples /// /// ``` /// use std::mem; /// /// let x = &mut 5; /// let y = &mut 42; /// /// mem::swap(x, y); /// /// assert_eq!(42, *x); /// assert_eq!(5, *y); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn swap<T>(x: &mut T, y: &mut T) { unsafe { // Give ourselves some scratch space to work with let mut t: T = uninitialized(); // Perform the swap, `&mut` pointers never alias ptr::copy_nonoverlapping(&*x, &mut t, 1); ptr::copy_nonoverlapping(&*y, x, 1); ptr::copy_nonoverlapping(&t, y, 1); // y and t now point to the same thing, but we need to completely // forget `t` because we do not want to run the destructor for `T` // on its value, which is still owned somewhere outside this function. forget(t); } } /// Replaces the value at a mutable location with a new one, returning the old value, without /// deinitialising or copying either one. /// /// This is primarily used for transferring and swapping ownership of a value in a mutable /// location. /// /// # Examples /// /// A simple example: /// /// ``` /// use std::mem; /// /// let mut v: Vec<i32> = Vec::new(); /// /// mem::replace(&mut v, Vec::new()); /// ``` /// /// This function allows consumption of one field of a struct by replacing it with another value. /// The normal approach doesn't always work: /// /// ```rust,ignore /// struct Buffer<T> { buf: Vec<T> } /// /// impl<T> Buffer<T> { /// fn get_and_reset(&mut self) -> Vec<T> { /// // error: cannot move out of dereference of `&mut`-pointer /// let buf = self.buf; /// self.buf = Vec::new(); /// buf /// } /// } /// ``` /// /// Note that `T` does not necessarily implement `Clone`, so it can't even clone and reset /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from /// `self`, allowing it to be returned: /// /// ``` /// use std::mem; /// # struct Buffer<T> { buf: Vec<T> } /// impl<T> Buffer<T> { /// fn get_and_reset(&mut self) -> Vec<T> { /// mem::replace(&mut self.buf, Vec::new()) /// } /// } /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn replace<T>(dest: &mut T, mut src: T) -> T { swap(dest, &mut src); src } /// Disposes of a value. /// /// This function can be used to destroy any value by allowing `drop` to take ownership of its /// argument. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let x = RefCell::new(1); /// /// let mut mutable_borrow = x.borrow_mut(); /// *mutable_borrow = 1; /// /// drop(mutable_borrow); // relinquish the mutable borrow on this slot /// /// let borrow = x.borrow(); /// println!("{}", *borrow); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn drop<T>(_x: T) { } macro_rules! repeat_u8_as_u32 { ($name:expr) => { (($name as u32) << 24 | ($name as u32) << 16 | ($name as u32) << 8 | ($name as u32)) } } macro_rules! repeat_u8_as_u64 { ($name:expr) => { ((repeat_u8_as_u32!($name) as u64) << 32 | (repeat_u8_as_u32!($name) as u64)) } } // NOTE: Keep synchronized with values used in librustc_trans::trans::adt. // // In particular, the POST_DROP_U8 marker must never equal the // DTOR_NEEDED_U8 marker. // // For a while pnkfelix was using 0xc1 here. // But having the sign bit set is a pain, so 0x1d is probably better. // // And of course, 0x00 brings back the old world of zero'ing on drop. #[unstable(feature = "filling_drop")] pub const POST_DROP_U8: u8 = 0x1d; #[unstable(feature = "filling_drop")] pub const POST_DROP_U32: u32 = repeat_u8_as_u32!(POST_DROP_U8); #[unstable(feature = "filling_drop")] pub const POST_DROP_U64: u64 = repeat_u8_as_u64!(POST_DROP_U8); #[cfg(target_pointer_width = "32")] #[unstable(feature = "filling_drop")] pub const POST_DROP_USIZE: usize = POST_DROP_U32 as usize; #[cfg(target_pointer_width = "64")] #[unstable(feature = "filling_drop")] pub const POST_DROP_USIZE: usize = POST_DROP_U64 as usize; /// Interprets `src` as `&U`, and then reads `src` without moving the contained /// value. /// /// This function will unsafely assume the pointer `src` is valid for /// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It /// will also unsafely create a copy of the contained value instead of moving /// out of `src`. /// /// It is not a compile-time error if `T` and `U` have different sizes, but it /// is highly encouraged to only invoke this function where `T` and `U` have the /// same size. This function triggers undefined behavior if `U` is larger than /// `T`. /// /// # Examples /// /// ``` /// use std::mem; /// /// let one = unsafe { mem::transmute_copy(&1) }; /// /// assert_eq!(1, one); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn transmute_copy<T, U>(src: &T) -> U { // FIXME(#23542) Replace with type ascription. #![allow(trivial_casts)] ptr::read(src as *const T as *const U) } /// Transforms lifetime of the second pointer to match the first. #[inline] #[unstable(feature = "copy_lifetime", reason = "this function may be removed in the future due to its \ questionable utility")] #[deprecated(since = "1.2.0", reason = "unclear that this function buys more safety and \ lifetimes are generally not handled as such in unsafe \ code today")] pub unsafe fn copy_lifetime<'a, S:?Sized, T:?Sized + 'a>(_ptr: &'a S, ptr: &T) -> &'a T { transmute(ptr) } /// Transforms lifetime of the second mutable pointer to match the first. #[inline] #[unstable(feature = "copy_lifetime", reason = "this function may be removed in the future due to its \ questionable utility")] #[deprecated(since = "1.2.0", reason = "unclear that this function buys more safety and \ lifetimes are generally not handled as such in unsafe \ code today")] pub unsafe fn copy_mut_lifetime<'a, S:?Sized, T:?Sized + 'a>(_ptr: &'a S, ptr: &mut T) -> &'a mut T { transmute(ptr) }
/// value and any resources that it owns. /// /// # Safety ///
random_line_split
mem.rs
// Copyright 2012-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. //! Basic functions for dealing with memory //! //! This module contains functions for querying the size and alignment of //! types, initializing and manipulating memory. #![stable(feature = "rust1", since = "1.0.0")] use marker::Sized; use intrinsics; use ptr; #[stable(feature = "rust1", since = "1.0.0")] pub use intrinsics::transmute; /// Leaks a value into the void, consuming ownership and never running its /// destructor. /// /// This function will take ownership of its argument, but is distinct from the /// `mem::drop` function in that it **does not run the destructor**, leaking the /// value and any resources that it owns. /// /// # Safety /// /// This function is not marked as `unsafe` as Rust does not guarantee that the /// `Drop` implementation for a value will always run. Note, however, that /// leaking resources such as memory or I/O objects is likely not desired, so /// this function is only recommended for specialized use cases. /// /// The safety of this function implies that when writing `unsafe` code /// yourself care must be taken when leveraging a destructor that is required to /// run to preserve memory safety. There are known situations where the /// destructor may not run (such as if ownership of the object with the /// destructor is returned) which must be taken into account. /// /// # Other forms of Leakage /// /// It's important to point out that this function is not the only method by /// which a value can be leaked in safe Rust code. Other known sources of /// leakage are: /// /// * `Rc` and `Arc` cycles /// * `mpsc::{Sender, Receiver}` cycles (they use `Arc` internally) /// * Panicking destructors are likely to leak local resources /// /// # When To Use /// /// There's only a few reasons to use this function. They mainly come /// up in unsafe code or FFI code. /// /// * You have an uninitialized value, perhaps for performance reasons, and /// need to prevent the destructor from running on it. /// * You have two copies of a value (like `std::mem::swap`), but need the /// destructor to only run once to prevent a double free. /// * Transferring resources across FFI boundries. /// /// # Example /// /// Leak some heap memory by never deallocating it. /// /// ```rust /// use std::mem; /// /// let heap_memory = Box::new(3); /// mem::forget(heap_memory); /// ``` /// /// Leak an I/O object, never closing the file. /// /// ```rust,no_run /// use std::mem; /// use std::fs::File; /// /// let file = File::open("foo.txt").unwrap(); /// mem::forget(file); /// ``` /// /// The swap function uses forget to good effect. /// /// ```rust /// use std::mem; /// use std::ptr; /// /// fn swap<T>(x: &mut T, y: &mut T) { /// unsafe { /// // Give ourselves some scratch space to work with /// let mut t: T = mem::uninitialized(); /// /// // Perform the swap, `&mut` pointers never alias /// ptr::copy_nonoverlapping(&*x, &mut t, 1); /// ptr::copy_nonoverlapping(&*y, x, 1); /// ptr::copy_nonoverlapping(&t, y, 1); /// /// // y and t now point to the same thing, but we need to completely /// // forget `t` because we do not want to run the destructor for `T` /// // on its value, which is still owned somewhere outside this function. /// mem::forget(t); /// } /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn forget<T>(t: T) { unsafe { intrinsics::forget(t) } } /// Returns the size of a type in bytes. /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::size_of::<i32>()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn size_of<T>() -> usize { unsafe { intrinsics::size_of::<T>() } } /// Returns the size of the type that `val` points to in bytes. /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::size_of_val(&5i32)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn size_of_val<T:?Sized>(val: &T) -> usize { unsafe { intrinsics::size_of_val(val) } } /// Returns the ABI-required minimum alignment of a type /// /// This is the alignment used for struct fields. It may be smaller than the preferred alignment. /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::min_align_of::<i32>()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[deprecated(reason = "use `align_of` instead", since = "1.2.0")] pub fn min_align_of<T>() -> usize { unsafe { intrinsics::min_align_of::<T>() } } /// Returns the ABI-required minimum alignment of the type of the value that `val` points to /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::min_align_of_val(&5i32)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[deprecated(reason = "use `align_of_val` instead", since = "1.2.0")] pub fn min_align_of_val<T:?Sized>(val: &T) -> usize
/// Returns the alignment in memory for a type. /// /// This is the alignment used for struct fields. It may be smaller than the preferred alignment. /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::align_of::<i32>()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn align_of<T>() -> usize { unsafe { intrinsics::min_align_of::<T>() } } /// Returns the ABI-required minimum alignment of the type of the value that `val` points to /// /// # Examples /// /// ``` /// use std::mem; /// /// assert_eq!(4, mem::align_of_val(&5i32)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn align_of_val<T:?Sized>(val: &T) -> usize { unsafe { intrinsics::min_align_of_val(val) } } /// Creates a value initialized to zero. /// /// This function is similar to allocating space for a local variable and zeroing it out (an unsafe /// operation). /// /// Care must be taken when using this function, if the type `T` has a destructor and the value /// falls out of scope (due to unwinding or returning) before being initialized, then the /// destructor will run on zeroed data, likely leading to crashes. /// /// This is useful for FFI functions sometimes, but should generally be avoided. /// /// # Examples /// /// ``` /// use std::mem; /// /// let x: i32 = unsafe { mem::zeroed() }; /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn zeroed<T>() -> T { intrinsics::init() } /// Creates a value initialized to an unspecified series of bytes. /// /// The byte sequence usually indicates that the value at the memory /// in question has been dropped. Thus, *if* T carries a drop flag, /// any associated destructor will not be run when the value falls out /// of scope. /// /// Some code at one time used the `zeroed` function above to /// accomplish this goal. /// /// This function is expected to be deprecated with the transition /// to non-zeroing drop. #[inline] #[unstable(feature = "filling_drop")] pub unsafe fn dropped<T>() -> T { #[inline(always)] unsafe fn dropped_impl<T>() -> T { intrinsics::init_dropped() } dropped_impl() } /// Creates an uninitialized value. /// /// Care must be taken when using this function, if the type `T` has a destructor and the value /// falls out of scope (due to unwinding or returning) before being initialized, then the /// destructor will run on uninitialized data, likely leading to crashes. /// /// This is useful for FFI functions sometimes, but should generally be avoided. /// /// # Examples /// /// ``` /// use std::mem; /// /// let x: i32 = unsafe { mem::uninitialized() }; /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn uninitialized<T>() -> T { intrinsics::uninit() } /// Swap the values at two mutable locations of the same type, without deinitialising or copying /// either one. /// /// # Examples /// /// ``` /// use std::mem; /// /// let x = &mut 5; /// let y = &mut 42; /// /// mem::swap(x, y); /// /// assert_eq!(42, *x); /// assert_eq!(5, *y); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn swap<T>(x: &mut T, y: &mut T) { unsafe { // Give ourselves some scratch space to work with let mut t: T = uninitialized(); // Perform the swap, `&mut` pointers never alias ptr::copy_nonoverlapping(&*x, &mut t, 1); ptr::copy_nonoverlapping(&*y, x, 1); ptr::copy_nonoverlapping(&t, y, 1); // y and t now point to the same thing, but we need to completely // forget `t` because we do not want to run the destructor for `T` // on its value, which is still owned somewhere outside this function. forget(t); } } /// Replaces the value at a mutable location with a new one, returning the old value, without /// deinitialising or copying either one. /// /// This is primarily used for transferring and swapping ownership of a value in a mutable /// location. /// /// # Examples /// /// A simple example: /// /// ``` /// use std::mem; /// /// let mut v: Vec<i32> = Vec::new(); /// /// mem::replace(&mut v, Vec::new()); /// ``` /// /// This function allows consumption of one field of a struct by replacing it with another value. /// The normal approach doesn't always work: /// /// ```rust,ignore /// struct Buffer<T> { buf: Vec<T> } /// /// impl<T> Buffer<T> { /// fn get_and_reset(&mut self) -> Vec<T> { /// // error: cannot move out of dereference of `&mut`-pointer /// let buf = self.buf; /// self.buf = Vec::new(); /// buf /// } /// } /// ``` /// /// Note that `T` does not necessarily implement `Clone`, so it can't even clone and reset /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from /// `self`, allowing it to be returned: /// /// ``` /// use std::mem; /// # struct Buffer<T> { buf: Vec<T> } /// impl<T> Buffer<T> { /// fn get_and_reset(&mut self) -> Vec<T> { /// mem::replace(&mut self.buf, Vec::new()) /// } /// } /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn replace<T>(dest: &mut T, mut src: T) -> T { swap(dest, &mut src); src } /// Disposes of a value. /// /// This function can be used to destroy any value by allowing `drop` to take ownership of its /// argument. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let x = RefCell::new(1); /// /// let mut mutable_borrow = x.borrow_mut(); /// *mutable_borrow = 1; /// /// drop(mutable_borrow); // relinquish the mutable borrow on this slot /// /// let borrow = x.borrow(); /// println!("{}", *borrow); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn drop<T>(_x: T) { } macro_rules! repeat_u8_as_u32 { ($name:expr) => { (($name as u32) << 24 | ($name as u32) << 16 | ($name as u32) << 8 | ($name as u32)) } } macro_rules! repeat_u8_as_u64 { ($name:expr) => { ((repeat_u8_as_u32!($name) as u64) << 32 | (repeat_u8_as_u32!($name) as u64)) } } // NOTE: Keep synchronized with values used in librustc_trans::trans::adt. // // In particular, the POST_DROP_U8 marker must never equal the // DTOR_NEEDED_U8 marker. // // For a while pnkfelix was using 0xc1 here. // But having the sign bit set is a pain, so 0x1d is probably better. // // And of course, 0x00 brings back the old world of zero'ing on drop. #[unstable(feature = "filling_drop")] pub const POST_DROP_U8: u8 = 0x1d; #[unstable(feature = "filling_drop")] pub const POST_DROP_U32: u32 = repeat_u8_as_u32!(POST_DROP_U8); #[unstable(feature = "filling_drop")] pub const POST_DROP_U64: u64 = repeat_u8_as_u64!(POST_DROP_U8); #[cfg(target_pointer_width = "32")] #[unstable(feature = "filling_drop")] pub const POST_DROP_USIZE: usize = POST_DROP_U32 as usize; #[cfg(target_pointer_width = "64")] #[unstable(feature = "filling_drop")] pub const POST_DROP_USIZE: usize = POST_DROP_U64 as usize; /// Interprets `src` as `&U`, and then reads `src` without moving the contained /// value. /// /// This function will unsafely assume the pointer `src` is valid for /// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It /// will also unsafely create a copy of the contained value instead of moving /// out of `src`. /// /// It is not a compile-time error if `T` and `U` have different sizes, but it /// is highly encouraged to only invoke this function where `T` and `U` have the /// same size. This function triggers undefined behavior if `U` is larger than /// `T`. /// /// # Examples /// /// ``` /// use std::mem; /// /// let one = unsafe { mem::transmute_copy(&1) }; /// /// assert_eq!(1, one); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn transmute_copy<T, U>(src: &T) -> U { // FIXME(#23542) Replace with type ascription. #![allow(trivial_casts)] ptr::read(src as *const T as *const U) } /// Transforms lifetime of the second pointer to match the first. #[inline] #[unstable(feature = "copy_lifetime", reason = "this function may be removed in the future due to its \ questionable utility")] #[deprecated(since = "1.2.0", reason = "unclear that this function buys more safety and \ lifetimes are generally not handled as such in unsafe \ code today")] pub unsafe fn copy_lifetime<'a, S:?Sized, T:?Sized + 'a>(_ptr: &'a S, ptr: &T) -> &'a T { transmute(ptr) } /// Transforms lifetime of the second mutable pointer to match the first. #[inline] #[unstable(feature = "copy_lifetime", reason = "this function may be removed in the future due to its \ questionable utility")] #[deprecated(since = "1.2.0", reason = "unclear that this function buys more safety and \ lifetimes are generally not handled as such in unsafe \ code today")] pub unsafe fn copy_mut_lifetime<'a, S:?Sized, T:?Sized + 'a>(_ptr: &'a S, ptr: &mut T) -> &'a mut T { transmute(ptr) }
{ unsafe { intrinsics::min_align_of_val(val) } }
identifier_body
main.rs
fn pe015() -> u64 { const LIMIT:usize = 20; let mut numerator = vec![]; let mut denominator = vec![]; for i in 0.. LIMIT { denominator.push(i+1); numerator.push(i+LIMIT+1); } // walk through lists and cast away multiples to reduce size of numbers from // factorials - this is incomplete factoring but sufficient for this problem // we could factor both completely if we wanted... let mut den:usize; let mut num:usize; for i in 0.. LIMIT { for j in 0.. LIMIT { den = denominator[i]; num = numerator[j]; if den!= 1 && num % den == 0 { numerator[j] = num / den; denominator[i] = 1; } } } let mut den64:u64; let mut num64:u64; num64 = 1; den64 = 1; for i in 0.. LIMIT { num64 = num64 * numerator[i] as u64; den64 = den64 * denominator[i] as u64; } num64 / den64 } fn main()
{ println!("{}", pe015()) }
identifier_body
main.rs
fn pe015() -> u64 { const LIMIT:usize = 20; let mut numerator = vec![]; let mut denominator = vec![]; for i in 0.. LIMIT { denominator.push(i+1); numerator.push(i+LIMIT+1); } // walk through lists and cast away multiples to reduce size of numbers from // factorials - this is incomplete factoring but sufficient for this problem // we could factor both completely if we wanted... let mut den:usize; let mut num:usize; for i in 0.. LIMIT { for j in 0.. LIMIT { den = denominator[i]; num = numerator[j]; if den!= 1 && num % den == 0
} } let mut den64:u64; let mut num64:u64; num64 = 1; den64 = 1; for i in 0.. LIMIT { num64 = num64 * numerator[i] as u64; den64 = den64 * denominator[i] as u64; } num64 / den64 } fn main() { println!("{}", pe015()) }
{ numerator[j] = num / den; denominator[i] = 1; }
conditional_block
main.rs
fn pe015() -> u64 { const LIMIT:usize = 20; let mut numerator = vec![]; let mut denominator = vec![]; for i in 0.. LIMIT { denominator.push(i+1); numerator.push(i+LIMIT+1); } // walk through lists and cast away multiples to reduce size of numbers from // factorials - this is incomplete factoring but sufficient for this problem // we could factor both completely if we wanted... let mut den:usize;
let mut num:usize; for i in 0.. LIMIT { for j in 0.. LIMIT { den = denominator[i]; num = numerator[j]; if den!= 1 && num % den == 0 { numerator[j] = num / den; denominator[i] = 1; } } } let mut den64:u64; let mut num64:u64; num64 = 1; den64 = 1; for i in 0.. LIMIT { num64 = num64 * numerator[i] as u64; den64 = den64 * denominator[i] as u64; } num64 / den64 } fn main() { println!("{}", pe015()) }
random_line_split
main.rs
fn
() -> u64 { const LIMIT:usize = 20; let mut numerator = vec![]; let mut denominator = vec![]; for i in 0.. LIMIT { denominator.push(i+1); numerator.push(i+LIMIT+1); } // walk through lists and cast away multiples to reduce size of numbers from // factorials - this is incomplete factoring but sufficient for this problem // we could factor both completely if we wanted... let mut den:usize; let mut num:usize; for i in 0.. LIMIT { for j in 0.. LIMIT { den = denominator[i]; num = numerator[j]; if den!= 1 && num % den == 0 { numerator[j] = num / den; denominator[i] = 1; } } } let mut den64:u64; let mut num64:u64; num64 = 1; den64 = 1; for i in 0.. LIMIT { num64 = num64 * numerator[i] as u64; den64 = den64 * denominator[i] as u64; } num64 / den64 } fn main() { println!("{}", pe015()) }
pe015
identifier_name
options.rs
use num_traits::FromPrimitive; use std::net::Ipv4Addr; #[derive(PartialEq, Clone)] pub struct RawDhcpOption { pub code: u8, pub data: Vec<u8>, } #[derive(PartialEq)] pub enum DhcpOption { DhcpMessageType(MessageType), ServerIdentifier(Ipv4Addr), ParameterRequestList(Vec<u8>), RequestedIpAddress(Ipv4Addr), HostName(String), Router(Vec<Ipv4Addr>), DomainNameServer(Vec<Ipv4Addr>), IpAddressLeaseTime(u32), SubnetMask(Ipv4Addr), Message(String), Unrecognized(RawDhcpOption), } impl DhcpOption { pub fn to_raw(&self) -> RawDhcpOption { match self { Self::DhcpMessageType(mtype) => RawDhcpOption { code: DHCP_MESSAGE_TYPE, data: vec![*mtype as u8], }, Self::ServerIdentifier(addr) => RawDhcpOption { code: SERVER_IDENTIFIER, data: addr.octets().to_vec(), }, Self::ParameterRequestList(prl) => RawDhcpOption { code: PARAMETER_REQUEST_LIST, data: prl.clone(), }, Self::RequestedIpAddress(addr) => RawDhcpOption { code: REQUESTED_IP_ADDRESS, data: addr.octets().to_vec(), }, Self::HostName(name) => RawDhcpOption { code: HOST_NAME, data: name.as_bytes().to_vec(), }, Self::Router(addrs) => RawDhcpOption { code: ROUTER, data: { let mut v = vec![]; for a in addrs { v.extend(a.octets().iter()); } v }, }, Self::DomainNameServer(addrs) => RawDhcpOption { code: DOMAIN_NAME_SERVER, data: { let mut v = vec![]; for a in addrs { v.extend(a.octets().iter()); } v }, }, Self::IpAddressLeaseTime(secs) => RawDhcpOption { code: IP_ADDRESS_LEASE_TIME, data: secs.to_be_bytes().to_vec(), }, Self::SubnetMask(mask) => RawDhcpOption { code: SUBNET_MASK, data: mask.octets().to_vec(), }, Self::Message(msg) => RawDhcpOption { code: MESSAGE, data: msg.as_bytes().to_vec(), }, Self::Unrecognized(raw) => raw.clone(), } } pub fn code(&self) -> u8 { match self { Self::DhcpMessageType(_) => DHCP_MESSAGE_TYPE, Self::ServerIdentifier(_) => SERVER_IDENTIFIER, Self::ParameterRequestList(_) => PARAMETER_REQUEST_LIST, Self::RequestedIpAddress(_) => REQUESTED_IP_ADDRESS, Self::HostName(_) => HOST_NAME, Self::Router(_) => ROUTER, Self::DomainNameServer(_) => DOMAIN_NAME_SERVER, Self::IpAddressLeaseTime(_) => IP_ADDRESS_LEASE_TIME, Self::SubnetMask(_) => SUBNET_MASK, Self::Message(_) => MESSAGE, Self::Unrecognized(x) => x.code, } } } // DHCP Options; pub const SUBNET_MASK: u8 = 1; pub const TIME_OFFSET: u8 = 2; pub const ROUTER: u8 = 3; pub const TIME_SERVER: u8 = 4; pub const NAME_SERVER: u8 = 5; pub const DOMAIN_NAME_SERVER: u8 = 6; pub const LOG_SERVER: u8 = 7; pub const COOKIE_SERVER: u8 = 8; pub const LPR_SERVER: u8 = 9; pub const IMPRESS_SERVER: u8 = 10; pub const RESOURCE_LOCATION_SERVER: u8 = 11; pub const HOST_NAME: u8 = 12; pub const BOOT_FILE_SIZE: u8 = 13; pub const MERIT_DUMP_FILE: u8 = 14; pub const DOMAIN_NAME: u8 = 15; pub const SWAP_SERVER: u8 = 16; pub const ROOT_PATH: u8 = 17; pub const EXTENSIONS_PATH: u8 = 18; // IP LAYER PARAMETERS PER HOST; pub const IP_FORWARDING_ENABLE_DISABLE: u8 = 19; pub const NON_LOCAL_SOURCE_ROUTING_ENABLE_DISABLE: u8 = 20; pub const POLICY_FILTER: u8 = 21; pub const MAXIMUM_DATAGRAM_REASSEMBLY_SIZE: u8 = 22; pub const DEFAULT_IP_TIME_TO_LIVE: u8 = 23; pub const PATH_MTU_AGING_TIMEOUT: u8 = 24; pub const PATH_MTU_PLATEAU_TABLE: u8 = 25; // IP LAYER PARAMETERS PER INTERFACE; pub const INTERFACE_MTU: u8 = 26; pub const ALL_SUBNETS_ARE_LOCAL: u8 = 27; pub const BROADCAST_ADDRESS: u8 = 28; pub const PERFORM_MASK_DISCOVERY: u8 = 29; pub const MASK_SUPPLIER: u8 = 30; pub const PERFORM_ROUTER_DISCOVERY: u8 = 31; pub const ROUTER_SOLICITATION_ADDRESS: u8 = 32; pub const STATIC_ROUTE: u8 = 33; // LINK LAYER PARAMETERS PER INTERFACE; pub const TRAILER_ENCAPSULATION: u8 = 34; pub const ARP_CACHE_TIMEOUT: u8 = 35; pub const ETHERNET_ENCAPSULATION: u8 = 36; // TCP PARAMETERS; pub const TCP_DEFAULT_TTL: u8 = 37; pub const TCP_KEEPALIVE_INTERVAL: u8 = 38; pub const TCP_KEEPALIVE_GARBAGE: u8 = 39; // APPLICATION AND SERVICE PARAMETERS; pub const NETWORK_INFORMATION_SERVICE_DOMAIN: u8 = 40; pub const NETWORK_INFORMATION_SERVERS: u8 = 41; pub const NETWORK_TIME_PROTOCOL_SERVERS: u8 = 42; pub const VENDOR_SPECIFIC_INFORMATION: u8 = 43; pub const NETBIOS_OVER_TCPIP_NAME_SERVER: u8 = 44; pub const NETBIOS_OVER_TCPIP_DATAGRAM_DISTRIBUTION_SERVER: u8 = 45; pub const NETBIOS_OVER_TCPIP_NODE_TYPE: u8 = 46; pub const NETBIOS_OVER_TCPIP_SCOPE: u8 = 47; pub const XWINDOW_SYSTEM_FONT_SERVER: u8 = 48; pub const XWINDOW_SYSTEM_DISPLAY_MANAGER: u8 = 49; pub const NETWORK_INFORMATION_SERVICEPLUS_DOMAIN: u8 = 64; pub const NETWORK_INFORMATION_SERVICEPLUS_SERVERS: u8 = 65; pub const MOBILE_IP_HOME_AGENT: u8 = 68; pub const SIMPLE_MAIL_TRANSPORT_PROTOCOL: u8 = 69; pub const POST_OFFICE_PROTOCOL_SERVER: u8 = 70; pub const NETWORK_NEWS_TRANSPORT_PROTOCOL: u8 = 71; pub const DEFAULT_WORLD_WIDE_WEB_SERVER: u8 = 72; pub const DEFAULT_FINGER_SERVER: u8 = 73; pub const DEFAULT_INTERNET_RELAY_CHAT_SERVER: u8 = 74; pub const STREETTALK_SERVER: u8 = 75; pub const STREETTALK_DIRECTORY_ASSISTANCE: u8 = 76; pub const RELAY_AGENT_INFORMATION: u8 = 82; // DHCP EXTENSIONS pub const REQUESTED_IP_ADDRESS: u8 = 50; pub const IP_ADDRESS_LEASE_TIME: u8 = 51; pub const OVERLOAD: u8 = 52; pub const DHCP_MESSAGE_TYPE: u8 = 53; pub const SERVER_IDENTIFIER: u8 = 54; pub const PARAMETER_REQUEST_LIST: u8 = 55; pub const MESSAGE: u8 = 56; pub const MAXIMUM_DHCP_MESSAGE_SIZE: u8 = 57; pub const RENEWAL_TIME_VALUE: u8 = 58; pub const REBINDING_TIME_VALUE: u8 = 59; pub const VENDOR_CLASS_IDENTIFIER: u8 = 60; pub const CLIENT_IDENTIFIER: u8 = 61;
pub const TFTP_SERVER_NAME: u8 = 66; pub const BOOTFILE_NAME: u8 = 67; pub const USER_CLASS: u8 = 77; pub const CLIENT_ARCHITECTURE: u8 = 93; pub const TZ_POSIX_STRING: u8 = 100; pub const TZ_DATABASE_STRING: u8 = 101; pub const CLASSLESS_ROUTE_FORMAT: u8 = 121; /// Returns title of DHCP Option code, if known. pub fn title(code: u8) -> Option<&'static str> { Some(match code { SUBNET_MASK => "Subnet Mask", TIME_OFFSET => "Time Offset", ROUTER => "Router", TIME_SERVER => "Time Server", NAME_SERVER => "Name Server", DOMAIN_NAME_SERVER => "Domain Name Server", LOG_SERVER => "Log Server", COOKIE_SERVER => "Cookie Server", LPR_SERVER => "LPR Server", IMPRESS_SERVER => "Impress Server", RESOURCE_LOCATION_SERVER => "Resource Location Server", HOST_NAME => "Host Name", BOOT_FILE_SIZE => "Boot File Size", MERIT_DUMP_FILE => "Merit Dump File", DOMAIN_NAME => "Domain Name", SWAP_SERVER => "Swap Server", ROOT_PATH => "Root Path", EXTENSIONS_PATH => "Extensions Path", // IP LAYER PARAMETERS PER HOST", IP_FORWARDING_ENABLE_DISABLE => "IP Forwarding Enable/Disable", NON_LOCAL_SOURCE_ROUTING_ENABLE_DISABLE => "Non-Local Source Routing Enable/Disable", POLICY_FILTER => "Policy Filter", MAXIMUM_DATAGRAM_REASSEMBLY_SIZE => "Maximum Datagram Reassembly Size", DEFAULT_IP_TIME_TO_LIVE => "Default IP Time-to-live", PATH_MTU_AGING_TIMEOUT => "Path MTU Aging Timeout", PATH_MTU_PLATEAU_TABLE => "Path MTU Plateau Table", // IP LAYER PARAMETERS PER INTERFACE", INTERFACE_MTU => "Interface MTU", ALL_SUBNETS_ARE_LOCAL => "All Subnets are Local", BROADCAST_ADDRESS => "Broadcast Address", PERFORM_MASK_DISCOVERY => "Perform Mask Discovery", MASK_SUPPLIER => "Mask Supplier", PERFORM_ROUTER_DISCOVERY => "Perform Router Discovery", ROUTER_SOLICITATION_ADDRESS => "Router Solicitation Address", STATIC_ROUTE => "Static Route", // LINK LAYER PARAMETERS PER INTERFACE", TRAILER_ENCAPSULATION => "Trailer Encapsulation", ARP_CACHE_TIMEOUT => "ARP Cache Timeout", ETHERNET_ENCAPSULATION => "Ethernet Encapsulation", // TCP PARAMETERS", TCP_DEFAULT_TTL => "TCP Default TTL", TCP_KEEPALIVE_INTERVAL => "TCP Keepalive Interval", TCP_KEEPALIVE_GARBAGE => "TCP Keepalive Garbage", // APPLICATION AND SERVICE PARAMETERS", NETWORK_INFORMATION_SERVICE_DOMAIN => "Network Information Service Domain", NETWORK_INFORMATION_SERVERS => "Network Information Servers", NETWORK_TIME_PROTOCOL_SERVERS => "Network Time Protocol Servers", VENDOR_SPECIFIC_INFORMATION => "Vendor Specific Information", NETBIOS_OVER_TCPIP_NAME_SERVER => "NetBIOS over TCP/IP Name Server", NETBIOS_OVER_TCPIP_DATAGRAM_DISTRIBUTION_SERVER => { "NetBIOS over TCP/IP Datagram Distribution Server" } NETBIOS_OVER_TCPIP_NODE_TYPE => "NetBIOS over TCP/IP Node Type", NETBIOS_OVER_TCPIP_SCOPE => "NetBIOS over TCP/IP Scope", XWINDOW_SYSTEM_FONT_SERVER => "X Window System Font Server", XWINDOW_SYSTEM_DISPLAY_MANAGER => "X Window System Display Manager", NETWORK_INFORMATION_SERVICEPLUS_DOMAIN => "Network Information Service+ Domain", NETWORK_INFORMATION_SERVICEPLUS_SERVERS => "Network Information Service+ Servers", MOBILE_IP_HOME_AGENT => "Mobile IP Home Agent", SIMPLE_MAIL_TRANSPORT_PROTOCOL => "Simple Mail Transport Protocol (SMTP) Server", POST_OFFICE_PROTOCOL_SERVER => "Post Office Protocol (POP3) Server", NETWORK_NEWS_TRANSPORT_PROTOCOL => "Network News Transport Protocol (NNTP) Server", DEFAULT_WORLD_WIDE_WEB_SERVER => "Default World Wide Web (WWW) Server", DEFAULT_FINGER_SERVER => "Default Finger Server", DEFAULT_INTERNET_RELAY_CHAT_SERVER => "Default Internet Relay Chat (IRC) Server", STREETTALK_SERVER => "StreetTalk Server", STREETTALK_DIRECTORY_ASSISTANCE => "StreetTalk Directory Assistance (STDA) Server", RELAY_AGENT_INFORMATION => "Relay Agent Information", // DHCP EXTENSIONS REQUESTED_IP_ADDRESS => "Requested IP Address", IP_ADDRESS_LEASE_TIME => "IP Address Lease Time", OVERLOAD => "Overload", DHCP_MESSAGE_TYPE => "DHCP Message Type", SERVER_IDENTIFIER => "Server Identifier", PARAMETER_REQUEST_LIST => "Parameter Request List", MESSAGE => "Message", MAXIMUM_DHCP_MESSAGE_SIZE => "Maximum DHCP Message Size", RENEWAL_TIME_VALUE => "Renewal (T1) Time Value", REBINDING_TIME_VALUE => "Rebinding (T2) Time Value", VENDOR_CLASS_IDENTIFIER => "Vendor class identifier", CLIENT_IDENTIFIER => "Client-identifier", // Find below TFTP_SERVER_NAME => "TFTP server name", BOOTFILE_NAME => "Bootfile name", USER_CLASS => "User Class", CLIENT_ARCHITECTURE => "Client Architecture", TZ_POSIX_STRING => "TZ-POSIX String", TZ_DATABASE_STRING => "TZ-Database String", CLASSLESS_ROUTE_FORMAT => "Classless Route Format", _ => return None, }) } /// /// DHCP Message Type. /// /// # Standards /// /// The semantics of the various DHCP message types are described in RFC 2131 (see Table 2). /// Their numeric values are described in Section 9.6 of RFC 2132, which begins: /// /// > This option is used to convey the type of the DHCP message. The code for this option is 53, /// > and its length is 1. /// #[derive(Primitive, Copy, Clone, PartialEq)] pub enum MessageType { /// Client broadcast to locate available servers. Discover = 1, /// Server to client in response to DHCPDISCOVER with offer of configuration parameters. Offer = 2, /// Client message to servers either (a) requesting offered parameters from one server and /// implicitly declining offers from all others, (b) confirming correctness of previously /// allocated address after, e.g., system reboot, or (c) extending the lease on a particular /// network address. Request = 3, /// Client to server indicating network address is already in use. Decline = 4, /// Server to client with configuration parameters, including committed network address. Ack = 5, /// Server to client indicating client's notion of network address is incorrect (e.g., client /// has moved to new subnet) or client's lease as expired. Nak = 6, /// Client to server relinquishing network address and cancelling remaining lease. Release = 7, /// Client to server, asking only for local configuration parameters; client already has /// externally configured network address. Inform = 8, } impl MessageType { pub fn from(val: u8) -> Result<MessageType, String> { MessageType::from_u8(val).ok_or_else(|| format!["Invalid DHCP Message Type: {:?}", val]) } }
random_line_split
options.rs
use num_traits::FromPrimitive; use std::net::Ipv4Addr; #[derive(PartialEq, Clone)] pub struct RawDhcpOption { pub code: u8, pub data: Vec<u8>, } #[derive(PartialEq)] pub enum DhcpOption { DhcpMessageType(MessageType), ServerIdentifier(Ipv4Addr), ParameterRequestList(Vec<u8>), RequestedIpAddress(Ipv4Addr), HostName(String), Router(Vec<Ipv4Addr>), DomainNameServer(Vec<Ipv4Addr>), IpAddressLeaseTime(u32), SubnetMask(Ipv4Addr), Message(String), Unrecognized(RawDhcpOption), } impl DhcpOption { pub fn to_raw(&self) -> RawDhcpOption
data: name.as_bytes().to_vec(), }, Self::Router(addrs) => RawDhcpOption { code: ROUTER, data: { let mut v = vec![]; for a in addrs { v.extend(a.octets().iter()); } v }, }, Self::DomainNameServer(addrs) => RawDhcpOption { code: DOMAIN_NAME_SERVER, data: { let mut v = vec![]; for a in addrs { v.extend(a.octets().iter()); } v }, }, Self::IpAddressLeaseTime(secs) => RawDhcpOption { code: IP_ADDRESS_LEASE_TIME, data: secs.to_be_bytes().to_vec(), }, Self::SubnetMask(mask) => RawDhcpOption { code: SUBNET_MASK, data: mask.octets().to_vec(), }, Self::Message(msg) => RawDhcpOption { code: MESSAGE, data: msg.as_bytes().to_vec(), }, Self::Unrecognized(raw) => raw.clone(), } } pub fn code(&self) -> u8 { match self { Self::DhcpMessageType(_) => DHCP_MESSAGE_TYPE, Self::ServerIdentifier(_) => SERVER_IDENTIFIER, Self::ParameterRequestList(_) => PARAMETER_REQUEST_LIST, Self::RequestedIpAddress(_) => REQUESTED_IP_ADDRESS, Self::HostName(_) => HOST_NAME, Self::Router(_) => ROUTER, Self::DomainNameServer(_) => DOMAIN_NAME_SERVER, Self::IpAddressLeaseTime(_) => IP_ADDRESS_LEASE_TIME, Self::SubnetMask(_) => SUBNET_MASK, Self::Message(_) => MESSAGE, Self::Unrecognized(x) => x.code, } } } // DHCP Options; pub const SUBNET_MASK: u8 = 1; pub const TIME_OFFSET: u8 = 2; pub const ROUTER: u8 = 3; pub const TIME_SERVER: u8 = 4; pub const NAME_SERVER: u8 = 5; pub const DOMAIN_NAME_SERVER: u8 = 6; pub const LOG_SERVER: u8 = 7; pub const COOKIE_SERVER: u8 = 8; pub const LPR_SERVER: u8 = 9; pub const IMPRESS_SERVER: u8 = 10; pub const RESOURCE_LOCATION_SERVER: u8 = 11; pub const HOST_NAME: u8 = 12; pub const BOOT_FILE_SIZE: u8 = 13; pub const MERIT_DUMP_FILE: u8 = 14; pub const DOMAIN_NAME: u8 = 15; pub const SWAP_SERVER: u8 = 16; pub const ROOT_PATH: u8 = 17; pub const EXTENSIONS_PATH: u8 = 18; // IP LAYER PARAMETERS PER HOST; pub const IP_FORWARDING_ENABLE_DISABLE: u8 = 19; pub const NON_LOCAL_SOURCE_ROUTING_ENABLE_DISABLE: u8 = 20; pub const POLICY_FILTER: u8 = 21; pub const MAXIMUM_DATAGRAM_REASSEMBLY_SIZE: u8 = 22; pub const DEFAULT_IP_TIME_TO_LIVE: u8 = 23; pub const PATH_MTU_AGING_TIMEOUT: u8 = 24; pub const PATH_MTU_PLATEAU_TABLE: u8 = 25; // IP LAYER PARAMETERS PER INTERFACE; pub const INTERFACE_MTU: u8 = 26; pub const ALL_SUBNETS_ARE_LOCAL: u8 = 27; pub const BROADCAST_ADDRESS: u8 = 28; pub const PERFORM_MASK_DISCOVERY: u8 = 29; pub const MASK_SUPPLIER: u8 = 30; pub const PERFORM_ROUTER_DISCOVERY: u8 = 31; pub const ROUTER_SOLICITATION_ADDRESS: u8 = 32; pub const STATIC_ROUTE: u8 = 33; // LINK LAYER PARAMETERS PER INTERFACE; pub const TRAILER_ENCAPSULATION: u8 = 34; pub const ARP_CACHE_TIMEOUT: u8 = 35; pub const ETHERNET_ENCAPSULATION: u8 = 36; // TCP PARAMETERS; pub const TCP_DEFAULT_TTL: u8 = 37; pub const TCP_KEEPALIVE_INTERVAL: u8 = 38; pub const TCP_KEEPALIVE_GARBAGE: u8 = 39; // APPLICATION AND SERVICE PARAMETERS; pub const NETWORK_INFORMATION_SERVICE_DOMAIN: u8 = 40; pub const NETWORK_INFORMATION_SERVERS: u8 = 41; pub const NETWORK_TIME_PROTOCOL_SERVERS: u8 = 42; pub const VENDOR_SPECIFIC_INFORMATION: u8 = 43; pub const NETBIOS_OVER_TCPIP_NAME_SERVER: u8 = 44; pub const NETBIOS_OVER_TCPIP_DATAGRAM_DISTRIBUTION_SERVER: u8 = 45; pub const NETBIOS_OVER_TCPIP_NODE_TYPE: u8 = 46; pub const NETBIOS_OVER_TCPIP_SCOPE: u8 = 47; pub const XWINDOW_SYSTEM_FONT_SERVER: u8 = 48; pub const XWINDOW_SYSTEM_DISPLAY_MANAGER: u8 = 49; pub const NETWORK_INFORMATION_SERVICEPLUS_DOMAIN: u8 = 64; pub const NETWORK_INFORMATION_SERVICEPLUS_SERVERS: u8 = 65; pub const MOBILE_IP_HOME_AGENT: u8 = 68; pub const SIMPLE_MAIL_TRANSPORT_PROTOCOL: u8 = 69; pub const POST_OFFICE_PROTOCOL_SERVER: u8 = 70; pub const NETWORK_NEWS_TRANSPORT_PROTOCOL: u8 = 71; pub const DEFAULT_WORLD_WIDE_WEB_SERVER: u8 = 72; pub const DEFAULT_FINGER_SERVER: u8 = 73; pub const DEFAULT_INTERNET_RELAY_CHAT_SERVER: u8 = 74; pub const STREETTALK_SERVER: u8 = 75; pub const STREETTALK_DIRECTORY_ASSISTANCE: u8 = 76; pub const RELAY_AGENT_INFORMATION: u8 = 82; // DHCP EXTENSIONS pub const REQUESTED_IP_ADDRESS: u8 = 50; pub const IP_ADDRESS_LEASE_TIME: u8 = 51; pub const OVERLOAD: u8 = 52; pub const DHCP_MESSAGE_TYPE: u8 = 53; pub const SERVER_IDENTIFIER: u8 = 54; pub const PARAMETER_REQUEST_LIST: u8 = 55; pub const MESSAGE: u8 = 56; pub const MAXIMUM_DHCP_MESSAGE_SIZE: u8 = 57; pub const RENEWAL_TIME_VALUE: u8 = 58; pub const REBINDING_TIME_VALUE: u8 = 59; pub const VENDOR_CLASS_IDENTIFIER: u8 = 60; pub const CLIENT_IDENTIFIER: u8 = 61; pub const TFTP_SERVER_NAME: u8 = 66; pub const BOOTFILE_NAME: u8 = 67; pub const USER_CLASS: u8 = 77; pub const CLIENT_ARCHITECTURE: u8 = 93; pub const TZ_POSIX_STRING: u8 = 100; pub const TZ_DATABASE_STRING: u8 = 101; pub const CLASSLESS_ROUTE_FORMAT: u8 = 121; /// Returns title of DHCP Option code, if known. pub fn title(code: u8) -> Option<&'static str> { Some(match code { SUBNET_MASK => "Subnet Mask", TIME_OFFSET => "Time Offset", ROUTER => "Router", TIME_SERVER => "Time Server", NAME_SERVER => "Name Server", DOMAIN_NAME_SERVER => "Domain Name Server", LOG_SERVER => "Log Server", COOKIE_SERVER => "Cookie Server", LPR_SERVER => "LPR Server", IMPRESS_SERVER => "Impress Server", RESOURCE_LOCATION_SERVER => "Resource Location Server", HOST_NAME => "Host Name", BOOT_FILE_SIZE => "Boot File Size", MERIT_DUMP_FILE => "Merit Dump File", DOMAIN_NAME => "Domain Name", SWAP_SERVER => "Swap Server", ROOT_PATH => "Root Path", EXTENSIONS_PATH => "Extensions Path", // IP LAYER PARAMETERS PER HOST", IP_FORWARDING_ENABLE_DISABLE => "IP Forwarding Enable/Disable", NON_LOCAL_SOURCE_ROUTING_ENABLE_DISABLE => "Non-Local Source Routing Enable/Disable", POLICY_FILTER => "Policy Filter", MAXIMUM_DATAGRAM_REASSEMBLY_SIZE => "Maximum Datagram Reassembly Size", DEFAULT_IP_TIME_TO_LIVE => "Default IP Time-to-live", PATH_MTU_AGING_TIMEOUT => "Path MTU Aging Timeout", PATH_MTU_PLATEAU_TABLE => "Path MTU Plateau Table", // IP LAYER PARAMETERS PER INTERFACE", INTERFACE_MTU => "Interface MTU", ALL_SUBNETS_ARE_LOCAL => "All Subnets are Local", BROADCAST_ADDRESS => "Broadcast Address", PERFORM_MASK_DISCOVERY => "Perform Mask Discovery", MASK_SUPPLIER => "Mask Supplier", PERFORM_ROUTER_DISCOVERY => "Perform Router Discovery", ROUTER_SOLICITATION_ADDRESS => "Router Solicitation Address", STATIC_ROUTE => "Static Route", // LINK LAYER PARAMETERS PER INTERFACE", TRAILER_ENCAPSULATION => "Trailer Encapsulation", ARP_CACHE_TIMEOUT => "ARP Cache Timeout", ETHERNET_ENCAPSULATION => "Ethernet Encapsulation", // TCP PARAMETERS", TCP_DEFAULT_TTL => "TCP Default TTL", TCP_KEEPALIVE_INTERVAL => "TCP Keepalive Interval", TCP_KEEPALIVE_GARBAGE => "TCP Keepalive Garbage", // APPLICATION AND SERVICE PARAMETERS", NETWORK_INFORMATION_SERVICE_DOMAIN => "Network Information Service Domain", NETWORK_INFORMATION_SERVERS => "Network Information Servers", NETWORK_TIME_PROTOCOL_SERVERS => "Network Time Protocol Servers", VENDOR_SPECIFIC_INFORMATION => "Vendor Specific Information", NETBIOS_OVER_TCPIP_NAME_SERVER => "NetBIOS over TCP/IP Name Server", NETBIOS_OVER_TCPIP_DATAGRAM_DISTRIBUTION_SERVER => { "NetBIOS over TCP/IP Datagram Distribution Server" } NETBIOS_OVER_TCPIP_NODE_TYPE => "NetBIOS over TCP/IP Node Type", NETBIOS_OVER_TCPIP_SCOPE => "NetBIOS over TCP/IP Scope", XWINDOW_SYSTEM_FONT_SERVER => "X Window System Font Server", XWINDOW_SYSTEM_DISPLAY_MANAGER => "X Window System Display Manager", NETWORK_INFORMATION_SERVICEPLUS_DOMAIN => "Network Information Service+ Domain", NETWORK_INFORMATION_SERVICEPLUS_SERVERS => "Network Information Service+ Servers", MOBILE_IP_HOME_AGENT => "Mobile IP Home Agent", SIMPLE_MAIL_TRANSPORT_PROTOCOL => "Simple Mail Transport Protocol (SMTP) Server", POST_OFFICE_PROTOCOL_SERVER => "Post Office Protocol (POP3) Server", NETWORK_NEWS_TRANSPORT_PROTOCOL => "Network News Transport Protocol (NNTP) Server", DEFAULT_WORLD_WIDE_WEB_SERVER => "Default World Wide Web (WWW) Server", DEFAULT_FINGER_SERVER => "Default Finger Server", DEFAULT_INTERNET_RELAY_CHAT_SERVER => "Default Internet Relay Chat (IRC) Server", STREETTALK_SERVER => "StreetTalk Server", STREETTALK_DIRECTORY_ASSISTANCE => "StreetTalk Directory Assistance (STDA) Server", RELAY_AGENT_INFORMATION => "Relay Agent Information", // DHCP EXTENSIONS REQUESTED_IP_ADDRESS => "Requested IP Address", IP_ADDRESS_LEASE_TIME => "IP Address Lease Time", OVERLOAD => "Overload", DHCP_MESSAGE_TYPE => "DHCP Message Type", SERVER_IDENTIFIER => "Server Identifier", PARAMETER_REQUEST_LIST => "Parameter Request List", MESSAGE => "Message", MAXIMUM_DHCP_MESSAGE_SIZE => "Maximum DHCP Message Size", RENEWAL_TIME_VALUE => "Renewal (T1) Time Value", REBINDING_TIME_VALUE => "Rebinding (T2) Time Value", VENDOR_CLASS_IDENTIFIER => "Vendor class identifier", CLIENT_IDENTIFIER => "Client-identifier", // Find below TFTP_SERVER_NAME => "TFTP server name", BOOTFILE_NAME => "Bootfile name", USER_CLASS => "User Class", CLIENT_ARCHITECTURE => "Client Architecture", TZ_POSIX_STRING => "TZ-POSIX String", TZ_DATABASE_STRING => "TZ-Database String", CLASSLESS_ROUTE_FORMAT => "Classless Route Format", _ => return None, }) } /// /// DHCP Message Type. /// /// # Standards /// /// The semantics of the various DHCP message types are described in RFC 2131 (see Table 2). /// Their numeric values are described in Section 9.6 of RFC 2132, which begins: /// /// > This option is used to convey the type of the DHCP message. The code for this option is 53, /// > and its length is 1. /// #[derive(Primitive, Copy, Clone, PartialEq)] pub enum MessageType { /// Client broadcast to locate available servers. Discover = 1, /// Server to client in response to DHCPDISCOVER with offer of configuration parameters. Offer = 2, /// Client message to servers either (a) requesting offered parameters from one server and /// implicitly declining offers from all others, (b) confirming correctness of previously /// allocated address after, e.g., system reboot, or (c) extending the lease on a particular /// network address. Request = 3, /// Client to server indicating network address is already in use. Decline = 4, /// Server to client with configuration parameters, including committed network address. Ack = 5, /// Server to client indicating client's notion of network address is incorrect (e.g., client /// has moved to new subnet) or client's lease as expired. Nak = 6, /// Client to server relinquishing network address and cancelling remaining lease. Release = 7, /// Client to server, asking only for local configuration parameters; client already has /// externally configured network address. Inform = 8, } impl MessageType { pub fn from(val: u8) -> Result<MessageType, String> { MessageType::from_u8(val).ok_or_else(|| format!["Invalid DHCP Message Type: {:?}", val]) } }
{ match self { Self::DhcpMessageType(mtype) => RawDhcpOption { code: DHCP_MESSAGE_TYPE, data: vec![*mtype as u8], }, Self::ServerIdentifier(addr) => RawDhcpOption { code: SERVER_IDENTIFIER, data: addr.octets().to_vec(), }, Self::ParameterRequestList(prl) => RawDhcpOption { code: PARAMETER_REQUEST_LIST, data: prl.clone(), }, Self::RequestedIpAddress(addr) => RawDhcpOption { code: REQUESTED_IP_ADDRESS, data: addr.octets().to_vec(), }, Self::HostName(name) => RawDhcpOption { code: HOST_NAME,
identifier_body
options.rs
use num_traits::FromPrimitive; use std::net::Ipv4Addr; #[derive(PartialEq, Clone)] pub struct RawDhcpOption { pub code: u8, pub data: Vec<u8>, } #[derive(PartialEq)] pub enum DhcpOption { DhcpMessageType(MessageType), ServerIdentifier(Ipv4Addr), ParameterRequestList(Vec<u8>), RequestedIpAddress(Ipv4Addr), HostName(String), Router(Vec<Ipv4Addr>), DomainNameServer(Vec<Ipv4Addr>), IpAddressLeaseTime(u32), SubnetMask(Ipv4Addr), Message(String), Unrecognized(RawDhcpOption), } impl DhcpOption { pub fn
(&self) -> RawDhcpOption { match self { Self::DhcpMessageType(mtype) => RawDhcpOption { code: DHCP_MESSAGE_TYPE, data: vec![*mtype as u8], }, Self::ServerIdentifier(addr) => RawDhcpOption { code: SERVER_IDENTIFIER, data: addr.octets().to_vec(), }, Self::ParameterRequestList(prl) => RawDhcpOption { code: PARAMETER_REQUEST_LIST, data: prl.clone(), }, Self::RequestedIpAddress(addr) => RawDhcpOption { code: REQUESTED_IP_ADDRESS, data: addr.octets().to_vec(), }, Self::HostName(name) => RawDhcpOption { code: HOST_NAME, data: name.as_bytes().to_vec(), }, Self::Router(addrs) => RawDhcpOption { code: ROUTER, data: { let mut v = vec![]; for a in addrs { v.extend(a.octets().iter()); } v }, }, Self::DomainNameServer(addrs) => RawDhcpOption { code: DOMAIN_NAME_SERVER, data: { let mut v = vec![]; for a in addrs { v.extend(a.octets().iter()); } v }, }, Self::IpAddressLeaseTime(secs) => RawDhcpOption { code: IP_ADDRESS_LEASE_TIME, data: secs.to_be_bytes().to_vec(), }, Self::SubnetMask(mask) => RawDhcpOption { code: SUBNET_MASK, data: mask.octets().to_vec(), }, Self::Message(msg) => RawDhcpOption { code: MESSAGE, data: msg.as_bytes().to_vec(), }, Self::Unrecognized(raw) => raw.clone(), } } pub fn code(&self) -> u8 { match self { Self::DhcpMessageType(_) => DHCP_MESSAGE_TYPE, Self::ServerIdentifier(_) => SERVER_IDENTIFIER, Self::ParameterRequestList(_) => PARAMETER_REQUEST_LIST, Self::RequestedIpAddress(_) => REQUESTED_IP_ADDRESS, Self::HostName(_) => HOST_NAME, Self::Router(_) => ROUTER, Self::DomainNameServer(_) => DOMAIN_NAME_SERVER, Self::IpAddressLeaseTime(_) => IP_ADDRESS_LEASE_TIME, Self::SubnetMask(_) => SUBNET_MASK, Self::Message(_) => MESSAGE, Self::Unrecognized(x) => x.code, } } } // DHCP Options; pub const SUBNET_MASK: u8 = 1; pub const TIME_OFFSET: u8 = 2; pub const ROUTER: u8 = 3; pub const TIME_SERVER: u8 = 4; pub const NAME_SERVER: u8 = 5; pub const DOMAIN_NAME_SERVER: u8 = 6; pub const LOG_SERVER: u8 = 7; pub const COOKIE_SERVER: u8 = 8; pub const LPR_SERVER: u8 = 9; pub const IMPRESS_SERVER: u8 = 10; pub const RESOURCE_LOCATION_SERVER: u8 = 11; pub const HOST_NAME: u8 = 12; pub const BOOT_FILE_SIZE: u8 = 13; pub const MERIT_DUMP_FILE: u8 = 14; pub const DOMAIN_NAME: u8 = 15; pub const SWAP_SERVER: u8 = 16; pub const ROOT_PATH: u8 = 17; pub const EXTENSIONS_PATH: u8 = 18; // IP LAYER PARAMETERS PER HOST; pub const IP_FORWARDING_ENABLE_DISABLE: u8 = 19; pub const NON_LOCAL_SOURCE_ROUTING_ENABLE_DISABLE: u8 = 20; pub const POLICY_FILTER: u8 = 21; pub const MAXIMUM_DATAGRAM_REASSEMBLY_SIZE: u8 = 22; pub const DEFAULT_IP_TIME_TO_LIVE: u8 = 23; pub const PATH_MTU_AGING_TIMEOUT: u8 = 24; pub const PATH_MTU_PLATEAU_TABLE: u8 = 25; // IP LAYER PARAMETERS PER INTERFACE; pub const INTERFACE_MTU: u8 = 26; pub const ALL_SUBNETS_ARE_LOCAL: u8 = 27; pub const BROADCAST_ADDRESS: u8 = 28; pub const PERFORM_MASK_DISCOVERY: u8 = 29; pub const MASK_SUPPLIER: u8 = 30; pub const PERFORM_ROUTER_DISCOVERY: u8 = 31; pub const ROUTER_SOLICITATION_ADDRESS: u8 = 32; pub const STATIC_ROUTE: u8 = 33; // LINK LAYER PARAMETERS PER INTERFACE; pub const TRAILER_ENCAPSULATION: u8 = 34; pub const ARP_CACHE_TIMEOUT: u8 = 35; pub const ETHERNET_ENCAPSULATION: u8 = 36; // TCP PARAMETERS; pub const TCP_DEFAULT_TTL: u8 = 37; pub const TCP_KEEPALIVE_INTERVAL: u8 = 38; pub const TCP_KEEPALIVE_GARBAGE: u8 = 39; // APPLICATION AND SERVICE PARAMETERS; pub const NETWORK_INFORMATION_SERVICE_DOMAIN: u8 = 40; pub const NETWORK_INFORMATION_SERVERS: u8 = 41; pub const NETWORK_TIME_PROTOCOL_SERVERS: u8 = 42; pub const VENDOR_SPECIFIC_INFORMATION: u8 = 43; pub const NETBIOS_OVER_TCPIP_NAME_SERVER: u8 = 44; pub const NETBIOS_OVER_TCPIP_DATAGRAM_DISTRIBUTION_SERVER: u8 = 45; pub const NETBIOS_OVER_TCPIP_NODE_TYPE: u8 = 46; pub const NETBIOS_OVER_TCPIP_SCOPE: u8 = 47; pub const XWINDOW_SYSTEM_FONT_SERVER: u8 = 48; pub const XWINDOW_SYSTEM_DISPLAY_MANAGER: u8 = 49; pub const NETWORK_INFORMATION_SERVICEPLUS_DOMAIN: u8 = 64; pub const NETWORK_INFORMATION_SERVICEPLUS_SERVERS: u8 = 65; pub const MOBILE_IP_HOME_AGENT: u8 = 68; pub const SIMPLE_MAIL_TRANSPORT_PROTOCOL: u8 = 69; pub const POST_OFFICE_PROTOCOL_SERVER: u8 = 70; pub const NETWORK_NEWS_TRANSPORT_PROTOCOL: u8 = 71; pub const DEFAULT_WORLD_WIDE_WEB_SERVER: u8 = 72; pub const DEFAULT_FINGER_SERVER: u8 = 73; pub const DEFAULT_INTERNET_RELAY_CHAT_SERVER: u8 = 74; pub const STREETTALK_SERVER: u8 = 75; pub const STREETTALK_DIRECTORY_ASSISTANCE: u8 = 76; pub const RELAY_AGENT_INFORMATION: u8 = 82; // DHCP EXTENSIONS pub const REQUESTED_IP_ADDRESS: u8 = 50; pub const IP_ADDRESS_LEASE_TIME: u8 = 51; pub const OVERLOAD: u8 = 52; pub const DHCP_MESSAGE_TYPE: u8 = 53; pub const SERVER_IDENTIFIER: u8 = 54; pub const PARAMETER_REQUEST_LIST: u8 = 55; pub const MESSAGE: u8 = 56; pub const MAXIMUM_DHCP_MESSAGE_SIZE: u8 = 57; pub const RENEWAL_TIME_VALUE: u8 = 58; pub const REBINDING_TIME_VALUE: u8 = 59; pub const VENDOR_CLASS_IDENTIFIER: u8 = 60; pub const CLIENT_IDENTIFIER: u8 = 61; pub const TFTP_SERVER_NAME: u8 = 66; pub const BOOTFILE_NAME: u8 = 67; pub const USER_CLASS: u8 = 77; pub const CLIENT_ARCHITECTURE: u8 = 93; pub const TZ_POSIX_STRING: u8 = 100; pub const TZ_DATABASE_STRING: u8 = 101; pub const CLASSLESS_ROUTE_FORMAT: u8 = 121; /// Returns title of DHCP Option code, if known. pub fn title(code: u8) -> Option<&'static str> { Some(match code { SUBNET_MASK => "Subnet Mask", TIME_OFFSET => "Time Offset", ROUTER => "Router", TIME_SERVER => "Time Server", NAME_SERVER => "Name Server", DOMAIN_NAME_SERVER => "Domain Name Server", LOG_SERVER => "Log Server", COOKIE_SERVER => "Cookie Server", LPR_SERVER => "LPR Server", IMPRESS_SERVER => "Impress Server", RESOURCE_LOCATION_SERVER => "Resource Location Server", HOST_NAME => "Host Name", BOOT_FILE_SIZE => "Boot File Size", MERIT_DUMP_FILE => "Merit Dump File", DOMAIN_NAME => "Domain Name", SWAP_SERVER => "Swap Server", ROOT_PATH => "Root Path", EXTENSIONS_PATH => "Extensions Path", // IP LAYER PARAMETERS PER HOST", IP_FORWARDING_ENABLE_DISABLE => "IP Forwarding Enable/Disable", NON_LOCAL_SOURCE_ROUTING_ENABLE_DISABLE => "Non-Local Source Routing Enable/Disable", POLICY_FILTER => "Policy Filter", MAXIMUM_DATAGRAM_REASSEMBLY_SIZE => "Maximum Datagram Reassembly Size", DEFAULT_IP_TIME_TO_LIVE => "Default IP Time-to-live", PATH_MTU_AGING_TIMEOUT => "Path MTU Aging Timeout", PATH_MTU_PLATEAU_TABLE => "Path MTU Plateau Table", // IP LAYER PARAMETERS PER INTERFACE", INTERFACE_MTU => "Interface MTU", ALL_SUBNETS_ARE_LOCAL => "All Subnets are Local", BROADCAST_ADDRESS => "Broadcast Address", PERFORM_MASK_DISCOVERY => "Perform Mask Discovery", MASK_SUPPLIER => "Mask Supplier", PERFORM_ROUTER_DISCOVERY => "Perform Router Discovery", ROUTER_SOLICITATION_ADDRESS => "Router Solicitation Address", STATIC_ROUTE => "Static Route", // LINK LAYER PARAMETERS PER INTERFACE", TRAILER_ENCAPSULATION => "Trailer Encapsulation", ARP_CACHE_TIMEOUT => "ARP Cache Timeout", ETHERNET_ENCAPSULATION => "Ethernet Encapsulation", // TCP PARAMETERS", TCP_DEFAULT_TTL => "TCP Default TTL", TCP_KEEPALIVE_INTERVAL => "TCP Keepalive Interval", TCP_KEEPALIVE_GARBAGE => "TCP Keepalive Garbage", // APPLICATION AND SERVICE PARAMETERS", NETWORK_INFORMATION_SERVICE_DOMAIN => "Network Information Service Domain", NETWORK_INFORMATION_SERVERS => "Network Information Servers", NETWORK_TIME_PROTOCOL_SERVERS => "Network Time Protocol Servers", VENDOR_SPECIFIC_INFORMATION => "Vendor Specific Information", NETBIOS_OVER_TCPIP_NAME_SERVER => "NetBIOS over TCP/IP Name Server", NETBIOS_OVER_TCPIP_DATAGRAM_DISTRIBUTION_SERVER => { "NetBIOS over TCP/IP Datagram Distribution Server" } NETBIOS_OVER_TCPIP_NODE_TYPE => "NetBIOS over TCP/IP Node Type", NETBIOS_OVER_TCPIP_SCOPE => "NetBIOS over TCP/IP Scope", XWINDOW_SYSTEM_FONT_SERVER => "X Window System Font Server", XWINDOW_SYSTEM_DISPLAY_MANAGER => "X Window System Display Manager", NETWORK_INFORMATION_SERVICEPLUS_DOMAIN => "Network Information Service+ Domain", NETWORK_INFORMATION_SERVICEPLUS_SERVERS => "Network Information Service+ Servers", MOBILE_IP_HOME_AGENT => "Mobile IP Home Agent", SIMPLE_MAIL_TRANSPORT_PROTOCOL => "Simple Mail Transport Protocol (SMTP) Server", POST_OFFICE_PROTOCOL_SERVER => "Post Office Protocol (POP3) Server", NETWORK_NEWS_TRANSPORT_PROTOCOL => "Network News Transport Protocol (NNTP) Server", DEFAULT_WORLD_WIDE_WEB_SERVER => "Default World Wide Web (WWW) Server", DEFAULT_FINGER_SERVER => "Default Finger Server", DEFAULT_INTERNET_RELAY_CHAT_SERVER => "Default Internet Relay Chat (IRC) Server", STREETTALK_SERVER => "StreetTalk Server", STREETTALK_DIRECTORY_ASSISTANCE => "StreetTalk Directory Assistance (STDA) Server", RELAY_AGENT_INFORMATION => "Relay Agent Information", // DHCP EXTENSIONS REQUESTED_IP_ADDRESS => "Requested IP Address", IP_ADDRESS_LEASE_TIME => "IP Address Lease Time", OVERLOAD => "Overload", DHCP_MESSAGE_TYPE => "DHCP Message Type", SERVER_IDENTIFIER => "Server Identifier", PARAMETER_REQUEST_LIST => "Parameter Request List", MESSAGE => "Message", MAXIMUM_DHCP_MESSAGE_SIZE => "Maximum DHCP Message Size", RENEWAL_TIME_VALUE => "Renewal (T1) Time Value", REBINDING_TIME_VALUE => "Rebinding (T2) Time Value", VENDOR_CLASS_IDENTIFIER => "Vendor class identifier", CLIENT_IDENTIFIER => "Client-identifier", // Find below TFTP_SERVER_NAME => "TFTP server name", BOOTFILE_NAME => "Bootfile name", USER_CLASS => "User Class", CLIENT_ARCHITECTURE => "Client Architecture", TZ_POSIX_STRING => "TZ-POSIX String", TZ_DATABASE_STRING => "TZ-Database String", CLASSLESS_ROUTE_FORMAT => "Classless Route Format", _ => return None, }) } /// /// DHCP Message Type. /// /// # Standards /// /// The semantics of the various DHCP message types are described in RFC 2131 (see Table 2). /// Their numeric values are described in Section 9.6 of RFC 2132, which begins: /// /// > This option is used to convey the type of the DHCP message. The code for this option is 53, /// > and its length is 1. /// #[derive(Primitive, Copy, Clone, PartialEq)] pub enum MessageType { /// Client broadcast to locate available servers. Discover = 1, /// Server to client in response to DHCPDISCOVER with offer of configuration parameters. Offer = 2, /// Client message to servers either (a) requesting offered parameters from one server and /// implicitly declining offers from all others, (b) confirming correctness of previously /// allocated address after, e.g., system reboot, or (c) extending the lease on a particular /// network address. Request = 3, /// Client to server indicating network address is already in use. Decline = 4, /// Server to client with configuration parameters, including committed network address. Ack = 5, /// Server to client indicating client's notion of network address is incorrect (e.g., client /// has moved to new subnet) or client's lease as expired. Nak = 6, /// Client to server relinquishing network address and cancelling remaining lease. Release = 7, /// Client to server, asking only for local configuration parameters; client already has /// externally configured network address. Inform = 8, } impl MessageType { pub fn from(val: u8) -> Result<MessageType, String> { MessageType::from_u8(val).ok_or_else(|| format!["Invalid DHCP Message Type: {:?}", val]) } }
to_raw
identifier_name
progressevent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::ProgressEventBinding; use dom::bindings::codegen::Bindings::ProgressEventBinding::ProgressEventMethods; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::event::{Event, EventBubbles, EventCancelable}; use util::str::DOMString; #[dom_struct] pub struct
{ event: Event, length_computable: bool, loaded: u64, total: u64 } impl ProgressEvent { fn new_inherited(length_computable: bool, loaded: u64, total: u64) -> ProgressEvent { ProgressEvent { event: Event::new_inherited(), length_computable: length_computable, loaded: loaded, total: total } } pub fn new(global: GlobalRef, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, length_computable: bool, loaded: u64, total: u64) -> Root<ProgressEvent> { let ev = reflect_dom_object(box ProgressEvent::new_inherited(length_computable, loaded, total), global, ProgressEventBinding::Wrap); { let event = ev.upcast::<Event>(); event.InitEvent(type_, can_bubble == EventBubbles::Bubbles, cancelable == EventCancelable::Cancelable); } ev } pub fn Constructor(global: GlobalRef, type_: DOMString, init: &ProgressEventBinding::ProgressEventInit) -> Fallible<Root<ProgressEvent>> { let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble }; let cancelable = if init.parent.cancelable { EventCancelable::Cancelable } else { EventCancelable::NotCancelable }; let ev = ProgressEvent::new(global, type_, bubbles, cancelable, init.lengthComputable, init.loaded, init.total); Ok(ev) } } impl ProgressEventMethods for ProgressEvent { // https://xhr.spec.whatwg.org/#dom-progressevent-lengthcomputable fn LengthComputable(&self) -> bool { self.length_computable } // https://xhr.spec.whatwg.org/#dom-progressevent-loaded fn Loaded(&self) -> u64 { self.loaded } // https://xhr.spec.whatwg.org/#dom-progressevent-total fn Total(&self) -> u64 { self.total } }
ProgressEvent
identifier_name
progressevent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::ProgressEventBinding; use dom::bindings::codegen::Bindings::ProgressEventBinding::ProgressEventMethods; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::event::{Event, EventBubbles, EventCancelable}; use util::str::DOMString; #[dom_struct] pub struct ProgressEvent { event: Event, length_computable: bool, loaded: u64, total: u64 } impl ProgressEvent { fn new_inherited(length_computable: bool, loaded: u64, total: u64) -> ProgressEvent { ProgressEvent { event: Event::new_inherited(), length_computable: length_computable, loaded: loaded, total: total } } pub fn new(global: GlobalRef, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, length_computable: bool, loaded: u64, total: u64) -> Root<ProgressEvent>
pub fn Constructor(global: GlobalRef, type_: DOMString, init: &ProgressEventBinding::ProgressEventInit) -> Fallible<Root<ProgressEvent>> { let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble }; let cancelable = if init.parent.cancelable { EventCancelable::Cancelable } else { EventCancelable::NotCancelable }; let ev = ProgressEvent::new(global, type_, bubbles, cancelable, init.lengthComputable, init.loaded, init.total); Ok(ev) } } impl ProgressEventMethods for ProgressEvent { // https://xhr.spec.whatwg.org/#dom-progressevent-lengthcomputable fn LengthComputable(&self) -> bool { self.length_computable } // https://xhr.spec.whatwg.org/#dom-progressevent-loaded fn Loaded(&self) -> u64 { self.loaded } // https://xhr.spec.whatwg.org/#dom-progressevent-total fn Total(&self) -> u64 { self.total } }
{ let ev = reflect_dom_object(box ProgressEvent::new_inherited(length_computable, loaded, total), global, ProgressEventBinding::Wrap); { let event = ev.upcast::<Event>(); event.InitEvent(type_, can_bubble == EventBubbles::Bubbles, cancelable == EventCancelable::Cancelable); } ev }
identifier_body
progressevent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::ProgressEventBinding; use dom::bindings::codegen::Bindings::ProgressEventBinding::ProgressEventMethods; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::event::{Event, EventBubbles, EventCancelable}; use util::str::DOMString; #[dom_struct] pub struct ProgressEvent { event: Event, length_computable: bool, loaded: u64, total: u64 } impl ProgressEvent { fn new_inherited(length_computable: bool, loaded: u64, total: u64) -> ProgressEvent { ProgressEvent { event: Event::new_inherited(), length_computable: length_computable, loaded: loaded, total: total } } pub fn new(global: GlobalRef, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, length_computable: bool, loaded: u64, total: u64) -> Root<ProgressEvent> { let ev = reflect_dom_object(box ProgressEvent::new_inherited(length_computable, loaded, total), global, ProgressEventBinding::Wrap); { let event = ev.upcast::<Event>(); event.InitEvent(type_, can_bubble == EventBubbles::Bubbles, cancelable == EventCancelable::Cancelable); } ev } pub fn Constructor(global: GlobalRef, type_: DOMString, init: &ProgressEventBinding::ProgressEventInit) -> Fallible<Root<ProgressEvent>> { let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble }; let cancelable = if init.parent.cancelable { EventCancelable::Cancelable } else { EventCancelable::NotCancelable }; let ev = ProgressEvent::new(global, type_, bubbles, cancelable, init.lengthComputable, init.loaded, init.total); Ok(ev) } } impl ProgressEventMethods for ProgressEvent { // https://xhr.spec.whatwg.org/#dom-progressevent-lengthcomputable fn LengthComputable(&self) -> bool { self.length_computable } // https://xhr.spec.whatwg.org/#dom-progressevent-loaded fn Loaded(&self) -> u64 { self.loaded }
} }
// https://xhr.spec.whatwg.org/#dom-progressevent-total fn Total(&self) -> u64 { self.total
random_line_split
progressevent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::ProgressEventBinding; use dom::bindings::codegen::Bindings::ProgressEventBinding::ProgressEventMethods; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::event::{Event, EventBubbles, EventCancelable}; use util::str::DOMString; #[dom_struct] pub struct ProgressEvent { event: Event, length_computable: bool, loaded: u64, total: u64 } impl ProgressEvent { fn new_inherited(length_computable: bool, loaded: u64, total: u64) -> ProgressEvent { ProgressEvent { event: Event::new_inherited(), length_computable: length_computable, loaded: loaded, total: total } } pub fn new(global: GlobalRef, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, length_computable: bool, loaded: u64, total: u64) -> Root<ProgressEvent> { let ev = reflect_dom_object(box ProgressEvent::new_inherited(length_computable, loaded, total), global, ProgressEventBinding::Wrap); { let event = ev.upcast::<Event>(); event.InitEvent(type_, can_bubble == EventBubbles::Bubbles, cancelable == EventCancelable::Cancelable); } ev } pub fn Constructor(global: GlobalRef, type_: DOMString, init: &ProgressEventBinding::ProgressEventInit) -> Fallible<Root<ProgressEvent>> { let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble }; let cancelable = if init.parent.cancelable
else { EventCancelable::NotCancelable }; let ev = ProgressEvent::new(global, type_, bubbles, cancelable, init.lengthComputable, init.loaded, init.total); Ok(ev) } } impl ProgressEventMethods for ProgressEvent { // https://xhr.spec.whatwg.org/#dom-progressevent-lengthcomputable fn LengthComputable(&self) -> bool { self.length_computable } // https://xhr.spec.whatwg.org/#dom-progressevent-loaded fn Loaded(&self) -> u64 { self.loaded } // https://xhr.spec.whatwg.org/#dom-progressevent-total fn Total(&self) -> u64 { self.total } }
{ EventCancelable::Cancelable }
conditional_block
crypto.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::CryptoBinding; use dom::bindings::codegen::Bindings::CryptoBinding::CryptoMethods; use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::cell::DOMRefCell; use js::jsapi::{JSContext, JSObject}; use js::jsapi::{JS_GetObjectAsArrayBufferView, JS_GetArrayBufferViewType, Type}; use std::ptr; use std::slice; use rand::{Rng, OsRng}; no_jsmanaged_fields!(OsRng); // https://developer.mozilla.org/en-US/docs/Web/API/Crypto #[dom_struct] #[derive(HeapSizeOf)] pub struct Crypto { reflector_: Reflector, rng: DOMRefCell<OsRng>, } impl Crypto { fn new_inherited() -> Crypto
pub fn new(global: GlobalRef) -> Root<Crypto> { reflect_dom_object(box Crypto::new_inherited(), global, CryptoBinding::Wrap) } } impl<'a> CryptoMethods for &'a Crypto { #[allow(unsafe_code)] // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues fn GetRandomValues(self, _cx: *mut JSContext, input: *mut JSObject) -> Fallible<*mut JSObject> { let mut length = 0; let mut data = ptr::null_mut(); if unsafe { JS_GetObjectAsArrayBufferView(input, &mut length, &mut data).is_null() } { return Err(Error::Type("Argument to Crypto.getRandomValues is not an ArrayBufferView".to_owned())); } if!is_integer_buffer(input) { return Err(Error::TypeMismatch); } if length > 65536 { return Err(Error::QuotaExceeded); } let mut buffer = unsafe { slice::from_raw_parts_mut(data, length as usize) }; self.rng.borrow_mut().fill_bytes(&mut buffer); Ok(input) } } #[allow(unsafe_code)] fn is_integer_buffer(input: *mut JSObject) -> bool { match unsafe { JS_GetArrayBufferViewType(input) } { Type::Uint8 | Type::Uint8Clamped | Type::Int8 | Type::Uint16 | Type::Int16 | Type::Uint32 | Type::Int32 => true, _ => false } }
{ Crypto { reflector_: Reflector::new(), rng: DOMRefCell::new(OsRng::new().unwrap()), } }
identifier_body
crypto.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::CryptoBinding; use dom::bindings::codegen::Bindings::CryptoBinding::CryptoMethods; use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::cell::DOMRefCell; use js::jsapi::{JSContext, JSObject}; use js::jsapi::{JS_GetObjectAsArrayBufferView, JS_GetArrayBufferViewType, Type}; use std::ptr; use std::slice; use rand::{Rng, OsRng}; no_jsmanaged_fields!(OsRng); // https://developer.mozilla.org/en-US/docs/Web/API/Crypto #[dom_struct] #[derive(HeapSizeOf)] pub struct Crypto { reflector_: Reflector, rng: DOMRefCell<OsRng>, } impl Crypto { fn new_inherited() -> Crypto { Crypto { reflector_: Reflector::new(), rng: DOMRefCell::new(OsRng::new().unwrap()), } } pub fn new(global: GlobalRef) -> Root<Crypto> { reflect_dom_object(box Crypto::new_inherited(), global, CryptoBinding::Wrap) } } impl<'a> CryptoMethods for &'a Crypto { #[allow(unsafe_code)] // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues fn GetRandomValues(self, _cx: *mut JSContext, input: *mut JSObject) -> Fallible<*mut JSObject> { let mut length = 0; let mut data = ptr::null_mut(); if unsafe { JS_GetObjectAsArrayBufferView(input, &mut length, &mut data).is_null() } { return Err(Error::Type("Argument to Crypto.getRandomValues is not an ArrayBufferView".to_owned())); } if!is_integer_buffer(input) { return Err(Error::TypeMismatch); } if length > 65536 { return Err(Error::QuotaExceeded); } let mut buffer = unsafe { slice::from_raw_parts_mut(data, length as usize) }; self.rng.borrow_mut().fill_bytes(&mut buffer);
#[allow(unsafe_code)] fn is_integer_buffer(input: *mut JSObject) -> bool { match unsafe { JS_GetArrayBufferViewType(input) } { Type::Uint8 | Type::Uint8Clamped | Type::Int8 | Type::Uint16 | Type::Int16 | Type::Uint32 | Type::Int32 => true, _ => false } }
Ok(input) } }
random_line_split
crypto.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::CryptoBinding; use dom::bindings::codegen::Bindings::CryptoBinding::CryptoMethods; use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::cell::DOMRefCell; use js::jsapi::{JSContext, JSObject}; use js::jsapi::{JS_GetObjectAsArrayBufferView, JS_GetArrayBufferViewType, Type}; use std::ptr; use std::slice; use rand::{Rng, OsRng}; no_jsmanaged_fields!(OsRng); // https://developer.mozilla.org/en-US/docs/Web/API/Crypto #[dom_struct] #[derive(HeapSizeOf)] pub struct Crypto { reflector_: Reflector, rng: DOMRefCell<OsRng>, } impl Crypto { fn
() -> Crypto { Crypto { reflector_: Reflector::new(), rng: DOMRefCell::new(OsRng::new().unwrap()), } } pub fn new(global: GlobalRef) -> Root<Crypto> { reflect_dom_object(box Crypto::new_inherited(), global, CryptoBinding::Wrap) } } impl<'a> CryptoMethods for &'a Crypto { #[allow(unsafe_code)] // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues fn GetRandomValues(self, _cx: *mut JSContext, input: *mut JSObject) -> Fallible<*mut JSObject> { let mut length = 0; let mut data = ptr::null_mut(); if unsafe { JS_GetObjectAsArrayBufferView(input, &mut length, &mut data).is_null() } { return Err(Error::Type("Argument to Crypto.getRandomValues is not an ArrayBufferView".to_owned())); } if!is_integer_buffer(input) { return Err(Error::TypeMismatch); } if length > 65536 { return Err(Error::QuotaExceeded); } let mut buffer = unsafe { slice::from_raw_parts_mut(data, length as usize) }; self.rng.borrow_mut().fill_bytes(&mut buffer); Ok(input) } } #[allow(unsafe_code)] fn is_integer_buffer(input: *mut JSObject) -> bool { match unsafe { JS_GetArrayBufferViewType(input) } { Type::Uint8 | Type::Uint8Clamped | Type::Int8 | Type::Uint16 | Type::Int16 | Type::Uint32 | Type::Int32 => true, _ => false } }
new_inherited
identifier_name
dirname.rs
#![crate_name = "dirname"] /* * This file is part of the uutils coreutils package. * * (c) Derek Chiang <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; use std::path::Path; static NAME: &'static str = "dirname"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("z", "zero", "separate output with NUL rather than newline"); opts.optflag("", "help", "display this help and exit"); opts.optflag("", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!("Invalid options\n{}", f) }; if matches.opt_present("help") { let msg = format!("{0} {1} - strip last component from file name Usage: {0} [OPTION] NAME... Output each NAME with its last non-slash component and trailing slashes removed; if NAME contains no /'s, output '.' (meaning the current directory).", NAME, VERSION); print!("{}", opts.usage(&msg)); return 0; } if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } let separator = match matches.opt_present("zero") { true => "\0", false => "\n" }; if!matches.free.is_empty() { for path in matches.free.iter() { let p = Path::new(path); let d = p.parent().unwrap().to_str(); if d.is_some() { print!("{}", d.unwrap()); } print!("{}", separator); } } else { println!("{0}: missing operand", NAME); println!("Try '{0} --help' for more information.", NAME); return 1; } 0 } #[allow(dead_code)] fn
() { std::process::exit(uumain(std::env::args().collect())); }
main
identifier_name
dirname.rs
#![crate_name = "dirname"] /* * This file is part of the uutils coreutils package. * * (c) Derek Chiang <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; use std::path::Path; static NAME: &'static str = "dirname"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("z", "zero", "separate output with NUL rather than newline"); opts.optflag("", "help", "display this help and exit"); opts.optflag("", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!("Invalid options\n{}", f) }; if matches.opt_present("help") { let msg = format!("{0} {1} - strip last component from file name Usage: {0} [OPTION] NAME... Output each NAME with its last non-slash component and trailing slashes removed; if NAME contains no /'s, output '.' (meaning the current directory).", NAME, VERSION); print!("{}", opts.usage(&msg)); return 0; } if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } let separator = match matches.opt_present("zero") { true => "\0", false => "\n" }; if!matches.free.is_empty() { for path in matches.free.iter() { let p = Path::new(path); let d = p.parent().unwrap().to_str(); if d.is_some() { print!("{}", d.unwrap()); } print!("{}", separator); } } else { println!("{0}: missing operand", NAME); println!("Try '{0} --help' for more information.", NAME); return 1; } 0 } #[allow(dead_code)] fn main()
{ std::process::exit(uumain(std::env::args().collect())); }
identifier_body
dirname.rs
#![crate_name = "dirname"] /* * This file is part of the uutils coreutils package. * * (c) Derek Chiang <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; use std::path::Path; static NAME: &'static str = "dirname"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("z", "zero", "separate output with NUL rather than newline"); opts.optflag("", "help", "display this help and exit");
}; if matches.opt_present("help") { let msg = format!("{0} {1} - strip last component from file name Usage: {0} [OPTION] NAME... Output each NAME with its last non-slash component and trailing slashes removed; if NAME contains no /'s, output '.' (meaning the current directory).", NAME, VERSION); print!("{}", opts.usage(&msg)); return 0; } if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } let separator = match matches.opt_present("zero") { true => "\0", false => "\n" }; if!matches.free.is_empty() { for path in matches.free.iter() { let p = Path::new(path); let d = p.parent().unwrap().to_str(); if d.is_some() { print!("{}", d.unwrap()); } print!("{}", separator); } } else { println!("{0}: missing operand", NAME); println!("Try '{0} --help' for more information.", NAME); return 1; } 0 } #[allow(dead_code)] fn main() { std::process::exit(uumain(std::env::args().collect())); }
opts.optflag("", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!("Invalid options\n{}", f)
random_line_split
main.rs
extern crate time; use std::sync::{Arc, mpsc}; use std::thread; type Float = f64; type Integer = u32; type Callback = Box<Fn(Float) -> Float + Send + Sync +'static>; type FnThread = Fn() -> Callback + Send + Sync; #[derive(Clone)] struct Integrator { f: Arc<FnThread>, a: Float, b: Float, n: Integer, } impl Integrator { fn new(func: Arc<FnThread>, a: Float, b: Float, iteration: Integer) -> Integrator { Integrator { f: func, a: a, b: b, n: iteration, } } fn call(&self, x: Float) -> Float { (self.f)()(x) } // parallel Monte-Carlo method // share the desired reporting interval and are distributing to threads fn monte_carlo(&self, threads: Integer) -> Float { let mut thread_list = Vec::new(); let h_step = (self.b - self.a) / self.n as Float; let t_step = self.n / threads; let (tx, rx) = mpsc::channel::<Float>(); for i in 0..threads { let local_tx = tx.clone(); let local_self = self.clone(); thread_list.push(thread::spawn(move || { let u_i = |i: Integer| -> Float { local_self.a + h_step * i as Float }; let (x0, x1) = (t_step * i, t_step * (i+1)); // main part of method let sum = (x0..x1).fold(0.0, |acc, i| acc + local_self.call(u_i(i))); local_tx.send(sum).expect("Data not sended!"); })); } let mut result = 0.0; for thread in thread_list { thread.join().expect("Thread can't joined!"); result += rx.recv().expect("Data not recieved!"); } result * h_step } } // linear Monte-Carlo method fn monte_carlo_linear(f: Arc<FnThread>, a: Float, b: Float, n: Integer) -> Float { let h = (b - a) / n as Float; let u_i = |i: Integer| -> Float { a + h * i as Float }; (0..n).fold(0.0, |acc, x| acc + (f())(u_i(x))) * h } // calculated function fn f() -> Callback { Box::new(|x: Float| -> Float { (x.powf(2.0) + 1.0).recip() }) } fn main() { // [a, b] -- interval // n -- iteration count let (a, b, n) = (0.0, 1.0, 10_000_000); let f_a = Integrator::new(Arc::new(f), a, b, n); println!("# Iteration count: {:E}", n as Float); let start = time::get_time(); let pi = monte_carlo_linear(Arc::new(f), a, b, n) * 4.0; let duration = time::get_time() - start; println!("# Linear code"); println!("result = {:+.16}", pi); println!(" err = {:+.16}", std::f64::consts::PI - pi); println!(" time = {} ms\n", duration.num_milliseconds()); for threads in (1..9).filter(|&x| x % 2 == 0) { println!("# Thread count: {}", threads); let start = time::get_time(); let pi = f_a.monte_carlo(threads) * 4.0; let duration = time::get_time() - start;
println!("result = {:+.16}", pi); println!(" err = {:+.16}", std::f64::consts::PI - pi); println!(" time = {} ms\n", duration.num_milliseconds()); } }
random_line_split
main.rs
extern crate time; use std::sync::{Arc, mpsc}; use std::thread; type Float = f64; type Integer = u32; type Callback = Box<Fn(Float) -> Float + Send + Sync +'static>; type FnThread = Fn() -> Callback + Send + Sync; #[derive(Clone)] struct Integrator { f: Arc<FnThread>, a: Float, b: Float, n: Integer, } impl Integrator { fn new(func: Arc<FnThread>, a: Float, b: Float, iteration: Integer) -> Integrator { Integrator { f: func, a: a, b: b, n: iteration, } } fn call(&self, x: Float) -> Float { (self.f)()(x) } // parallel Monte-Carlo method // share the desired reporting interval and are distributing to threads fn
(&self, threads: Integer) -> Float { let mut thread_list = Vec::new(); let h_step = (self.b - self.a) / self.n as Float; let t_step = self.n / threads; let (tx, rx) = mpsc::channel::<Float>(); for i in 0..threads { let local_tx = tx.clone(); let local_self = self.clone(); thread_list.push(thread::spawn(move || { let u_i = |i: Integer| -> Float { local_self.a + h_step * i as Float }; let (x0, x1) = (t_step * i, t_step * (i+1)); // main part of method let sum = (x0..x1).fold(0.0, |acc, i| acc + local_self.call(u_i(i))); local_tx.send(sum).expect("Data not sended!"); })); } let mut result = 0.0; for thread in thread_list { thread.join().expect("Thread can't joined!"); result += rx.recv().expect("Data not recieved!"); } result * h_step } } // linear Monte-Carlo method fn monte_carlo_linear(f: Arc<FnThread>, a: Float, b: Float, n: Integer) -> Float { let h = (b - a) / n as Float; let u_i = |i: Integer| -> Float { a + h * i as Float }; (0..n).fold(0.0, |acc, x| acc + (f())(u_i(x))) * h } // calculated function fn f() -> Callback { Box::new(|x: Float| -> Float { (x.powf(2.0) + 1.0).recip() }) } fn main() { // [a, b] -- interval // n -- iteration count let (a, b, n) = (0.0, 1.0, 10_000_000); let f_a = Integrator::new(Arc::new(f), a, b, n); println!("# Iteration count: {:E}", n as Float); let start = time::get_time(); let pi = monte_carlo_linear(Arc::new(f), a, b, n) * 4.0; let duration = time::get_time() - start; println!("# Linear code"); println!("result = {:+.16}", pi); println!(" err = {:+.16}", std::f64::consts::PI - pi); println!(" time = {} ms\n", duration.num_milliseconds()); for threads in (1..9).filter(|&x| x % 2 == 0) { println!("# Thread count: {}", threads); let start = time::get_time(); let pi = f_a.monte_carlo(threads) * 4.0; let duration = time::get_time() - start; println!("result = {:+.16}", pi); println!(" err = {:+.16}", std::f64::consts::PI - pi); println!(" time = {} ms\n", duration.num_milliseconds()); } }
monte_carlo
identifier_name
main.rs
extern crate time; use std::sync::{Arc, mpsc}; use std::thread; type Float = f64; type Integer = u32; type Callback = Box<Fn(Float) -> Float + Send + Sync +'static>; type FnThread = Fn() -> Callback + Send + Sync; #[derive(Clone)] struct Integrator { f: Arc<FnThread>, a: Float, b: Float, n: Integer, } impl Integrator { fn new(func: Arc<FnThread>, a: Float, b: Float, iteration: Integer) -> Integrator { Integrator { f: func, a: a, b: b, n: iteration, } } fn call(&self, x: Float) -> Float { (self.f)()(x) } // parallel Monte-Carlo method // share the desired reporting interval and are distributing to threads fn monte_carlo(&self, threads: Integer) -> Float { let mut thread_list = Vec::new(); let h_step = (self.b - self.a) / self.n as Float; let t_step = self.n / threads; let (tx, rx) = mpsc::channel::<Float>(); for i in 0..threads { let local_tx = tx.clone(); let local_self = self.clone(); thread_list.push(thread::spawn(move || { let u_i = |i: Integer| -> Float { local_self.a + h_step * i as Float }; let (x0, x1) = (t_step * i, t_step * (i+1)); // main part of method let sum = (x0..x1).fold(0.0, |acc, i| acc + local_self.call(u_i(i))); local_tx.send(sum).expect("Data not sended!"); })); } let mut result = 0.0; for thread in thread_list { thread.join().expect("Thread can't joined!"); result += rx.recv().expect("Data not recieved!"); } result * h_step } } // linear Monte-Carlo method fn monte_carlo_linear(f: Arc<FnThread>, a: Float, b: Float, n: Integer) -> Float { let h = (b - a) / n as Float; let u_i = |i: Integer| -> Float { a + h * i as Float }; (0..n).fold(0.0, |acc, x| acc + (f())(u_i(x))) * h } // calculated function fn f() -> Callback { Box::new(|x: Float| -> Float { (x.powf(2.0) + 1.0).recip() }) } fn main()
println!(" time = {} ms\n", duration.num_milliseconds()); } }
{ // [a, b] -- interval // n -- iteration count let (a, b, n) = (0.0, 1.0, 10_000_000); let f_a = Integrator::new(Arc::new(f), a, b, n); println!("# Iteration count: {:E}", n as Float); let start = time::get_time(); let pi = monte_carlo_linear(Arc::new(f), a, b, n) * 4.0; let duration = time::get_time() - start; println!("# Linear code"); println!("result = {:+.16}", pi); println!(" err = {:+.16}", std::f64::consts::PI - pi); println!(" time = {} ms\n", duration.num_milliseconds()); for threads in (1..9).filter(|&x| x % 2 == 0) { println!("# Thread count: {}", threads); let start = time::get_time(); let pi = f_a.monte_carlo(threads) * 4.0; let duration = time::get_time() - start; println!("result = {:+.16}", pi); println!(" err = {:+.16}", std::f64::consts::PI - pi);
identifier_body
pad_controller.rs
// Copyright 2013-2018, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib::IsA; use glib::translate::*; use PadActionEntry; use PadController; pub trait PadControllerExtManual:'static { #[cfg(any(feature = "v3_22", feature = "dox"))] fn set_action_entries(&self, entries: &[PadActionEntry]); }
let n_entries = entries.len() as i32; let entries = entries.as_ptr(); unsafe { ffi::gtk_pad_controller_set_action_entries(self.as_ref().to_glib_none().0, mut_override(entries as *const _), n_entries); } } }
impl<O: IsA<PadController>> PadControllerExtManual for O { #[cfg(any(feature = "v3_22", feature = "dox"))] fn set_action_entries(&self, entries: &[PadActionEntry]) {
random_line_split
pad_controller.rs
// Copyright 2013-2018, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib::IsA; use glib::translate::*; use PadActionEntry; use PadController; pub trait PadControllerExtManual:'static { #[cfg(any(feature = "v3_22", feature = "dox"))] fn set_action_entries(&self, entries: &[PadActionEntry]); } impl<O: IsA<PadController>> PadControllerExtManual for O { #[cfg(any(feature = "v3_22", feature = "dox"))] fn
(&self, entries: &[PadActionEntry]) { let n_entries = entries.len() as i32; let entries = entries.as_ptr(); unsafe { ffi::gtk_pad_controller_set_action_entries(self.as_ref().to_glib_none().0, mut_override(entries as *const _), n_entries); } } }
set_action_entries
identifier_name
pad_controller.rs
// Copyright 2013-2018, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib::IsA; use glib::translate::*; use PadActionEntry; use PadController; pub trait PadControllerExtManual:'static { #[cfg(any(feature = "v3_22", feature = "dox"))] fn set_action_entries(&self, entries: &[PadActionEntry]); } impl<O: IsA<PadController>> PadControllerExtManual for O { #[cfg(any(feature = "v3_22", feature = "dox"))] fn set_action_entries(&self, entries: &[PadActionEntry])
}
{ let n_entries = entries.len() as i32; let entries = entries.as_ptr(); unsafe { ffi::gtk_pad_controller_set_action_entries(self.as_ref().to_glib_none().0, mut_override(entries as *const _), n_entries); } }
identifier_body
server_trait.rs
// // This file is part of Osmium. // Osmium 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 3 of the License, or // (at your option) any later version. // Osmium 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 Osmium. If not, see <http://www.gnu.org/licenses/>. // TODO move this trait use shared::connection_handle::ConnectionHandle; pub trait OsmiumServer { type Request; type Response; fn process(&self, request: Self::Request, handle: Box<&mut ConnectionHandle>) -> Self::Response; }
// Copyright 2017 ThetaSinner
random_line_split
test_uio.rs
use nix::sys::uio::*; use nix::unistd::*; use rand::{thread_rng, Rng}; use std::{cmp, iter}; use std::fs::{OpenOptions}; use std::os::unix::io::AsRawFd; use tempdir::TempDir; use tempfile::tempfile; #[test] fn test_writev() { let mut to_write = Vec::with_capacity(16 * 128); for _ in 0..16 { let s: String = thread_rng().gen_ascii_chars().take(128).collect(); let b = s.as_bytes(); to_write.extend(b.iter().map(|x| x.clone())); } // Allocate and fill iovecs let mut iovecs = Vec::new(); let mut consumed = 0; while consumed < to_write.len() { let left = to_write.len() - consumed; let slice_len = if left <= 64 { left } else { thread_rng().gen_range(64, cmp::min(256, left)) }; let b = &to_write[consumed..consumed+slice_len]; iovecs.push(IoVec::from_slice(b)); consumed += slice_len; } let pipe_res = pipe(); assert!(pipe_res.is_ok()); let (reader, writer) = pipe_res.ok().unwrap(); // FileDesc will close its filedesc (reader). let mut read_buf: Vec<u8> = iter::repeat(0u8).take(128 * 16).collect(); // Blocking io, should write all data. let write_res = writev(writer, &iovecs); // Successful write assert!(write_res.is_ok()); let written = write_res.ok().unwrap(); // Check whether we written all data assert_eq!(to_write.len(), written); let read_res = read(reader, &mut read_buf[..]); // Successful read assert!(read_res.is_ok()); let read = read_res.ok().unwrap() as usize; // Check we have read as much as we written assert_eq!(read, written); // Check equality of written and read data assert_eq!(&to_write, &read_buf); let close_res = close(writer); assert!(close_res.is_ok()); let close_res = close(reader); assert!(close_res.is_ok()); } #[test] fn test_readv() { let s:String = thread_rng().gen_ascii_chars().take(128).collect(); let to_write = s.as_bytes().to_vec(); let mut storage = Vec::new(); let mut allocated = 0; while allocated < to_write.len() { let left = to_write.len() - allocated; let vec_len = if left <= 64 { left } else { thread_rng().gen_range(64, cmp::min(256, left)) }; let v: Vec<u8> = iter::repeat(0u8).take(vec_len).collect(); storage.push(v); allocated += vec_len; } let mut iovecs = Vec::with_capacity(storage.len()); for v in storage.iter_mut() { iovecs.push(IoVec::from_mut_slice(&mut v[..])); } let pipe_res = pipe(); assert!(pipe_res.is_ok()); let (reader, writer) = pipe_res.ok().unwrap(); // Blocking io, should write all data. let write_res = write(writer, &to_write); // Successful write assert!(write_res.is_ok()); let read_res = readv(reader, &mut iovecs[..]); assert!(read_res.is_ok()); let read = read_res.ok().unwrap(); // Check whether we've read all data assert_eq!(to_write.len(), read); // Cccumulate data from iovecs let mut read_buf = Vec::with_capacity(to_write.len()); for iovec in iovecs.iter() { read_buf.extend(iovec.as_slice().iter().map(|x| x.clone())); } // Check whether iovecs contain all written data assert_eq!(read_buf.len(), to_write.len()); // Check equality of written and read data assert_eq!(&read_buf, &to_write); let close_res = close(reader); assert!(close_res.is_ok()); let close_res = close(writer); assert!(close_res.is_ok()); } #[test] fn test_pwrite() { use std::io::Read; let mut file = tempfile().unwrap(); let buf = [1u8;8]; assert_eq!(Ok(8), pwrite(file.as_raw_fd(), &buf, 8)); let mut file_content = Vec::new(); file.read_to_end(&mut file_content).unwrap(); let mut expected = vec![0u8;8]; expected.extend(vec![1;8]); assert_eq!(file_content, expected); } #[test] fn test_pread()
#[test] #[cfg(target_os = "linux")] fn test_pwritev() { use std::io::Read; let to_write: Vec<u8> = (0..128).collect(); let expected: Vec<u8> = [vec![0;100], to_write.clone()].concat(); let iovecs = [ IoVec::from_slice(&to_write[0..17]), IoVec::from_slice(&to_write[17..64]), IoVec::from_slice(&to_write[64..128]), ]; let tempdir = TempDir::new("nix-test_pwritev").unwrap(); // pwritev them into a temporary file let path = tempdir.path().join("pwritev_test_file"); let mut file = OpenOptions::new().write(true).read(true).create(true) .truncate(true).open(path).unwrap(); let written = pwritev(file.as_raw_fd(), &iovecs, 100).ok().unwrap(); assert_eq!(written, to_write.len()); // Read the data back and make sure it matches let mut contents = Vec::new(); file.read_to_end(&mut contents).unwrap(); assert_eq!(contents, expected); } #[test] #[cfg(target_os = "linux")] fn test_preadv() { use std::io::Write; let to_write: Vec<u8> = (0..200).collect(); let expected: Vec<u8> = (100..200).collect(); let tempdir = TempDir::new("nix-test_preadv").unwrap(); let path = tempdir.path().join("preadv_test_file"); let mut file = OpenOptions::new().read(true).write(true).create(true) .truncate(true).open(path).unwrap(); file.write_all(&to_write).unwrap(); let mut buffers: Vec<Vec<u8>> = vec![ vec![0; 24], vec![0; 1], vec![0; 75], ]; { // Borrow the buffers into IoVecs and preadv into them let mut iovecs: Vec<_> = buffers.iter_mut().map( |buf| IoVec::from_mut_slice(&mut buf[..])).collect(); assert_eq!(Ok(100), preadv(file.as_raw_fd(), &mut iovecs, 100)); } let all = buffers.concat(); assert_eq!(all, expected); } #[test] #[cfg(target_os = "linux")] // FIXME: qemu-user doesn't implement process_vm_readv/writev on most arches #[cfg_attr(not(any(target_arch = "x86", target_arch = "x86_64")), ignore)] fn test_process_vm_readv() { use nix::unistd::ForkResult::*; use nix::sys::signal::*; use nix::sys::wait::*; use std::str; #[allow(unused_variables)] let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test"); // Pre-allocate memory in the child, since allocation isn't safe // post-fork (~= async-signal-safe) let mut vector = vec![1u8, 2, 3, 4, 5]; let (r, w) = pipe().unwrap(); match fork() { Ok(Parent { child }) => { close(w).unwrap(); // wait for child read(r, &mut vec![0u8]).unwrap(); close(r).unwrap(); let ptr = vector.as_ptr() as usize; let remote_iov = RemoteIoVec { base: ptr, len: 5 }; let mut buf = vec![0u8; 5]; let ret = process_vm_readv(child, &[IoVec::from_mut_slice(&mut buf)], &[remote_iov]); kill(child, SIGTERM).unwrap(); waitpid(child, None).unwrap(); assert_eq!(Ok(5), ret); assert_eq!(20u8, buf.iter().sum()); }, Ok(Child) => { let _ = close(r); for i in vector.iter_mut() { *i += 1; } let _ = write(w, b"\0"); let _ = close(w); loop { let _ = pause(); } }, Err(_) => panic!("fork failed") } }
{ use std::io::Write; let tempdir = TempDir::new("nix-test_pread").unwrap(); let path = tempdir.path().join("pread_test_file"); let mut file = OpenOptions::new().write(true).read(true).create(true) .truncate(true).open(path).unwrap(); let file_content: Vec<u8> = (0..64).collect(); file.write_all(&file_content).unwrap(); let mut buf = [0u8;16]; assert_eq!(Ok(16), pread(file.as_raw_fd(), &mut buf, 16)); let expected: Vec<_> = (16..32).collect(); assert_eq!(&buf[..], &expected[..]); }
identifier_body
test_uio.rs
use nix::sys::uio::*; use nix::unistd::*; use rand::{thread_rng, Rng}; use std::{cmp, iter}; use std::fs::{OpenOptions}; use std::os::unix::io::AsRawFd; use tempdir::TempDir; use tempfile::tempfile; #[test] fn test_writev() { let mut to_write = Vec::with_capacity(16 * 128); for _ in 0..16 { let s: String = thread_rng().gen_ascii_chars().take(128).collect(); let b = s.as_bytes(); to_write.extend(b.iter().map(|x| x.clone())); } // Allocate and fill iovecs let mut iovecs = Vec::new(); let mut consumed = 0; while consumed < to_write.len() { let left = to_write.len() - consumed; let slice_len = if left <= 64 { left } else { thread_rng().gen_range(64, cmp::min(256, left)) }; let b = &to_write[consumed..consumed+slice_len]; iovecs.push(IoVec::from_slice(b)); consumed += slice_len; } let pipe_res = pipe(); assert!(pipe_res.is_ok()); let (reader, writer) = pipe_res.ok().unwrap(); // FileDesc will close its filedesc (reader). let mut read_buf: Vec<u8> = iter::repeat(0u8).take(128 * 16).collect(); // Blocking io, should write all data. let write_res = writev(writer, &iovecs); // Successful write assert!(write_res.is_ok()); let written = write_res.ok().unwrap(); // Check whether we written all data assert_eq!(to_write.len(), written); let read_res = read(reader, &mut read_buf[..]); // Successful read assert!(read_res.is_ok()); let read = read_res.ok().unwrap() as usize; // Check we have read as much as we written assert_eq!(read, written); // Check equality of written and read data assert_eq!(&to_write, &read_buf); let close_res = close(writer); assert!(close_res.is_ok()); let close_res = close(reader); assert!(close_res.is_ok()); } #[test] fn test_readv() { let s:String = thread_rng().gen_ascii_chars().take(128).collect(); let to_write = s.as_bytes().to_vec(); let mut storage = Vec::new(); let mut allocated = 0; while allocated < to_write.len() { let left = to_write.len() - allocated; let vec_len = if left <= 64 { left } else { thread_rng().gen_range(64, cmp::min(256, left)) }; let v: Vec<u8> = iter::repeat(0u8).take(vec_len).collect(); storage.push(v); allocated += vec_len; } let mut iovecs = Vec::with_capacity(storage.len()); for v in storage.iter_mut() { iovecs.push(IoVec::from_mut_slice(&mut v[..])); } let pipe_res = pipe(); assert!(pipe_res.is_ok()); let (reader, writer) = pipe_res.ok().unwrap(); // Blocking io, should write all data. let write_res = write(writer, &to_write); // Successful write assert!(write_res.is_ok()); let read_res = readv(reader, &mut iovecs[..]); assert!(read_res.is_ok()); let read = read_res.ok().unwrap(); // Check whether we've read all data assert_eq!(to_write.len(), read); // Cccumulate data from iovecs let mut read_buf = Vec::with_capacity(to_write.len()); for iovec in iovecs.iter() { read_buf.extend(iovec.as_slice().iter().map(|x| x.clone())); } // Check whether iovecs contain all written data assert_eq!(read_buf.len(), to_write.len()); // Check equality of written and read data assert_eq!(&read_buf, &to_write); let close_res = close(reader); assert!(close_res.is_ok()); let close_res = close(writer); assert!(close_res.is_ok()); } #[test] fn test_pwrite() { use std::io::Read; let mut file = tempfile().unwrap(); let buf = [1u8;8]; assert_eq!(Ok(8), pwrite(file.as_raw_fd(), &buf, 8)); let mut file_content = Vec::new(); file.read_to_end(&mut file_content).unwrap(); let mut expected = vec![0u8;8]; expected.extend(vec![1;8]); assert_eq!(file_content, expected); } #[test] fn test_pread() { use std::io::Write; let tempdir = TempDir::new("nix-test_pread").unwrap(); let path = tempdir.path().join("pread_test_file"); let mut file = OpenOptions::new().write(true).read(true).create(true) .truncate(true).open(path).unwrap(); let file_content: Vec<u8> = (0..64).collect(); file.write_all(&file_content).unwrap(); let mut buf = [0u8;16]; assert_eq!(Ok(16), pread(file.as_raw_fd(), &mut buf, 16)); let expected: Vec<_> = (16..32).collect(); assert_eq!(&buf[..], &expected[..]); } #[test] #[cfg(target_os = "linux")] fn
() { use std::io::Read; let to_write: Vec<u8> = (0..128).collect(); let expected: Vec<u8> = [vec![0;100], to_write.clone()].concat(); let iovecs = [ IoVec::from_slice(&to_write[0..17]), IoVec::from_slice(&to_write[17..64]), IoVec::from_slice(&to_write[64..128]), ]; let tempdir = TempDir::new("nix-test_pwritev").unwrap(); // pwritev them into a temporary file let path = tempdir.path().join("pwritev_test_file"); let mut file = OpenOptions::new().write(true).read(true).create(true) .truncate(true).open(path).unwrap(); let written = pwritev(file.as_raw_fd(), &iovecs, 100).ok().unwrap(); assert_eq!(written, to_write.len()); // Read the data back and make sure it matches let mut contents = Vec::new(); file.read_to_end(&mut contents).unwrap(); assert_eq!(contents, expected); } #[test] #[cfg(target_os = "linux")] fn test_preadv() { use std::io::Write; let to_write: Vec<u8> = (0..200).collect(); let expected: Vec<u8> = (100..200).collect(); let tempdir = TempDir::new("nix-test_preadv").unwrap(); let path = tempdir.path().join("preadv_test_file"); let mut file = OpenOptions::new().read(true).write(true).create(true) .truncate(true).open(path).unwrap(); file.write_all(&to_write).unwrap(); let mut buffers: Vec<Vec<u8>> = vec![ vec![0; 24], vec![0; 1], vec![0; 75], ]; { // Borrow the buffers into IoVecs and preadv into them let mut iovecs: Vec<_> = buffers.iter_mut().map( |buf| IoVec::from_mut_slice(&mut buf[..])).collect(); assert_eq!(Ok(100), preadv(file.as_raw_fd(), &mut iovecs, 100)); } let all = buffers.concat(); assert_eq!(all, expected); } #[test] #[cfg(target_os = "linux")] // FIXME: qemu-user doesn't implement process_vm_readv/writev on most arches #[cfg_attr(not(any(target_arch = "x86", target_arch = "x86_64")), ignore)] fn test_process_vm_readv() { use nix::unistd::ForkResult::*; use nix::sys::signal::*; use nix::sys::wait::*; use std::str; #[allow(unused_variables)] let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test"); // Pre-allocate memory in the child, since allocation isn't safe // post-fork (~= async-signal-safe) let mut vector = vec![1u8, 2, 3, 4, 5]; let (r, w) = pipe().unwrap(); match fork() { Ok(Parent { child }) => { close(w).unwrap(); // wait for child read(r, &mut vec![0u8]).unwrap(); close(r).unwrap(); let ptr = vector.as_ptr() as usize; let remote_iov = RemoteIoVec { base: ptr, len: 5 }; let mut buf = vec![0u8; 5]; let ret = process_vm_readv(child, &[IoVec::from_mut_slice(&mut buf)], &[remote_iov]); kill(child, SIGTERM).unwrap(); waitpid(child, None).unwrap(); assert_eq!(Ok(5), ret); assert_eq!(20u8, buf.iter().sum()); }, Ok(Child) => { let _ = close(r); for i in vector.iter_mut() { *i += 1; } let _ = write(w, b"\0"); let _ = close(w); loop { let _ = pause(); } }, Err(_) => panic!("fork failed") } }
test_pwritev
identifier_name
test_uio.rs
use nix::sys::uio::*; use nix::unistd::*; use rand::{thread_rng, Rng}; use std::{cmp, iter}; use std::fs::{OpenOptions}; use std::os::unix::io::AsRawFd; use tempdir::TempDir; use tempfile::tempfile; #[test] fn test_writev() { let mut to_write = Vec::with_capacity(16 * 128);
let b = s.as_bytes(); to_write.extend(b.iter().map(|x| x.clone())); } // Allocate and fill iovecs let mut iovecs = Vec::new(); let mut consumed = 0; while consumed < to_write.len() { let left = to_write.len() - consumed; let slice_len = if left <= 64 { left } else { thread_rng().gen_range(64, cmp::min(256, left)) }; let b = &to_write[consumed..consumed+slice_len]; iovecs.push(IoVec::from_slice(b)); consumed += slice_len; } let pipe_res = pipe(); assert!(pipe_res.is_ok()); let (reader, writer) = pipe_res.ok().unwrap(); // FileDesc will close its filedesc (reader). let mut read_buf: Vec<u8> = iter::repeat(0u8).take(128 * 16).collect(); // Blocking io, should write all data. let write_res = writev(writer, &iovecs); // Successful write assert!(write_res.is_ok()); let written = write_res.ok().unwrap(); // Check whether we written all data assert_eq!(to_write.len(), written); let read_res = read(reader, &mut read_buf[..]); // Successful read assert!(read_res.is_ok()); let read = read_res.ok().unwrap() as usize; // Check we have read as much as we written assert_eq!(read, written); // Check equality of written and read data assert_eq!(&to_write, &read_buf); let close_res = close(writer); assert!(close_res.is_ok()); let close_res = close(reader); assert!(close_res.is_ok()); } #[test] fn test_readv() { let s:String = thread_rng().gen_ascii_chars().take(128).collect(); let to_write = s.as_bytes().to_vec(); let mut storage = Vec::new(); let mut allocated = 0; while allocated < to_write.len() { let left = to_write.len() - allocated; let vec_len = if left <= 64 { left } else { thread_rng().gen_range(64, cmp::min(256, left)) }; let v: Vec<u8> = iter::repeat(0u8).take(vec_len).collect(); storage.push(v); allocated += vec_len; } let mut iovecs = Vec::with_capacity(storage.len()); for v in storage.iter_mut() { iovecs.push(IoVec::from_mut_slice(&mut v[..])); } let pipe_res = pipe(); assert!(pipe_res.is_ok()); let (reader, writer) = pipe_res.ok().unwrap(); // Blocking io, should write all data. let write_res = write(writer, &to_write); // Successful write assert!(write_res.is_ok()); let read_res = readv(reader, &mut iovecs[..]); assert!(read_res.is_ok()); let read = read_res.ok().unwrap(); // Check whether we've read all data assert_eq!(to_write.len(), read); // Cccumulate data from iovecs let mut read_buf = Vec::with_capacity(to_write.len()); for iovec in iovecs.iter() { read_buf.extend(iovec.as_slice().iter().map(|x| x.clone())); } // Check whether iovecs contain all written data assert_eq!(read_buf.len(), to_write.len()); // Check equality of written and read data assert_eq!(&read_buf, &to_write); let close_res = close(reader); assert!(close_res.is_ok()); let close_res = close(writer); assert!(close_res.is_ok()); } #[test] fn test_pwrite() { use std::io::Read; let mut file = tempfile().unwrap(); let buf = [1u8;8]; assert_eq!(Ok(8), pwrite(file.as_raw_fd(), &buf, 8)); let mut file_content = Vec::new(); file.read_to_end(&mut file_content).unwrap(); let mut expected = vec![0u8;8]; expected.extend(vec![1;8]); assert_eq!(file_content, expected); } #[test] fn test_pread() { use std::io::Write; let tempdir = TempDir::new("nix-test_pread").unwrap(); let path = tempdir.path().join("pread_test_file"); let mut file = OpenOptions::new().write(true).read(true).create(true) .truncate(true).open(path).unwrap(); let file_content: Vec<u8> = (0..64).collect(); file.write_all(&file_content).unwrap(); let mut buf = [0u8;16]; assert_eq!(Ok(16), pread(file.as_raw_fd(), &mut buf, 16)); let expected: Vec<_> = (16..32).collect(); assert_eq!(&buf[..], &expected[..]); } #[test] #[cfg(target_os = "linux")] fn test_pwritev() { use std::io::Read; let to_write: Vec<u8> = (0..128).collect(); let expected: Vec<u8> = [vec![0;100], to_write.clone()].concat(); let iovecs = [ IoVec::from_slice(&to_write[0..17]), IoVec::from_slice(&to_write[17..64]), IoVec::from_slice(&to_write[64..128]), ]; let tempdir = TempDir::new("nix-test_pwritev").unwrap(); // pwritev them into a temporary file let path = tempdir.path().join("pwritev_test_file"); let mut file = OpenOptions::new().write(true).read(true).create(true) .truncate(true).open(path).unwrap(); let written = pwritev(file.as_raw_fd(), &iovecs, 100).ok().unwrap(); assert_eq!(written, to_write.len()); // Read the data back and make sure it matches let mut contents = Vec::new(); file.read_to_end(&mut contents).unwrap(); assert_eq!(contents, expected); } #[test] #[cfg(target_os = "linux")] fn test_preadv() { use std::io::Write; let to_write: Vec<u8> = (0..200).collect(); let expected: Vec<u8> = (100..200).collect(); let tempdir = TempDir::new("nix-test_preadv").unwrap(); let path = tempdir.path().join("preadv_test_file"); let mut file = OpenOptions::new().read(true).write(true).create(true) .truncate(true).open(path).unwrap(); file.write_all(&to_write).unwrap(); let mut buffers: Vec<Vec<u8>> = vec![ vec![0; 24], vec![0; 1], vec![0; 75], ]; { // Borrow the buffers into IoVecs and preadv into them let mut iovecs: Vec<_> = buffers.iter_mut().map( |buf| IoVec::from_mut_slice(&mut buf[..])).collect(); assert_eq!(Ok(100), preadv(file.as_raw_fd(), &mut iovecs, 100)); } let all = buffers.concat(); assert_eq!(all, expected); } #[test] #[cfg(target_os = "linux")] // FIXME: qemu-user doesn't implement process_vm_readv/writev on most arches #[cfg_attr(not(any(target_arch = "x86", target_arch = "x86_64")), ignore)] fn test_process_vm_readv() { use nix::unistd::ForkResult::*; use nix::sys::signal::*; use nix::sys::wait::*; use std::str; #[allow(unused_variables)] let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test"); // Pre-allocate memory in the child, since allocation isn't safe // post-fork (~= async-signal-safe) let mut vector = vec![1u8, 2, 3, 4, 5]; let (r, w) = pipe().unwrap(); match fork() { Ok(Parent { child }) => { close(w).unwrap(); // wait for child read(r, &mut vec![0u8]).unwrap(); close(r).unwrap(); let ptr = vector.as_ptr() as usize; let remote_iov = RemoteIoVec { base: ptr, len: 5 }; let mut buf = vec![0u8; 5]; let ret = process_vm_readv(child, &[IoVec::from_mut_slice(&mut buf)], &[remote_iov]); kill(child, SIGTERM).unwrap(); waitpid(child, None).unwrap(); assert_eq!(Ok(5), ret); assert_eq!(20u8, buf.iter().sum()); }, Ok(Child) => { let _ = close(r); for i in vector.iter_mut() { *i += 1; } let _ = write(w, b"\0"); let _ = close(w); loop { let _ = pause(); } }, Err(_) => panic!("fork failed") } }
for _ in 0..16 { let s: String = thread_rng().gen_ascii_chars().take(128).collect();
random_line_split
test_uio.rs
use nix::sys::uio::*; use nix::unistd::*; use rand::{thread_rng, Rng}; use std::{cmp, iter}; use std::fs::{OpenOptions}; use std::os::unix::io::AsRawFd; use tempdir::TempDir; use tempfile::tempfile; #[test] fn test_writev() { let mut to_write = Vec::with_capacity(16 * 128); for _ in 0..16 { let s: String = thread_rng().gen_ascii_chars().take(128).collect(); let b = s.as_bytes(); to_write.extend(b.iter().map(|x| x.clone())); } // Allocate and fill iovecs let mut iovecs = Vec::new(); let mut consumed = 0; while consumed < to_write.len() { let left = to_write.len() - consumed; let slice_len = if left <= 64 { left } else { thread_rng().gen_range(64, cmp::min(256, left)) }; let b = &to_write[consumed..consumed+slice_len]; iovecs.push(IoVec::from_slice(b)); consumed += slice_len; } let pipe_res = pipe(); assert!(pipe_res.is_ok()); let (reader, writer) = pipe_res.ok().unwrap(); // FileDesc will close its filedesc (reader). let mut read_buf: Vec<u8> = iter::repeat(0u8).take(128 * 16).collect(); // Blocking io, should write all data. let write_res = writev(writer, &iovecs); // Successful write assert!(write_res.is_ok()); let written = write_res.ok().unwrap(); // Check whether we written all data assert_eq!(to_write.len(), written); let read_res = read(reader, &mut read_buf[..]); // Successful read assert!(read_res.is_ok()); let read = read_res.ok().unwrap() as usize; // Check we have read as much as we written assert_eq!(read, written); // Check equality of written and read data assert_eq!(&to_write, &read_buf); let close_res = close(writer); assert!(close_res.is_ok()); let close_res = close(reader); assert!(close_res.is_ok()); } #[test] fn test_readv() { let s:String = thread_rng().gen_ascii_chars().take(128).collect(); let to_write = s.as_bytes().to_vec(); let mut storage = Vec::new(); let mut allocated = 0; while allocated < to_write.len() { let left = to_write.len() - allocated; let vec_len = if left <= 64 { left } else
; let v: Vec<u8> = iter::repeat(0u8).take(vec_len).collect(); storage.push(v); allocated += vec_len; } let mut iovecs = Vec::with_capacity(storage.len()); for v in storage.iter_mut() { iovecs.push(IoVec::from_mut_slice(&mut v[..])); } let pipe_res = pipe(); assert!(pipe_res.is_ok()); let (reader, writer) = pipe_res.ok().unwrap(); // Blocking io, should write all data. let write_res = write(writer, &to_write); // Successful write assert!(write_res.is_ok()); let read_res = readv(reader, &mut iovecs[..]); assert!(read_res.is_ok()); let read = read_res.ok().unwrap(); // Check whether we've read all data assert_eq!(to_write.len(), read); // Cccumulate data from iovecs let mut read_buf = Vec::with_capacity(to_write.len()); for iovec in iovecs.iter() { read_buf.extend(iovec.as_slice().iter().map(|x| x.clone())); } // Check whether iovecs contain all written data assert_eq!(read_buf.len(), to_write.len()); // Check equality of written and read data assert_eq!(&read_buf, &to_write); let close_res = close(reader); assert!(close_res.is_ok()); let close_res = close(writer); assert!(close_res.is_ok()); } #[test] fn test_pwrite() { use std::io::Read; let mut file = tempfile().unwrap(); let buf = [1u8;8]; assert_eq!(Ok(8), pwrite(file.as_raw_fd(), &buf, 8)); let mut file_content = Vec::new(); file.read_to_end(&mut file_content).unwrap(); let mut expected = vec![0u8;8]; expected.extend(vec![1;8]); assert_eq!(file_content, expected); } #[test] fn test_pread() { use std::io::Write; let tempdir = TempDir::new("nix-test_pread").unwrap(); let path = tempdir.path().join("pread_test_file"); let mut file = OpenOptions::new().write(true).read(true).create(true) .truncate(true).open(path).unwrap(); let file_content: Vec<u8> = (0..64).collect(); file.write_all(&file_content).unwrap(); let mut buf = [0u8;16]; assert_eq!(Ok(16), pread(file.as_raw_fd(), &mut buf, 16)); let expected: Vec<_> = (16..32).collect(); assert_eq!(&buf[..], &expected[..]); } #[test] #[cfg(target_os = "linux")] fn test_pwritev() { use std::io::Read; let to_write: Vec<u8> = (0..128).collect(); let expected: Vec<u8> = [vec![0;100], to_write.clone()].concat(); let iovecs = [ IoVec::from_slice(&to_write[0..17]), IoVec::from_slice(&to_write[17..64]), IoVec::from_slice(&to_write[64..128]), ]; let tempdir = TempDir::new("nix-test_pwritev").unwrap(); // pwritev them into a temporary file let path = tempdir.path().join("pwritev_test_file"); let mut file = OpenOptions::new().write(true).read(true).create(true) .truncate(true).open(path).unwrap(); let written = pwritev(file.as_raw_fd(), &iovecs, 100).ok().unwrap(); assert_eq!(written, to_write.len()); // Read the data back and make sure it matches let mut contents = Vec::new(); file.read_to_end(&mut contents).unwrap(); assert_eq!(contents, expected); } #[test] #[cfg(target_os = "linux")] fn test_preadv() { use std::io::Write; let to_write: Vec<u8> = (0..200).collect(); let expected: Vec<u8> = (100..200).collect(); let tempdir = TempDir::new("nix-test_preadv").unwrap(); let path = tempdir.path().join("preadv_test_file"); let mut file = OpenOptions::new().read(true).write(true).create(true) .truncate(true).open(path).unwrap(); file.write_all(&to_write).unwrap(); let mut buffers: Vec<Vec<u8>> = vec![ vec![0; 24], vec![0; 1], vec![0; 75], ]; { // Borrow the buffers into IoVecs and preadv into them let mut iovecs: Vec<_> = buffers.iter_mut().map( |buf| IoVec::from_mut_slice(&mut buf[..])).collect(); assert_eq!(Ok(100), preadv(file.as_raw_fd(), &mut iovecs, 100)); } let all = buffers.concat(); assert_eq!(all, expected); } #[test] #[cfg(target_os = "linux")] // FIXME: qemu-user doesn't implement process_vm_readv/writev on most arches #[cfg_attr(not(any(target_arch = "x86", target_arch = "x86_64")), ignore)] fn test_process_vm_readv() { use nix::unistd::ForkResult::*; use nix::sys::signal::*; use nix::sys::wait::*; use std::str; #[allow(unused_variables)] let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test"); // Pre-allocate memory in the child, since allocation isn't safe // post-fork (~= async-signal-safe) let mut vector = vec![1u8, 2, 3, 4, 5]; let (r, w) = pipe().unwrap(); match fork() { Ok(Parent { child }) => { close(w).unwrap(); // wait for child read(r, &mut vec![0u8]).unwrap(); close(r).unwrap(); let ptr = vector.as_ptr() as usize; let remote_iov = RemoteIoVec { base: ptr, len: 5 }; let mut buf = vec![0u8; 5]; let ret = process_vm_readv(child, &[IoVec::from_mut_slice(&mut buf)], &[remote_iov]); kill(child, SIGTERM).unwrap(); waitpid(child, None).unwrap(); assert_eq!(Ok(5), ret); assert_eq!(20u8, buf.iter().sum()); }, Ok(Child) => { let _ = close(r); for i in vector.iter_mut() { *i += 1; } let _ = write(w, b"\0"); let _ = close(w); loop { let _ = pause(); } }, Err(_) => panic!("fork failed") } }
{ thread_rng().gen_range(64, cmp::min(256, left)) }
conditional_block
trait-default-method-bound-subst.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 A<T> { fn
<U>(&self, x: T, y: U) -> (T, U) { (x, y) } } impl A<i32> for i32 { } impl<T> A<T> for u32 { } fn f<T, U, V: A<T>>(i: V, j: T, k: U) -> (T, U) { i.g(j, k) } pub fn main () { assert_eq!(f(0, 1, 2), (1, 2)); assert_eq!(f(0, 1, 2), (1, 2)); }
g
identifier_name
trait-default-method-bound-subst.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 A<T> { fn g<U>(&self, x: T, y: U) -> (T, U) { (x, y) } } impl A<i32> for i32 { } impl<T> A<T> for u32 { } fn f<T, U, V: A<T>>(i: V, j: T, k: U) -> (T, U) { i.g(j, k) } pub fn main ()
{ assert_eq!(f(0, 1, 2), (1, 2)); assert_eq!(f(0, 1, 2), (1, 2)); }
identifier_body
trait-default-method-bound-subst.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 A<T> { fn g<U>(&self, x: T, y: U) -> (T, U) { (x, y) }
impl A<i32> for i32 { } impl<T> A<T> for u32 { } fn f<T, U, V: A<T>>(i: V, j: T, k: U) -> (T, U) { i.g(j, k) } pub fn main () { assert_eq!(f(0, 1, 2), (1, 2)); assert_eq!(f(0, 1, 2), (1, 2)); }
}
random_line_split
mock.rs
//! BDCS Mock API handling //! //! # Overview //! //! This module provides a mock API service that reads json files from a static directory and serves up //! the data from the file as-is. //! //! Requests like /route are read from a file named route.json //! Requests like /route/param are read from route-param.json //! Requests like /route/action/param are handled slightly differently, depending on the file. //! //! If the route-action.json file has an Array in it then it will be searched for a "name" key //! matching param. If that is found just that matching entry will be returned. //! //! The mock files should follow the (API rules here)[path/to/rules.html], using a top level //! object named the same as the route to hold the child object or array. Examples of valid //! files can be found in the tests/results/ directory. //! //! # Example Response //! //! eg. /recipes/info/http-server //! ```json //! {"limit":20,"offset":0,"recipes":{"description":"An example http //! server","modules":[{"name":"fm-httpd","version":"23.*"},{"name":"fm-php","version":"11.6.*"}],"name":"http-server","packages":[{"name":"tmux","version":"2.2"}]}} //! ``` //! // Copyright (C) 2016-2017 Red Hat, Inc. // // This file is part of bdcs-api-server. // // bdcs-api-server 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 3 of the License, or // (at your option) any later version. // // bdcs-api-server 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 bdcs-api-server. If not, see <http://www.gnu.org/licenses/>. // A lot of the code generated via rocket uses pass-by-value that clippy // disagrees with. Ignore these warnings. #![cfg_attr(feature="cargo-clippy", allow(needless_pass_by_value))] use std::fs::File; use std::path::Path; use rocket::config; use rocket_contrib::JSON; use rocket::response::NamedFile; use serde_json::{self, Value}; use api::{CORS, Filter, OFFSET, LIMIT}; /// A nice little macro to create simple Maps. Really convenient for /// returning ad-hoc JSON messages. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate rocket_contrib; /// use std::collections::HashMap; /// # fn main() { /// let map: HashMap<&str, usize> = map! { /// "status" => 0, /// "count" => 100 /// }; /// /// assert_eq!(map.len(), 2); /// assert_eq!(map.get("status"), Some(&0)); /// assert_eq!(map.get("count"), Some(&100)); /// # } /// ``` /// /// Borrowed from rocket.rs and modified to use serde_json::value::Map macro_rules! json_map { ($($key:expr => $value:expr),+) => ({ use serde_json::value::Map; let mut map = Map::new(); $(map.insert($key.to_string(), $value);)+ map }); ($($key:expr => $value:expr),+,) => { json_map!($($key => $value),+) }; } /// Handler for a bare route with offset and/or limit #[get("/<route>?<filter>")] pub fn static_route_filter(route: &str, filter: Filter) -> CORS<Option<NamedFile>> { static_json(route, None, filter.offset.unwrap_or(OFFSET), filter.limit.unwrap_or(LIMIT)) } /// Handler for a bare route with no filtering #[get("/<route>", rank=2)] pub fn static_route(route: &str) -> CORS<Option<NamedFile>> { static_json(route, None, OFFSET, LIMIT) } /// Handler for a route with a single parameter and offset and/or limit #[get("/<route>/<param>?<filter>")] pub fn static_route_param_filter(route: &str, param: &str, filter: Filter) -> CORS<Option<NamedFile>> { static_json(route, Some(param), filter.offset.unwrap_or(OFFSET), filter.limit.unwrap_or(LIMIT)) } /// Handler for a route with a single parameter and no filtering #[get("/<route>/<param>", rank=2)] pub fn static_route_param(route: &str, param: &str) -> CORS<Option<NamedFile>> { static_json(route, Some(param), OFFSET, LIMIT) } /// Handler for a route with an action, a parameter and offset/limit #[get("/<route>/<action>/<param>?<filter>")] pub fn static_route_action_filter(route: &str, action: &str, param: &str, filter: Filter) -> CORS<JSON<Value>> { filter_json(route, action, param, filter.offset.unwrap_or(OFFSET), filter.limit.unwrap_or(LIMIT)) } /// Handler for a route with an action, a parameter and no filtering #[get("/<route>/<action>/<param>", rank=2)] pub fn static_route_action(route: &str, action: &str, param: &str) -> CORS<JSON<Value>> { filter_json(route, action, param, OFFSET, LIMIT) } /// Return a static json file based on the route and parameter passed to the API /// /// # Arguments /// /// * `route` - The 1st argument on the API path /// * `param` - The 2nd argument on the API path /// * `offset` - Number of results to skip before returning results. Default is 0. /// * `limit` - Maximum number of results to return. It may return less. Default is 20. /// /// # Response /// /// * JSON response read from the file. /// /// The filename returned is constructed by joining the route and the param with a '-' and /// appending.json to it. eg. `/modules/list` will read from a file named `modules-list.json` /// /// The filtering arguments, offset and limit, are ignored. Any offset or limit in the file /// are returned as-is. /// fn static_json(route: &str, param: Option<&str>, offset: i64, limit: i64) -> CORS<Option<NamedFile>>
/// Filter the contents of a static json file based on the action and parameter passed to the API /// /// # Arguments /// /// * `route` - The 1st argument on the API path /// * `action` - The 2nd argument on the API path /// * `param` - The 3rd argument on the API path /// * `offset` - Number of results to skip before returning results. Default is 0. /// * `limit` - Maximum number of results to return. It may return less. Default is 20. /// /// # Response /// /// * JSON response selected from the file. /// /// The filename to read is constructed by joining the route and the action with a '-' and /// appending.json to it. eg. `/modules/info/http-server` will read from a file named `modules-info.json` /// /// The filtering arguments, offset and limit, are ignored but are returned as part of the /// response. /// /// The file is expected to contain valid json with an object named for the route. If the route /// object is not an array, it is returned as-is, along with the offset and limit values. /// /// eg. A file with only an object: /// ```json /// {"modules":{"name": "http-server",...}} /// ``` /// /// If the route object contains an array then it is searched for a `"name"` key that is equal to the /// `param` passed to the API. A response is constructed using the route and the single /// object from the file. If nothing is found then a `null` is returned. /// /// eg. A file with an array /// ```json /// {"modules":[{"name": "http-server",...}, {"name": "nfs-server",...}]} /// ``` /// fn filter_json(route: &str, action: &str, param: &str, offset: i64, limit: i64) -> CORS<JSON<Value>> { info!("mock request"; "route" => route, "action" => action, "param" => param, "offset" => offset, "limit" => limit); let mock_path = config::active() .unwrap() .get_str("mockfiles_path") .unwrap_or("/var/tmp/bdcs-mockfiles/"); let file = format!("{}-{}.json", route, action); let json_data: Value = serde_json::from_reader(File::open(Path::new(mock_path).join(file)) .unwrap()) .unwrap(); let json_obj = json_data.as_object().unwrap(); debug!("json object"; "json" => format!("{:?}", json_obj)); // Properly formatted with {"<route>":... if let Some(api_route) = json_obj.get(route) { // If the route is an array search for a "name" key set to the value of param. if api_route.is_array() { if let Some(json_array) = api_route.as_array() { for item in json_array { if item.get("name") == Some(&Value::String(param.to_string())) { info!("Found it!"; "json" => format!("{:?}", item)); return CORS(JSON(Value::Object(json_map! { route => Value::Array(vec![item.clone()]), "offset" => serde_json::to_value(offset).unwrap(), "limit" => serde_json::to_value(limit).unwrap() }))); } } } } else { // Not an array, just return it return CORS(JSON(Value::Object(json_map! { route => api_route.clone(), "offset" => serde_json::to_value(offset).unwrap(), "limit" => serde_json::to_value(limit).unwrap() }))); } } // Nothing to return CORS(JSON(Value::Object(json_map! { route => Value::Null, "offset" => serde_json::to_value(offset).unwrap(), "limit" => serde_json::to_value(limit).unwrap() }))) }
{ info!("mock request"; "route" => route, "param" => param, "offset" => offset, "limit" => limit); let mock_path = config::active() .unwrap() .get_str("mockfiles_path") .unwrap_or("/var/tmp/bdcs-mockfiles/"); // TODO Better way to construct this... let param = match param { Some(p) => format!("-{}", p), None => "".to_string() }; let file = format!("{}{}.json", route, param); CORS(NamedFile::open(Path::new(mock_path).join(file)).ok()) }
identifier_body
mock.rs
//! BDCS Mock API handling //! //! # Overview //! //! This module provides a mock API service that reads json files from a static directory and serves up //! the data from the file as-is. //! //! Requests like /route are read from a file named route.json //! Requests like /route/param are read from route-param.json //! Requests like /route/action/param are handled slightly differently, depending on the file. //! //! If the route-action.json file has an Array in it then it will be searched for a "name" key //! matching param. If that is found just that matching entry will be returned. //! //! The mock files should follow the (API rules here)[path/to/rules.html], using a top level //! object named the same as the route to hold the child object or array. Examples of valid //! files can be found in the tests/results/ directory. //! //! # Example Response //! //! eg. /recipes/info/http-server //! ```json //! {"limit":20,"offset":0,"recipes":{"description":"An example http //! server","modules":[{"name":"fm-httpd","version":"23.*"},{"name":"fm-php","version":"11.6.*"}],"name":"http-server","packages":[{"name":"tmux","version":"2.2"}]}} //! ``` //! // Copyright (C) 2016-2017 Red Hat, Inc. // // This file is part of bdcs-api-server. // // bdcs-api-server 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 3 of the License, or // (at your option) any later version. // // bdcs-api-server 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 bdcs-api-server. If not, see <http://www.gnu.org/licenses/>. // A lot of the code generated via rocket uses pass-by-value that clippy // disagrees with. Ignore these warnings. #![cfg_attr(feature="cargo-clippy", allow(needless_pass_by_value))] use std::fs::File; use std::path::Path; use rocket::config; use rocket_contrib::JSON; use rocket::response::NamedFile; use serde_json::{self, Value}; use api::{CORS, Filter, OFFSET, LIMIT}; /// A nice little macro to create simple Maps. Really convenient for /// returning ad-hoc JSON messages. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate rocket_contrib; /// use std::collections::HashMap; /// # fn main() { /// let map: HashMap<&str, usize> = map! { /// "status" => 0, /// "count" => 100 /// }; /// /// assert_eq!(map.len(), 2); /// assert_eq!(map.get("status"), Some(&0)); /// assert_eq!(map.get("count"), Some(&100)); /// # } /// ``` /// /// Borrowed from rocket.rs and modified to use serde_json::value::Map macro_rules! json_map { ($($key:expr => $value:expr),+) => ({ use serde_json::value::Map; let mut map = Map::new(); $(map.insert($key.to_string(), $value);)+ map }); ($($key:expr => $value:expr),+,) => { json_map!($($key => $value),+) }; } /// Handler for a bare route with offset and/or limit #[get("/<route>?<filter>")] pub fn static_route_filter(route: &str, filter: Filter) -> CORS<Option<NamedFile>> { static_json(route, None, filter.offset.unwrap_or(OFFSET), filter.limit.unwrap_or(LIMIT)) } /// Handler for a bare route with no filtering #[get("/<route>", rank=2)] pub fn static_route(route: &str) -> CORS<Option<NamedFile>> { static_json(route, None, OFFSET, LIMIT) } /// Handler for a route with a single parameter and offset and/or limit #[get("/<route>/<param>?<filter>")] pub fn static_route_param_filter(route: &str, param: &str, filter: Filter) -> CORS<Option<NamedFile>> { static_json(route, Some(param), filter.offset.unwrap_or(OFFSET), filter.limit.unwrap_or(LIMIT)) } /// Handler for a route with a single parameter and no filtering #[get("/<route>/<param>", rank=2)] pub fn static_route_param(route: &str, param: &str) -> CORS<Option<NamedFile>> { static_json(route, Some(param), OFFSET, LIMIT) } /// Handler for a route with an action, a parameter and offset/limit #[get("/<route>/<action>/<param>?<filter>")] pub fn static_route_action_filter(route: &str, action: &str, param: &str, filter: Filter) -> CORS<JSON<Value>> { filter_json(route, action, param, filter.offset.unwrap_or(OFFSET), filter.limit.unwrap_or(LIMIT)) } /// Handler for a route with an action, a parameter and no filtering #[get("/<route>/<action>/<param>", rank=2)] pub fn static_route_action(route: &str, action: &str, param: &str) -> CORS<JSON<Value>> { filter_json(route, action, param, OFFSET, LIMIT) } /// Return a static json file based on the route and parameter passed to the API /// /// # Arguments /// /// * `route` - The 1st argument on the API path /// * `param` - The 2nd argument on the API path /// * `offset` - Number of results to skip before returning results. Default is 0. /// * `limit` - Maximum number of results to return. It may return less. Default is 20. /// /// # Response /// /// * JSON response read from the file. /// /// The filename returned is constructed by joining the route and the param with a '-' and /// appending.json to it. eg. `/modules/list` will read from a file named `modules-list.json` /// /// The filtering arguments, offset and limit, are ignored. Any offset or limit in the file /// are returned as-is. /// fn static_json(route: &str, param: Option<&str>, offset: i64, limit: i64) -> CORS<Option<NamedFile>> { info!("mock request"; "route" => route, "param" => param, "offset" => offset, "limit" => limit); let mock_path = config::active() .unwrap() .get_str("mockfiles_path") .unwrap_or("/var/tmp/bdcs-mockfiles/"); // TODO Better way to construct this... let param = match param { Some(p) => format!("-{}", p), None => "".to_string() }; let file = format!("{}{}.json", route, param); CORS(NamedFile::open(Path::new(mock_path).join(file)).ok()) } /// Filter the contents of a static json file based on the action and parameter passed to the API /// /// # Arguments /// /// * `route` - The 1st argument on the API path /// * `action` - The 2nd argument on the API path /// * `param` - The 3rd argument on the API path /// * `offset` - Number of results to skip before returning results. Default is 0. /// * `limit` - Maximum number of results to return. It may return less. Default is 20. /// /// # Response /// /// * JSON response selected from the file. /// /// The filename to read is constructed by joining the route and the action with a '-' and /// appending.json to it. eg. `/modules/info/http-server` will read from a file named `modules-info.json` /// /// The filtering arguments, offset and limit, are ignored but are returned as part of the /// response. /// /// The file is expected to contain valid json with an object named for the route. If the route /// object is not an array, it is returned as-is, along with the offset and limit values. /// /// eg. A file with only an object: /// ```json /// {"modules":{"name": "http-server",...}} /// ``` /// /// If the route object contains an array then it is searched for a `"name"` key that is equal to the /// `param` passed to the API. A response is constructed using the route and the single /// object from the file. If nothing is found then a `null` is returned. /// /// eg. A file with an array /// ```json /// {"modules":[{"name": "http-server",...}, {"name": "nfs-server",...}]} /// ``` /// fn filter_json(route: &str, action: &str, param: &str, offset: i64, limit: i64) -> CORS<JSON<Value>> { info!("mock request"; "route" => route, "action" => action, "param" => param, "offset" => offset, "limit" => limit); let mock_path = config::active() .unwrap() .get_str("mockfiles_path") .unwrap_or("/var/tmp/bdcs-mockfiles/"); let file = format!("{}-{}.json", route, action); let json_data: Value = serde_json::from_reader(File::open(Path::new(mock_path).join(file)) .unwrap()) .unwrap(); let json_obj = json_data.as_object().unwrap(); debug!("json object"; "json" => format!("{:?}", json_obj)); // Properly formatted with {"<route>":... if let Some(api_route) = json_obj.get(route) { // If the route is an array search for a "name" key set to the value of param. if api_route.is_array() { if let Some(json_array) = api_route.as_array() { for item in json_array { if item.get("name") == Some(&Value::String(param.to_string())) { info!("Found it!"; "json" => format!("{:?}", item)); return CORS(JSON(Value::Object(json_map! { route => Value::Array(vec![item.clone()]), "offset" => serde_json::to_value(offset).unwrap(), "limit" => serde_json::to_value(limit).unwrap() }))); } } } } else
} // Nothing to return CORS(JSON(Value::Object(json_map! { route => Value::Null, "offset" => serde_json::to_value(offset).unwrap(), "limit" => serde_json::to_value(limit).unwrap() }))) }
{ // Not an array, just return it return CORS(JSON(Value::Object(json_map! { route => api_route.clone(), "offset" => serde_json::to_value(offset).unwrap(), "limit" => serde_json::to_value(limit).unwrap() }))); }
conditional_block
mock.rs
//! BDCS Mock API handling //! //! # Overview //! //! This module provides a mock API service that reads json files from a static directory and serves up //! the data from the file as-is. //! //! Requests like /route are read from a file named route.json //! Requests like /route/param are read from route-param.json //! Requests like /route/action/param are handled slightly differently, depending on the file. //! //! If the route-action.json file has an Array in it then it will be searched for a "name" key //! matching param. If that is found just that matching entry will be returned. //! //! The mock files should follow the (API rules here)[path/to/rules.html], using a top level //! object named the same as the route to hold the child object or array. Examples of valid //! files can be found in the tests/results/ directory. //! //! # Example Response //! //! eg. /recipes/info/http-server //! ```json //! {"limit":20,"offset":0,"recipes":{"description":"An example http //! server","modules":[{"name":"fm-httpd","version":"23.*"},{"name":"fm-php","version":"11.6.*"}],"name":"http-server","packages":[{"name":"tmux","version":"2.2"}]}} //! ``` //! // Copyright (C) 2016-2017 Red Hat, Inc. // // This file is part of bdcs-api-server. // // bdcs-api-server 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 3 of the License, or // (at your option) any later version. // // bdcs-api-server 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 bdcs-api-server. If not, see <http://www.gnu.org/licenses/>. // A lot of the code generated via rocket uses pass-by-value that clippy // disagrees with. Ignore these warnings. #![cfg_attr(feature="cargo-clippy", allow(needless_pass_by_value))] use std::fs::File; use std::path::Path; use rocket::config; use rocket_contrib::JSON; use rocket::response::NamedFile; use serde_json::{self, Value}; use api::{CORS, Filter, OFFSET, LIMIT}; /// A nice little macro to create simple Maps. Really convenient for /// returning ad-hoc JSON messages. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate rocket_contrib; /// use std::collections::HashMap; /// # fn main() { /// let map: HashMap<&str, usize> = map! { /// "status" => 0, /// "count" => 100 /// }; /// /// assert_eq!(map.len(), 2); /// assert_eq!(map.get("status"), Some(&0)); /// assert_eq!(map.get("count"), Some(&100)); /// # } /// ``` /// /// Borrowed from rocket.rs and modified to use serde_json::value::Map macro_rules! json_map { ($($key:expr => $value:expr),+) => ({ use serde_json::value::Map; let mut map = Map::new(); $(map.insert($key.to_string(), $value);)+ map }); ($($key:expr => $value:expr),+,) => { json_map!($($key => $value),+) }; } /// Handler for a bare route with offset and/or limit #[get("/<route>?<filter>")] pub fn static_route_filter(route: &str, filter: Filter) -> CORS<Option<NamedFile>> { static_json(route, None, filter.offset.unwrap_or(OFFSET), filter.limit.unwrap_or(LIMIT)) } /// Handler for a bare route with no filtering #[get("/<route>", rank=2)] pub fn static_route(route: &str) -> CORS<Option<NamedFile>> { static_json(route, None, OFFSET, LIMIT) } /// Handler for a route with a single parameter and offset and/or limit #[get("/<route>/<param>?<filter>")] pub fn static_route_param_filter(route: &str, param: &str, filter: Filter) -> CORS<Option<NamedFile>> { static_json(route, Some(param), filter.offset.unwrap_or(OFFSET), filter.limit.unwrap_or(LIMIT)) } /// Handler for a route with a single parameter and no filtering #[get("/<route>/<param>", rank=2)] pub fn static_route_param(route: &str, param: &str) -> CORS<Option<NamedFile>> { static_json(route, Some(param), OFFSET, LIMIT) } /// Handler for a route with an action, a parameter and offset/limit #[get("/<route>/<action>/<param>?<filter>")] pub fn static_route_action_filter(route: &str, action: &str, param: &str, filter: Filter) -> CORS<JSON<Value>> { filter_json(route, action, param, filter.offset.unwrap_or(OFFSET), filter.limit.unwrap_or(LIMIT)) } /// Handler for a route with an action, a parameter and no filtering #[get("/<route>/<action>/<param>", rank=2)] pub fn static_route_action(route: &str, action: &str, param: &str) -> CORS<JSON<Value>> { filter_json(route, action, param, OFFSET, LIMIT) } /// Return a static json file based on the route and parameter passed to the API /// /// # Arguments /// /// * `route` - The 1st argument on the API path /// * `param` - The 2nd argument on the API path /// * `offset` - Number of results to skip before returning results. Default is 0. /// * `limit` - Maximum number of results to return. It may return less. Default is 20. /// /// # Response /// /// * JSON response read from the file. /// /// The filename returned is constructed by joining the route and the param with a '-' and /// appending.json to it. eg. `/modules/list` will read from a file named `modules-list.json` /// /// The filtering arguments, offset and limit, are ignored. Any offset or limit in the file /// are returned as-is. /// fn static_json(route: &str, param: Option<&str>, offset: i64, limit: i64) -> CORS<Option<NamedFile>> { info!("mock request"; "route" => route, "param" => param, "offset" => offset, "limit" => limit); let mock_path = config::active() .unwrap() .get_str("mockfiles_path") .unwrap_or("/var/tmp/bdcs-mockfiles/"); // TODO Better way to construct this... let param = match param { Some(p) => format!("-{}", p), None => "".to_string() }; let file = format!("{}{}.json", route, param); CORS(NamedFile::open(Path::new(mock_path).join(file)).ok()) } /// Filter the contents of a static json file based on the action and parameter passed to the API /// /// # Arguments /// /// * `route` - The 1st argument on the API path /// * `action` - The 2nd argument on the API path /// * `param` - The 3rd argument on the API path
/// # Response /// /// * JSON response selected from the file. /// /// The filename to read is constructed by joining the route and the action with a '-' and /// appending.json to it. eg. `/modules/info/http-server` will read from a file named `modules-info.json` /// /// The filtering arguments, offset and limit, are ignored but are returned as part of the /// response. /// /// The file is expected to contain valid json with an object named for the route. If the route /// object is not an array, it is returned as-is, along with the offset and limit values. /// /// eg. A file with only an object: /// ```json /// {"modules":{"name": "http-server",...}} /// ``` /// /// If the route object contains an array then it is searched for a `"name"` key that is equal to the /// `param` passed to the API. A response is constructed using the route and the single /// object from the file. If nothing is found then a `null` is returned. /// /// eg. A file with an array /// ```json /// {"modules":[{"name": "http-server",...}, {"name": "nfs-server",...}]} /// ``` /// fn filter_json(route: &str, action: &str, param: &str, offset: i64, limit: i64) -> CORS<JSON<Value>> { info!("mock request"; "route" => route, "action" => action, "param" => param, "offset" => offset, "limit" => limit); let mock_path = config::active() .unwrap() .get_str("mockfiles_path") .unwrap_or("/var/tmp/bdcs-mockfiles/"); let file = format!("{}-{}.json", route, action); let json_data: Value = serde_json::from_reader(File::open(Path::new(mock_path).join(file)) .unwrap()) .unwrap(); let json_obj = json_data.as_object().unwrap(); debug!("json object"; "json" => format!("{:?}", json_obj)); // Properly formatted with {"<route>":... if let Some(api_route) = json_obj.get(route) { // If the route is an array search for a "name" key set to the value of param. if api_route.is_array() { if let Some(json_array) = api_route.as_array() { for item in json_array { if item.get("name") == Some(&Value::String(param.to_string())) { info!("Found it!"; "json" => format!("{:?}", item)); return CORS(JSON(Value::Object(json_map! { route => Value::Array(vec![item.clone()]), "offset" => serde_json::to_value(offset).unwrap(), "limit" => serde_json::to_value(limit).unwrap() }))); } } } } else { // Not an array, just return it return CORS(JSON(Value::Object(json_map! { route => api_route.clone(), "offset" => serde_json::to_value(offset).unwrap(), "limit" => serde_json::to_value(limit).unwrap() }))); } } // Nothing to return CORS(JSON(Value::Object(json_map! { route => Value::Null, "offset" => serde_json::to_value(offset).unwrap(), "limit" => serde_json::to_value(limit).unwrap() }))) }
/// * `offset` - Number of results to skip before returning results. Default is 0. /// * `limit` - Maximum number of results to return. It may return less. Default is 20. ///
random_line_split
mock.rs
//! BDCS Mock API handling //! //! # Overview //! //! This module provides a mock API service that reads json files from a static directory and serves up //! the data from the file as-is. //! //! Requests like /route are read from a file named route.json //! Requests like /route/param are read from route-param.json //! Requests like /route/action/param are handled slightly differently, depending on the file. //! //! If the route-action.json file has an Array in it then it will be searched for a "name" key //! matching param. If that is found just that matching entry will be returned. //! //! The mock files should follow the (API rules here)[path/to/rules.html], using a top level //! object named the same as the route to hold the child object or array. Examples of valid //! files can be found in the tests/results/ directory. //! //! # Example Response //! //! eg. /recipes/info/http-server //! ```json //! {"limit":20,"offset":0,"recipes":{"description":"An example http //! server","modules":[{"name":"fm-httpd","version":"23.*"},{"name":"fm-php","version":"11.6.*"}],"name":"http-server","packages":[{"name":"tmux","version":"2.2"}]}} //! ``` //! // Copyright (C) 2016-2017 Red Hat, Inc. // // This file is part of bdcs-api-server. // // bdcs-api-server 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 3 of the License, or // (at your option) any later version. // // bdcs-api-server 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 bdcs-api-server. If not, see <http://www.gnu.org/licenses/>. // A lot of the code generated via rocket uses pass-by-value that clippy // disagrees with. Ignore these warnings. #![cfg_attr(feature="cargo-clippy", allow(needless_pass_by_value))] use std::fs::File; use std::path::Path; use rocket::config; use rocket_contrib::JSON; use rocket::response::NamedFile; use serde_json::{self, Value}; use api::{CORS, Filter, OFFSET, LIMIT}; /// A nice little macro to create simple Maps. Really convenient for /// returning ad-hoc JSON messages. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate rocket_contrib; /// use std::collections::HashMap; /// # fn main() { /// let map: HashMap<&str, usize> = map! { /// "status" => 0, /// "count" => 100 /// }; /// /// assert_eq!(map.len(), 2); /// assert_eq!(map.get("status"), Some(&0)); /// assert_eq!(map.get("count"), Some(&100)); /// # } /// ``` /// /// Borrowed from rocket.rs and modified to use serde_json::value::Map macro_rules! json_map { ($($key:expr => $value:expr),+) => ({ use serde_json::value::Map; let mut map = Map::new(); $(map.insert($key.to_string(), $value);)+ map }); ($($key:expr => $value:expr),+,) => { json_map!($($key => $value),+) }; } /// Handler for a bare route with offset and/or limit #[get("/<route>?<filter>")] pub fn static_route_filter(route: &str, filter: Filter) -> CORS<Option<NamedFile>> { static_json(route, None, filter.offset.unwrap_or(OFFSET), filter.limit.unwrap_or(LIMIT)) } /// Handler for a bare route with no filtering #[get("/<route>", rank=2)] pub fn static_route(route: &str) -> CORS<Option<NamedFile>> { static_json(route, None, OFFSET, LIMIT) } /// Handler for a route with a single parameter and offset and/or limit #[get("/<route>/<param>?<filter>")] pub fn static_route_param_filter(route: &str, param: &str, filter: Filter) -> CORS<Option<NamedFile>> { static_json(route, Some(param), filter.offset.unwrap_or(OFFSET), filter.limit.unwrap_or(LIMIT)) } /// Handler for a route with a single parameter and no filtering #[get("/<route>/<param>", rank=2)] pub fn static_route_param(route: &str, param: &str) -> CORS<Option<NamedFile>> { static_json(route, Some(param), OFFSET, LIMIT) } /// Handler for a route with an action, a parameter and offset/limit #[get("/<route>/<action>/<param>?<filter>")] pub fn static_route_action_filter(route: &str, action: &str, param: &str, filter: Filter) -> CORS<JSON<Value>> { filter_json(route, action, param, filter.offset.unwrap_or(OFFSET), filter.limit.unwrap_or(LIMIT)) } /// Handler for a route with an action, a parameter and no filtering #[get("/<route>/<action>/<param>", rank=2)] pub fn
(route: &str, action: &str, param: &str) -> CORS<JSON<Value>> { filter_json(route, action, param, OFFSET, LIMIT) } /// Return a static json file based on the route and parameter passed to the API /// /// # Arguments /// /// * `route` - The 1st argument on the API path /// * `param` - The 2nd argument on the API path /// * `offset` - Number of results to skip before returning results. Default is 0. /// * `limit` - Maximum number of results to return. It may return less. Default is 20. /// /// # Response /// /// * JSON response read from the file. /// /// The filename returned is constructed by joining the route and the param with a '-' and /// appending.json to it. eg. `/modules/list` will read from a file named `modules-list.json` /// /// The filtering arguments, offset and limit, are ignored. Any offset or limit in the file /// are returned as-is. /// fn static_json(route: &str, param: Option<&str>, offset: i64, limit: i64) -> CORS<Option<NamedFile>> { info!("mock request"; "route" => route, "param" => param, "offset" => offset, "limit" => limit); let mock_path = config::active() .unwrap() .get_str("mockfiles_path") .unwrap_or("/var/tmp/bdcs-mockfiles/"); // TODO Better way to construct this... let param = match param { Some(p) => format!("-{}", p), None => "".to_string() }; let file = format!("{}{}.json", route, param); CORS(NamedFile::open(Path::new(mock_path).join(file)).ok()) } /// Filter the contents of a static json file based on the action and parameter passed to the API /// /// # Arguments /// /// * `route` - The 1st argument on the API path /// * `action` - The 2nd argument on the API path /// * `param` - The 3rd argument on the API path /// * `offset` - Number of results to skip before returning results. Default is 0. /// * `limit` - Maximum number of results to return. It may return less. Default is 20. /// /// # Response /// /// * JSON response selected from the file. /// /// The filename to read is constructed by joining the route and the action with a '-' and /// appending.json to it. eg. `/modules/info/http-server` will read from a file named `modules-info.json` /// /// The filtering arguments, offset and limit, are ignored but are returned as part of the /// response. /// /// The file is expected to contain valid json with an object named for the route. If the route /// object is not an array, it is returned as-is, along with the offset and limit values. /// /// eg. A file with only an object: /// ```json /// {"modules":{"name": "http-server",...}} /// ``` /// /// If the route object contains an array then it is searched for a `"name"` key that is equal to the /// `param` passed to the API. A response is constructed using the route and the single /// object from the file. If nothing is found then a `null` is returned. /// /// eg. A file with an array /// ```json /// {"modules":[{"name": "http-server",...}, {"name": "nfs-server",...}]} /// ``` /// fn filter_json(route: &str, action: &str, param: &str, offset: i64, limit: i64) -> CORS<JSON<Value>> { info!("mock request"; "route" => route, "action" => action, "param" => param, "offset" => offset, "limit" => limit); let mock_path = config::active() .unwrap() .get_str("mockfiles_path") .unwrap_or("/var/tmp/bdcs-mockfiles/"); let file = format!("{}-{}.json", route, action); let json_data: Value = serde_json::from_reader(File::open(Path::new(mock_path).join(file)) .unwrap()) .unwrap(); let json_obj = json_data.as_object().unwrap(); debug!("json object"; "json" => format!("{:?}", json_obj)); // Properly formatted with {"<route>":... if let Some(api_route) = json_obj.get(route) { // If the route is an array search for a "name" key set to the value of param. if api_route.is_array() { if let Some(json_array) = api_route.as_array() { for item in json_array { if item.get("name") == Some(&Value::String(param.to_string())) { info!("Found it!"; "json" => format!("{:?}", item)); return CORS(JSON(Value::Object(json_map! { route => Value::Array(vec![item.clone()]), "offset" => serde_json::to_value(offset).unwrap(), "limit" => serde_json::to_value(limit).unwrap() }))); } } } } else { // Not an array, just return it return CORS(JSON(Value::Object(json_map! { route => api_route.clone(), "offset" => serde_json::to_value(offset).unwrap(), "limit" => serde_json::to_value(limit).unwrap() }))); } } // Nothing to return CORS(JSON(Value::Object(json_map! { route => Value::Null, "offset" => serde_json::to_value(offset).unwrap(), "limit" => serde_json::to_value(limit).unwrap() }))) }
static_route_action
identifier_name
random.rs
use orderings::ORDERINGS; use random::Seed; use slices::{random_values_from_slice, RandomValuesFromSlice}; use std::cmp::Ordering; use std::iter::Cloned; pub type RandomOrderings = Cloned<RandomValuesFromSlice<'static, Ordering>>; /// Generates a random `Ordering` that has an equal probability of being `Less`, `Greater`, or /// `Equal`. /// /// $P(<) = P(=) = P(>) = \frac{1}{3}$. /// /// The output length is infinite. /// /// # Expected worst-case complexity /// /// Constant time and additional memory. /// /// # Examples /// ``` /// extern crate itertools; /// /// use itertools::Itertools; /// /// use malachite_base::orderings::random::random_orderings; /// use malachite_base::random::EXAMPLE_SEED; /// use std::cmp::Ordering::{self, Equal, Greater, Less}; /// /// assert_eq!( /// random_orderings(EXAMPLE_SEED).take(10).collect_vec(), /// &[Less, Equal, Less, Greater, Less, Less, Equal, Less, Equal, Greater] /// ) /// ``` #[inline] pub fn
(seed: Seed) -> RandomOrderings { random_values_from_slice(seed, &ORDERINGS).cloned() }
random_orderings
identifier_name
random.rs
use orderings::ORDERINGS; use random::Seed; use slices::{random_values_from_slice, RandomValuesFromSlice}; use std::cmp::Ordering; use std::iter::Cloned; pub type RandomOrderings = Cloned<RandomValuesFromSlice<'static, Ordering>>; /// Generates a random `Ordering` that has an equal probability of being `Less`, `Greater`, or /// `Equal`. /// /// $P(<) = P(=) = P(>) = \frac{1}{3}$. /// /// The output length is infinite. /// /// # Expected worst-case complexity /// /// Constant time and additional memory. /// /// # Examples /// ``` /// extern crate itertools; /// /// use itertools::Itertools; /// /// use malachite_base::orderings::random::random_orderings; /// use malachite_base::random::EXAMPLE_SEED; /// use std::cmp::Ordering::{self, Equal, Greater, Less}; /// /// assert_eq!( /// random_orderings(EXAMPLE_SEED).take(10).collect_vec(), /// &[Less, Equal, Less, Greater, Less, Less, Equal, Less, Equal, Greater] /// ) /// ``` #[inline] pub fn random_orderings(seed: Seed) -> RandomOrderings
{ random_values_from_slice(seed, &ORDERINGS).cloned() }
identifier_body
random.rs
use orderings::ORDERINGS; use random::Seed; use slices::{random_values_from_slice, RandomValuesFromSlice}; use std::cmp::Ordering; use std::iter::Cloned; pub type RandomOrderings = Cloned<RandomValuesFromSlice<'static, Ordering>>; /// Generates a random `Ordering` that has an equal probability of being `Less`, `Greater`, or /// `Equal`. /// /// $P(<) = P(=) = P(>) = \frac{1}{3}$. /// /// The output length is infinite. /// /// # Expected worst-case complexity /// /// Constant time and additional memory. /// /// # Examples /// ``` /// extern crate itertools; /// /// use itertools::Itertools; /// /// use malachite_base::orderings::random::random_orderings; /// use malachite_base::random::EXAMPLE_SEED; /// use std::cmp::Ordering::{self, Equal, Greater, Less}; /// /// assert_eq!( /// random_orderings(EXAMPLE_SEED).take(10).collect_vec(), /// &[Less, Equal, Less, Greater, Less, Less, Equal, Less, Equal, Greater] /// ) /// ``` #[inline] pub fn random_orderings(seed: Seed) -> RandomOrderings {
random_values_from_slice(seed, &ORDERINGS).cloned() }
random_line_split
39-2.rs
/* Problem 39: Integer right triangles * * If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are * exactly three solutions for p = 120. * * {20,48,52}, {24,45,51}, {30,40,50} * * For which value of p ≤ 1000, is the number of solutions maximised? */ const MAX_PERIMETER: f64 = 1_000.0; // Alternative implementation for problem 39. Much faster fn main() { let mut counts = [0usize; MAX_PERIMETER as usize]; let max_perimeter_by_3 = MAX_PERIMETER / 3.0; let two_thirds_of_max = 2.0 * max_perimeter_by_3; let mut a = 1.0; while a < max_perimeter_by_3 { let a_squared = a * a; let mut b = a + 1.0; while b < two_thirds_of_max - a { let b_squared = b * b; let c = (a_squared + b_squared).sqrt(); let is_integer = c == c.floor(); if!is_integer {
b += 1.0; continue; } let perimeter = a + b + c; if perimeter < MAX_PERIMETER { counts[(perimeter as usize) - 1] += 1; } b += 1.0; } a += 1.0; } let mut max_count = 0; let mut max = 0; for (index, &count) in counts.iter().enumerate() { if count > max_count { max_count = count; max = index + 1; } } println!("{}", max); }
random_line_split
39-2.rs
/* Problem 39: Integer right triangles * * If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are * exactly three solutions for p = 120. * * {20,48,52}, {24,45,51}, {30,40,50} * * For which value of p ≤ 1000, is the number of solutions maximised? */ const MAX_PERIMETER: f64 = 1_000.0; // Alternative implementation for problem 39. Much faster fn ma
{ let mut counts = [0usize; MAX_PERIMETER as usize]; let max_perimeter_by_3 = MAX_PERIMETER / 3.0; let two_thirds_of_max = 2.0 * max_perimeter_by_3; let mut a = 1.0; while a < max_perimeter_by_3 { let a_squared = a * a; let mut b = a + 1.0; while b < two_thirds_of_max - a { let b_squared = b * b; let c = (a_squared + b_squared).sqrt(); let is_integer = c == c.floor(); if!is_integer { b += 1.0; continue; } let perimeter = a + b + c; if perimeter < MAX_PERIMETER { counts[(perimeter as usize) - 1] += 1; } b += 1.0; } a += 1.0; } let mut max_count = 0; let mut max = 0; for (index, &count) in counts.iter().enumerate() { if count > max_count { max_count = count; max = index + 1; } } println!("{}", max); }
in()
identifier_name
39-2.rs
/* Problem 39: Integer right triangles * * If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are * exactly three solutions for p = 120. * * {20,48,52}, {24,45,51}, {30,40,50} * * For which value of p ≤ 1000, is the number of solutions maximised? */ const MAX_PERIMETER: f64 = 1_000.0; // Alternative implementation for problem 39. Much faster fn main() { let mut counts = [0usize; MAX_PERIMETER as usize]; let max_perimeter_by_3 = MAX_PERIMETER / 3.0; let two_thirds_of_max = 2.0 * max_perimeter_by_3; let mut a = 1.0; while a < max_perimeter_by_3 { let a_squared = a * a; let mut b = a + 1.0; while b < two_thirds_of_max - a { let b_squared = b * b; let c = (a_squared + b_squared).sqrt(); let is_integer = c == c.floor(); if!is_integer {
let perimeter = a + b + c; if perimeter < MAX_PERIMETER { counts[(perimeter as usize) - 1] += 1; } b += 1.0; } a += 1.0; } let mut max_count = 0; let mut max = 0; for (index, &count) in counts.iter().enumerate() { if count > max_count { max_count = count; max = index + 1; } } println!("{}", max); }
b += 1.0; continue; }
conditional_block
39-2.rs
/* Problem 39: Integer right triangles * * If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are * exactly three solutions for p = 120. * * {20,48,52}, {24,45,51}, {30,40,50} * * For which value of p ≤ 1000, is the number of solutions maximised? */ const MAX_PERIMETER: f64 = 1_000.0; // Alternative implementation for problem 39. Much faster fn main() {
} let perimeter = a + b + c; if perimeter < MAX_PERIMETER { counts[(perimeter as usize) - 1] += 1; } b += 1.0; } a += 1.0; } let mut max_count = 0; let mut max = 0; for (index, &count) in counts.iter().enumerate() { if count > max_count { max_count = count; max = index + 1; } } println!("{}", max); }
let mut counts = [0usize; MAX_PERIMETER as usize]; let max_perimeter_by_3 = MAX_PERIMETER / 3.0; let two_thirds_of_max = 2.0 * max_perimeter_by_3; let mut a = 1.0; while a < max_perimeter_by_3 { let a_squared = a * a; let mut b = a + 1.0; while b < two_thirds_of_max - a { let b_squared = b * b; let c = (a_squared + b_squared).sqrt(); let is_integer = c == c.floor(); if !is_integer { b += 1.0; continue;
identifier_body
issue-22684.rs
// Copyright 2016 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.
mod foo { pub struct Foo; impl Foo { fn bar(&self) {} } pub trait Baz { fn bar(&self) -> bool { true } } impl Baz for Foo {} } fn main() { use foo::Baz; // Check that `bar` resolves to the trait method, not the inherent impl method. let _: () = foo::Foo.bar(); //~ ERROR mismatched types }
random_line_split
issue-22684.rs
// Copyright 2016 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. mod foo { pub struct Foo; impl Foo { fn bar(&self) {} } pub trait Baz { fn
(&self) -> bool { true } } impl Baz for Foo {} } fn main() { use foo::Baz; // Check that `bar` resolves to the trait method, not the inherent impl method. let _: () = foo::Foo.bar(); //~ ERROR mismatched types }
bar
identifier_name
issue-22684.rs
// Copyright 2016 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. mod foo { pub struct Foo; impl Foo { fn bar(&self) {} } pub trait Baz { fn bar(&self) -> bool { true } } impl Baz for Foo {} } fn main()
{ use foo::Baz; // Check that `bar` resolves to the trait method, not the inherent impl method. let _: () = foo::Foo.bar(); //~ ERROR mismatched types }
identifier_body
server.rs
// Copyright 2017 PingCAP, Inc. // // 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, // See the License for the specific language governing permissions and // limitations under the License. extern crate clap; extern crate futures; extern crate grpcio as grpc; extern crate grpcio_proto as grpc_proto; extern crate interop; #[macro_use] extern crate log; use std::sync::Arc; use clap::{App, Arg}; use futures::{future, Future}; use grpc::{Environment, ServerBuilder}; use grpc_proto::testing::test_grpc::create_test_service; use grpc_proto::util; use interop::InteropTestService; fn main()
) .get_matches(); let host = matches.value_of("host").unwrap_or("127.0.0.1"); let port: u16 = matches.value_of("port").unwrap_or("8080").parse().unwrap(); let use_tls: bool = matches .value_of("use_tls") .unwrap_or("false") .parse() .unwrap(); let env = Arc::new(Environment::new(2)); let service = create_test_service(InteropTestService); let mut builder = ServerBuilder::new(env).register_service(service); builder = if use_tls { let creds = util::create_test_server_credentials(); builder.bind_secure(host, port, creds) } else { builder.bind(host, port) }; let mut server = builder.build().unwrap(); for &(ref host, port) in server.bind_addrs() { info!("listening on {}:{}", host, port); } server.start(); let _ = future::empty::<(), ()>().wait(); }
{ let matches = App::new("Interoperability Test Server") .about("ref https://github.com/grpc/grpc/blob/v1.3.x/doc/interop-test-descriptions.md") .arg( Arg::with_name("host") .long("host") .help("The server host to listen to. For example, \"localhost\" or \"127.0.0.1\"") .takes_value(true), ) .arg( Arg::with_name("port") .long("port") .help("The port to listen on. For example, \"8080\"") .takes_value(true), ) .arg( Arg::with_name("use_tls") .long("use_tls") .help("Whether to use a plaintext or encrypted connection") .takes_value(true),
identifier_body
server.rs
// Copyright 2017 PingCAP, Inc. // // 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, // See the License for the specific language governing permissions and // limitations under the License. extern crate clap; extern crate futures; extern crate grpcio as grpc; extern crate grpcio_proto as grpc_proto; extern crate interop; #[macro_use] extern crate log; use std::sync::Arc; use clap::{App, Arg}; use futures::{future, Future}; use grpc::{Environment, ServerBuilder}; use grpc_proto::testing::test_grpc::create_test_service; use grpc_proto::util; use interop::InteropTestService; fn main() { let matches = App::new("Interoperability Test Server") .about("ref https://github.com/grpc/grpc/blob/v1.3.x/doc/interop-test-descriptions.md") .arg( Arg::with_name("host") .long("host") .help("The server host to listen to. For example, \"localhost\" or \"127.0.0.1\"") .takes_value(true), ) .arg( Arg::with_name("port") .long("port") .help("The port to listen on. For example, \"8080\"") .takes_value(true), ) .arg( Arg::with_name("use_tls") .long("use_tls") .help("Whether to use a plaintext or encrypted connection") .takes_value(true), ) .get_matches(); let host = matches.value_of("host").unwrap_or("127.0.0.1"); let port: u16 = matches.value_of("port").unwrap_or("8080").parse().unwrap(); let use_tls: bool = matches .value_of("use_tls") .unwrap_or("false") .parse() .unwrap(); let env = Arc::new(Environment::new(2)); let service = create_test_service(InteropTestService); let mut builder = ServerBuilder::new(env).register_service(service); builder = if use_tls { let creds = util::create_test_server_credentials(); builder.bind_secure(host, port, creds) } else
; let mut server = builder.build().unwrap(); for &(ref host, port) in server.bind_addrs() { info!("listening on {}:{}", host, port); } server.start(); let _ = future::empty::<(), ()>().wait(); }
{ builder.bind(host, port) }
conditional_block
server.rs
// Copyright 2017 PingCAP, Inc. // // 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, // See the License for the specific language governing permissions and // limitations under the License. extern crate clap; extern crate futures; extern crate grpcio as grpc; extern crate grpcio_proto as grpc_proto; extern crate interop; #[macro_use] extern crate log; use std::sync::Arc; use clap::{App, Arg}; use futures::{future, Future}; use grpc::{Environment, ServerBuilder}; use grpc_proto::testing::test_grpc::create_test_service; use grpc_proto::util; use interop::InteropTestService; fn main() { let matches = App::new("Interoperability Test Server") .about("ref https://github.com/grpc/grpc/blob/v1.3.x/doc/interop-test-descriptions.md") .arg( Arg::with_name("host") .long("host") .help("The server host to listen to. For example, \"localhost\" or \"127.0.0.1\"") .takes_value(true), ) .arg( Arg::with_name("port") .long("port")
.arg( Arg::with_name("use_tls") .long("use_tls") .help("Whether to use a plaintext or encrypted connection") .takes_value(true), ) .get_matches(); let host = matches.value_of("host").unwrap_or("127.0.0.1"); let port: u16 = matches.value_of("port").unwrap_or("8080").parse().unwrap(); let use_tls: bool = matches .value_of("use_tls") .unwrap_or("false") .parse() .unwrap(); let env = Arc::new(Environment::new(2)); let service = create_test_service(InteropTestService); let mut builder = ServerBuilder::new(env).register_service(service); builder = if use_tls { let creds = util::create_test_server_credentials(); builder.bind_secure(host, port, creds) } else { builder.bind(host, port) }; let mut server = builder.build().unwrap(); for &(ref host, port) in server.bind_addrs() { info!("listening on {}:{}", host, port); } server.start(); let _ = future::empty::<(), ()>().wait(); }
.help("The port to listen on. For example, \"8080\"") .takes_value(true), )
random_line_split
server.rs
// Copyright 2017 PingCAP, Inc. // // 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, // See the License for the specific language governing permissions and // limitations under the License. extern crate clap; extern crate futures; extern crate grpcio as grpc; extern crate grpcio_proto as grpc_proto; extern crate interop; #[macro_use] extern crate log; use std::sync::Arc; use clap::{App, Arg}; use futures::{future, Future}; use grpc::{Environment, ServerBuilder}; use grpc_proto::testing::test_grpc::create_test_service; use grpc_proto::util; use interop::InteropTestService; fn
() { let matches = App::new("Interoperability Test Server") .about("ref https://github.com/grpc/grpc/blob/v1.3.x/doc/interop-test-descriptions.md") .arg( Arg::with_name("host") .long("host") .help("The server host to listen to. For example, \"localhost\" or \"127.0.0.1\"") .takes_value(true), ) .arg( Arg::with_name("port") .long("port") .help("The port to listen on. For example, \"8080\"") .takes_value(true), ) .arg( Arg::with_name("use_tls") .long("use_tls") .help("Whether to use a plaintext or encrypted connection") .takes_value(true), ) .get_matches(); let host = matches.value_of("host").unwrap_or("127.0.0.1"); let port: u16 = matches.value_of("port").unwrap_or("8080").parse().unwrap(); let use_tls: bool = matches .value_of("use_tls") .unwrap_or("false") .parse() .unwrap(); let env = Arc::new(Environment::new(2)); let service = create_test_service(InteropTestService); let mut builder = ServerBuilder::new(env).register_service(service); builder = if use_tls { let creds = util::create_test_server_credentials(); builder.bind_secure(host, port, creds) } else { builder.bind(host, port) }; let mut server = builder.build().unwrap(); for &(ref host, port) in server.bind_addrs() { info!("listening on {}:{}", host, port); } server.start(); let _ = future::empty::<(), ()>().wait(); }
main
identifier_name
issue-3563-3.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. // ASCII art shape renderer. // Demonstrates traits, impls, operator overloading, non-copyable struct, unit testing. // To run execute: rustc --test shapes.rs &&./shapes // Rust's std library is tightly bound to the language itself so it is automatically linked in. // However the extra library is designed to be optional (for code that must run on constrained // environments like embedded devices or special environments like kernel code) so it must // be explicitly linked in. // Extern mod controls linkage. Use controls the visibility of names to modules that are // already linked in. Using WriterUtil allows us to use the write_line method. use std::str; use std::slice; use std::fmt; // Represents a position on a canvas. struct Point { x: int, y: int, } // Represents an offset on a canvas. (This has the same structure as a Point. // but different semantics). struct Size { width: int, height: int, } struct Rect { top_left: Point, size: Size, } // Contains the information needed to do shape rendering via ASCII art. struct AsciiArt { width: uint, height: uint, fill: char, lines: Vec<Vec<char> >, // This struct can be quite large so we'll disable copying: developers need // to either pass these structs around via references or move them. } impl Drop for AsciiArt { fn drop(&mut self) {} } // It's common to define a constructor sort of function to create struct instances. // If there is a canonical constructor it is typically named the same as the type. // Other constructor sort of functions are typically named from_foo, from_bar, etc. fn AsciiArt(width: uint, height: uint, fill: char) -> AsciiArt { // Use an anonymous function to build a vector of vectors containing // blank characters for each position in our canvas. let mut lines = Vec::new(); for _ in range(0, height) { lines.push(Vec::from_elem(width, '.')); } // Rust code often returns values by omitting the trailing semi-colon // instead of using an explicit return statement. AsciiArt {width: width, height: height, fill: fill, lines: lines} } // Methods particular to the AsciiArt struct. impl AsciiArt { fn add_pt(&mut self, x: int, y: int) { if x >= 0 && x < self.width as int { if y >= 0 && y < self.height as int { // Note that numeric types don't implicitly convert to each other. let v = y as uint; let h = x as uint; // Vector subscripting will normally copy the element, but &v[i] // will return a reference which is what we need because the // element is: // 1) potentially large // 2) needs to be modified let row = self.lines.get_mut(v); *row.get_mut(h) = self.fill; } } } } // Allows AsciiArt to be converted to a string using the libcore ToStr trait. // Note that the %s fmt! specifier will not call this automatically. impl fmt::Show for AsciiArt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Convert each line into a string. let lines = self.lines.iter() .map(|line| { str::from_chars(line.as_slice()).to_string() }) .collect::<Vec<String>>(); // Concatenate the lines together using a new-line. write!(f, "{}", lines.connect("\n")) } } // This is similar to an interface in other languages: it defines a protocol which // developers can implement for arbitrary concrete types. trait Canvas { fn add_point(&mut self, shape: Point); fn add_rect(&mut self, shape: Rect); // Unlike interfaces traits support default implementations. // Got an ICE as soon as I added this method. fn add_points(&mut self, shapes: &[Point]) { for pt in shapes.iter() {self.add_point(*pt)}; } } // Here we provide an implementation of the Canvas methods for AsciiArt. // Other implementations could also be provided (e.g. for PDF or Apple's Quartz) // and code can use them polymorphically via the Canvas trait. impl Canvas for AsciiArt { fn add_point(&mut self, shape: Point) { self.add_pt(shape.x, shape.y); } fn add_rect(&mut self, shape: Rect) { // Add the top and bottom lines. for x in range(shape.top_left.x, shape.top_left.x + shape.size.width) { self.add_pt(x, shape.top_left.y); self.add_pt(x, shape.top_left.y + shape.size.height - 1); } // Add the left and right lines. for y in range(shape.top_left.y, shape.top_left.y + shape.size.height) { self.add_pt(shape.top_left.x, y); self.add_pt(shape.top_left.x + shape.size.width - 1, y); } } } // Rust's unit testing framework is currently a bit under-developed so we'll use // this little helper. pub fn check_strs(actual: &str, expected: &str) -> bool { if actual!= expected { println!("Found:\n{}\nbut expected\n{}", actual, expected); return false; } return true; } fn test_ascii_art_ctor() { let art = AsciiArt(3, 3, '*'); assert!(check_strs(art.to_str().as_slice(), "...\n...\n...")); } fn test_add_pt() { let mut art = AsciiArt(3, 3, '*'); art.add_pt(0, 0); art.add_pt(0, -10); art.add_pt(1, 2); assert!(check_strs(art.to_str().as_slice(), "*..\n...\n.*.")); } fn test_shapes() { let mut art = AsciiArt(4, 4, '*'); art.add_rect(Rect {top_left: Point {x: 0, y: 0}, size: Size {width: 4, height: 4}}); art.add_point(Point {x: 2, y: 2}); assert!(check_strs(art.to_str().as_slice(), "****\n*..*\n*.**\n****")); } pub fn main()
{ test_ascii_art_ctor(); test_add_pt(); test_shapes(); }
identifier_body
issue-3563-3.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. // ASCII art shape renderer. // Demonstrates traits, impls, operator overloading, non-copyable struct, unit testing. // To run execute: rustc --test shapes.rs &&./shapes // Rust's std library is tightly bound to the language itself so it is automatically linked in. // However the extra library is designed to be optional (for code that must run on constrained // environments like embedded devices or special environments like kernel code) so it must // be explicitly linked in. // Extern mod controls linkage. Use controls the visibility of names to modules that are // already linked in. Using WriterUtil allows us to use the write_line method. use std::str; use std::slice; use std::fmt; // Represents a position on a canvas. struct Point { x: int, y: int, } // Represents an offset on a canvas. (This has the same structure as a Point. // but different semantics). struct Size { width: int, height: int, } struct Rect { top_left: Point, size: Size, } // Contains the information needed to do shape rendering via ASCII art. struct AsciiArt { width: uint, height: uint, fill: char, lines: Vec<Vec<char> >, // This struct can be quite large so we'll disable copying: developers need // to either pass these structs around via references or move them. } impl Drop for AsciiArt { fn drop(&mut self) {} } // It's common to define a constructor sort of function to create struct instances. // If there is a canonical constructor it is typically named the same as the type. // Other constructor sort of functions are typically named from_foo, from_bar, etc. fn AsciiArt(width: uint, height: uint, fill: char) -> AsciiArt { // Use an anonymous function to build a vector of vectors containing // blank characters for each position in our canvas. let mut lines = Vec::new(); for _ in range(0, height) { lines.push(Vec::from_elem(width, '.')); } // Rust code often returns values by omitting the trailing semi-colon // instead of using an explicit return statement. AsciiArt {width: width, height: height, fill: fill, lines: lines} } // Methods particular to the AsciiArt struct. impl AsciiArt { fn add_pt(&mut self, x: int, y: int) { if x >= 0 && x < self.width as int { if y >= 0 && y < self.height as int { // Note that numeric types don't implicitly convert to each other. let v = y as uint; let h = x as uint; // Vector subscripting will normally copy the element, but &v[i] // will return a reference which is what we need because the // element is: // 1) potentially large // 2) needs to be modified let row = self.lines.get_mut(v); *row.get_mut(h) = self.fill; } } } } // Allows AsciiArt to be converted to a string using the libcore ToStr trait. // Note that the %s fmt! specifier will not call this automatically. impl fmt::Show for AsciiArt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Convert each line into a string. let lines = self.lines.iter() .map(|line| { str::from_chars(line.as_slice()).to_string() }) .collect::<Vec<String>>(); // Concatenate the lines together using a new-line. write!(f, "{}", lines.connect("\n")) } } // This is similar to an interface in other languages: it defines a protocol which // developers can implement for arbitrary concrete types. trait Canvas { fn add_point(&mut self, shape: Point); fn add_rect(&mut self, shape: Rect); // Unlike interfaces traits support default implementations. // Got an ICE as soon as I added this method. fn add_points(&mut self, shapes: &[Point]) { for pt in shapes.iter() {self.add_point(*pt)}; } } // Here we provide an implementation of the Canvas methods for AsciiArt. // Other implementations could also be provided (e.g. for PDF or Apple's Quartz) // and code can use them polymorphically via the Canvas trait. impl Canvas for AsciiArt { fn add_point(&mut self, shape: Point) { self.add_pt(shape.x, shape.y); } fn add_rect(&mut self, shape: Rect) { // Add the top and bottom lines. for x in range(shape.top_left.x, shape.top_left.x + shape.size.width) { self.add_pt(x, shape.top_left.y); self.add_pt(x, shape.top_left.y + shape.size.height - 1); } // Add the left and right lines. for y in range(shape.top_left.y, shape.top_left.y + shape.size.height) { self.add_pt(shape.top_left.x, y); self.add_pt(shape.top_left.x + shape.size.width - 1, y); } } } // Rust's unit testing framework is currently a bit under-developed so we'll use // this little helper. pub fn
(actual: &str, expected: &str) -> bool { if actual!= expected { println!("Found:\n{}\nbut expected\n{}", actual, expected); return false; } return true; } fn test_ascii_art_ctor() { let art = AsciiArt(3, 3, '*'); assert!(check_strs(art.to_str().as_slice(), "...\n...\n...")); } fn test_add_pt() { let mut art = AsciiArt(3, 3, '*'); art.add_pt(0, 0); art.add_pt(0, -10); art.add_pt(1, 2); assert!(check_strs(art.to_str().as_slice(), "*..\n...\n.*.")); } fn test_shapes() { let mut art = AsciiArt(4, 4, '*'); art.add_rect(Rect {top_left: Point {x: 0, y: 0}, size: Size {width: 4, height: 4}}); art.add_point(Point {x: 2, y: 2}); assert!(check_strs(art.to_str().as_slice(), "****\n*..*\n*.**\n****")); } pub fn main() { test_ascii_art_ctor(); test_add_pt(); test_shapes(); }
check_strs
identifier_name
issue-3563-3.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. // ASCII art shape renderer. // Demonstrates traits, impls, operator overloading, non-copyable struct, unit testing. // To run execute: rustc --test shapes.rs &&./shapes // Rust's std library is tightly bound to the language itself so it is automatically linked in. // However the extra library is designed to be optional (for code that must run on constrained // environments like embedded devices or special environments like kernel code) so it must // be explicitly linked in. // Extern mod controls linkage. Use controls the visibility of names to modules that are // already linked in. Using WriterUtil allows us to use the write_line method. use std::str; use std::slice; use std::fmt; // Represents a position on a canvas. struct Point { x: int, y: int, } // Represents an offset on a canvas. (This has the same structure as a Point. // but different semantics). struct Size { width: int, height: int, } struct Rect { top_left: Point, size: Size, } // Contains the information needed to do shape rendering via ASCII art. struct AsciiArt { width: uint, height: uint, fill: char, lines: Vec<Vec<char> >, // This struct can be quite large so we'll disable copying: developers need // to either pass these structs around via references or move them. } impl Drop for AsciiArt { fn drop(&mut self) {} } // It's common to define a constructor sort of function to create struct instances. // If there is a canonical constructor it is typically named the same as the type. // Other constructor sort of functions are typically named from_foo, from_bar, etc. fn AsciiArt(width: uint, height: uint, fill: char) -> AsciiArt { // Use an anonymous function to build a vector of vectors containing // blank characters for each position in our canvas. let mut lines = Vec::new(); for _ in range(0, height) { lines.push(Vec::from_elem(width, '.')); } // Rust code often returns values by omitting the trailing semi-colon // instead of using an explicit return statement. AsciiArt {width: width, height: height, fill: fill, lines: lines} } // Methods particular to the AsciiArt struct. impl AsciiArt { fn add_pt(&mut self, x: int, y: int) { if x >= 0 && x < self.width as int
} } // Allows AsciiArt to be converted to a string using the libcore ToStr trait. // Note that the %s fmt! specifier will not call this automatically. impl fmt::Show for AsciiArt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Convert each line into a string. let lines = self.lines.iter() .map(|line| { str::from_chars(line.as_slice()).to_string() }) .collect::<Vec<String>>(); // Concatenate the lines together using a new-line. write!(f, "{}", lines.connect("\n")) } } // This is similar to an interface in other languages: it defines a protocol which // developers can implement for arbitrary concrete types. trait Canvas { fn add_point(&mut self, shape: Point); fn add_rect(&mut self, shape: Rect); // Unlike interfaces traits support default implementations. // Got an ICE as soon as I added this method. fn add_points(&mut self, shapes: &[Point]) { for pt in shapes.iter() {self.add_point(*pt)}; } } // Here we provide an implementation of the Canvas methods for AsciiArt. // Other implementations could also be provided (e.g. for PDF or Apple's Quartz) // and code can use them polymorphically via the Canvas trait. impl Canvas for AsciiArt { fn add_point(&mut self, shape: Point) { self.add_pt(shape.x, shape.y); } fn add_rect(&mut self, shape: Rect) { // Add the top and bottom lines. for x in range(shape.top_left.x, shape.top_left.x + shape.size.width) { self.add_pt(x, shape.top_left.y); self.add_pt(x, shape.top_left.y + shape.size.height - 1); } // Add the left and right lines. for y in range(shape.top_left.y, shape.top_left.y + shape.size.height) { self.add_pt(shape.top_left.x, y); self.add_pt(shape.top_left.x + shape.size.width - 1, y); } } } // Rust's unit testing framework is currently a bit under-developed so we'll use // this little helper. pub fn check_strs(actual: &str, expected: &str) -> bool { if actual!= expected { println!("Found:\n{}\nbut expected\n{}", actual, expected); return false; } return true; } fn test_ascii_art_ctor() { let art = AsciiArt(3, 3, '*'); assert!(check_strs(art.to_str().as_slice(), "...\n...\n...")); } fn test_add_pt() { let mut art = AsciiArt(3, 3, '*'); art.add_pt(0, 0); art.add_pt(0, -10); art.add_pt(1, 2); assert!(check_strs(art.to_str().as_slice(), "*..\n...\n.*.")); } fn test_shapes() { let mut art = AsciiArt(4, 4, '*'); art.add_rect(Rect {top_left: Point {x: 0, y: 0}, size: Size {width: 4, height: 4}}); art.add_point(Point {x: 2, y: 2}); assert!(check_strs(art.to_str().as_slice(), "****\n*..*\n*.**\n****")); } pub fn main() { test_ascii_art_ctor(); test_add_pt(); test_shapes(); }
{ if y >= 0 && y < self.height as int { // Note that numeric types don't implicitly convert to each other. let v = y as uint; let h = x as uint; // Vector subscripting will normally copy the element, but &v[i] // will return a reference which is what we need because the // element is: // 1) potentially large // 2) needs to be modified let row = self.lines.get_mut(v); *row.get_mut(h) = self.fill; } }
conditional_block
issue-3563-3.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. // ASCII art shape renderer. // Demonstrates traits, impls, operator overloading, non-copyable struct, unit testing. // To run execute: rustc --test shapes.rs &&./shapes // Rust's std library is tightly bound to the language itself so it is automatically linked in. // However the extra library is designed to be optional (for code that must run on constrained // environments like embedded devices or special environments like kernel code) so it must // be explicitly linked in. // Extern mod controls linkage. Use controls the visibility of names to modules that are // already linked in. Using WriterUtil allows us to use the write_line method. use std::str; use std::slice; use std::fmt; // Represents a position on a canvas. struct Point { x: int, y: int, } // Represents an offset on a canvas. (This has the same structure as a Point. // but different semantics). struct Size { width: int, height: int, } struct Rect { top_left: Point, size: Size, } // Contains the information needed to do shape rendering via ASCII art. struct AsciiArt { width: uint, height: uint, fill: char, lines: Vec<Vec<char> >, // This struct can be quite large so we'll disable copying: developers need // to either pass these structs around via references or move them. } impl Drop for AsciiArt { fn drop(&mut self) {} } // It's common to define a constructor sort of function to create struct instances. // If there is a canonical constructor it is typically named the same as the type.
for _ in range(0, height) { lines.push(Vec::from_elem(width, '.')); } // Rust code often returns values by omitting the trailing semi-colon // instead of using an explicit return statement. AsciiArt {width: width, height: height, fill: fill, lines: lines} } // Methods particular to the AsciiArt struct. impl AsciiArt { fn add_pt(&mut self, x: int, y: int) { if x >= 0 && x < self.width as int { if y >= 0 && y < self.height as int { // Note that numeric types don't implicitly convert to each other. let v = y as uint; let h = x as uint; // Vector subscripting will normally copy the element, but &v[i] // will return a reference which is what we need because the // element is: // 1) potentially large // 2) needs to be modified let row = self.lines.get_mut(v); *row.get_mut(h) = self.fill; } } } } // Allows AsciiArt to be converted to a string using the libcore ToStr trait. // Note that the %s fmt! specifier will not call this automatically. impl fmt::Show for AsciiArt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Convert each line into a string. let lines = self.lines.iter() .map(|line| { str::from_chars(line.as_slice()).to_string() }) .collect::<Vec<String>>(); // Concatenate the lines together using a new-line. write!(f, "{}", lines.connect("\n")) } } // This is similar to an interface in other languages: it defines a protocol which // developers can implement for arbitrary concrete types. trait Canvas { fn add_point(&mut self, shape: Point); fn add_rect(&mut self, shape: Rect); // Unlike interfaces traits support default implementations. // Got an ICE as soon as I added this method. fn add_points(&mut self, shapes: &[Point]) { for pt in shapes.iter() {self.add_point(*pt)}; } } // Here we provide an implementation of the Canvas methods for AsciiArt. // Other implementations could also be provided (e.g. for PDF or Apple's Quartz) // and code can use them polymorphically via the Canvas trait. impl Canvas for AsciiArt { fn add_point(&mut self, shape: Point) { self.add_pt(shape.x, shape.y); } fn add_rect(&mut self, shape: Rect) { // Add the top and bottom lines. for x in range(shape.top_left.x, shape.top_left.x + shape.size.width) { self.add_pt(x, shape.top_left.y); self.add_pt(x, shape.top_left.y + shape.size.height - 1); } // Add the left and right lines. for y in range(shape.top_left.y, shape.top_left.y + shape.size.height) { self.add_pt(shape.top_left.x, y); self.add_pt(shape.top_left.x + shape.size.width - 1, y); } } } // Rust's unit testing framework is currently a bit under-developed so we'll use // this little helper. pub fn check_strs(actual: &str, expected: &str) -> bool { if actual!= expected { println!("Found:\n{}\nbut expected\n{}", actual, expected); return false; } return true; } fn test_ascii_art_ctor() { let art = AsciiArt(3, 3, '*'); assert!(check_strs(art.to_str().as_slice(), "...\n...\n...")); } fn test_add_pt() { let mut art = AsciiArt(3, 3, '*'); art.add_pt(0, 0); art.add_pt(0, -10); art.add_pt(1, 2); assert!(check_strs(art.to_str().as_slice(), "*..\n...\n.*.")); } fn test_shapes() { let mut art = AsciiArt(4, 4, '*'); art.add_rect(Rect {top_left: Point {x: 0, y: 0}, size: Size {width: 4, height: 4}}); art.add_point(Point {x: 2, y: 2}); assert!(check_strs(art.to_str().as_slice(), "****\n*..*\n*.**\n****")); } pub fn main() { test_ascii_art_ctor(); test_add_pt(); test_shapes(); }
// Other constructor sort of functions are typically named from_foo, from_bar, etc. fn AsciiArt(width: uint, height: uint, fill: char) -> AsciiArt { // Use an anonymous function to build a vector of vectors containing // blank characters for each position in our canvas. let mut lines = Vec::new();
random_line_split
var_int.rs
use bytes::BytesMut; use criterion::{black_box, criterion_group, criterion_main, Benchmark, Criterion}; use protocol::{Decode, Encode, Var}; fn criterion_benchmark(c: &mut Criterion) { c.bench( "benches", Benchmark::new("write_var_u64", move |b| { b.iter(|| { let mut buf = BytesMut::with_capacity(10); Var(black_box(12_456_456_456_465_464u64)).encode(black_box(&mut buf)) }) }), );
b.iter(|| { let mut buf = BytesMut::with_capacity(10); Var(black_box(3_000_000_000u32)).encode(black_box(&mut buf)) }) }), ); c.bench( "benches", Benchmark::new("read_var_u64", move |b| { let mut buf = BytesMut::new(); Var(12_456_456_456_465_464u64).encode(&mut buf); b.iter(|| Var::<u64>::decode(&mut (black_box(&buf[0..]))).unwrap()) }), ); c.bench( "benches", Benchmark::new("read_var_u32", move |b| { let mut buf = BytesMut::new(); Var(3_000_000_000u32).encode(&mut buf); b.iter(|| Var::<u32>::decode(&mut (black_box(&buf[0..]))).unwrap()) }), ); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
c.bench( "benches", Benchmark::new("write_var_u32", move |b| {
random_line_split
var_int.rs
use bytes::BytesMut; use criterion::{black_box, criterion_group, criterion_main, Benchmark, Criterion}; use protocol::{Decode, Encode, Var}; fn
(c: &mut Criterion) { c.bench( "benches", Benchmark::new("write_var_u64", move |b| { b.iter(|| { let mut buf = BytesMut::with_capacity(10); Var(black_box(12_456_456_456_465_464u64)).encode(black_box(&mut buf)) }) }), ); c.bench( "benches", Benchmark::new("write_var_u32", move |b| { b.iter(|| { let mut buf = BytesMut::with_capacity(10); Var(black_box(3_000_000_000u32)).encode(black_box(&mut buf)) }) }), ); c.bench( "benches", Benchmark::new("read_var_u64", move |b| { let mut buf = BytesMut::new(); Var(12_456_456_456_465_464u64).encode(&mut buf); b.iter(|| Var::<u64>::decode(&mut (black_box(&buf[0..]))).unwrap()) }), ); c.bench( "benches", Benchmark::new("read_var_u32", move |b| { let mut buf = BytesMut::new(); Var(3_000_000_000u32).encode(&mut buf); b.iter(|| Var::<u32>::decode(&mut (black_box(&buf[0..]))).unwrap()) }), ); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
criterion_benchmark
identifier_name
var_int.rs
use bytes::BytesMut; use criterion::{black_box, criterion_group, criterion_main, Benchmark, Criterion}; use protocol::{Decode, Encode, Var}; fn criterion_benchmark(c: &mut Criterion)
c.bench( "benches", Benchmark::new("read_var_u64", move |b| { let mut buf = BytesMut::new(); Var(12_456_456_456_465_464u64).encode(&mut buf); b.iter(|| Var::<u64>::decode(&mut (black_box(&buf[0..]))).unwrap()) }), ); c.bench( "benches", Benchmark::new("read_var_u32", move |b| { let mut buf = BytesMut::new(); Var(3_000_000_000u32).encode(&mut buf); b.iter(|| Var::<u32>::decode(&mut (black_box(&buf[0..]))).unwrap()) }), ); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
{ c.bench( "benches", Benchmark::new("write_var_u64", move |b| { b.iter(|| { let mut buf = BytesMut::with_capacity(10); Var(black_box(12_456_456_456_465_464u64)).encode(black_box(&mut buf)) }) }), ); c.bench( "benches", Benchmark::new("write_var_u32", move |b| { b.iter(|| { let mut buf = BytesMut::with_capacity(10); Var(black_box(3_000_000_000u32)).encode(black_box(&mut buf)) }) }), );
identifier_body
framed.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::cmp; use std::io; use std::io::{ErrorKind, Read, Write}; use super::{TReadTransport, TReadTransportFactory, TWriteTransport, TWriteTransportFactory}; /// Default capacity of the read buffer in bytes. const READ_CAPACITY: usize = 4096; /// Default capacity of the write buffer in bytes. const WRITE_CAPACITY: usize = 4096; /// Transport that reads framed messages. /// /// A `TFramedReadTransport` maintains a fixed-size internal read buffer. /// On a call to `TFramedReadTransport::read(...)` one full message - both /// fixed-length header and bytes - is read from the wrapped channel and /// buffered. Subsequent read calls are serviced from the internal buffer /// until it is exhausted, at which point the next full message is read /// from the wrapped channel. /// /// # Examples /// /// Create and use a `TFramedReadTransport`. /// /// ```no_run /// use std::io::Read; /// use thrift::transport::{TFramedReadTransport, TTcpChannel}; /// /// let mut c = TTcpChannel::new(); /// c.open("localhost:9090").unwrap(); /// /// let mut t = TFramedReadTransport::new(c); /// /// t.read(&mut vec![0u8; 1]).unwrap(); /// ``` #[derive(Debug)] pub struct TFramedReadTransport<C> where C: Read, { buf: Box<[u8]>, pos: usize, cap: usize, chan: C, } impl<C> TFramedReadTransport<C> where C: Read, { /// Create a `TFramedTransport` with default-sized internal read and /// write buffers that wraps the given `TIoChannel`. pub fn new(channel: C) -> TFramedReadTransport<C> { TFramedReadTransport::with_capacity(READ_CAPACITY, channel) } /// Create a `TFramedTransport` with an internal read buffer of size /// `read_capacity` and an internal write buffer of size /// `write_capacity` that wraps the given `TIoChannel`. pub fn with_capacity(read_capacity: usize, channel: C) -> TFramedReadTransport<C> { TFramedReadTransport { buf: vec![0; read_capacity].into_boxed_slice(), pos: 0, cap: 0, chan: channel, } } } impl<C> Read for TFramedReadTransport<C> where C: Read, { fn read(&mut self, b: &mut [u8]) -> io::Result<usize> { if self.cap - self.pos == 0 { let message_size = self.chan.read_i32::<BigEndian>()? as usize; if message_size > self.buf.len() { return Err( io::Error::new( ErrorKind::Other, format!( "bytes to be read ({}) exceeds buffer \ capacity ({})", message_size, self.buf.len() ), ), ); } self.chan.read_exact(&mut self.buf[..message_size])?; self.pos = 0; self.cap = message_size as usize; } let nread = cmp::min(b.len(), self.cap - self.pos); b[..nread].clone_from_slice(&self.buf[self.pos..self.pos + nread]); self.pos += nread; Ok(nread) } } /// Factory for creating instances of `TFramedReadTransport`. #[derive(Default)] pub struct TFramedReadTransportFactory; impl TFramedReadTransportFactory { pub fn new() -> TFramedReadTransportFactory { TFramedReadTransportFactory {} } } impl TReadTransportFactory for TFramedReadTransportFactory { /// Create a `TFramedReadTransport`. fn create(&self, channel: Box<Read + Send>) -> Box<TReadTransport + Send> { Box::new(TFramedReadTransport::new(channel)) } } /// Transport that writes framed messages. /// /// A `TFramedWriteTransport` maintains a fixed-size internal write buffer. All /// writes are made to this buffer and are sent to the wrapped channel only /// when `TFramedWriteTransport::flush()` is called. On a flush a fixed-length /// header with a count of the buffered bytes is written, followed by the bytes /// themselves. /// /// # Examples /// /// Create and use a `TFramedWriteTransport`. /// /// ```no_run /// use std::io::Write; /// use thrift::transport::{TFramedWriteTransport, TTcpChannel}; /// /// let mut c = TTcpChannel::new(); /// c.open("localhost:9090").unwrap(); /// /// let mut t = TFramedWriteTransport::new(c); /// /// t.write(&[0x00]).unwrap(); /// t.flush().unwrap(); /// ``` #[derive(Debug)] pub struct TFramedWriteTransport<C> where C: Write, { buf: Box<[u8]>, pos: usize, channel: C, } impl<C> TFramedWriteTransport<C> where C: Write, { /// Create a `TFramedTransport` with default-sized internal read and /// write buffers that wraps the given `TIoChannel`. pub fn new(channel: C) -> TFramedWriteTransport<C> { TFramedWriteTransport::with_capacity(WRITE_CAPACITY, channel) } /// Create a `TFramedTransport` with an internal read buffer of size /// `read_capacity` and an internal write buffer of size /// `write_capacity` that wraps the given `TIoChannel`. pub fn with_capacity(write_capacity: usize, channel: C) -> TFramedWriteTransport<C> { TFramedWriteTransport { buf: vec![0; write_capacity].into_boxed_slice(), pos: 0, channel: channel, } } } impl<C> Write for TFramedWriteTransport<C> where C: Write, { fn write(&mut self, b: &[u8]) -> io::Result<usize> { if b.len() > (self.buf.len() - self.pos)
let nwrite = b.len(); // always less than available write buffer capacity self.buf[self.pos..(self.pos + nwrite)].clone_from_slice(b); self.pos += nwrite; Ok(nwrite) } fn flush(&mut self) -> io::Result<()> { let message_size = self.pos; if let 0 = message_size { return Ok(()); } else { self.channel .write_i32::<BigEndian>(message_size as i32)?; } let mut byte_index = 0; while byte_index < self.pos { let nwrite = self.channel.write(&self.buf[byte_index..self.pos])?; byte_index = cmp::min(byte_index + nwrite, self.pos); } self.pos = 0; self.channel.flush() } } /// Factory for creating instances of `TFramedWriteTransport`. #[derive(Default)] pub struct TFramedWriteTransportFactory; impl TFramedWriteTransportFactory { pub fn new() -> TFramedWriteTransportFactory { TFramedWriteTransportFactory {} } } impl TWriteTransportFactory for TFramedWriteTransportFactory { /// Create a `TFramedWriteTransport`. fn create(&self, channel: Box<Write + Send>) -> Box<TWriteTransport + Send> { Box::new(TFramedWriteTransport::new(channel)) } } #[cfg(test)] mod tests { // use std::io::{Read, Write}; // // use super::*; // use ::transport::mem::TBufferChannel; }
{ return Err( io::Error::new( ErrorKind::Other, format!( "bytes to be written ({}) exceeds buffer \ capacity ({})", b.len(), self.buf.len() - self.pos ), ), ); }
conditional_block
framed.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::cmp; use std::io; use std::io::{ErrorKind, Read, Write}; use super::{TReadTransport, TReadTransportFactory, TWriteTransport, TWriteTransportFactory}; /// Default capacity of the read buffer in bytes. const READ_CAPACITY: usize = 4096; /// Default capacity of the write buffer in bytes. const WRITE_CAPACITY: usize = 4096; /// Transport that reads framed messages. /// /// A `TFramedReadTransport` maintains a fixed-size internal read buffer. /// On a call to `TFramedReadTransport::read(...)` one full message - both /// fixed-length header and bytes - is read from the wrapped channel and /// buffered. Subsequent read calls are serviced from the internal buffer /// until it is exhausted, at which point the next full message is read /// from the wrapped channel. /// /// # Examples /// /// Create and use a `TFramedReadTransport`. /// /// ```no_run /// use std::io::Read; /// use thrift::transport::{TFramedReadTransport, TTcpChannel}; /// /// let mut c = TTcpChannel::new(); /// c.open("localhost:9090").unwrap(); /// /// let mut t = TFramedReadTransport::new(c); /// /// t.read(&mut vec![0u8; 1]).unwrap(); /// ``` #[derive(Debug)] pub struct TFramedReadTransport<C> where C: Read, { buf: Box<[u8]>, pos: usize, cap: usize, chan: C, } impl<C> TFramedReadTransport<C> where C: Read, { /// Create a `TFramedTransport` with default-sized internal read and /// write buffers that wraps the given `TIoChannel`. pub fn new(channel: C) -> TFramedReadTransport<C> { TFramedReadTransport::with_capacity(READ_CAPACITY, channel) } /// Create a `TFramedTransport` with an internal read buffer of size /// `read_capacity` and an internal write buffer of size /// `write_capacity` that wraps the given `TIoChannel`. pub fn with_capacity(read_capacity: usize, channel: C) -> TFramedReadTransport<C> { TFramedReadTransport { buf: vec![0; read_capacity].into_boxed_slice(), pos: 0, cap: 0, chan: channel, } } } impl<C> Read for TFramedReadTransport<C> where C: Read, { fn read(&mut self, b: &mut [u8]) -> io::Result<usize> { if self.cap - self.pos == 0 { let message_size = self.chan.read_i32::<BigEndian>()? as usize; if message_size > self.buf.len() { return Err( io::Error::new( ErrorKind::Other, format!( "bytes to be read ({}) exceeds buffer \ capacity ({})", message_size, self.buf.len() ), ), ); } self.chan.read_exact(&mut self.buf[..message_size])?; self.pos = 0; self.cap = message_size as usize; } let nread = cmp::min(b.len(), self.cap - self.pos); b[..nread].clone_from_slice(&self.buf[self.pos..self.pos + nread]); self.pos += nread; Ok(nread) } } /// Factory for creating instances of `TFramedReadTransport`. #[derive(Default)] pub struct TFramedReadTransportFactory; impl TFramedReadTransportFactory { pub fn new() -> TFramedReadTransportFactory { TFramedReadTransportFactory {} } } impl TReadTransportFactory for TFramedReadTransportFactory { /// Create a `TFramedReadTransport`. fn create(&self, channel: Box<Read + Send>) -> Box<TReadTransport + Send> { Box::new(TFramedReadTransport::new(channel)) } } /// Transport that writes framed messages. /// /// A `TFramedWriteTransport` maintains a fixed-size internal write buffer. All /// writes are made to this buffer and are sent to the wrapped channel only /// when `TFramedWriteTransport::flush()` is called. On a flush a fixed-length /// header with a count of the buffered bytes is written, followed by the bytes /// themselves. /// /// # Examples /// /// Create and use a `TFramedWriteTransport`. /// /// ```no_run /// use std::io::Write; /// use thrift::transport::{TFramedWriteTransport, TTcpChannel}; /// /// let mut c = TTcpChannel::new(); /// c.open("localhost:9090").unwrap(); /// /// let mut t = TFramedWriteTransport::new(c); /// /// t.write(&[0x00]).unwrap(); /// t.flush().unwrap(); /// ``` #[derive(Debug)] pub struct TFramedWriteTransport<C> where C: Write, { buf: Box<[u8]>, pos: usize, channel: C, } impl<C> TFramedWriteTransport<C> where C: Write, { /// Create a `TFramedTransport` with default-sized internal read and /// write buffers that wraps the given `TIoChannel`. pub fn new(channel: C) -> TFramedWriteTransport<C> { TFramedWriteTransport::with_capacity(WRITE_CAPACITY, channel) } /// Create a `TFramedTransport` with an internal read buffer of size /// `read_capacity` and an internal write buffer of size /// `write_capacity` that wraps the given `TIoChannel`. pub fn with_capacity(write_capacity: usize, channel: C) -> TFramedWriteTransport<C> { TFramedWriteTransport { buf: vec![0; write_capacity].into_boxed_slice(), pos: 0, channel: channel, } } } impl<C> Write for TFramedWriteTransport<C> where C: Write, { fn write(&mut self, b: &[u8]) -> io::Result<usize> { if b.len() > (self.buf.len() - self.pos) { return Err( io::Error::new( ErrorKind::Other, format!( "bytes to be written ({}) exceeds buffer \ capacity ({})", b.len(), self.buf.len() - self.pos ), ), ); } let nwrite = b.len(); // always less than available write buffer capacity self.buf[self.pos..(self.pos + nwrite)].clone_from_slice(b); self.pos += nwrite; Ok(nwrite) } fn flush(&mut self) -> io::Result<()> { let message_size = self.pos; if let 0 = message_size { return Ok(()); } else { self.channel .write_i32::<BigEndian>(message_size as i32)?; } let mut byte_index = 0; while byte_index < self.pos { let nwrite = self.channel.write(&self.buf[byte_index..self.pos])?; byte_index = cmp::min(byte_index + nwrite, self.pos); } self.pos = 0; self.channel.flush() } } /// Factory for creating instances of `TFramedWriteTransport`. #[derive(Default)] pub struct TFramedWriteTransportFactory; impl TFramedWriteTransportFactory { pub fn new() -> TFramedWriteTransportFactory
} impl TWriteTransportFactory for TFramedWriteTransportFactory { /// Create a `TFramedWriteTransport`. fn create(&self, channel: Box<Write + Send>) -> Box<TWriteTransport + Send> { Box::new(TFramedWriteTransport::new(channel)) } } #[cfg(test)] mod tests { // use std::io::{Read, Write}; // // use super::*; // use ::transport::mem::TBufferChannel; }
{ TFramedWriteTransportFactory {} }
identifier_body
framed.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::cmp; use std::io; use std::io::{ErrorKind, Read, Write}; use super::{TReadTransport, TReadTransportFactory, TWriteTransport, TWriteTransportFactory}; /// Default capacity of the read buffer in bytes. const READ_CAPACITY: usize = 4096; /// Default capacity of the write buffer in bytes. const WRITE_CAPACITY: usize = 4096; /// Transport that reads framed messages. /// /// A `TFramedReadTransport` maintains a fixed-size internal read buffer. /// On a call to `TFramedReadTransport::read(...)` one full message - both /// fixed-length header and bytes - is read from the wrapped channel and /// buffered. Subsequent read calls are serviced from the internal buffer /// until it is exhausted, at which point the next full message is read /// from the wrapped channel. /// /// # Examples /// /// Create and use a `TFramedReadTransport`. /// /// ```no_run /// use std::io::Read; /// use thrift::transport::{TFramedReadTransport, TTcpChannel}; /// /// let mut c = TTcpChannel::new(); /// c.open("localhost:9090").unwrap(); /// /// let mut t = TFramedReadTransport::new(c); /// /// t.read(&mut vec![0u8; 1]).unwrap(); /// ``` #[derive(Debug)] pub struct TFramedReadTransport<C> where C: Read, { buf: Box<[u8]>, pos: usize, cap: usize, chan: C, } impl<C> TFramedReadTransport<C> where C: Read, { /// Create a `TFramedTransport` with default-sized internal read and /// write buffers that wraps the given `TIoChannel`. pub fn new(channel: C) -> TFramedReadTransport<C> { TFramedReadTransport::with_capacity(READ_CAPACITY, channel) } /// Create a `TFramedTransport` with an internal read buffer of size /// `read_capacity` and an internal write buffer of size /// `write_capacity` that wraps the given `TIoChannel`. pub fn with_capacity(read_capacity: usize, channel: C) -> TFramedReadTransport<C> { TFramedReadTransport { buf: vec![0; read_capacity].into_boxed_slice(), pos: 0, cap: 0, chan: channel, } } } impl<C> Read for TFramedReadTransport<C> where C: Read, { fn read(&mut self, b: &mut [u8]) -> io::Result<usize> { if self.cap - self.pos == 0 { let message_size = self.chan.read_i32::<BigEndian>()? as usize; if message_size > self.buf.len() { return Err( io::Error::new( ErrorKind::Other, format!( "bytes to be read ({}) exceeds buffer \ capacity ({})", message_size, self.buf.len() ), ), ); } self.chan.read_exact(&mut self.buf[..message_size])?; self.pos = 0; self.cap = message_size as usize; } let nread = cmp::min(b.len(), self.cap - self.pos); b[..nread].clone_from_slice(&self.buf[self.pos..self.pos + nread]); self.pos += nread; Ok(nread) } } /// Factory for creating instances of `TFramedReadTransport`. #[derive(Default)] pub struct TFramedReadTransportFactory; impl TFramedReadTransportFactory { pub fn new() -> TFramedReadTransportFactory { TFramedReadTransportFactory {} } } impl TReadTransportFactory for TFramedReadTransportFactory { /// Create a `TFramedReadTransport`. fn create(&self, channel: Box<Read + Send>) -> Box<TReadTransport + Send> { Box::new(TFramedReadTransport::new(channel)) } } /// Transport that writes framed messages. /// /// A `TFramedWriteTransport` maintains a fixed-size internal write buffer. All /// writes are made to this buffer and are sent to the wrapped channel only /// when `TFramedWriteTransport::flush()` is called. On a flush a fixed-length /// header with a count of the buffered bytes is written, followed by the bytes /// themselves. /// /// # Examples /// /// Create and use a `TFramedWriteTransport`. /// /// ```no_run /// use std::io::Write; /// use thrift::transport::{TFramedWriteTransport, TTcpChannel}; /// /// let mut c = TTcpChannel::new(); /// c.open("localhost:9090").unwrap(); /// /// let mut t = TFramedWriteTransport::new(c); /// /// t.write(&[0x00]).unwrap(); /// t.flush().unwrap(); /// ``` #[derive(Debug)] pub struct
<C> where C: Write, { buf: Box<[u8]>, pos: usize, channel: C, } impl<C> TFramedWriteTransport<C> where C: Write, { /// Create a `TFramedTransport` with default-sized internal read and /// write buffers that wraps the given `TIoChannel`. pub fn new(channel: C) -> TFramedWriteTransport<C> { TFramedWriteTransport::with_capacity(WRITE_CAPACITY, channel) } /// Create a `TFramedTransport` with an internal read buffer of size /// `read_capacity` and an internal write buffer of size /// `write_capacity` that wraps the given `TIoChannel`. pub fn with_capacity(write_capacity: usize, channel: C) -> TFramedWriteTransport<C> { TFramedWriteTransport { buf: vec![0; write_capacity].into_boxed_slice(), pos: 0, channel: channel, } } } impl<C> Write for TFramedWriteTransport<C> where C: Write, { fn write(&mut self, b: &[u8]) -> io::Result<usize> { if b.len() > (self.buf.len() - self.pos) { return Err( io::Error::new( ErrorKind::Other, format!( "bytes to be written ({}) exceeds buffer \ capacity ({})", b.len(), self.buf.len() - self.pos ), ), ); } let nwrite = b.len(); // always less than available write buffer capacity self.buf[self.pos..(self.pos + nwrite)].clone_from_slice(b); self.pos += nwrite; Ok(nwrite) } fn flush(&mut self) -> io::Result<()> { let message_size = self.pos; if let 0 = message_size { return Ok(()); } else { self.channel .write_i32::<BigEndian>(message_size as i32)?; } let mut byte_index = 0; while byte_index < self.pos { let nwrite = self.channel.write(&self.buf[byte_index..self.pos])?; byte_index = cmp::min(byte_index + nwrite, self.pos); } self.pos = 0; self.channel.flush() } } /// Factory for creating instances of `TFramedWriteTransport`. #[derive(Default)] pub struct TFramedWriteTransportFactory; impl TFramedWriteTransportFactory { pub fn new() -> TFramedWriteTransportFactory { TFramedWriteTransportFactory {} } } impl TWriteTransportFactory for TFramedWriteTransportFactory { /// Create a `TFramedWriteTransport`. fn create(&self, channel: Box<Write + Send>) -> Box<TWriteTransport + Send> { Box::new(TFramedWriteTransport::new(channel)) } } #[cfg(test)] mod tests { // use std::io::{Read, Write}; // // use super::*; // use ::transport::mem::TBufferChannel; }
TFramedWriteTransport
identifier_name
framed.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::cmp; use std::io; use std::io::{ErrorKind, Read, Write}; use super::{TReadTransport, TReadTransportFactory, TWriteTransport, TWriteTransportFactory}; /// Default capacity of the read buffer in bytes. const READ_CAPACITY: usize = 4096; /// Default capacity of the write buffer in bytes. const WRITE_CAPACITY: usize = 4096; /// Transport that reads framed messages. /// /// A `TFramedReadTransport` maintains a fixed-size internal read buffer. /// On a call to `TFramedReadTransport::read(...)` one full message - both /// fixed-length header and bytes - is read from the wrapped channel and /// buffered. Subsequent read calls are serviced from the internal buffer /// until it is exhausted, at which point the next full message is read /// from the wrapped channel. /// /// # Examples
/// ```no_run /// use std::io::Read; /// use thrift::transport::{TFramedReadTransport, TTcpChannel}; /// /// let mut c = TTcpChannel::new(); /// c.open("localhost:9090").unwrap(); /// /// let mut t = TFramedReadTransport::new(c); /// /// t.read(&mut vec![0u8; 1]).unwrap(); /// ``` #[derive(Debug)] pub struct TFramedReadTransport<C> where C: Read, { buf: Box<[u8]>, pos: usize, cap: usize, chan: C, } impl<C> TFramedReadTransport<C> where C: Read, { /// Create a `TFramedTransport` with default-sized internal read and /// write buffers that wraps the given `TIoChannel`. pub fn new(channel: C) -> TFramedReadTransport<C> { TFramedReadTransport::with_capacity(READ_CAPACITY, channel) } /// Create a `TFramedTransport` with an internal read buffer of size /// `read_capacity` and an internal write buffer of size /// `write_capacity` that wraps the given `TIoChannel`. pub fn with_capacity(read_capacity: usize, channel: C) -> TFramedReadTransport<C> { TFramedReadTransport { buf: vec![0; read_capacity].into_boxed_slice(), pos: 0, cap: 0, chan: channel, } } } impl<C> Read for TFramedReadTransport<C> where C: Read, { fn read(&mut self, b: &mut [u8]) -> io::Result<usize> { if self.cap - self.pos == 0 { let message_size = self.chan.read_i32::<BigEndian>()? as usize; if message_size > self.buf.len() { return Err( io::Error::new( ErrorKind::Other, format!( "bytes to be read ({}) exceeds buffer \ capacity ({})", message_size, self.buf.len() ), ), ); } self.chan.read_exact(&mut self.buf[..message_size])?; self.pos = 0; self.cap = message_size as usize; } let nread = cmp::min(b.len(), self.cap - self.pos); b[..nread].clone_from_slice(&self.buf[self.pos..self.pos + nread]); self.pos += nread; Ok(nread) } } /// Factory for creating instances of `TFramedReadTransport`. #[derive(Default)] pub struct TFramedReadTransportFactory; impl TFramedReadTransportFactory { pub fn new() -> TFramedReadTransportFactory { TFramedReadTransportFactory {} } } impl TReadTransportFactory for TFramedReadTransportFactory { /// Create a `TFramedReadTransport`. fn create(&self, channel: Box<Read + Send>) -> Box<TReadTransport + Send> { Box::new(TFramedReadTransport::new(channel)) } } /// Transport that writes framed messages. /// /// A `TFramedWriteTransport` maintains a fixed-size internal write buffer. All /// writes are made to this buffer and are sent to the wrapped channel only /// when `TFramedWriteTransport::flush()` is called. On a flush a fixed-length /// header with a count of the buffered bytes is written, followed by the bytes /// themselves. /// /// # Examples /// /// Create and use a `TFramedWriteTransport`. /// /// ```no_run /// use std::io::Write; /// use thrift::transport::{TFramedWriteTransport, TTcpChannel}; /// /// let mut c = TTcpChannel::new(); /// c.open("localhost:9090").unwrap(); /// /// let mut t = TFramedWriteTransport::new(c); /// /// t.write(&[0x00]).unwrap(); /// t.flush().unwrap(); /// ``` #[derive(Debug)] pub struct TFramedWriteTransport<C> where C: Write, { buf: Box<[u8]>, pos: usize, channel: C, } impl<C> TFramedWriteTransport<C> where C: Write, { /// Create a `TFramedTransport` with default-sized internal read and /// write buffers that wraps the given `TIoChannel`. pub fn new(channel: C) -> TFramedWriteTransport<C> { TFramedWriteTransport::with_capacity(WRITE_CAPACITY, channel) } /// Create a `TFramedTransport` with an internal read buffer of size /// `read_capacity` and an internal write buffer of size /// `write_capacity` that wraps the given `TIoChannel`. pub fn with_capacity(write_capacity: usize, channel: C) -> TFramedWriteTransport<C> { TFramedWriteTransport { buf: vec![0; write_capacity].into_boxed_slice(), pos: 0, channel: channel, } } } impl<C> Write for TFramedWriteTransport<C> where C: Write, { fn write(&mut self, b: &[u8]) -> io::Result<usize> { if b.len() > (self.buf.len() - self.pos) { return Err( io::Error::new( ErrorKind::Other, format!( "bytes to be written ({}) exceeds buffer \ capacity ({})", b.len(), self.buf.len() - self.pos ), ), ); } let nwrite = b.len(); // always less than available write buffer capacity self.buf[self.pos..(self.pos + nwrite)].clone_from_slice(b); self.pos += nwrite; Ok(nwrite) } fn flush(&mut self) -> io::Result<()> { let message_size = self.pos; if let 0 = message_size { return Ok(()); } else { self.channel .write_i32::<BigEndian>(message_size as i32)?; } let mut byte_index = 0; while byte_index < self.pos { let nwrite = self.channel.write(&self.buf[byte_index..self.pos])?; byte_index = cmp::min(byte_index + nwrite, self.pos); } self.pos = 0; self.channel.flush() } } /// Factory for creating instances of `TFramedWriteTransport`. #[derive(Default)] pub struct TFramedWriteTransportFactory; impl TFramedWriteTransportFactory { pub fn new() -> TFramedWriteTransportFactory { TFramedWriteTransportFactory {} } } impl TWriteTransportFactory for TFramedWriteTransportFactory { /// Create a `TFramedWriteTransport`. fn create(&self, channel: Box<Write + Send>) -> Box<TWriteTransport + Send> { Box::new(TFramedWriteTransport::new(channel)) } } #[cfg(test)] mod tests { // use std::io::{Read, Write}; // // use super::*; // use ::transport::mem::TBufferChannel; }
/// /// Create and use a `TFramedReadTransport`. ///
random_line_split
json.rs
//! Serialize `Script`s to `json` /// Serialize the given `Script` into a `json` /// /// Serialize the given `Script` into the following `json` format and write /// it to the given `Writer`. /// /// # Example /// /// ```json /// [ /// [ /// { /// "place": "Snowy Landscape", /// "type": "external", /// "parts": [{ /// "page": 1, /// "direction": "Swirls of snow obscure the rocky formations of a mountain (...)" /// },{ /// "page": 1, /// "direction": "Five ragged men attack a young girl, SINTEL, (...)" /// },{ /// "page": 1, /// "character": "Shaman", /// "dialog": [ /// "You’re lucky to be alive. (...)" /// ] /// },{ /// "page": 2, /// "direction": "Finally she collapses into the snow, her eyes shut tight." /// },{ /// "page": 2, /// "direction": "BLACK" /// },{ /// "page": 2, /// "character": "Shaman", /// "mode": "VO", /// "dialog": [ /// { "direction": "(To Sintel)" }, /// "Here, take a sip." /// ] /// }] /// } /// ] /// ] /// ``` pub fn format_script<W: Write>(scenes: &Script, output: &mut W) -> json::EncodeResult<()> { let mut writer = IoFmtWriter { writer: output }; let mut encoder = json::Encoder::new_pretty(&mut writer); try!(scenes.encode(&mut encoder)); Ok(()) } use ::{DialogPart, Location, LocationType, ScenePart, Script}; use rustc_serialize::Encodable; use rustc_serialize::{Encoder, json}; use std::io::Write; use std::fmt; /// Needed because rustc-serialize uses fmt::Write instead of io::Write. /// See https://github.com/rust-lang-nursery/rustc-serialize/issues/111 struct IoFmtWriter<'a> { writer: &'a mut Write } /// Pass all writes to the underlying io::Write. impl<'a> fmt::Write for IoFmtWriter<'a> { fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { if let Err(_) = self.writer.write_all(s.as_bytes()) { Err(fmt::Error) } else { Ok(()) } } } /// Flush the underlying io::Write when dropping the object. impl<'a> Drop for IoFmtWriter<'a> { fn drop(&mut self) { self.writer.flush().ok(); } } impl Encodable for Location { fn en
: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { s.emit_map(3, |s| { try!(emit_map_key_val(s, 0, "place", |s| self.name.encode(s))); match self.kind { LocationType::Undefined => {} ref kind => { let kind: &str = kind.clone().into(); try!(emit_map_key_val(s, 1, "type", |s| kind.encode(s))); } } try!(emit_map_key_val(s, 2, "parts", |s| self.parts.encode(s))); Ok(()) }) } } impl Encodable for ScenePart { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { match self { &ScenePart::Direction { ref direction, ref page } => { s.emit_map(2, |s| { try!(emit_map_key_val(s, 0, "page", |s| page.encode(s))); try!(emit_map_key_val(s, 1, "direction", |s| direction.encode(s))); Ok(()) }) } &ScenePart::Dialog { ref speaker, ref dialog, ref page } => { s.emit_map(3, |s| { try!(emit_map_key_val(s, 0, "page", |s| page.encode(s))); try!(emit_map_key_val(s, 1, "character", |s| speaker.encode(s))); try!(emit_map_key_val(s, 2, "dialog", |s| dialog.encode(s))); Ok(()) }) } } } } impl Encodable for DialogPart { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { match self { &DialogPart::Dialog(ref dialog) => { s.emit_str(dialog) } &DialogPart::Direction(ref direction) => { s.emit_map(1, |s| { emit_map_key_val(s, 0, "direction", |s| direction.encode(s)) }) } } } } /// Convenience function for emitting both key and value of a map entry fn emit_map_key_val<S, F>(s: &mut S, idx: usize, key: &str, f: F) -> Result<(), S::Error> where S: Encoder, F: FnOnce(&mut S) -> Result<(), S::Error> { try!(s.emit_map_elt_key(idx, |s| key.encode(s))); try!(s.emit_map_elt_val(idx, f)); Ok(()) }
code<S
identifier_name
json.rs
//! Serialize `Script`s to `json` /// Serialize the given `Script` into a `json` /// /// Serialize the given `Script` into the following `json` format and write /// it to the given `Writer`. /// /// # Example /// /// ```json /// [ /// [ /// { /// "place": "Snowy Landscape", /// "type": "external", /// "parts": [{ /// "page": 1, /// "direction": "Swirls of snow obscure the rocky formations of a mountain (...)" /// },{ /// "page": 1, /// "direction": "Five ragged men attack a young girl, SINTEL, (...)" /// },{ /// "page": 1, /// "character": "Shaman", /// "dialog": [ /// "You’re lucky to be alive. (...)" /// ] /// },{ /// "page": 2, /// "direction": "Finally she collapses into the snow, her eyes shut tight." /// },{ /// "page": 2, /// "direction": "BLACK" /// },{ /// "page": 2, /// "character": "Shaman", /// "mode": "VO", /// "dialog": [ /// { "direction": "(To Sintel)" }, /// "Here, take a sip." /// ] /// }] /// } /// ] /// ] /// ``` pub fn format_script<W: Write>(scenes: &Script, output: &mut W) -> json::EncodeResult<()> { let mut writer = IoFmtWriter { writer: output }; let mut encoder = json::Encoder::new_pretty(&mut writer); try!(scenes.encode(&mut encoder)); Ok(()) } use ::{DialogPart, Location, LocationType, ScenePart, Script}; use rustc_serialize::Encodable; use rustc_serialize::{Encoder, json}; use std::io::Write; use std::fmt; /// Needed because rustc-serialize uses fmt::Write instead of io::Write. /// See https://github.com/rust-lang-nursery/rustc-serialize/issues/111 struct IoFmtWriter<'a> { writer: &'a mut Write } /// Pass all writes to the underlying io::Write. impl<'a> fmt::Write for IoFmtWriter<'a> { fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { if let Err(_) = self.writer.write_all(s.as_bytes()) { Err(fmt::Error) } else { Ok(()) } } } /// Flush the underlying io::Write when dropping the object. impl<'a> Drop for IoFmtWriter<'a> { fn drop(&mut self) { self.writer.flush().ok(); } } impl Encodable for Location { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { s.emit_map(3, |s| { try!(emit_map_key_val(s, 0, "place", |s| self.name.encode(s))); match self.kind { LocationType::Undefined => {} ref kind => { let kind: &str = kind.clone().into(); try!(emit_map_key_val(s, 1, "type", |s| kind.encode(s))); } } try!(emit_map_key_val(s, 2, "parts", |s| self.parts.encode(s))); Ok(()) }) } } impl Encodable for ScenePart { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { match self { &ScenePart::Direction { ref direction, ref page } => { s.emit_map(2, |s| { try!(emit_map_key_val(s, 0, "page", |s| page.encode(s))); try!(emit_map_key_val(s, 1, "direction", |s| direction.encode(s))); Ok(()) }) } &ScenePart::Dialog { ref speaker, ref dialog, ref page } => {
} } } impl Encodable for DialogPart { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { match self { &DialogPart::Dialog(ref dialog) => { s.emit_str(dialog) } &DialogPart::Direction(ref direction) => { s.emit_map(1, |s| { emit_map_key_val(s, 0, "direction", |s| direction.encode(s)) }) } } } } /// Convenience function for emitting both key and value of a map entry fn emit_map_key_val<S, F>(s: &mut S, idx: usize, key: &str, f: F) -> Result<(), S::Error> where S: Encoder, F: FnOnce(&mut S) -> Result<(), S::Error> { try!(s.emit_map_elt_key(idx, |s| key.encode(s))); try!(s.emit_map_elt_val(idx, f)); Ok(()) }
s.emit_map(3, |s| { try!(emit_map_key_val(s, 0, "page", |s| page.encode(s))); try!(emit_map_key_val(s, 1, "character", |s| speaker.encode(s))); try!(emit_map_key_val(s, 2, "dialog", |s| dialog.encode(s))); Ok(()) }) }
conditional_block
json.rs
//! Serialize `Script`s to `json` /// Serialize the given `Script` into a `json` /// /// Serialize the given `Script` into the following `json` format and write /// it to the given `Writer`. /// /// # Example /// /// ```json /// [ /// [ /// { /// "place": "Snowy Landscape", /// "type": "external", /// "parts": [{ /// "page": 1, /// "direction": "Swirls of snow obscure the rocky formations of a mountain (...)" /// },{ /// "page": 1, /// "direction": "Five ragged men attack a young girl, SINTEL, (...)" /// },{ /// "page": 1, /// "character": "Shaman", /// "dialog": [ /// "You’re lucky to be alive. (...)" /// ] /// },{ /// "page": 2, /// "direction": "Finally she collapses into the snow, her eyes shut tight." /// },{ /// "page": 2, /// "direction": "BLACK" /// },{ /// "page": 2, /// "character": "Shaman", /// "mode": "VO", /// "dialog": [ /// { "direction": "(To Sintel)" }, /// "Here, take a sip." /// ] /// }] /// } /// ] /// ] /// ``` pub fn format_script<W: Write>(scenes: &Script, output: &mut W) -> json::EncodeResult<()> { let mut writer = IoFmtWriter { writer: output }; let mut encoder = json::Encoder::new_pretty(&mut writer); try!(scenes.encode(&mut encoder)); Ok(())
use ::{DialogPart, Location, LocationType, ScenePart, Script}; use rustc_serialize::Encodable; use rustc_serialize::{Encoder, json}; use std::io::Write; use std::fmt; /// Needed because rustc-serialize uses fmt::Write instead of io::Write. /// See https://github.com/rust-lang-nursery/rustc-serialize/issues/111 struct IoFmtWriter<'a> { writer: &'a mut Write } /// Pass all writes to the underlying io::Write. impl<'a> fmt::Write for IoFmtWriter<'a> { fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { if let Err(_) = self.writer.write_all(s.as_bytes()) { Err(fmt::Error) } else { Ok(()) } } } /// Flush the underlying io::Write when dropping the object. impl<'a> Drop for IoFmtWriter<'a> { fn drop(&mut self) { self.writer.flush().ok(); } } impl Encodable for Location { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { s.emit_map(3, |s| { try!(emit_map_key_val(s, 0, "place", |s| self.name.encode(s))); match self.kind { LocationType::Undefined => {} ref kind => { let kind: &str = kind.clone().into(); try!(emit_map_key_val(s, 1, "type", |s| kind.encode(s))); } } try!(emit_map_key_val(s, 2, "parts", |s| self.parts.encode(s))); Ok(()) }) } } impl Encodable for ScenePart { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { match self { &ScenePart::Direction { ref direction, ref page } => { s.emit_map(2, |s| { try!(emit_map_key_val(s, 0, "page", |s| page.encode(s))); try!(emit_map_key_val(s, 1, "direction", |s| direction.encode(s))); Ok(()) }) } &ScenePart::Dialog { ref speaker, ref dialog, ref page } => { s.emit_map(3, |s| { try!(emit_map_key_val(s, 0, "page", |s| page.encode(s))); try!(emit_map_key_val(s, 1, "character", |s| speaker.encode(s))); try!(emit_map_key_val(s, 2, "dialog", |s| dialog.encode(s))); Ok(()) }) } } } } impl Encodable for DialogPart { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { match self { &DialogPart::Dialog(ref dialog) => { s.emit_str(dialog) } &DialogPart::Direction(ref direction) => { s.emit_map(1, |s| { emit_map_key_val(s, 0, "direction", |s| direction.encode(s)) }) } } } } /// Convenience function for emitting both key and value of a map entry fn emit_map_key_val<S, F>(s: &mut S, idx: usize, key: &str, f: F) -> Result<(), S::Error> where S: Encoder, F: FnOnce(&mut S) -> Result<(), S::Error> { try!(s.emit_map_elt_key(idx, |s| key.encode(s))); try!(s.emit_map_elt_val(idx, f)); Ok(()) }
}
random_line_split