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
text.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/. */ //! Text layout. use layout::box::{RenderBox, RenderBoxBase, TextRenderBox, UnscannedTextRenderBoxClass}; use gfx::text::text_run::TextRun; use servo_util::range::Range; pub struct TextBoxData { run: @TextRun, range: Range, } impl TextBoxData { pub fn new(run: @TextRun, range: Range) -> TextBoxData { TextBoxData { run: run, range: range, } } } pub fn adapt_textbox_with_range(mut base: RenderBoxBase, run: @TextRun, range: Range) -> TextRenderBox { assert!(range.begin() < run.char_len()); assert!(range.end() <= run.char_len());
range.length(), run.text); let new_text_data = TextBoxData::new(run, range); let metrics = run.metrics_for_range(&range); base.position.size = metrics.bounding_box.size; TextRenderBox { base: base, text_data: new_text_data, } } pub trait UnscannedMethods { /// Copies out the text from an unscanned text box. Fails if this is not an unscanned text box. fn raw_text(&self) -> ~str; } impl UnscannedMethods for RenderBox { fn raw_text(&self) -> ~str { match *self { UnscannedTextRenderBoxClass(text_box) => copy text_box.text, _ => fail!(~"unsupported operation: box.raw_text() on non-unscanned text box."), } } }
assert!(range.length() > 0); debug!("Creating textbox with span: (strlen=%u, off=%u, len=%u) of textrun: %s", run.char_len(), range.begin(),
random_line_split
text.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/. */ //! Text layout. use layout::box::{RenderBox, RenderBoxBase, TextRenderBox, UnscannedTextRenderBoxClass}; use gfx::text::text_run::TextRun; use servo_util::range::Range; pub struct TextBoxData { run: @TextRun, range: Range, } impl TextBoxData { pub fn new(run: @TextRun, range: Range) -> TextBoxData { TextBoxData { run: run, range: range, } } } pub fn adapt_textbox_with_range(mut base: RenderBoxBase, run: @TextRun, range: Range) -> TextRenderBox { assert!(range.begin() < run.char_len()); assert!(range.end() <= run.char_len()); assert!(range.length() > 0); debug!("Creating textbox with span: (strlen=%u, off=%u, len=%u) of textrun: %s", run.char_len(), range.begin(), range.length(), run.text); let new_text_data = TextBoxData::new(run, range); let metrics = run.metrics_for_range(&range); base.position.size = metrics.bounding_box.size; TextRenderBox { base: base, text_data: new_text_data, } } pub trait UnscannedMethods { /// Copies out the text from an unscanned text box. Fails if this is not an unscanned text box. fn raw_text(&self) -> ~str; } impl UnscannedMethods for RenderBox { fn
(&self) -> ~str { match *self { UnscannedTextRenderBoxClass(text_box) => copy text_box.text, _ => fail!(~"unsupported operation: box.raw_text() on non-unscanned text box."), } } }
raw_text
identifier_name
body.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::FormDataBinding::FormDataMethods; use dom::bindings::error::{Error, Fallible}; use dom::bindings::js::Root; use dom::bindings::reflector::Reflectable; use dom::bindings::str::USVString; use dom::blob::{Blob, BlobImpl}; use dom::formdata::FormData; use dom::globalscope::GlobalScope; use dom::promise::Promise; use encoding::all::UTF_8; use encoding::types::{DecoderTrap, Encoding}; use js::jsapi::JSContext; use js::jsapi::JS_ClearPendingException; use js::jsapi::JS_ParseJSON; use js::jsapi::Value as JSValue; use js::jsval::UndefinedValue; use mime::{Mime, TopLevel, SubLevel}; use std::cell::Ref; use std::rc::Rc; use std::str; use url::form_urlencoded; #[derive(Copy, Clone, JSTraceable, HeapSizeOf)] pub enum BodyType { Blob, FormData, Json, Text } pub enum FetchedData { Text(String), Json(JSValue), BlobData(Root<Blob>), FormData(Root<FormData>), } // https://fetch.spec.whatwg.org/#concept-body-consume-body #[allow(unrooted_must_root)] pub fn consume_body<T: BodyOperations + Reflectable>(object: &T, body_type: BodyType) -> Rc<Promise> { let promise = Promise::new(&object.global()); // Step 1 if object.get_body_used() || object.is_locked() { promise.reject_error(promise.global().get_cx(), Error::Type( "The response's stream is disturbed or locked".to_string())); return promise; } object.set_body_promise(&promise, body_type); // Steps 2-4 // TODO: Body does not yet have a stream. consume_body_with_promise(object, body_type, &promise); promise } // https://fetch.spec.whatwg.org/#concept-body-consume-body #[allow(unrooted_must_root)] pub fn consume_body_with_promise<T: BodyOperations + Reflectable>(object: &T, body_type: BodyType, promise: &Promise) { // Step 5 let body = match object.take_body() { Some(body) => body, None => return, }; let pkg_data_results = run_package_data_algorithm(object, body, body_type, object.get_mime_type()); let cx = promise.global().get_cx(); match pkg_data_results { Ok(results) => { match results { FetchedData::Text(s) => promise.resolve_native(cx, &USVString(s)), FetchedData::Json(j) => promise.resolve_native(cx, &j), FetchedData::BlobData(b) => promise.resolve_native(cx, &b), FetchedData::FormData(f) => promise.resolve_native(cx, &f), }; }, Err(err) => promise.reject_error(cx, err), } } // https://fetch.spec.whatwg.org/#concept-body-package-data #[allow(unsafe_code)] fn run_package_data_algorithm<T: BodyOperations + Reflectable>(object: &T, bytes: Vec<u8>, body_type: BodyType, mime_type: Ref<Vec<u8>>) -> Fallible<FetchedData> { let global = object.global(); let cx = global.get_cx(); let mime = &*mime_type; match body_type { BodyType::Text => run_text_data_algorithm(bytes), BodyType::Json => run_json_data_algorithm(cx, bytes), BodyType::Blob => run_blob_data_algorithm(&global, bytes, mime), BodyType::FormData => run_form_data_algorithm(&global, bytes, mime), } } fn run_text_data_algorithm(bytes: Vec<u8>) -> Fallible<FetchedData> { let text = UTF_8.decode(&bytes, DecoderTrap::Replace).unwrap(); Ok(FetchedData::Text(text)) } #[allow(unsafe_code)] fn run_json_data_algorithm(cx: *mut JSContext, bytes: Vec<u8>) -> Fallible<FetchedData> { let json_text = UTF_8.decode(&bytes, DecoderTrap::Replace).unwrap(); let json_text: Vec<u16> = json_text.encode_utf16().collect(); rooted!(in(cx) let mut rval = UndefinedValue()); unsafe { if!JS_ParseJSON(cx, json_text.as_ptr(), json_text.len() as u32, rval.handle_mut()) { JS_ClearPendingException(cx); // TODO: See issue #13464. Exception should be thrown instead of cleared. return Err(Error::Type("Failed to parse JSON".to_string())); } Ok(FetchedData::Json(rval.get())) } } fn
(root: &GlobalScope, bytes: Vec<u8>, mime: &[u8]) -> Fallible<FetchedData> { let mime_string = if let Ok(s) = String::from_utf8(mime.to_vec()) { s } else { "".to_string() }; let blob = Blob::new(root, BlobImpl::new_from_bytes(bytes), mime_string); Ok(FetchedData::BlobData(blob)) } fn run_form_data_algorithm(root: &GlobalScope, bytes: Vec<u8>, mime: &[u8]) -> Fallible<FetchedData> { let mime_str = if let Ok(s) = str::from_utf8(mime) { s } else { "" }; let mime: Mime = try!(mime_str.parse().map_err( |_| Error::Type("Inappropriate MIME-type for Body".to_string()))); match mime { // TODO //... Parser for Mime(TopLevel::Multipart, SubLevel::FormData, _) //... is not fully determined yet. Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _) => { let entries = form_urlencoded::parse(&bytes); let formdata = FormData::new(None, root); for (k, e) in entries { formdata.Append(USVString(k.into_owned()), USVString(e.into_owned())); } return Ok(FetchedData::FormData(formdata)); }, _ => return Err(Error::Type("Inappropriate MIME-type for Body".to_string())), } } pub trait BodyOperations { fn get_body_used(&self) -> bool; fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType); /// Returns `Some(_)` if the body is complete, `None` if there is more to /// come. fn take_body(&self) -> Option<Vec<u8>>; fn is_locked(&self) -> bool; fn get_mime_type(&self) -> Ref<Vec<u8>>; }
run_blob_data_algorithm
identifier_name
body.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::FormDataBinding::FormDataMethods; use dom::bindings::error::{Error, Fallible}; use dom::bindings::js::Root; use dom::bindings::reflector::Reflectable; use dom::bindings::str::USVString; use dom::blob::{Blob, BlobImpl}; use dom::formdata::FormData; use dom::globalscope::GlobalScope; use dom::promise::Promise; use encoding::all::UTF_8; use encoding::types::{DecoderTrap, Encoding}; use js::jsapi::JSContext; use js::jsapi::JS_ClearPendingException; use js::jsapi::JS_ParseJSON; use js::jsapi::Value as JSValue; use js::jsval::UndefinedValue; use mime::{Mime, TopLevel, SubLevel}; use std::cell::Ref; use std::rc::Rc; use std::str; use url::form_urlencoded; #[derive(Copy, Clone, JSTraceable, HeapSizeOf)] pub enum BodyType { Blob, FormData, Json, Text } pub enum FetchedData { Text(String), Json(JSValue), BlobData(Root<Blob>), FormData(Root<FormData>), } // https://fetch.spec.whatwg.org/#concept-body-consume-body #[allow(unrooted_must_root)] pub fn consume_body<T: BodyOperations + Reflectable>(object: &T, body_type: BodyType) -> Rc<Promise> { let promise = Promise::new(&object.global()); // Step 1 if object.get_body_used() || object.is_locked() { promise.reject_error(promise.global().get_cx(), Error::Type( "The response's stream is disturbed or locked".to_string())); return promise; } object.set_body_promise(&promise, body_type); // Steps 2-4 // TODO: Body does not yet have a stream. consume_body_with_promise(object, body_type, &promise); promise
#[allow(unrooted_must_root)] pub fn consume_body_with_promise<T: BodyOperations + Reflectable>(object: &T, body_type: BodyType, promise: &Promise) { // Step 5 let body = match object.take_body() { Some(body) => body, None => return, }; let pkg_data_results = run_package_data_algorithm(object, body, body_type, object.get_mime_type()); let cx = promise.global().get_cx(); match pkg_data_results { Ok(results) => { match results { FetchedData::Text(s) => promise.resolve_native(cx, &USVString(s)), FetchedData::Json(j) => promise.resolve_native(cx, &j), FetchedData::BlobData(b) => promise.resolve_native(cx, &b), FetchedData::FormData(f) => promise.resolve_native(cx, &f), }; }, Err(err) => promise.reject_error(cx, err), } } // https://fetch.spec.whatwg.org/#concept-body-package-data #[allow(unsafe_code)] fn run_package_data_algorithm<T: BodyOperations + Reflectable>(object: &T, bytes: Vec<u8>, body_type: BodyType, mime_type: Ref<Vec<u8>>) -> Fallible<FetchedData> { let global = object.global(); let cx = global.get_cx(); let mime = &*mime_type; match body_type { BodyType::Text => run_text_data_algorithm(bytes), BodyType::Json => run_json_data_algorithm(cx, bytes), BodyType::Blob => run_blob_data_algorithm(&global, bytes, mime), BodyType::FormData => run_form_data_algorithm(&global, bytes, mime), } } fn run_text_data_algorithm(bytes: Vec<u8>) -> Fallible<FetchedData> { let text = UTF_8.decode(&bytes, DecoderTrap::Replace).unwrap(); Ok(FetchedData::Text(text)) } #[allow(unsafe_code)] fn run_json_data_algorithm(cx: *mut JSContext, bytes: Vec<u8>) -> Fallible<FetchedData> { let json_text = UTF_8.decode(&bytes, DecoderTrap::Replace).unwrap(); let json_text: Vec<u16> = json_text.encode_utf16().collect(); rooted!(in(cx) let mut rval = UndefinedValue()); unsafe { if!JS_ParseJSON(cx, json_text.as_ptr(), json_text.len() as u32, rval.handle_mut()) { JS_ClearPendingException(cx); // TODO: See issue #13464. Exception should be thrown instead of cleared. return Err(Error::Type("Failed to parse JSON".to_string())); } Ok(FetchedData::Json(rval.get())) } } fn run_blob_data_algorithm(root: &GlobalScope, bytes: Vec<u8>, mime: &[u8]) -> Fallible<FetchedData> { let mime_string = if let Ok(s) = String::from_utf8(mime.to_vec()) { s } else { "".to_string() }; let blob = Blob::new(root, BlobImpl::new_from_bytes(bytes), mime_string); Ok(FetchedData::BlobData(blob)) } fn run_form_data_algorithm(root: &GlobalScope, bytes: Vec<u8>, mime: &[u8]) -> Fallible<FetchedData> { let mime_str = if let Ok(s) = str::from_utf8(mime) { s } else { "" }; let mime: Mime = try!(mime_str.parse().map_err( |_| Error::Type("Inappropriate MIME-type for Body".to_string()))); match mime { // TODO //... Parser for Mime(TopLevel::Multipart, SubLevel::FormData, _) //... is not fully determined yet. Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _) => { let entries = form_urlencoded::parse(&bytes); let formdata = FormData::new(None, root); for (k, e) in entries { formdata.Append(USVString(k.into_owned()), USVString(e.into_owned())); } return Ok(FetchedData::FormData(formdata)); }, _ => return Err(Error::Type("Inappropriate MIME-type for Body".to_string())), } } pub trait BodyOperations { fn get_body_used(&self) -> bool; fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType); /// Returns `Some(_)` if the body is complete, `None` if there is more to /// come. fn take_body(&self) -> Option<Vec<u8>>; fn is_locked(&self) -> bool; fn get_mime_type(&self) -> Ref<Vec<u8>>; }
} // https://fetch.spec.whatwg.org/#concept-body-consume-body
random_line_split
body.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::FormDataBinding::FormDataMethods; use dom::bindings::error::{Error, Fallible}; use dom::bindings::js::Root; use dom::bindings::reflector::Reflectable; use dom::bindings::str::USVString; use dom::blob::{Blob, BlobImpl}; use dom::formdata::FormData; use dom::globalscope::GlobalScope; use dom::promise::Promise; use encoding::all::UTF_8; use encoding::types::{DecoderTrap, Encoding}; use js::jsapi::JSContext; use js::jsapi::JS_ClearPendingException; use js::jsapi::JS_ParseJSON; use js::jsapi::Value as JSValue; use js::jsval::UndefinedValue; use mime::{Mime, TopLevel, SubLevel}; use std::cell::Ref; use std::rc::Rc; use std::str; use url::form_urlencoded; #[derive(Copy, Clone, JSTraceable, HeapSizeOf)] pub enum BodyType { Blob, FormData, Json, Text } pub enum FetchedData { Text(String), Json(JSValue), BlobData(Root<Blob>), FormData(Root<FormData>), } // https://fetch.spec.whatwg.org/#concept-body-consume-body #[allow(unrooted_must_root)] pub fn consume_body<T: BodyOperations + Reflectable>(object: &T, body_type: BodyType) -> Rc<Promise> { let promise = Promise::new(&object.global()); // Step 1 if object.get_body_used() || object.is_locked() { promise.reject_error(promise.global().get_cx(), Error::Type( "The response's stream is disturbed or locked".to_string())); return promise; } object.set_body_promise(&promise, body_type); // Steps 2-4 // TODO: Body does not yet have a stream. consume_body_with_promise(object, body_type, &promise); promise } // https://fetch.spec.whatwg.org/#concept-body-consume-body #[allow(unrooted_must_root)] pub fn consume_body_with_promise<T: BodyOperations + Reflectable>(object: &T, body_type: BodyType, promise: &Promise) { // Step 5 let body = match object.take_body() { Some(body) => body, None => return, }; let pkg_data_results = run_package_data_algorithm(object, body, body_type, object.get_mime_type()); let cx = promise.global().get_cx(); match pkg_data_results { Ok(results) => { match results { FetchedData::Text(s) => promise.resolve_native(cx, &USVString(s)), FetchedData::Json(j) => promise.resolve_native(cx, &j), FetchedData::BlobData(b) => promise.resolve_native(cx, &b), FetchedData::FormData(f) => promise.resolve_native(cx, &f), }; }, Err(err) => promise.reject_error(cx, err), } } // https://fetch.spec.whatwg.org/#concept-body-package-data #[allow(unsafe_code)] fn run_package_data_algorithm<T: BodyOperations + Reflectable>(object: &T, bytes: Vec<u8>, body_type: BodyType, mime_type: Ref<Vec<u8>>) -> Fallible<FetchedData> { let global = object.global(); let cx = global.get_cx(); let mime = &*mime_type; match body_type { BodyType::Text => run_text_data_algorithm(bytes), BodyType::Json => run_json_data_algorithm(cx, bytes), BodyType::Blob => run_blob_data_algorithm(&global, bytes, mime), BodyType::FormData => run_form_data_algorithm(&global, bytes, mime), } } fn run_text_data_algorithm(bytes: Vec<u8>) -> Fallible<FetchedData> { let text = UTF_8.decode(&bytes, DecoderTrap::Replace).unwrap(); Ok(FetchedData::Text(text)) } #[allow(unsafe_code)] fn run_json_data_algorithm(cx: *mut JSContext, bytes: Vec<u8>) -> Fallible<FetchedData> { let json_text = UTF_8.decode(&bytes, DecoderTrap::Replace).unwrap(); let json_text: Vec<u16> = json_text.encode_utf16().collect(); rooted!(in(cx) let mut rval = UndefinedValue()); unsafe { if!JS_ParseJSON(cx, json_text.as_ptr(), json_text.len() as u32, rval.handle_mut()) { JS_ClearPendingException(cx); // TODO: See issue #13464. Exception should be thrown instead of cleared. return Err(Error::Type("Failed to parse JSON".to_string())); } Ok(FetchedData::Json(rval.get())) } } fn run_blob_data_algorithm(root: &GlobalScope, bytes: Vec<u8>, mime: &[u8]) -> Fallible<FetchedData> { let mime_string = if let Ok(s) = String::from_utf8(mime.to_vec()) { s } else { "".to_string() }; let blob = Blob::new(root, BlobImpl::new_from_bytes(bytes), mime_string); Ok(FetchedData::BlobData(blob)) } fn run_form_data_algorithm(root: &GlobalScope, bytes: Vec<u8>, mime: &[u8]) -> Fallible<FetchedData>
_ => return Err(Error::Type("Inappropriate MIME-type for Body".to_string())), } } pub trait BodyOperations { fn get_body_used(&self) -> bool; fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType); /// Returns `Some(_)` if the body is complete, `None` if there is more to /// come. fn take_body(&self) -> Option<Vec<u8>>; fn is_locked(&self) -> bool; fn get_mime_type(&self) -> Ref<Vec<u8>>; }
{ let mime_str = if let Ok(s) = str::from_utf8(mime) { s } else { "" }; let mime: Mime = try!(mime_str.parse().map_err( |_| Error::Type("Inappropriate MIME-type for Body".to_string()))); match mime { // TODO // ... Parser for Mime(TopLevel::Multipart, SubLevel::FormData, _) // ... is not fully determined yet. Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _) => { let entries = form_urlencoded::parse(&bytes); let formdata = FormData::new(None, root); for (k, e) in entries { formdata.Append(USVString(k.into_owned()), USVString(e.into_owned())); } return Ok(FetchedData::FormData(formdata)); },
identifier_body
mod.rs
use jsonwebtoken::Header; static CERT_CHAIN: [&str; 3] = include!("cert_chain.json"); #[test] fn x5c_der_empty_chain() { let header = Header { x5c: None,..Default::default() }; assert_eq!(header.x5c_der().unwrap(), None); let header = Header { x5c: Some(Vec::new()),..Default::default() }; assert_eq!(header.x5c_der().unwrap(), Some(Vec::new())); } #[test] fn
() { let der_chain: Vec<Vec<u8>> = CERT_CHAIN.iter().map(base64::decode).collect::<Result<_, _>>().unwrap(); let x5c = Some(CERT_CHAIN.iter().map(ToString::to_string).collect()); let header = Header { x5c,..Default::default() }; assert_eq!(header.x5c_der().unwrap(), Some(der_chain)); } #[test] fn x5c_der_invalid_chain() { let mut x5c: Vec<_> = CERT_CHAIN.iter().map(ToString::to_string).collect(); x5c.push("invalid base64 data".to_string()); let x5c = Some(x5c); let header = Header { x5c,..Default::default() }; assert!(header.x5c_der().is_err()); }
x5c_der_valid_chain
identifier_name
mod.rs
use jsonwebtoken::Header; static CERT_CHAIN: [&str; 3] = include!("cert_chain.json"); #[test] fn x5c_der_empty_chain() { let header = Header { x5c: None,..Default::default() };
let header = Header { x5c: Some(Vec::new()),..Default::default() }; assert_eq!(header.x5c_der().unwrap(), Some(Vec::new())); } #[test] fn x5c_der_valid_chain() { let der_chain: Vec<Vec<u8>> = CERT_CHAIN.iter().map(base64::decode).collect::<Result<_, _>>().unwrap(); let x5c = Some(CERT_CHAIN.iter().map(ToString::to_string).collect()); let header = Header { x5c,..Default::default() }; assert_eq!(header.x5c_der().unwrap(), Some(der_chain)); } #[test] fn x5c_der_invalid_chain() { let mut x5c: Vec<_> = CERT_CHAIN.iter().map(ToString::to_string).collect(); x5c.push("invalid base64 data".to_string()); let x5c = Some(x5c); let header = Header { x5c,..Default::default() }; assert!(header.x5c_der().is_err()); }
assert_eq!(header.x5c_der().unwrap(), None);
random_line_split
mod.rs
use jsonwebtoken::Header; static CERT_CHAIN: [&str; 3] = include!("cert_chain.json"); #[test] fn x5c_der_empty_chain()
#[test] fn x5c_der_valid_chain() { let der_chain: Vec<Vec<u8>> = CERT_CHAIN.iter().map(base64::decode).collect::<Result<_, _>>().unwrap(); let x5c = Some(CERT_CHAIN.iter().map(ToString::to_string).collect()); let header = Header { x5c,..Default::default() }; assert_eq!(header.x5c_der().unwrap(), Some(der_chain)); } #[test] fn x5c_der_invalid_chain() { let mut x5c: Vec<_> = CERT_CHAIN.iter().map(ToString::to_string).collect(); x5c.push("invalid base64 data".to_string()); let x5c = Some(x5c); let header = Header { x5c,..Default::default() }; assert!(header.x5c_der().is_err()); }
{ let header = Header { x5c: None, ..Default::default() }; assert_eq!(header.x5c_der().unwrap(), None); let header = Header { x5c: Some(Vec::new()), ..Default::default() }; assert_eq!(header.x5c_der().unwrap(), Some(Vec::new())); }
identifier_body
controller.rs
use std::collections::HashMap; use std::rc::Rc; use rustc_serialize::{Decodable, Decoder}; use animation::AnimationClip; use transform::{Transform, FromTransform}; use blend_tree::{BlendTreeNode, BlendTreeNodeDef, ClipId}; use skeleton::Skeleton; const MAX_JOINTS: usize = 64; /// A state that an AnimationController can be in, consisting /// of a blend tree and a collection of transitions to other states pub struct AnimationState<T: Transform> { /// The blend tree used to determine the final blended pose /// for this state pub blend_tree: BlendTreeNode<T>, /// Transitions from this state to other AnimationStates pub transitions: Vec<AnimationTransition>, } /// Representation of a state transition to a target state, with a condition and a duration #[derive(Debug, Clone, RustcDecodable)] pub struct AnimationTransition { /// The name of the target state to transition to pub target_state: String, /// The condition that will be checked in order to determine /// if the controller should transition to the target state pub condition: TransitionCondition, /// The duration of the transition, during which a linear blend /// transition between the current and target states should occur pub duration: f32, } /// Representation of a condition to check for an AnimationTransition #[derive(Debug, Clone, RustcDecodable)] pub struct TransitionCondition { /// The name of the controller parameter to compare with pub parameter: String, /// The comparision operator to use pub operator: Operator, /// The constant value to compare with the controller parameter value pub value: f32, } impl TransitionCondition { /// Returns true if the condition is satisfied pub fn is_true(&self, parameters: &HashMap<String, f32>) -> bool { match self.operator { Operator::LessThan => parameters[&self.parameter[..]] < self.value, Operator::GreaterThan => parameters[&self.parameter[..]] > self.value, Operator::LessThanEqual => parameters[&self.parameter[..]] <= self.value, Operator::GreaterThanEqual => parameters[&self.parameter[..]] >= self.value, Operator::Equal => parameters[&self.parameter[..]] == self.value, Operator::NotEqual => parameters[&self.parameter[..]]!= self.value, } } } #[derive(Debug, Clone)] pub enum Operator { LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, Equal, NotEqual, } impl Decodable for Operator { fn decode<D: Decoder>(decoder: &mut D) -> Result<Operator, D::Error> { match &try!(decoder.read_str())[..] { "<" => Ok(Operator::LessThan), ">" => Ok(Operator::GreaterThan), "<=" => Ok(Operator::LessThanEqual), ">=" => Ok(Operator::GreaterThanEqual), "=" => Ok(Operator::Equal), "!=" => Ok(Operator::NotEqual), _ => Ok(Operator::Equal), // FIXME -- figure out how to throw a D::Error... } } } /// Definition struct for an AnimationController, which can be deserialized from JSON /// and converted to an AnimationController instance at runtime #[derive(Clone, Debug, RustcDecodable)] pub struct AnimationControllerDef { /// Identifying name for the controller definition pub name: String, /// Declaration list of all parameters that are used by the AnimationController, /// including state transition conditions and blend tree parameters pub parameters: Vec<String>, /// List of animation state definitions pub states: Vec<AnimationStateDef>, /// The name of the state that the AnimationController should start in pub initial_state: String, } /// Definition struct for an AnimationState, which can be deserialized from JSON /// and converted to an AnimationState instance at runtime #[derive(Clone, Debug)] pub struct AnimationStateDef { /// The identifying name for the state pub name: String, /// The blend tree definition for this state pub blend_tree: BlendTreeNodeDef, /// The transitions to other states that can occur from this state pub transitions: Vec<AnimationTransition>, } impl Decodable for AnimationStateDef { fn decode<D: Decoder>(decoder: &mut D) -> Result<AnimationStateDef, D::Error> { decoder.read_struct("root", 0, |decoder| { let name = try!(decoder.read_struct_field("name", 0, |decoder| { Ok(try!(decoder.read_str())) })); let blend_tree = try!(decoder.read_struct_field("blend_tree", 0, Decodable::decode)); let transitions = try!(decoder.read_struct_field("transitions", 0, |decoder| { decoder.read_seq(|decoder, len| { let mut transitions = Vec::new(); for i in (0.. len) { transitions.push(try!(decoder.read_seq_elt(i, Decodable::decode))); } Ok(transitions) }) })); Ok(AnimationStateDef { name: name, blend_tree: blend_tree, transitions: transitions, }) }) } } /// A runtime representation of an Animation State Machine, consisting of one or more /// AnimationStates connected by AnimationTransitions, where the output animation /// pose depends on the current state or any active transitions between states. pub struct AnimationController<T: Transform> { /// Parameters that will be referenced by blend tree nodes and animation states parameters: HashMap<String, f32>, /// Shared reference to the skeleton this controller is using skeleton: Rc<Skeleton>, /// Tracks seconds since controller started running local_clock: f64, /// Playback speed multiplier. playback_speed: f64, /// Mapping of all animation state names to their instances states: HashMap<String, AnimationState<T>>, /// The name of the current active AnimationState current_state: String, /// The current active AnimationTransition and its start time, if any transition: Option<(f64, AnimationTransition)>, } impl<T: Transform> AnimationController<T> { /// Create an AnimationController instance from its definition, the desired skeleton, and a /// collection of currently loaded animation clips. pub fn new(controller_def: AnimationControllerDef, skeleton: Rc<Skeleton>, animations: &HashMap<ClipId, Rc<AnimationClip<T>>>) -> AnimationController<T> { let mut parameters = HashMap::new(); for parameter in controller_def.parameters.iter() { parameters.insert(parameter.clone(), 0.0); }; let mut states = HashMap::new(); for state_def in controller_def.states.iter() { let mut blend_tree = BlendTreeNode::from_def(state_def.blend_tree.clone(), animations); blend_tree.synchronize_subtree(0.0, &parameters); states.insert(state_def.name.clone(), AnimationState { blend_tree: blend_tree, transitions: state_def.transitions.clone() }); } AnimationController { parameters: parameters, skeleton: skeleton.clone(), local_clock: 0.0, playback_speed: 1.0, states: states, current_state: controller_def.initial_state, transition: None, } } /// Update the controller's local clock with the given time delta pub fn update(&mut self, delta_time: f64)
/// Checks if controller should transition to a different state, or if currently /// in a transition, checks if the transition is complete fn update_state(&mut self, ext_dt: f64) { match self.transition.clone() { Some((ref start_time, ref transition)) => { // If transition is finished, switch state to new transition if self.local_clock + ext_dt >= start_time + transition.duration as f64{ self.current_state = transition.target_state.clone(); self.transition = None; } }, None => { // Check for any transitions with passing conditions let current_state = &self.states[&self.current_state[..]]; for transition in current_state.transitions.iter() { if transition.condition.is_true(&self.parameters) { self.transition = Some((self.local_clock + ext_dt, transition.clone())); break; } } } } } /// Set the playback speed for the controller pub fn set_playback_speed(&mut self, speed: f64) { self.playback_speed = speed; } /// Set the value for the given controller parameter pub fn set_param_value(&mut self, name: &str, value: f32) { self.parameters.insert(name.to_string(), value); // :( } /// Return the value for the given controller parameter pub fn get_param_value(&self, name: &str) -> f32 { self.parameters[name] } /// Return a read-only reference to the controller parameter map pub fn get_parameters(&self) -> &HashMap<String, f32> { &self.parameters } /// Calculate global skeletal joint poses for the given time since last update pub fn get_output_pose<TOutput: Transform + FromTransform<T>>(&mut self, ext_dt: f64, output_poses: &mut [TOutput]) { self.update_state(ext_dt); let elapsed_time = self.local_clock + ext_dt * self.playback_speed; let mut local_poses = [ T::identity(); MAX_JOINTS ]; { let current_state = self.states.get_mut(&self.current_state[..]).unwrap(); current_state.blend_tree.get_output_pose(elapsed_time as f32, &self.parameters, &mut local_poses[..]); } // TODO - would be kinda cool if you could just use a lerp node that pointed to the two // blend trees, but then we'd need RC pointers? if let Some((transition_start_time, ref transition)) = self.transition { // Blend with the target state... let mut target_poses = [ T::identity(); MAX_JOINTS ]; let target_state = self.states.get_mut(&transition.target_state[..]).unwrap(); target_state.blend_tree.get_output_pose(elapsed_time as f32, &self.parameters, &mut target_poses[..]); let blend_parameter = ((self.local_clock + ext_dt - transition_start_time) / transition.duration as f64) as f32; for i in (0.. output_poses.len()) { let pose_1 = &mut local_poses[i]; let pose_2 = target_poses[i]; *pose_1 = pose_1.lerp(pose_2, blend_parameter); } } self.calculate_global_poses(&local_poses[..], output_poses); } /// Calculate global poses from the controller's skeleton and the given local poses fn calculate_global_poses<TOutput: Transform + FromTransform<T>>( &self, local_poses: &[T], global_poses: &mut [TOutput], ) { for (joint_index, joint) in self.skeleton.joints.iter().enumerate() { let parent_pose = if!joint.is_root() { global_poses[joint.parent_index as usize] } else { TOutput::identity() }; let local_pose = local_poses[joint_index]; global_poses[joint_index] = parent_pose.concat(TOutput::from_transform(local_pose)); } } }
{ self.local_clock += delta_time * self.playback_speed; }
identifier_body
controller.rs
use std::collections::HashMap; use std::rc::Rc; use rustc_serialize::{Decodable, Decoder}; use animation::AnimationClip; use transform::{Transform, FromTransform}; use blend_tree::{BlendTreeNode, BlendTreeNodeDef, ClipId}; use skeleton::Skeleton; const MAX_JOINTS: usize = 64; /// A state that an AnimationController can be in, consisting /// of a blend tree and a collection of transitions to other states pub struct AnimationState<T: Transform> { /// The blend tree used to determine the final blended pose /// for this state pub blend_tree: BlendTreeNode<T>, /// Transitions from this state to other AnimationStates pub transitions: Vec<AnimationTransition>, } /// Representation of a state transition to a target state, with a condition and a duration #[derive(Debug, Clone, RustcDecodable)] pub struct AnimationTransition { /// The name of the target state to transition to pub target_state: String, /// The condition that will be checked in order to determine /// if the controller should transition to the target state pub condition: TransitionCondition, /// The duration of the transition, during which a linear blend /// transition between the current and target states should occur pub duration: f32, } /// Representation of a condition to check for an AnimationTransition #[derive(Debug, Clone, RustcDecodable)] pub struct TransitionCondition { /// The name of the controller parameter to compare with pub parameter: String, /// The comparision operator to use pub operator: Operator, /// The constant value to compare with the controller parameter value pub value: f32, } impl TransitionCondition { /// Returns true if the condition is satisfied pub fn is_true(&self, parameters: &HashMap<String, f32>) -> bool { match self.operator { Operator::LessThan => parameters[&self.parameter[..]] < self.value, Operator::GreaterThan => parameters[&self.parameter[..]] > self.value, Operator::LessThanEqual => parameters[&self.parameter[..]] <= self.value, Operator::GreaterThanEqual => parameters[&self.parameter[..]] >= self.value, Operator::Equal => parameters[&self.parameter[..]] == self.value, Operator::NotEqual => parameters[&self.parameter[..]]!= self.value, } } } #[derive(Debug, Clone)] pub enum Operator { LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, Equal, NotEqual, } impl Decodable for Operator { fn decode<D: Decoder>(decoder: &mut D) -> Result<Operator, D::Error> { match &try!(decoder.read_str())[..] { "<" => Ok(Operator::LessThan), ">" => Ok(Operator::GreaterThan), "<=" => Ok(Operator::LessThanEqual), ">=" => Ok(Operator::GreaterThanEqual), "=" => Ok(Operator::Equal), "!=" => Ok(Operator::NotEqual), _ => Ok(Operator::Equal), // FIXME -- figure out how to throw a D::Error... } } } /// Definition struct for an AnimationController, which can be deserialized from JSON /// and converted to an AnimationController instance at runtime #[derive(Clone, Debug, RustcDecodable)] pub struct AnimationControllerDef { /// Identifying name for the controller definition pub name: String, /// Declaration list of all parameters that are used by the AnimationController, /// including state transition conditions and blend tree parameters pub parameters: Vec<String>, /// List of animation state definitions pub states: Vec<AnimationStateDef>, /// The name of the state that the AnimationController should start in pub initial_state: String, } /// Definition struct for an AnimationState, which can be deserialized from JSON /// and converted to an AnimationState instance at runtime #[derive(Clone, Debug)] pub struct AnimationStateDef { /// The identifying name for the state pub name: String, /// The blend tree definition for this state pub blend_tree: BlendTreeNodeDef, /// The transitions to other states that can occur from this state pub transitions: Vec<AnimationTransition>, } impl Decodable for AnimationStateDef { fn decode<D: Decoder>(decoder: &mut D) -> Result<AnimationStateDef, D::Error> { decoder.read_struct("root", 0, |decoder| { let name = try!(decoder.read_struct_field("name", 0, |decoder| { Ok(try!(decoder.read_str())) })); let blend_tree = try!(decoder.read_struct_field("blend_tree", 0, Decodable::decode)); let transitions = try!(decoder.read_struct_field("transitions", 0, |decoder| { decoder.read_seq(|decoder, len| { let mut transitions = Vec::new(); for i in (0.. len) { transitions.push(try!(decoder.read_seq_elt(i, Decodable::decode))); }
}) })); Ok(AnimationStateDef { name: name, blend_tree: blend_tree, transitions: transitions, }) }) } } /// A runtime representation of an Animation State Machine, consisting of one or more /// AnimationStates connected by AnimationTransitions, where the output animation /// pose depends on the current state or any active transitions between states. pub struct AnimationController<T: Transform> { /// Parameters that will be referenced by blend tree nodes and animation states parameters: HashMap<String, f32>, /// Shared reference to the skeleton this controller is using skeleton: Rc<Skeleton>, /// Tracks seconds since controller started running local_clock: f64, /// Playback speed multiplier. playback_speed: f64, /// Mapping of all animation state names to their instances states: HashMap<String, AnimationState<T>>, /// The name of the current active AnimationState current_state: String, /// The current active AnimationTransition and its start time, if any transition: Option<(f64, AnimationTransition)>, } impl<T: Transform> AnimationController<T> { /// Create an AnimationController instance from its definition, the desired skeleton, and a /// collection of currently loaded animation clips. pub fn new(controller_def: AnimationControllerDef, skeleton: Rc<Skeleton>, animations: &HashMap<ClipId, Rc<AnimationClip<T>>>) -> AnimationController<T> { let mut parameters = HashMap::new(); for parameter in controller_def.parameters.iter() { parameters.insert(parameter.clone(), 0.0); }; let mut states = HashMap::new(); for state_def in controller_def.states.iter() { let mut blend_tree = BlendTreeNode::from_def(state_def.blend_tree.clone(), animations); blend_tree.synchronize_subtree(0.0, &parameters); states.insert(state_def.name.clone(), AnimationState { blend_tree: blend_tree, transitions: state_def.transitions.clone() }); } AnimationController { parameters: parameters, skeleton: skeleton.clone(), local_clock: 0.0, playback_speed: 1.0, states: states, current_state: controller_def.initial_state, transition: None, } } /// Update the controller's local clock with the given time delta pub fn update(&mut self, delta_time: f64) { self.local_clock += delta_time * self.playback_speed; } /// Checks if controller should transition to a different state, or if currently /// in a transition, checks if the transition is complete fn update_state(&mut self, ext_dt: f64) { match self.transition.clone() { Some((ref start_time, ref transition)) => { // If transition is finished, switch state to new transition if self.local_clock + ext_dt >= start_time + transition.duration as f64{ self.current_state = transition.target_state.clone(); self.transition = None; } }, None => { // Check for any transitions with passing conditions let current_state = &self.states[&self.current_state[..]]; for transition in current_state.transitions.iter() { if transition.condition.is_true(&self.parameters) { self.transition = Some((self.local_clock + ext_dt, transition.clone())); break; } } } } } /// Set the playback speed for the controller pub fn set_playback_speed(&mut self, speed: f64) { self.playback_speed = speed; } /// Set the value for the given controller parameter pub fn set_param_value(&mut self, name: &str, value: f32) { self.parameters.insert(name.to_string(), value); // :( } /// Return the value for the given controller parameter pub fn get_param_value(&self, name: &str) -> f32 { self.parameters[name] } /// Return a read-only reference to the controller parameter map pub fn get_parameters(&self) -> &HashMap<String, f32> { &self.parameters } /// Calculate global skeletal joint poses for the given time since last update pub fn get_output_pose<TOutput: Transform + FromTransform<T>>(&mut self, ext_dt: f64, output_poses: &mut [TOutput]) { self.update_state(ext_dt); let elapsed_time = self.local_clock + ext_dt * self.playback_speed; let mut local_poses = [ T::identity(); MAX_JOINTS ]; { let current_state = self.states.get_mut(&self.current_state[..]).unwrap(); current_state.blend_tree.get_output_pose(elapsed_time as f32, &self.parameters, &mut local_poses[..]); } // TODO - would be kinda cool if you could just use a lerp node that pointed to the two // blend trees, but then we'd need RC pointers? if let Some((transition_start_time, ref transition)) = self.transition { // Blend with the target state... let mut target_poses = [ T::identity(); MAX_JOINTS ]; let target_state = self.states.get_mut(&transition.target_state[..]).unwrap(); target_state.blend_tree.get_output_pose(elapsed_time as f32, &self.parameters, &mut target_poses[..]); let blend_parameter = ((self.local_clock + ext_dt - transition_start_time) / transition.duration as f64) as f32; for i in (0.. output_poses.len()) { let pose_1 = &mut local_poses[i]; let pose_2 = target_poses[i]; *pose_1 = pose_1.lerp(pose_2, blend_parameter); } } self.calculate_global_poses(&local_poses[..], output_poses); } /// Calculate global poses from the controller's skeleton and the given local poses fn calculate_global_poses<TOutput: Transform + FromTransform<T>>( &self, local_poses: &[T], global_poses: &mut [TOutput], ) { for (joint_index, joint) in self.skeleton.joints.iter().enumerate() { let parent_pose = if!joint.is_root() { global_poses[joint.parent_index as usize] } else { TOutput::identity() }; let local_pose = local_poses[joint_index]; global_poses[joint_index] = parent_pose.concat(TOutput::from_transform(local_pose)); } } }
Ok(transitions)
random_line_split
controller.rs
use std::collections::HashMap; use std::rc::Rc; use rustc_serialize::{Decodable, Decoder}; use animation::AnimationClip; use transform::{Transform, FromTransform}; use blend_tree::{BlendTreeNode, BlendTreeNodeDef, ClipId}; use skeleton::Skeleton; const MAX_JOINTS: usize = 64; /// A state that an AnimationController can be in, consisting /// of a blend tree and a collection of transitions to other states pub struct AnimationState<T: Transform> { /// The blend tree used to determine the final blended pose /// for this state pub blend_tree: BlendTreeNode<T>, /// Transitions from this state to other AnimationStates pub transitions: Vec<AnimationTransition>, } /// Representation of a state transition to a target state, with a condition and a duration #[derive(Debug, Clone, RustcDecodable)] pub struct AnimationTransition { /// The name of the target state to transition to pub target_state: String, /// The condition that will be checked in order to determine /// if the controller should transition to the target state pub condition: TransitionCondition, /// The duration of the transition, during which a linear blend /// transition between the current and target states should occur pub duration: f32, } /// Representation of a condition to check for an AnimationTransition #[derive(Debug, Clone, RustcDecodable)] pub struct TransitionCondition { /// The name of the controller parameter to compare with pub parameter: String, /// The comparision operator to use pub operator: Operator, /// The constant value to compare with the controller parameter value pub value: f32, } impl TransitionCondition { /// Returns true if the condition is satisfied pub fn
(&self, parameters: &HashMap<String, f32>) -> bool { match self.operator { Operator::LessThan => parameters[&self.parameter[..]] < self.value, Operator::GreaterThan => parameters[&self.parameter[..]] > self.value, Operator::LessThanEqual => parameters[&self.parameter[..]] <= self.value, Operator::GreaterThanEqual => parameters[&self.parameter[..]] >= self.value, Operator::Equal => parameters[&self.parameter[..]] == self.value, Operator::NotEqual => parameters[&self.parameter[..]]!= self.value, } } } #[derive(Debug, Clone)] pub enum Operator { LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, Equal, NotEqual, } impl Decodable for Operator { fn decode<D: Decoder>(decoder: &mut D) -> Result<Operator, D::Error> { match &try!(decoder.read_str())[..] { "<" => Ok(Operator::LessThan), ">" => Ok(Operator::GreaterThan), "<=" => Ok(Operator::LessThanEqual), ">=" => Ok(Operator::GreaterThanEqual), "=" => Ok(Operator::Equal), "!=" => Ok(Operator::NotEqual), _ => Ok(Operator::Equal), // FIXME -- figure out how to throw a D::Error... } } } /// Definition struct for an AnimationController, which can be deserialized from JSON /// and converted to an AnimationController instance at runtime #[derive(Clone, Debug, RustcDecodable)] pub struct AnimationControllerDef { /// Identifying name for the controller definition pub name: String, /// Declaration list of all parameters that are used by the AnimationController, /// including state transition conditions and blend tree parameters pub parameters: Vec<String>, /// List of animation state definitions pub states: Vec<AnimationStateDef>, /// The name of the state that the AnimationController should start in pub initial_state: String, } /// Definition struct for an AnimationState, which can be deserialized from JSON /// and converted to an AnimationState instance at runtime #[derive(Clone, Debug)] pub struct AnimationStateDef { /// The identifying name for the state pub name: String, /// The blend tree definition for this state pub blend_tree: BlendTreeNodeDef, /// The transitions to other states that can occur from this state pub transitions: Vec<AnimationTransition>, } impl Decodable for AnimationStateDef { fn decode<D: Decoder>(decoder: &mut D) -> Result<AnimationStateDef, D::Error> { decoder.read_struct("root", 0, |decoder| { let name = try!(decoder.read_struct_field("name", 0, |decoder| { Ok(try!(decoder.read_str())) })); let blend_tree = try!(decoder.read_struct_field("blend_tree", 0, Decodable::decode)); let transitions = try!(decoder.read_struct_field("transitions", 0, |decoder| { decoder.read_seq(|decoder, len| { let mut transitions = Vec::new(); for i in (0.. len) { transitions.push(try!(decoder.read_seq_elt(i, Decodable::decode))); } Ok(transitions) }) })); Ok(AnimationStateDef { name: name, blend_tree: blend_tree, transitions: transitions, }) }) } } /// A runtime representation of an Animation State Machine, consisting of one or more /// AnimationStates connected by AnimationTransitions, where the output animation /// pose depends on the current state or any active transitions between states. pub struct AnimationController<T: Transform> { /// Parameters that will be referenced by blend tree nodes and animation states parameters: HashMap<String, f32>, /// Shared reference to the skeleton this controller is using skeleton: Rc<Skeleton>, /// Tracks seconds since controller started running local_clock: f64, /// Playback speed multiplier. playback_speed: f64, /// Mapping of all animation state names to their instances states: HashMap<String, AnimationState<T>>, /// The name of the current active AnimationState current_state: String, /// The current active AnimationTransition and its start time, if any transition: Option<(f64, AnimationTransition)>, } impl<T: Transform> AnimationController<T> { /// Create an AnimationController instance from its definition, the desired skeleton, and a /// collection of currently loaded animation clips. pub fn new(controller_def: AnimationControllerDef, skeleton: Rc<Skeleton>, animations: &HashMap<ClipId, Rc<AnimationClip<T>>>) -> AnimationController<T> { let mut parameters = HashMap::new(); for parameter in controller_def.parameters.iter() { parameters.insert(parameter.clone(), 0.0); }; let mut states = HashMap::new(); for state_def in controller_def.states.iter() { let mut blend_tree = BlendTreeNode::from_def(state_def.blend_tree.clone(), animations); blend_tree.synchronize_subtree(0.0, &parameters); states.insert(state_def.name.clone(), AnimationState { blend_tree: blend_tree, transitions: state_def.transitions.clone() }); } AnimationController { parameters: parameters, skeleton: skeleton.clone(), local_clock: 0.0, playback_speed: 1.0, states: states, current_state: controller_def.initial_state, transition: None, } } /// Update the controller's local clock with the given time delta pub fn update(&mut self, delta_time: f64) { self.local_clock += delta_time * self.playback_speed; } /// Checks if controller should transition to a different state, or if currently /// in a transition, checks if the transition is complete fn update_state(&mut self, ext_dt: f64) { match self.transition.clone() { Some((ref start_time, ref transition)) => { // If transition is finished, switch state to new transition if self.local_clock + ext_dt >= start_time + transition.duration as f64{ self.current_state = transition.target_state.clone(); self.transition = None; } }, None => { // Check for any transitions with passing conditions let current_state = &self.states[&self.current_state[..]]; for transition in current_state.transitions.iter() { if transition.condition.is_true(&self.parameters) { self.transition = Some((self.local_clock + ext_dt, transition.clone())); break; } } } } } /// Set the playback speed for the controller pub fn set_playback_speed(&mut self, speed: f64) { self.playback_speed = speed; } /// Set the value for the given controller parameter pub fn set_param_value(&mut self, name: &str, value: f32) { self.parameters.insert(name.to_string(), value); // :( } /// Return the value for the given controller parameter pub fn get_param_value(&self, name: &str) -> f32 { self.parameters[name] } /// Return a read-only reference to the controller parameter map pub fn get_parameters(&self) -> &HashMap<String, f32> { &self.parameters } /// Calculate global skeletal joint poses for the given time since last update pub fn get_output_pose<TOutput: Transform + FromTransform<T>>(&mut self, ext_dt: f64, output_poses: &mut [TOutput]) { self.update_state(ext_dt); let elapsed_time = self.local_clock + ext_dt * self.playback_speed; let mut local_poses = [ T::identity(); MAX_JOINTS ]; { let current_state = self.states.get_mut(&self.current_state[..]).unwrap(); current_state.blend_tree.get_output_pose(elapsed_time as f32, &self.parameters, &mut local_poses[..]); } // TODO - would be kinda cool if you could just use a lerp node that pointed to the two // blend trees, but then we'd need RC pointers? if let Some((transition_start_time, ref transition)) = self.transition { // Blend with the target state... let mut target_poses = [ T::identity(); MAX_JOINTS ]; let target_state = self.states.get_mut(&transition.target_state[..]).unwrap(); target_state.blend_tree.get_output_pose(elapsed_time as f32, &self.parameters, &mut target_poses[..]); let blend_parameter = ((self.local_clock + ext_dt - transition_start_time) / transition.duration as f64) as f32; for i in (0.. output_poses.len()) { let pose_1 = &mut local_poses[i]; let pose_2 = target_poses[i]; *pose_1 = pose_1.lerp(pose_2, blend_parameter); } } self.calculate_global_poses(&local_poses[..], output_poses); } /// Calculate global poses from the controller's skeleton and the given local poses fn calculate_global_poses<TOutput: Transform + FromTransform<T>>( &self, local_poses: &[T], global_poses: &mut [TOutput], ) { for (joint_index, joint) in self.skeleton.joints.iter().enumerate() { let parent_pose = if!joint.is_root() { global_poses[joint.parent_index as usize] } else { TOutput::identity() }; let local_pose = local_poses[joint_index]; global_poses[joint_index] = parent_pose.concat(TOutput::from_transform(local_pose)); } } }
is_true
identifier_name
plist_extractor.rs
use memmem::{Searcher, TwoWaySearcher}; const PLIST_PREFIX: &[u8] = b"<?xml version="; const PLIST_SUFFIX: &[u8] = b"</plist>"; /// Attempts to find a plist content in a `data` and return it as a slice. /// /// Since mobileprovision files contain "garbage" at the start and the end you need to extract /// a plist content before the xml parsing. pub fn find(data: &[u8]) -> Option<&[u8]> { let prefix_searcher = TwoWaySearcher::new(PLIST_PREFIX); let suffix_searcher = TwoWaySearcher::new(PLIST_SUFFIX); let start_i = prefix_searcher.search_in(data); let end_i = suffix_searcher .search_in(data) .map(|i| i + PLIST_SUFFIX.len()); if let (Some(start_i), Some(end_i)) = (start_i, end_i) { if end_i <= data.len()
} None } #[cfg(test)] mod tests { use super::*; use expectest::expect; use expectest::prelude::*; #[test] fn test_find_plist() { let data: &[u8] = b"<?xml version=</plist>"; expect!(find(&data)).to(be_some().value(data)); let data: &[u8] = b" <?xml version=abcd</plist> "; expect!(find(&data)).to(be_some().value(b"<?xml version=abcd</plist>")); } }
{ return Some(&data[start_i..end_i]); }
conditional_block
plist_extractor.rs
use memmem::{Searcher, TwoWaySearcher}; const PLIST_PREFIX: &[u8] = b"<?xml version="; const PLIST_SUFFIX: &[u8] = b"</plist>"; /// Attempts to find a plist content in a `data` and return it as a slice. /// /// Since mobileprovision files contain "garbage" at the start and the end you need to extract /// a plist content before the xml parsing. pub fn find(data: &[u8]) -> Option<&[u8]> { let prefix_searcher = TwoWaySearcher::new(PLIST_PREFIX); let suffix_searcher = TwoWaySearcher::new(PLIST_SUFFIX); let start_i = prefix_searcher.search_in(data); let end_i = suffix_searcher .search_in(data) .map(|i| i + PLIST_SUFFIX.len()); if let (Some(start_i), Some(end_i)) = (start_i, end_i) { if end_i <= data.len() { return Some(&data[start_i..end_i]); } } None } #[cfg(test)] mod tests { use super::*; use expectest::expect; use expectest::prelude::*; #[test] fn
() { let data: &[u8] = b"<?xml version=</plist>"; expect!(find(&data)).to(be_some().value(data)); let data: &[u8] = b" <?xml version=abcd</plist> "; expect!(find(&data)).to(be_some().value(b"<?xml version=abcd</plist>")); } }
test_find_plist
identifier_name
plist_extractor.rs
use memmem::{Searcher, TwoWaySearcher}; const PLIST_PREFIX: &[u8] = b"<?xml version="; const PLIST_SUFFIX: &[u8] = b"</plist>"; /// Attempts to find a plist content in a `data` and return it as a slice. /// /// Since mobileprovision files contain "garbage" at the start and the end you need to extract /// a plist content before the xml parsing. pub fn find(data: &[u8]) -> Option<&[u8]> { let prefix_searcher = TwoWaySearcher::new(PLIST_PREFIX); let suffix_searcher = TwoWaySearcher::new(PLIST_SUFFIX); let start_i = prefix_searcher.search_in(data); let end_i = suffix_searcher .search_in(data) .map(|i| i + PLIST_SUFFIX.len());
return Some(&data[start_i..end_i]); } } None } #[cfg(test)] mod tests { use super::*; use expectest::expect; use expectest::prelude::*; #[test] fn test_find_plist() { let data: &[u8] = b"<?xml version=</plist>"; expect!(find(&data)).to(be_some().value(data)); let data: &[u8] = b" <?xml version=abcd</plist> "; expect!(find(&data)).to(be_some().value(b"<?xml version=abcd</plist>")); } }
if let (Some(start_i), Some(end_i)) = (start_i, end_i) { if end_i <= data.len() {
random_line_split
plist_extractor.rs
use memmem::{Searcher, TwoWaySearcher}; const PLIST_PREFIX: &[u8] = b"<?xml version="; const PLIST_SUFFIX: &[u8] = b"</plist>"; /// Attempts to find a plist content in a `data` and return it as a slice. /// /// Since mobileprovision files contain "garbage" at the start and the end you need to extract /// a plist content before the xml parsing. pub fn find(data: &[u8]) -> Option<&[u8]>
#[cfg(test)] mod tests { use super::*; use expectest::expect; use expectest::prelude::*; #[test] fn test_find_plist() { let data: &[u8] = b"<?xml version=</plist>"; expect!(find(&data)).to(be_some().value(data)); let data: &[u8] = b" <?xml version=abcd</plist> "; expect!(find(&data)).to(be_some().value(b"<?xml version=abcd</plist>")); } }
{ let prefix_searcher = TwoWaySearcher::new(PLIST_PREFIX); let suffix_searcher = TwoWaySearcher::new(PLIST_SUFFIX); let start_i = prefix_searcher.search_in(data); let end_i = suffix_searcher .search_in(data) .map(|i| i + PLIST_SUFFIX.len()); if let (Some(start_i), Some(end_i)) = (start_i, end_i) { if end_i <= data.len() { return Some(&data[start_i..end_i]); } } None }
identifier_body
rand.rs
use crate::io; use crate::mem; use crate::sys::c; #[cfg(not(target_vendor = "uwp"))] pub fn hashmap_random_keys() -> (u64, u64) { let mut v = (0, 0); let ret = unsafe { c::RtlGenRandom(&mut v as *mut _ as *mut u8, mem::size_of_val(&v) as c::ULONG) }; if ret == 0 { panic!("couldn't generate random bytes: {}", io::Error::last_os_error()); }
#[cfg(target_vendor = "uwp")] pub fn hashmap_random_keys() -> (u64, u64) { use crate::ptr; let mut v = (0, 0); let ret = unsafe { c::BCryptGenRandom( ptr::null_mut(), &mut v as *mut _ as *mut u8, mem::size_of_val(&v) as c::ULONG, c::BCRYPT_USE_SYSTEM_PREFERRED_RNG, ) }; if ret!= 0 { panic!("couldn't generate random bytes: {}", io::Error::last_os_error()); } return v; }
v }
random_line_split
rand.rs
use crate::io; use crate::mem; use crate::sys::c; #[cfg(not(target_vendor = "uwp"))] pub fn hashmap_random_keys() -> (u64, u64) { let mut v = (0, 0); let ret = unsafe { c::RtlGenRandom(&mut v as *mut _ as *mut u8, mem::size_of_val(&v) as c::ULONG) }; if ret == 0 { panic!("couldn't generate random bytes: {}", io::Error::last_os_error()); } v } #[cfg(target_vendor = "uwp")] pub fn hashmap_random_keys() -> (u64, u64) { use crate::ptr; let mut v = (0, 0); let ret = unsafe { c::BCryptGenRandom( ptr::null_mut(), &mut v as *mut _ as *mut u8, mem::size_of_val(&v) as c::ULONG, c::BCRYPT_USE_SYSTEM_PREFERRED_RNG, ) }; if ret!= 0
return v; }
{ panic!("couldn't generate random bytes: {}", io::Error::last_os_error()); }
conditional_block
rand.rs
use crate::io; use crate::mem; use crate::sys::c; #[cfg(not(target_vendor = "uwp"))] pub fn hashmap_random_keys() -> (u64, u64) { let mut v = (0, 0); let ret = unsafe { c::RtlGenRandom(&mut v as *mut _ as *mut u8, mem::size_of_val(&v) as c::ULONG) }; if ret == 0 { panic!("couldn't generate random bytes: {}", io::Error::last_os_error()); } v } #[cfg(target_vendor = "uwp")] pub fn hashmap_random_keys() -> (u64, u64)
{ use crate::ptr; let mut v = (0, 0); let ret = unsafe { c::BCryptGenRandom( ptr::null_mut(), &mut v as *mut _ as *mut u8, mem::size_of_val(&v) as c::ULONG, c::BCRYPT_USE_SYSTEM_PREFERRED_RNG, ) }; if ret != 0 { panic!("couldn't generate random bytes: {}", io::Error::last_os_error()); } return v; }
identifier_body
rand.rs
use crate::io; use crate::mem; use crate::sys::c; #[cfg(not(target_vendor = "uwp"))] pub fn hashmap_random_keys() -> (u64, u64) { let mut v = (0, 0); let ret = unsafe { c::RtlGenRandom(&mut v as *mut _ as *mut u8, mem::size_of_val(&v) as c::ULONG) }; if ret == 0 { panic!("couldn't generate random bytes: {}", io::Error::last_os_error()); } v } #[cfg(target_vendor = "uwp")] pub fn
() -> (u64, u64) { use crate::ptr; let mut v = (0, 0); let ret = unsafe { c::BCryptGenRandom( ptr::null_mut(), &mut v as *mut _ as *mut u8, mem::size_of_val(&v) as c::ULONG, c::BCRYPT_USE_SYSTEM_PREFERRED_RNG, ) }; if ret!= 0 { panic!("couldn't generate random bytes: {}", io::Error::last_os_error()); } return v; }
hashmap_random_keys
identifier_name
quartic_depressed.rs
// Copyright (c) 2015, Mikhail Vorotilov // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use super::super::FloatType; use super::super::Roots; /// Solves a depressed quartic equation x^4 + a2*x^2 + a1*x + a0 = 0. /// /// Returned roots are ordered. Precision is about 1e-14 for f64. /// /// # Examples /// /// ``` /// use roots::find_roots_quartic_depressed; /// /// let one_root = find_roots_quartic_depressed(1f64, 0f64, 0f64); /// // Returns Roots::One([0f64]) as 'x^4 = 0' has one root 0 /// /// let two_roots = find_roots_quartic_depressed(1f32, 0f32, -1f32); /// // Returns Roots::Two([-1f32, 1f32]) as 'x^4 - 1 = 0' has roots -1 and 1 /// ``` pub fn find_roots_quartic_depressed<F: FloatType>(a2: F, a1: F, a0: F) -> Roots<F> { // Handle non-standard cases if a1 == F::zero() { // a1 = 0; x^4 + a2*x^2 + a0 = 0; solve biquadratic equation super::biquadratic::find_roots_biquadratic(F::one(), a2, a0) } else if a0 == F::zero() { // a0 = 0; x^4 + a2*x^2 + a1*x = 0; reduce to normalized cubic and add zero root super::cubic_normalized::find_roots_cubic_normalized(F::zero(), a2, a1).add_new_root(F::zero()) } else { let _2 = F::from(2i16); let _5 = F::from(5i16); // Solve the auxiliary equation y^3 + (5/2)*a2*y^2 + (2*a2^2-a0)*y + (a2^3/2 - a2*a0/2 - a1^2/8) = 0 let a2_pow_2 = a2 * a2; let a1_div_2 = a1 / _2; let b2 = a2 * _5 / _2; let b1 = _2 * a2_pow_2 - a0; let b0 = (a2_pow_2 * a2 - a2 * a0 - a1_div_2 * a1_div_2) / _2; // At least one root always exists. The last root is the maximal one. let resolvent_roots = super::cubic_normalized::find_roots_cubic_normalized(b2, b1, b0); let y = resolvent_roots.as_ref().iter().last().unwrap(); let _a2_plus_2y = a2 + _2 * *y; if _a2_plus_2y > F::zero() { let sqrt_a2_plus_2y = _a2_plus_2y.sqrt(); let q0a = a2 + *y - a1_div_2 / sqrt_a2_plus_2y; let q0b = a2 + *y + a1_div_2 / sqrt_a2_plus_2y; let mut roots = super::quadratic::find_roots_quadratic(F::one(), sqrt_a2_plus_2y, q0a); for x in super::quadratic::find_roots_quadratic(F::one(), -sqrt_a2_plus_2y, q0b) .as_ref() .iter() { roots = roots.add_new_root(*x); } roots } else { Roots::No([]) } } } #[cfg(test)] mod test { use super::super::super::*; #[test] fn
() { assert_eq!(find_roots_quartic_depressed(0f32, 0f32, 0f32), Roots::One([0f32])); assert_eq!(find_roots_quartic_depressed(1f32, 1f32, 1f32), Roots::No([])); // Thanks WolframAlpha for the test data match find_roots_quartic_depressed(1f64, 1f64, -1f64) { Roots::Two(x) => { assert_float_array_eq!(1e-15, x, [-1f64, 0.5698402909980532659114f64]); } _ => { assert!(false); } } match find_roots_quartic_depressed(-10f64, 5f64, 1f64) { Roots::Four(x) => { assert_float_array_eq!( 1e-15, x, [ -3.3754294311910698f64, -0.1531811728532153f64, 0.67861075799846644f64, 2.84999984604581877f64 ] ); } _ => { assert!(false); } } } }
test_find_roots_quartic_depressed
identifier_name
quartic_depressed.rs
// Copyright (c) 2015, Mikhail Vorotilov // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use super::super::FloatType; use super::super::Roots; /// Solves a depressed quartic equation x^4 + a2*x^2 + a1*x + a0 = 0. /// /// Returned roots are ordered. Precision is about 1e-14 for f64. /// /// # Examples /// /// ``` /// use roots::find_roots_quartic_depressed; /// /// let one_root = find_roots_quartic_depressed(1f64, 0f64, 0f64); /// // Returns Roots::One([0f64]) as 'x^4 = 0' has one root 0 /// /// let two_roots = find_roots_quartic_depressed(1f32, 0f32, -1f32); /// // Returns Roots::Two([-1f32, 1f32]) as 'x^4 - 1 = 0' has roots -1 and 1 /// ``` pub fn find_roots_quartic_depressed<F: FloatType>(a2: F, a1: F, a0: F) -> Roots<F>
let resolvent_roots = super::cubic_normalized::find_roots_cubic_normalized(b2, b1, b0); let y = resolvent_roots.as_ref().iter().last().unwrap(); let _a2_plus_2y = a2 + _2 * *y; if _a2_plus_2y > F::zero() { let sqrt_a2_plus_2y = _a2_plus_2y.sqrt(); let q0a = a2 + *y - a1_div_2 / sqrt_a2_plus_2y; let q0b = a2 + *y + a1_div_2 / sqrt_a2_plus_2y; let mut roots = super::quadratic::find_roots_quadratic(F::one(), sqrt_a2_plus_2y, q0a); for x in super::quadratic::find_roots_quadratic(F::one(), -sqrt_a2_plus_2y, q0b) .as_ref() .iter() { roots = roots.add_new_root(*x); } roots } else { Roots::No([]) } } } #[cfg(test)] mod test { use super::super::super::*; #[test] fn test_find_roots_quartic_depressed() { assert_eq!(find_roots_quartic_depressed(0f32, 0f32, 0f32), Roots::One([0f32])); assert_eq!(find_roots_quartic_depressed(1f32, 1f32, 1f32), Roots::No([])); // Thanks WolframAlpha for the test data match find_roots_quartic_depressed(1f64, 1f64, -1f64) { Roots::Two(x) => { assert_float_array_eq!(1e-15, x, [-1f64, 0.5698402909980532659114f64]); } _ => { assert!(false); } } match find_roots_quartic_depressed(-10f64, 5f64, 1f64) { Roots::Four(x) => { assert_float_array_eq!( 1e-15, x, [ -3.3754294311910698f64, -0.1531811728532153f64, 0.67861075799846644f64, 2.84999984604581877f64 ] ); } _ => { assert!(false); } } } }
{ // Handle non-standard cases if a1 == F::zero() { // a1 = 0; x^4 + a2*x^2 + a0 = 0; solve biquadratic equation super::biquadratic::find_roots_biquadratic(F::one(), a2, a0) } else if a0 == F::zero() { // a0 = 0; x^4 + a2*x^2 + a1*x = 0; reduce to normalized cubic and add zero root super::cubic_normalized::find_roots_cubic_normalized(F::zero(), a2, a1).add_new_root(F::zero()) } else { let _2 = F::from(2i16); let _5 = F::from(5i16); // Solve the auxiliary equation y^3 + (5/2)*a2*y^2 + (2*a2^2-a0)*y + (a2^3/2 - a2*a0/2 - a1^2/8) = 0 let a2_pow_2 = a2 * a2; let a1_div_2 = a1 / _2; let b2 = a2 * _5 / _2; let b1 = _2 * a2_pow_2 - a0; let b0 = (a2_pow_2 * a2 - a2 * a0 - a1_div_2 * a1_div_2) / _2; // At least one root always exists. The last root is the maximal one.
identifier_body
quartic_depressed.rs
// Copyright (c) 2015, Mikhail Vorotilov // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use super::super::FloatType; use super::super::Roots; /// Solves a depressed quartic equation x^4 + a2*x^2 + a1*x + a0 = 0. /// /// Returned roots are ordered. Precision is about 1e-14 for f64. /// /// # Examples /// /// ``` /// use roots::find_roots_quartic_depressed; /// /// let one_root = find_roots_quartic_depressed(1f64, 0f64, 0f64); /// // Returns Roots::One([0f64]) as 'x^4 = 0' has one root 0 /// /// let two_roots = find_roots_quartic_depressed(1f32, 0f32, -1f32); /// // Returns Roots::Two([-1f32, 1f32]) as 'x^4 - 1 = 0' has roots -1 and 1 /// ``` pub fn find_roots_quartic_depressed<F: FloatType>(a2: F, a1: F, a0: F) -> Roots<F> { // Handle non-standard cases if a1 == F::zero() { // a1 = 0; x^4 + a2*x^2 + a0 = 0; solve biquadratic equation super::biquadratic::find_roots_biquadratic(F::one(), a2, a0) } else if a0 == F::zero() { // a0 = 0; x^4 + a2*x^2 + a1*x = 0; reduce to normalized cubic and add zero root super::cubic_normalized::find_roots_cubic_normalized(F::zero(), a2, a1).add_new_root(F::zero()) } else { let _2 = F::from(2i16); let _5 = F::from(5i16); // Solve the auxiliary equation y^3 + (5/2)*a2*y^2 + (2*a2^2-a0)*y + (a2^3/2 - a2*a0/2 - a1^2/8) = 0 let a2_pow_2 = a2 * a2; let a1_div_2 = a1 / _2; let b2 = a2 * _5 / _2; let b1 = _2 * a2_pow_2 - a0; let b0 = (a2_pow_2 * a2 - a2 * a0 - a1_div_2 * a1_div_2) / _2; // At least one root always exists. The last root is the maximal one. let resolvent_roots = super::cubic_normalized::find_roots_cubic_normalized(b2, b1, b0); let y = resolvent_roots.as_ref().iter().last().unwrap(); let _a2_plus_2y = a2 + _2 * *y; if _a2_plus_2y > F::zero() { let sqrt_a2_plus_2y = _a2_plus_2y.sqrt(); let q0a = a2 + *y - a1_div_2 / sqrt_a2_plus_2y; let q0b = a2 + *y + a1_div_2 / sqrt_a2_plus_2y; let mut roots = super::quadratic::find_roots_quadratic(F::one(), sqrt_a2_plus_2y, q0a); for x in super::quadratic::find_roots_quadratic(F::one(), -sqrt_a2_plus_2y, q0b) .as_ref() .iter() { roots = roots.add_new_root(*x); } roots } else { Roots::No([]) } } } #[cfg(test)] mod test { use super::super::super::*;
fn test_find_roots_quartic_depressed() { assert_eq!(find_roots_quartic_depressed(0f32, 0f32, 0f32), Roots::One([0f32])); assert_eq!(find_roots_quartic_depressed(1f32, 1f32, 1f32), Roots::No([])); // Thanks WolframAlpha for the test data match find_roots_quartic_depressed(1f64, 1f64, -1f64) { Roots::Two(x) => { assert_float_array_eq!(1e-15, x, [-1f64, 0.5698402909980532659114f64]); } _ => { assert!(false); } } match find_roots_quartic_depressed(-10f64, 5f64, 1f64) { Roots::Four(x) => { assert_float_array_eq!( 1e-15, x, [ -3.3754294311910698f64, -0.1531811728532153f64, 0.67861075799846644f64, 2.84999984604581877f64 ] ); } _ => { assert!(false); } } } }
#[test]
random_line_split
quartic_depressed.rs
// Copyright (c) 2015, Mikhail Vorotilov // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use super::super::FloatType; use super::super::Roots; /// Solves a depressed quartic equation x^4 + a2*x^2 + a1*x + a0 = 0. /// /// Returned roots are ordered. Precision is about 1e-14 for f64. /// /// # Examples /// /// ``` /// use roots::find_roots_quartic_depressed; /// /// let one_root = find_roots_quartic_depressed(1f64, 0f64, 0f64); /// // Returns Roots::One([0f64]) as 'x^4 = 0' has one root 0 /// /// let two_roots = find_roots_quartic_depressed(1f32, 0f32, -1f32); /// // Returns Roots::Two([-1f32, 1f32]) as 'x^4 - 1 = 0' has roots -1 and 1 /// ``` pub fn find_roots_quartic_depressed<F: FloatType>(a2: F, a1: F, a0: F) -> Roots<F> { // Handle non-standard cases if a1 == F::zero()
else if a0 == F::zero() { // a0 = 0; x^4 + a2*x^2 + a1*x = 0; reduce to normalized cubic and add zero root super::cubic_normalized::find_roots_cubic_normalized(F::zero(), a2, a1).add_new_root(F::zero()) } else { let _2 = F::from(2i16); let _5 = F::from(5i16); // Solve the auxiliary equation y^3 + (5/2)*a2*y^2 + (2*a2^2-a0)*y + (a2^3/2 - a2*a0/2 - a1^2/8) = 0 let a2_pow_2 = a2 * a2; let a1_div_2 = a1 / _2; let b2 = a2 * _5 / _2; let b1 = _2 * a2_pow_2 - a0; let b0 = (a2_pow_2 * a2 - a2 * a0 - a1_div_2 * a1_div_2) / _2; // At least one root always exists. The last root is the maximal one. let resolvent_roots = super::cubic_normalized::find_roots_cubic_normalized(b2, b1, b0); let y = resolvent_roots.as_ref().iter().last().unwrap(); let _a2_plus_2y = a2 + _2 * *y; if _a2_plus_2y > F::zero() { let sqrt_a2_plus_2y = _a2_plus_2y.sqrt(); let q0a = a2 + *y - a1_div_2 / sqrt_a2_plus_2y; let q0b = a2 + *y + a1_div_2 / sqrt_a2_plus_2y; let mut roots = super::quadratic::find_roots_quadratic(F::one(), sqrt_a2_plus_2y, q0a); for x in super::quadratic::find_roots_quadratic(F::one(), -sqrt_a2_plus_2y, q0b) .as_ref() .iter() { roots = roots.add_new_root(*x); } roots } else { Roots::No([]) } } } #[cfg(test)] mod test { use super::super::super::*; #[test] fn test_find_roots_quartic_depressed() { assert_eq!(find_roots_quartic_depressed(0f32, 0f32, 0f32), Roots::One([0f32])); assert_eq!(find_roots_quartic_depressed(1f32, 1f32, 1f32), Roots::No([])); // Thanks WolframAlpha for the test data match find_roots_quartic_depressed(1f64, 1f64, -1f64) { Roots::Two(x) => { assert_float_array_eq!(1e-15, x, [-1f64, 0.5698402909980532659114f64]); } _ => { assert!(false); } } match find_roots_quartic_depressed(-10f64, 5f64, 1f64) { Roots::Four(x) => { assert_float_array_eq!( 1e-15, x, [ -3.3754294311910698f64, -0.1531811728532153f64, 0.67861075799846644f64, 2.84999984604581877f64 ] ); } _ => { assert!(false); } } } }
{ // a1 = 0; x^4 + a2*x^2 + a0 = 0; solve biquadratic equation super::biquadratic::find_roots_biquadratic(F::one(), a2, a0) }
conditional_block
issue-17718.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(const_fn)] use std::sync::atomic; pub const C1: usize = 1; pub const C2: atomic::AtomicUsize = atomic::AtomicUsize::new(0); pub const C3: fn() = foo; pub const C4: usize = C1 * C1 + C1 / C1; pub const C5: &'static usize = &C4; pub static S1: usize = 3; pub static S2: atomic::AtomicUsize = atomic::AtomicUsize::new(0); fn
() {}
foo
identifier_name
issue-17718.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(const_fn)] use std::sync::atomic; pub const C1: usize = 1; pub const C2: atomic::AtomicUsize = atomic::AtomicUsize::new(0); pub const C3: fn() = foo; pub const C4: usize = C1 * C1 + C1 / C1; pub const C5: &'static usize = &C4; pub static S1: usize = 3; pub static S2: atomic::AtomicUsize = atomic::AtomicUsize::new(0); fn foo()
{}
identifier_body
issue-17718.rs
// 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. #![feature(const_fn)] use std::sync::atomic; pub const C1: usize = 1; pub const C2: atomic::AtomicUsize = atomic::AtomicUsize::new(0); pub const C3: fn() = foo; pub const C4: usize = C1 * C1 + C1 / C1; pub const C5: &'static usize = &C4; pub static S1: usize = 3; pub static S2: atomic::AtomicUsize = atomic::AtomicUsize::new(0); fn foo() {}
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
random_line_split
lib.rs
extern crate byteorder; extern crate encoding; #[macro_use] extern crate log; use std::io::{Read, Write}; use std::io; /// PC crypto. Used by patch server on BB as well. The Dreamcast and /// PC versions share this crypto. pub mod pc; /// Blue Burst-specific crypto. A lot more complex than PC and GC. pub mod bb; /// Gamecube games' crypto. PSO Episodes 1 & 2 and Episode 3 use /// this crypto algorithm. pub mod gc; pub use self::bb::BbCipher; pub use self::pc::PcCipher; pub trait Encryptor { fn encrypt(&mut self, input: &[u8], output: &mut [u8]) -> Result<(), String>; fn encrypt_in_place(&mut self, buf: &mut [u8]) -> Result<(), String> { let temp = buf.to_vec(); self.encrypt(&temp, buf) } } pub trait Decryptor { fn decrypt(&mut self, input: &[u8], output: &mut [u8]) -> Result<(), String>; fn decrypt_in_place(&mut self, buf: &mut [u8]) -> Result<(), String> { let temp = buf.to_vec(); self.decrypt(&temp, buf) } } pub struct DecryptReader<R: Read, D: Decryptor> { r: R, d: D } impl<R: Read, D: Decryptor> DecryptReader<R, D> { pub fn new(read: R, decrypt: D) -> Self { DecryptReader { r: read, d: decrypt } } pub fn into_inner(self) -> R { self.r } } impl<R: Read, D: Decryptor> Read for DecryptReader<R, D> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let mut int_buf = vec![0u8; buf.len()]; let bytes_read = try!(self.r.read(&mut int_buf[..])); // decrypt into output buffer if let Err(e) = self.d.decrypt(&int_buf[..bytes_read], &mut buf[..bytes_read]) { return Err(io::Error::new(io::ErrorKind::Other, e)) } Ok(bytes_read) } } pub struct EncryptWriter<W: Write, E: Encryptor> { w: W, e: E } impl<W: Write, E: Encryptor> EncryptWriter<W, E> { pub fn new(write: W, encrypt: E) -> Self { EncryptWriter { w: write, e: encrypt } } pub fn into_inner(self) -> W { self.w } } impl<W: Write, E: Encryptor> Write for EncryptWriter<W, E> { fn
(&mut self, buf: &[u8]) -> io::Result<usize> { let mut int_buf = vec![0u8; buf.len()]; // encrypt into int buffer if let Err(e) = self.e.encrypt(buf, &mut int_buf[..]) { return Err(io::Error::new(io::ErrorKind::Other, e)) } try!(self.w.write_all(&int_buf[..])); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { self.w.flush() } }
write
identifier_name
lib.rs
extern crate byteorder; extern crate encoding; #[macro_use] extern crate log; use std::io::{Read, Write}; use std::io; /// PC crypto. Used by patch server on BB as well. The Dreamcast and /// PC versions share this crypto. pub mod pc; /// Blue Burst-specific crypto. A lot more complex than PC and GC. pub mod bb; /// Gamecube games' crypto. PSO Episodes 1 & 2 and Episode 3 use /// this crypto algorithm. pub mod gc; pub use self::bb::BbCipher; pub use self::pc::PcCipher; pub trait Encryptor { fn encrypt(&mut self, input: &[u8], output: &mut [u8]) -> Result<(), String>; fn encrypt_in_place(&mut self, buf: &mut [u8]) -> Result<(), String> { let temp = buf.to_vec(); self.encrypt(&temp, buf) } } pub trait Decryptor { fn decrypt(&mut self, input: &[u8], output: &mut [u8]) -> Result<(), String>; fn decrypt_in_place(&mut self, buf: &mut [u8]) -> Result<(), String> { let temp = buf.to_vec(); self.decrypt(&temp, buf) } } pub struct DecryptReader<R: Read, D: Decryptor> { r: R, d: D } impl<R: Read, D: Decryptor> DecryptReader<R, D> { pub fn new(read: R, decrypt: D) -> Self { DecryptReader { r: read, d: decrypt } } pub fn into_inner(self) -> R { self.r } } impl<R: Read, D: Decryptor> Read for DecryptReader<R, D> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let mut int_buf = vec![0u8; buf.len()]; let bytes_read = try!(self.r.read(&mut int_buf[..])); // decrypt into output buffer if let Err(e) = self.d.decrypt(&int_buf[..bytes_read], &mut buf[..bytes_read]) { return Err(io::Error::new(io::ErrorKind::Other, e)) } Ok(bytes_read) } } pub struct EncryptWriter<W: Write, E: Encryptor> { w: W, e: E } impl<W: Write, E: Encryptor> EncryptWriter<W, E> { pub fn new(write: W, encrypt: E) -> Self { EncryptWriter { w: write, e: encrypt } } pub fn into_inner(self) -> W { self.w } } impl<W: Write, E: Encryptor> Write for EncryptWriter<W, E> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let mut int_buf = vec![0u8; buf.len()]; // encrypt into int buffer if let Err(e) = self.e.encrypt(buf, &mut int_buf[..])
try!(self.w.write_all(&int_buf[..])); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { self.w.flush() } }
{ return Err(io::Error::new(io::ErrorKind::Other, e)) }
conditional_block
lib.rs
extern crate byteorder; extern crate encoding; #[macro_use] extern crate log; use std::io::{Read, Write}; use std::io; /// PC crypto. Used by patch server on BB as well. The Dreamcast and /// PC versions share this crypto. pub mod pc; /// Blue Burst-specific crypto. A lot more complex than PC and GC. pub mod bb; /// Gamecube games' crypto. PSO Episodes 1 & 2 and Episode 3 use /// this crypto algorithm. pub mod gc; pub use self::bb::BbCipher; pub use self::pc::PcCipher; pub trait Encryptor { fn encrypt(&mut self, input: &[u8], output: &mut [u8]) -> Result<(), String>; fn encrypt_in_place(&mut self, buf: &mut [u8]) -> Result<(), String> { let temp = buf.to_vec(); self.encrypt(&temp, buf) } } pub trait Decryptor {
} } pub struct DecryptReader<R: Read, D: Decryptor> { r: R, d: D } impl<R: Read, D: Decryptor> DecryptReader<R, D> { pub fn new(read: R, decrypt: D) -> Self { DecryptReader { r: read, d: decrypt } } pub fn into_inner(self) -> R { self.r } } impl<R: Read, D: Decryptor> Read for DecryptReader<R, D> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let mut int_buf = vec![0u8; buf.len()]; let bytes_read = try!(self.r.read(&mut int_buf[..])); // decrypt into output buffer if let Err(e) = self.d.decrypt(&int_buf[..bytes_read], &mut buf[..bytes_read]) { return Err(io::Error::new(io::ErrorKind::Other, e)) } Ok(bytes_read) } } pub struct EncryptWriter<W: Write, E: Encryptor> { w: W, e: E } impl<W: Write, E: Encryptor> EncryptWriter<W, E> { pub fn new(write: W, encrypt: E) -> Self { EncryptWriter { w: write, e: encrypt } } pub fn into_inner(self) -> W { self.w } } impl<W: Write, E: Encryptor> Write for EncryptWriter<W, E> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let mut int_buf = vec![0u8; buf.len()]; // encrypt into int buffer if let Err(e) = self.e.encrypt(buf, &mut int_buf[..]) { return Err(io::Error::new(io::ErrorKind::Other, e)) } try!(self.w.write_all(&int_buf[..])); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { self.w.flush() } }
fn decrypt(&mut self, input: &[u8], output: &mut [u8]) -> Result<(), String>; fn decrypt_in_place(&mut self, buf: &mut [u8]) -> Result<(), String> { let temp = buf.to_vec(); self.decrypt(&temp, buf)
random_line_split
rpn.rs
//! Uses RPN expression extern crate rand; fn main() { use rand::Rng; use std::io::{self, Write}; let mut rng = rand::thread_rng(); let stdin = io::stdin(); let mut stdout = io::stdout(); // generating 4 numbers let choices: Vec<u32> = (0..4).map(|_| rng.gen_range(1, 10)).collect(); println!("Make 24 with the following numbers"); // start the game loop let mut buffer = String::new(); loop { println!( "Your numbers: {}, {}, {}, {}", choices[0], choices[1], choices[2], choices[3] ); buffer.clear(); stdin.read_line(&mut buffer).expect("Failed to read line!"); match check_input(&buffer[..], &choices[..]) { Ok(()) => { println!("Good job!"); break; } Err(e) => println!("{}", e), } print!("Try again? (y/n): "); stdout.flush().unwrap(); buffer.clear(); stdin.read_line(&mut buffer).expect("Failed to read line!"); if buffer.trim()!= "y" { break; } } } fn check_input(expr: &str, choices: &[u32]) -> Result<(), String> { let mut stack: Vec<u32> = Vec::new(); for token in expr.split_whitespace() { if is_operator(token) { let (a, b) = (stack.pop(), stack.pop()); match (a, b) { (Some(x), Some(y)) => stack.push(evaluate(y, x, token)), (_, _) => return Err("Not a valid RPN expression!".to_string()), } } else { match token.parse::<u32>() { Ok(n) => { // check if the number is valid if!choices.contains(&n) { return Err(format!("Cannot use {}", n)); } stack.push(n) } Err(_) => return Err(format!("Invalid input: {}", token)), } } } let ans = stack.pop(); if!stack.is_empty() { return Err("Not a valid RPN expression!".to_string()); } match ans { Some(x) if x == 24 => Ok(()), Some(x) => Err(format!("Wrong answer. Result: {}", x)), None => Err("Error encountered!".to_string()), } } fn evaluate(a: u32, b: u32, op: &str) -> u32 { match op { "+" => a + b, "-" => a - b, "*" => a * b, "/" => a / b, _ => unreachable!(), } } fn is_operator(op: &str) -> bool { ["*", "-", "+", "/"].contains(&op) } #[cfg(tests)] mod tests { const v1: [u32; 4] = [4u32, 3, 6, 2]; #[test] fn correct_result() { assert_eq!(check_input("4 3 * 6 2 * +", &v1), Ok(())); } #[test] fn incorrect_result()
#[test] fn wrong_numbers_in_input() { assert_eq!( check_input("4 5 + 6 2 * -", &v1), Err("Cannot use 5".to_string()) ); } #[test] fn invalid_chars_in_input() { assert_eq!( check_input("4 ) + _ 2 * -", &v1), Err("Invalid input: )".to_string()) ); } fn invalid_rpn_expression() { assert_eq!( check_input("4 3 + 6 2 *", &v1), Err("Not a valid RPN expression!".to_string()) ); } }
{ assert_eq!( check_input("4 3 * 2 6 + -", &v1), Err("Wrong answer. Result: 4".to_string()) ); }
identifier_body
rpn.rs
//! Uses RPN expression extern crate rand; fn main() { use rand::Rng; use std::io::{self, Write}; let mut rng = rand::thread_rng(); let stdin = io::stdin(); let mut stdout = io::stdout(); // generating 4 numbers let choices: Vec<u32> = (0..4).map(|_| rng.gen_range(1, 10)).collect(); println!("Make 24 with the following numbers"); // start the game loop let mut buffer = String::new(); loop { println!( "Your numbers: {}, {}, {}, {}", choices[0], choices[1], choices[2], choices[3] ); buffer.clear();
stdin.read_line(&mut buffer).expect("Failed to read line!"); match check_input(&buffer[..], &choices[..]) { Ok(()) => { println!("Good job!"); break; } Err(e) => println!("{}", e), } print!("Try again? (y/n): "); stdout.flush().unwrap(); buffer.clear(); stdin.read_line(&mut buffer).expect("Failed to read line!"); if buffer.trim()!= "y" { break; } } } fn check_input(expr: &str, choices: &[u32]) -> Result<(), String> { let mut stack: Vec<u32> = Vec::new(); for token in expr.split_whitespace() { if is_operator(token) { let (a, b) = (stack.pop(), stack.pop()); match (a, b) { (Some(x), Some(y)) => stack.push(evaluate(y, x, token)), (_, _) => return Err("Not a valid RPN expression!".to_string()), } } else { match token.parse::<u32>() { Ok(n) => { // check if the number is valid if!choices.contains(&n) { return Err(format!("Cannot use {}", n)); } stack.push(n) } Err(_) => return Err(format!("Invalid input: {}", token)), } } } let ans = stack.pop(); if!stack.is_empty() { return Err("Not a valid RPN expression!".to_string()); } match ans { Some(x) if x == 24 => Ok(()), Some(x) => Err(format!("Wrong answer. Result: {}", x)), None => Err("Error encountered!".to_string()), } } fn evaluate(a: u32, b: u32, op: &str) -> u32 { match op { "+" => a + b, "-" => a - b, "*" => a * b, "/" => a / b, _ => unreachable!(), } } fn is_operator(op: &str) -> bool { ["*", "-", "+", "/"].contains(&op) } #[cfg(tests)] mod tests { const v1: [u32; 4] = [4u32, 3, 6, 2]; #[test] fn correct_result() { assert_eq!(check_input("4 3 * 6 2 * +", &v1), Ok(())); } #[test] fn incorrect_result() { assert_eq!( check_input("4 3 * 2 6 + -", &v1), Err("Wrong answer. Result: 4".to_string()) ); } #[test] fn wrong_numbers_in_input() { assert_eq!( check_input("4 5 + 6 2 * -", &v1), Err("Cannot use 5".to_string()) ); } #[test] fn invalid_chars_in_input() { assert_eq!( check_input("4 ) + _ 2 * -", &v1), Err("Invalid input: )".to_string()) ); } fn invalid_rpn_expression() { assert_eq!( check_input("4 3 + 6 2 *", &v1), Err("Not a valid RPN expression!".to_string()) ); } }
random_line_split
rpn.rs
//! Uses RPN expression extern crate rand; fn main() { use rand::Rng; use std::io::{self, Write}; let mut rng = rand::thread_rng(); let stdin = io::stdin(); let mut stdout = io::stdout(); // generating 4 numbers let choices: Vec<u32> = (0..4).map(|_| rng.gen_range(1, 10)).collect(); println!("Make 24 with the following numbers"); // start the game loop let mut buffer = String::new(); loop { println!( "Your numbers: {}, {}, {}, {}", choices[0], choices[1], choices[2], choices[3] ); buffer.clear(); stdin.read_line(&mut buffer).expect("Failed to read line!"); match check_input(&buffer[..], &choices[..]) { Ok(()) => { println!("Good job!"); break; } Err(e) => println!("{}", e), } print!("Try again? (y/n): "); stdout.flush().unwrap(); buffer.clear(); stdin.read_line(&mut buffer).expect("Failed to read line!"); if buffer.trim()!= "y" { break; } } } fn check_input(expr: &str, choices: &[u32]) -> Result<(), String> { let mut stack: Vec<u32> = Vec::new(); for token in expr.split_whitespace() { if is_operator(token) { let (a, b) = (stack.pop(), stack.pop()); match (a, b) { (Some(x), Some(y)) => stack.push(evaluate(y, x, token)), (_, _) => return Err("Not a valid RPN expression!".to_string()), } } else { match token.parse::<u32>() { Ok(n) => { // check if the number is valid if!choices.contains(&n) { return Err(format!("Cannot use {}", n)); } stack.push(n) } Err(_) => return Err(format!("Invalid input: {}", token)), } } } let ans = stack.pop(); if!stack.is_empty()
match ans { Some(x) if x == 24 => Ok(()), Some(x) => Err(format!("Wrong answer. Result: {}", x)), None => Err("Error encountered!".to_string()), } } fn evaluate(a: u32, b: u32, op: &str) -> u32 { match op { "+" => a + b, "-" => a - b, "*" => a * b, "/" => a / b, _ => unreachable!(), } } fn is_operator(op: &str) -> bool { ["*", "-", "+", "/"].contains(&op) } #[cfg(tests)] mod tests { const v1: [u32; 4] = [4u32, 3, 6, 2]; #[test] fn correct_result() { assert_eq!(check_input("4 3 * 6 2 * +", &v1), Ok(())); } #[test] fn incorrect_result() { assert_eq!( check_input("4 3 * 2 6 + -", &v1), Err("Wrong answer. Result: 4".to_string()) ); } #[test] fn wrong_numbers_in_input() { assert_eq!( check_input("4 5 + 6 2 * -", &v1), Err("Cannot use 5".to_string()) ); } #[test] fn invalid_chars_in_input() { assert_eq!( check_input("4 ) + _ 2 * -", &v1), Err("Invalid input: )".to_string()) ); } fn invalid_rpn_expression() { assert_eq!( check_input("4 3 + 6 2 *", &v1), Err("Not a valid RPN expression!".to_string()) ); } }
{ return Err("Not a valid RPN expression!".to_string()); }
conditional_block
rpn.rs
//! Uses RPN expression extern crate rand; fn main() { use rand::Rng; use std::io::{self, Write}; let mut rng = rand::thread_rng(); let stdin = io::stdin(); let mut stdout = io::stdout(); // generating 4 numbers let choices: Vec<u32> = (0..4).map(|_| rng.gen_range(1, 10)).collect(); println!("Make 24 with the following numbers"); // start the game loop let mut buffer = String::new(); loop { println!( "Your numbers: {}, {}, {}, {}", choices[0], choices[1], choices[2], choices[3] ); buffer.clear(); stdin.read_line(&mut buffer).expect("Failed to read line!"); match check_input(&buffer[..], &choices[..]) { Ok(()) => { println!("Good job!"); break; } Err(e) => println!("{}", e), } print!("Try again? (y/n): "); stdout.flush().unwrap(); buffer.clear(); stdin.read_line(&mut buffer).expect("Failed to read line!"); if buffer.trim()!= "y" { break; } } } fn
(expr: &str, choices: &[u32]) -> Result<(), String> { let mut stack: Vec<u32> = Vec::new(); for token in expr.split_whitespace() { if is_operator(token) { let (a, b) = (stack.pop(), stack.pop()); match (a, b) { (Some(x), Some(y)) => stack.push(evaluate(y, x, token)), (_, _) => return Err("Not a valid RPN expression!".to_string()), } } else { match token.parse::<u32>() { Ok(n) => { // check if the number is valid if!choices.contains(&n) { return Err(format!("Cannot use {}", n)); } stack.push(n) } Err(_) => return Err(format!("Invalid input: {}", token)), } } } let ans = stack.pop(); if!stack.is_empty() { return Err("Not a valid RPN expression!".to_string()); } match ans { Some(x) if x == 24 => Ok(()), Some(x) => Err(format!("Wrong answer. Result: {}", x)), None => Err("Error encountered!".to_string()), } } fn evaluate(a: u32, b: u32, op: &str) -> u32 { match op { "+" => a + b, "-" => a - b, "*" => a * b, "/" => a / b, _ => unreachable!(), } } fn is_operator(op: &str) -> bool { ["*", "-", "+", "/"].contains(&op) } #[cfg(tests)] mod tests { const v1: [u32; 4] = [4u32, 3, 6, 2]; #[test] fn correct_result() { assert_eq!(check_input("4 3 * 6 2 * +", &v1), Ok(())); } #[test] fn incorrect_result() { assert_eq!( check_input("4 3 * 2 6 + -", &v1), Err("Wrong answer. Result: 4".to_string()) ); } #[test] fn wrong_numbers_in_input() { assert_eq!( check_input("4 5 + 6 2 * -", &v1), Err("Cannot use 5".to_string()) ); } #[test] fn invalid_chars_in_input() { assert_eq!( check_input("4 ) + _ 2 * -", &v1), Err("Invalid input: )".to_string()) ); } fn invalid_rpn_expression() { assert_eq!( check_input("4 3 + 6 2 *", &v1), Err("Not a valid RPN expression!".to_string()) ); } }
check_input
identifier_name
lib.rs
where `t! r` //! is the protocol "send something of type `t` then proceed with //! protocol `r`", the protocol `t? r` is "receive something of type `t` then proceed //! with protocol `r`, and `eps` is a special marker indicating the end of a //! communication session. //! //! Our session type library allows the user to create channels that adhere to a //! specified protocol. For example, a channel like the above would have the type //! `Chan<(), Send<i64, Recv<bool, Eps>>>`, and the full program could look like this: //! //! ``` //! extern crate session_types; //! use session_types::*; //! //! type Server = Recv<i64, Send<bool, Eps>>; //! type Client = Send<i64, Recv<bool, Eps>>; //! //! fn srv(c: Chan<(), Server>) { //! let (c, n) = c.recv(); //! if n % 2 == 0 { //! c.send(true).close() //! } else { //! c.send(false).close() //! } //! } //! //! fn cli(c: Chan<(), Client>) { //! let n = 42; //! let c = c.send(n); //! let (c, b) = c.recv(); //! //! if b { //! println!("{} is even", n); //! } else { //! println!("{} is odd", n); //! } //! //! c.close(); //! } //! //! fn main() { //! connect(srv, cli); //! } //! ``` #![cfg_attr(feature = "cargo-clippy", allow(clippy::double_must_use))] #![cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] extern crate crossbeam_channel; use std::marker::PhantomData; use std::thread::spawn; use std::{marker, mem, ptr}; use std::collections::HashMap; use crossbeam_channel::{unbounded, Receiver, Sender}; use crossbeam_channel::Select; pub use Branch::*; /// A session typed channel. `P` is the protocol and `E` is the environment, /// containing potential recursion targets #[must_use] pub struct Chan<E, P>(Sender<*mut u8>, Receiver<*mut u8>, PhantomData<(E, P)>); unsafe impl<E: marker::Send, P: marker::Send> marker::Send for Chan<E, P> {} unsafe fn write_chan<A: marker::Send +'static, E, P>(&Chan(ref tx, _, _): &Chan<E, P>, x: A) { tx.send(Box::into_raw(Box::new(x)) as *mut _).unwrap() } unsafe fn read_chan<A: marker::Send +'static, E, P>(&Chan(_, ref rx, _): &Chan<E, P>) -> A { *Box::from_raw(rx.recv().unwrap() as *mut A) } unsafe fn try_read_chan<A: marker::Send +'static, E, P>( &Chan(_, ref rx, _): &Chan<E, P>, ) -> Option<A> { match rx.try_recv() { Ok(a) => Some(*Box::from_raw(a as *mut A)), Err(_) => None, } } /// Peano numbers: Zero #[allow(missing_copy_implementations)] pub struct Z; /// Peano numbers: Increment pub struct S<N>(PhantomData<N>); /// End of communication session (epsilon) #[allow(missing_copy_implementations)] pub struct Eps; /// Receive `A`, then `P` pub struct Recv<A, P>(PhantomData<(A, P)>); /// Send `A`, then `P` pub struct Send<A, P>(PhantomData<(A, P)>); /// Active choice between `P` and `Q` pub struct Choose<P, Q>(PhantomData<(P, Q)>); /// Passive choice (offer) between `P` and `Q` pub struct Offer<P, Q>(PhantomData<(P, Q)>); /// Enter a recursive environment pub struct Rec<P>(PhantomData<P>); /// Recurse. N indicates how many layers of the recursive environment we recurse /// out of. pub struct Var<N>(PhantomData<N>); /// The HasDual trait defines the dual relationship between protocols. /// /// Any valid protocol has a corresponding dual. /// /// This trait is sealed and cannot be implemented outside of session-types pub trait HasDual: private::Sealed { type Dual; } impl HasDual for Eps { type Dual = Eps; } impl<A, P: HasDual> HasDual for Send<A, P> { type Dual = Recv<A, P::Dual>; } impl<A, P: HasDual> HasDual for Recv<A, P> { type Dual = Send<A, P::Dual>; } impl<P: HasDual, Q: HasDual> HasDual for Choose<P, Q> { type Dual = Offer<P::Dual, Q::Dual>; } impl<P: HasDual, Q: HasDual> HasDual for Offer<P, Q> { type Dual = Choose<P::Dual, Q::Dual>; } impl HasDual for Var<Z> { type Dual = Var<Z>; } impl<N> HasDual for Var<S<N>> { type Dual = Var<S<N>>; } impl<P: HasDual> HasDual for Rec<P> { type Dual = Rec<P::Dual>; } pub enum Branch<L, R> { Left(L), Right(R), } impl<E, P> Drop for Chan<E, P> { fn drop(&mut self) { panic!("Session channel prematurely dropped"); } } impl<E> Chan<E, Eps> { /// Close a channel. Should always be used at the end of your program. pub fn close(self) { // This method cleans up the channel without running the panicky destructor // In essence, it calls the drop glue bypassing the `Drop::drop` method let this = mem::ManuallyDrop::new(self); let sender = unsafe { ptr::read(&(this).0 as *const _) }; let receiver = unsafe { ptr::read(&(this).1 as *const _) }; drop(sender); drop(receiver); // drop them } } impl<E, P> Chan<E, P> { unsafe fn cast<E2, P2>(self) -> Chan<E2, P2> { let this = mem::ManuallyDrop::new(self); Chan( ptr::read(&(this).0 as *const _), ptr::read(&(this).1 as *const _), PhantomData, ) } } impl<E, P, A: marker::Send +'static> Chan<E, Send<A, P>> { /// Send a value of type `A` over the channel. Returns a channel with /// protocol `P` #[must_use] pub fn send(self, v: A) -> Chan<E, P> { unsafe { write_chan(&self, v); self.cast() } } } impl<E, P, A: marker::Send +'static> Chan<E, Recv<A, P>> { /// Receives a value of type `A` from the channel. Returns a tuple /// containing the resulting channel and the received value. #[must_use] pub fn recv(self) -> (Chan<E, P>, A) { unsafe { let v = read_chan(&self); (self.cast(), v) } } /// Non-blocking receive. #[must_use] pub fn try_recv(self) -> Result<(Chan<E, P>, A), Self> { unsafe { if let Some(v) = try_read_chan(&self) { Ok((self.cast(), v)) } else { Err(self) } } } } impl<E, P, Q> Chan<E, Choose<P, Q>> { /// Perform an active choice, selecting protocol `P`. #[must_use] pub fn sel1(self) -> Chan<E, P> { unsafe { write_chan(&self, true); self.cast() } } /// Perform an active choice, selecting protocol `Q`. #[must_use] pub fn sel2(self) -> Chan<E, Q> { unsafe { write_chan(&self, false); self.cast() } } } /// Convenience function. This is identical to `.sel2()` impl<Z, A, B> Chan<Z, Choose<A, B>> { #[must_use] pub fn skip(self) -> Chan<Z, B> { self.sel2() } } /// Convenience function. This is identical to `.sel2().sel2()` impl<Z, A, B, C> Chan<Z, Choose<A, Choose<B, C>>> { #[must_use] pub fn skip2(self) -> Chan<Z, C> { self.sel2().sel2() } } /// Convenience function. This is identical to `.sel2().sel2().sel2()` impl<Z, A, B, C, D> Chan<Z, Choose<A, Choose<B, Choose<C, D>>>> { #[must_use] pub fn skip3(self) -> Chan<Z, D> { self.sel2().sel2().sel2() } } /// Convenience function. This is identical to `.sel2().sel2().sel2().sel2()` impl<Z, A, B, C, D, E> Chan<Z, Choose<A, Choose<B, Choose<C, Choose<D, E>>>>> { #[must_use] pub fn skip4(self) -> Chan<Z, E> { self.sel2().sel2().sel2().sel2() } } /// Convenience function. This is identical to `.sel2().sel2().sel2().sel2().sel2()` impl<Z, A, B, C, D, E, F> Chan<Z, Choose<A, Choose<B, Choose<C, Choose<D, Choose<E, F>>>>>> { #[must_use] pub fn skip5(self) -> Chan<Z, F> { self.sel2().sel2().sel2().sel2().sel2() } } /// Convenience function. impl<Z, A, B, C, D, E, F, G> Chan<Z, Choose<A, Choose<B, Choose<C, Choose<D, Choose<E, Choose<F, G>>>>>>> { #[must_use] pub fn skip6(self) -> Chan<Z, G> { self.sel2().sel2().sel2().sel2().sel2().sel2() } } /// Convenience function. impl<Z, A, B, C, D, E, F, G, H> Chan<Z, Choose<A, Choose<B, Choose<C, Choose<D, Choose<E, Choose<F, Choose<G, H>>>>>>>> { #[must_use] pub fn skip7(self) -> Chan<Z, H> { self.sel2().sel2().sel2().sel2().sel2().sel2().sel2() } } impl<E, P, Q> Chan<E, Offer<P, Q>> { /// Passive choice. This allows the other end of the channel to select one /// of two options for continuing the protocol: either `P` or `Q`. #[must_use] pub fn offer(self) -> Branch<Chan<E, P>, Chan<E, Q>> { unsafe { let b = read_chan(&self); if b { Left(self.cast()) } else { Right(self.cast()) } } } /// Poll for choice. #[must_use] pub fn try_offer(self) -> Result<Branch<Chan<E, P>, Chan<E, Q>>, Self> { unsafe { if let Some(b) = try_read_chan(&self) { if b
else { Ok(Right(self.cast())) } } else { Err(self) } } } } impl<E, P> Chan<E, Rec<P>> { /// Enter a recursive environment, putting the current environment on the /// top of the environment stack. #[must_use] pub fn enter(self) -> Chan<(P, E), P> { unsafe { self.cast() } } } impl<E, P> Chan<(P, E), Var<Z>> { /// Recurse to the environment on the top of the environment stack. #[must_use] pub fn zero(self) -> Chan<(P, E), P> { unsafe { self.cast() } } } impl<E, P, N> Chan<(P, E), Var<S<N>>> { /// Pop the top environment from the environment stack. #[must_use] pub fn succ(self) -> Chan<E, Var<N>> { unsafe { self.cast() } } } /// Homogeneous select. We have a vector of channels, all obeying the same /// protocol (and in the exact same point of the protocol), wait for one of them /// to receive. Removes the receiving channel from the vector and returns both /// the channel and the new vector. #[must_use] pub fn hselect<E, P, A>( mut chans: Vec<Chan<E, Recv<A, P>>>, ) -> (Chan<E, Recv<A, P>>, Vec<Chan<E, Recv<A, P>>>) { let i = iselect(&chans); let c = chans.remove(i); (c, chans) } /// An alternative version of homogeneous select, returning the index of the Chan /// that is ready to receive. pub fn iselect<E, P, A>(chans: &[Chan<E, Recv<A, P>>]) -> usize { let mut map = HashMap::new(); let id = { let mut sel = Select::new(); let mut handles = Vec::with_capacity(chans.len()); // collect all the handles for (i, chan) in chans.iter().enumerate() { let &Chan(_, ref rx, _) = chan; let handle = sel.recv(rx); map.insert(handle, i); handles.push(handle); } sel.ready() }; map.remove(&id).unwrap() } /// Heterogeneous selection structure for channels /// /// This builds a structure of channels that we wish to select over. This is /// structured in a way such that the channels selected over cannot be /// interacted with (consumed) as long as the borrowing ChanSelect object /// exists. This is necessary to ensure memory safety. /// /// The type parameter T is a return type, ie we store a value of some type T /// that is returned in case its associated channels is selected on `wait()` pub struct ChanSelect<'c> { receivers: Vec<&'c Receiver<*mut u8>>, } impl<'c> ChanSelect<'c> { pub fn new() -> ChanSelect<'c> { ChanSelect { receivers: Vec::new(), } } /// Add a channel whose next step is `Recv` /// /// Once a channel has been added it cannot be interacted with as long as it /// is borrowed here (by virtue of borrow checking and lifetimes). pub fn add_recv<E, P, A: marker::Send>(&mut self, chan: &'c Chan<E, Recv<A, P>>) { let &Chan(_, ref rx, _) = chan; let _ = self.receivers.push(rx); } pub fn add_offer<E, P, Q>(&mut self, chan: &'c Chan<E, Offer<P, Q>>) { let &Chan(_, ref rx, _) = chan; let _ = self.receivers.push(rx); } /// Find a Receiver (and hence a Chan) that is ready to receive. /// /// This method consumes the ChanSelect, freeing up the borrowed Receivers /// to be consumed. pub fn wait(self) -> usize { let mut sel = Select::new(); for rx in self.receivers.into_iter() { sel.recv(rx); } sel.ready() } /// How many channels are there in the structure? pub fn len(&self) -> usize { self.receivers.len() } pub fn is_empty(&self) -> bool { self.receivers.is_empty() } } impl<'c> Default for ChanSelect<'c> { fn default() -> Self { Self::new() } } /// Returns two session channels #[must_use] pub fn session_channel<P: HasDual>() -> (Chan<(), P>, Chan<(), P::Dual>) { let (tx1, rx1) = unbounded(); let (tx2, rx2) = unbounded(); let c1 = Chan(tx1, rx2, PhantomData); let c2 = Chan(tx2, rx1, PhantomData); (c1, c2) } /// Connect two functions using a session typed channel. pub fn connect<F1, F2, P>(srv: F1, cli: F2) where F1: Fn(Chan<(), P>) + marker::Send +'static, F2: Fn(Chan<(), P::Dual>) + marker::Send, P: HasDual + marker::Send +'static, P::Dual: HasDual + marker::Send +'static, { let (c1, c2) = session_channel(); let t = spawn(move || srv(c1)); cli(c2); t.join().unwrap(); } mod private { use super::*; pub trait Sealed {} // Impl for all exported protocol types impl Sealed for Eps {} impl<A, P> Sealed for Send<A, P> {} impl<A, P> Sealed for Recv<A, P> {} impl<P, Q> Sealed for Choose<P, Q> {} impl<P, Q> Sealed for Offer<P, Q> {} impl<Z> Sealed for Var<Z> {} impl<P> Sealed for Rec<P> {} } /// This macro is convenient for server-like protocols of the form: /// /// `Offer<A, Offer<B, Offer<C,... >>>` /// /// # Examples /// /// Assume we have a protocol `Offer<Recv<u64, Eps>, Offer<Recv<String, Eps>,Eps>>>` /// we can use the `offer!` macro as follows: /// /// ```rust /// extern crate session_types; /// use session_types::*; /// use std::thread::spawn; /// /// fn srv(c: Chan<(), Offer<Recv<u64, Eps>, Offer<Recv<String, Eps>, Eps>>>) { /// offer! { c, /// Number => { /// let (c, n) = c.recv(); /// assert_eq!(42, n); /// c.close(); /// }, /// String => { /// c.recv().0.close(); /// }, /// Quit => { /// c.close(); /// } /// } /// } /// /// fn cli(c: Chan<(), Choose<Send<u64, Eps>, Choose<Send<String, Eps>, Eps>>>) { /// c.sel1().send(42).close(); /// } /// /// fn main() { /// let (s, c) = session_channel(); /// spawn(move|| cli(c)); /// srv(s); /// } /// ``` /// /// The identifiers on the left-hand side of the arrows have no semantic /// meaning, they only provide a meaningful name for the reader. #[macro_export] macro_rules! offer { ( $id:ident, $branch:ident => $code:expr, $($t:tt)+ ) => ( match $id.offer() { $crate::Left($id) => $code, $crate::Right($id) => offer!{ $id, $($t)+ } } ); ( $id:ident, $branch:ident => $code:expr ) => ( $code ) } /// Returns the channel unchanged on `TryRecvError::Empty`. #[macro_export] macro_rules! try_offer { ( $id:ident, $branch:ident => $code:expr, $($t:tt)+ ) => ( match $id.try_offer() { Ok($crate::Left($id)) => $code, Ok($crate::Right($id)) => try_offer!{ $id, $($t)+ }, Err($id) => Err($id) } ); ( $id:ident, $branch:ident => $code:expr ) => ( $code ) } /// This macro plays the same role as the `select!` macro does for `Receiver`s. /// /// It also supports a second form with `Offer`s (see the example below). /// /// # Examples /// /// ```rust /// extern crate session_types; /// use session_types::*; /// use std::thread::spawn; /// /// fn send_str(c: Chan<(), Send<String, Eps>>) { /// c.send("Hello, World!".to_string()).close(); /// } /// /// fn send_usize(c: Chan<(), Send<usize, Eps>>) { /// c.send(42).close(); /// } /// /// fn main() { /// let (tcs, rcs) = session_channel(); /// let (tcu, rcu) = session_channel(); /// /// // Spawn threads /// spawn(move|| send_str(tcs)); /// spawn(move|| send_usize(tcu)); /// /// chan_select! { /// (c, s) = rcs.recv() => { /// assert_eq!("Hello, World!".to_string(), s); /// c.close(); /// rcu.recv().0.close(); /// }, /// (c, i) = rcu.recv() => { /// assert_eq!(42, i); /// c.close(); /// rcs.recv().0.close(); /// } /// } /// } /// ``` /// /// ```rust /// extern crate session_types; /// extern crate rand; /// /// use std::thread::spawn; /// use session_types::*; /// /// type Igo = Choose<Send<String, Eps>, Send<u64, Eps>>; /// type Ugo = Offer<Recv<String, Eps>, Recv<u64, Eps>>; /// /// fn srv(chan_one: Chan<(), Ugo>, chan_two: Chan<(), Ugo>) { /// let _ign; /// chan_select! { /// _ign = chan_one.offer() => { /// String => { /// let (c, s) = chan_one.recv(); /// assert_eq!("Hello, World!".to_string(), s); /// c.close(); /// match chan_two.offer() { /// Left(c) => c.recv().0.close(), /// Right(c) => c.recv().0.close(), /// } /// }, /// Number => { /// chan_one.recv().0.close(); /// match chan_two.offer() { /// Left(c) => c.recv().0.close(), /// Right(c) => c.recv().0.close(), /// } /// } /// }, /// _ign = chan_two.offer() => { /// String => { /// chan_two.recv().0.close(); /// match chan_one.offer() { /// Left(c) => c.recv().0.close(), /// Right(c) => c.recv().0.close(), /// } /// }, /// Number => { /// chan_two.recv().0.close(); /// match chan_one.offer() { /// Left(c) => c.recv().0.close(), /// Right(c) => c.recv().0.close(), /// } /// } /// } /// } /// } /// /// fn cli(c: Chan<(), Igo>) { /// c.sel1().send("Hello, World!".to_string()).close(); /// } /// /// fn main() { /// let (ca1, ca2) = session_channel(); ///
{ Ok(Left(self.cast())) }
conditional_block
lib.rs
)` where `t! r` //! is the protocol "send something of type `t` then proceed with //! protocol `r`", the protocol `t? r` is "receive something of type `t` then proceed //! with protocol `r`, and `eps` is a special marker indicating the end of a //! communication session. //! //! Our session type library allows the user to create channels that adhere to a //! specified protocol. For example, a channel like the above would have the type //! `Chan<(), Send<i64, Recv<bool, Eps>>>`, and the full program could look like this: //! //! ``` //! extern crate session_types; //! use session_types::*; //! //! type Server = Recv<i64, Send<bool, Eps>>; //! type Client = Send<i64, Recv<bool, Eps>>; //! //! fn srv(c: Chan<(), Server>) { //! let (c, n) = c.recv(); //! if n % 2 == 0 { //! c.send(true).close() //! } else { //! c.send(false).close() //! } //! } //! //! fn cli(c: Chan<(), Client>) { //! let n = 42; //! let c = c.send(n); //! let (c, b) = c.recv(); //! //! if b { //! println!("{} is even", n); //! } else { //! println!("{} is odd", n); //! } //! //! c.close(); //! } //! //! fn main() { //! connect(srv, cli); //! } //! ``` #![cfg_attr(feature = "cargo-clippy", allow(clippy::double_must_use))] #![cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] extern crate crossbeam_channel; use std::marker::PhantomData; use std::thread::spawn; use std::{marker, mem, ptr}; use std::collections::HashMap; use crossbeam_channel::{unbounded, Receiver, Sender}; use crossbeam_channel::Select; pub use Branch::*; /// A session typed channel. `P` is the protocol and `E` is the environment, /// containing potential recursion targets #[must_use] pub struct Chan<E, P>(Sender<*mut u8>, Receiver<*mut u8>, PhantomData<(E, P)>); unsafe impl<E: marker::Send, P: marker::Send> marker::Send for Chan<E, P> {} unsafe fn write_chan<A: marker::Send +'static, E, P>(&Chan(ref tx, _, _): &Chan<E, P>, x: A) { tx.send(Box::into_raw(Box::new(x)) as *mut _).unwrap() } unsafe fn read_chan<A: marker::Send +'static, E, P>(&Chan(_, ref rx, _): &Chan<E, P>) -> A { *Box::from_raw(rx.recv().unwrap() as *mut A) } unsafe fn try_read_chan<A: marker::Send +'static, E, P>( &Chan(_, ref rx, _): &Chan<E, P>, ) -> Option<A> { match rx.try_recv() { Ok(a) => Some(*Box::from_raw(a as *mut A)), Err(_) => None, } } /// Peano numbers: Zero #[allow(missing_copy_implementations)] pub struct Z; /// Peano numbers: Increment pub struct S<N>(PhantomData<N>); /// End of communication session (epsilon) #[allow(missing_copy_implementations)] pub struct Eps; /// Receive `A`, then `P` pub struct Recv<A, P>(PhantomData<(A, P)>); /// Send `A`, then `P` pub struct Send<A, P>(PhantomData<(A, P)>); /// Active choice between `P` and `Q` pub struct Choose<P, Q>(PhantomData<(P, Q)>); /// Passive choice (offer) between `P` and `Q` pub struct Offer<P, Q>(PhantomData<(P, Q)>); /// Enter a recursive environment pub struct Rec<P>(PhantomData<P>); /// Recurse. N indicates how many layers of the recursive environment we recurse /// out of. pub struct Var<N>(PhantomData<N>); /// The HasDual trait defines the dual relationship between protocols. /// /// Any valid protocol has a corresponding dual. /// /// This trait is sealed and cannot be implemented outside of session-types pub trait HasDual: private::Sealed { type Dual; } impl HasDual for Eps { type Dual = Eps; } impl<A, P: HasDual> HasDual for Send<A, P> { type Dual = Recv<A, P::Dual>; } impl<A, P: HasDual> HasDual for Recv<A, P> { type Dual = Send<A, P::Dual>; } impl<P: HasDual, Q: HasDual> HasDual for Choose<P, Q> { type Dual = Offer<P::Dual, Q::Dual>; } impl<P: HasDual, Q: HasDual> HasDual for Offer<P, Q> { type Dual = Choose<P::Dual, Q::Dual>; } impl HasDual for Var<Z> { type Dual = Var<Z>; } impl<N> HasDual for Var<S<N>> { type Dual = Var<S<N>>; } impl<P: HasDual> HasDual for Rec<P> { type Dual = Rec<P::Dual>; } pub enum Branch<L, R> { Left(L), Right(R), } impl<E, P> Drop for Chan<E, P> { fn drop(&mut self) { panic!("Session channel prematurely dropped"); } } impl<E> Chan<E, Eps> { /// Close a channel. Should always be used at the end of your program. pub fn close(self) { // This method cleans up the channel without running the panicky destructor // In essence, it calls the drop glue bypassing the `Drop::drop` method let this = mem::ManuallyDrop::new(self); let sender = unsafe { ptr::read(&(this).0 as *const _) }; let receiver = unsafe { ptr::read(&(this).1 as *const _) }; drop(sender); drop(receiver); // drop them } } impl<E, P> Chan<E, P> { unsafe fn cast<E2, P2>(self) -> Chan<E2, P2> { let this = mem::ManuallyDrop::new(self); Chan( ptr::read(&(this).0 as *const _), ptr::read(&(this).1 as *const _), PhantomData, )
/// protocol `P` #[must_use] pub fn send(self, v: A) -> Chan<E, P> { unsafe { write_chan(&self, v); self.cast() } } } impl<E, P, A: marker::Send +'static> Chan<E, Recv<A, P>> { /// Receives a value of type `A` from the channel. Returns a tuple /// containing the resulting channel and the received value. #[must_use] pub fn recv(self) -> (Chan<E, P>, A) { unsafe { let v = read_chan(&self); (self.cast(), v) } } /// Non-blocking receive. #[must_use] pub fn try_recv(self) -> Result<(Chan<E, P>, A), Self> { unsafe { if let Some(v) = try_read_chan(&self) { Ok((self.cast(), v)) } else { Err(self) } } } } impl<E, P, Q> Chan<E, Choose<P, Q>> { /// Perform an active choice, selecting protocol `P`. #[must_use] pub fn sel1(self) -> Chan<E, P> { unsafe { write_chan(&self, true); self.cast() } } /// Perform an active choice, selecting protocol `Q`. #[must_use] pub fn sel2(self) -> Chan<E, Q> { unsafe { write_chan(&self, false); self.cast() } } } /// Convenience function. This is identical to `.sel2()` impl<Z, A, B> Chan<Z, Choose<A, B>> { #[must_use] pub fn skip(self) -> Chan<Z, B> { self.sel2() } } /// Convenience function. This is identical to `.sel2().sel2()` impl<Z, A, B, C> Chan<Z, Choose<A, Choose<B, C>>> { #[must_use] pub fn skip2(self) -> Chan<Z, C> { self.sel2().sel2() } } /// Convenience function. This is identical to `.sel2().sel2().sel2()` impl<Z, A, B, C, D> Chan<Z, Choose<A, Choose<B, Choose<C, D>>>> { #[must_use] pub fn skip3(self) -> Chan<Z, D> { self.sel2().sel2().sel2() } } /// Convenience function. This is identical to `.sel2().sel2().sel2().sel2()` impl<Z, A, B, C, D, E> Chan<Z, Choose<A, Choose<B, Choose<C, Choose<D, E>>>>> { #[must_use] pub fn skip4(self) -> Chan<Z, E> { self.sel2().sel2().sel2().sel2() } } /// Convenience function. This is identical to `.sel2().sel2().sel2().sel2().sel2()` impl<Z, A, B, C, D, E, F> Chan<Z, Choose<A, Choose<B, Choose<C, Choose<D, Choose<E, F>>>>>> { #[must_use] pub fn skip5(self) -> Chan<Z, F> { self.sel2().sel2().sel2().sel2().sel2() } } /// Convenience function. impl<Z, A, B, C, D, E, F, G> Chan<Z, Choose<A, Choose<B, Choose<C, Choose<D, Choose<E, Choose<F, G>>>>>>> { #[must_use] pub fn skip6(self) -> Chan<Z, G> { self.sel2().sel2().sel2().sel2().sel2().sel2() } } /// Convenience function. impl<Z, A, B, C, D, E, F, G, H> Chan<Z, Choose<A, Choose<B, Choose<C, Choose<D, Choose<E, Choose<F, Choose<G, H>>>>>>>> { #[must_use] pub fn skip7(self) -> Chan<Z, H> { self.sel2().sel2().sel2().sel2().sel2().sel2().sel2() } } impl<E, P, Q> Chan<E, Offer<P, Q>> { /// Passive choice. This allows the other end of the channel to select one /// of two options for continuing the protocol: either `P` or `Q`. #[must_use] pub fn offer(self) -> Branch<Chan<E, P>, Chan<E, Q>> { unsafe { let b = read_chan(&self); if b { Left(self.cast()) } else { Right(self.cast()) } } } /// Poll for choice. #[must_use] pub fn try_offer(self) -> Result<Branch<Chan<E, P>, Chan<E, Q>>, Self> { unsafe { if let Some(b) = try_read_chan(&self) { if b { Ok(Left(self.cast())) } else { Ok(Right(self.cast())) } } else { Err(self) } } } } impl<E, P> Chan<E, Rec<P>> { /// Enter a recursive environment, putting the current environment on the /// top of the environment stack. #[must_use] pub fn enter(self) -> Chan<(P, E), P> { unsafe { self.cast() } } } impl<E, P> Chan<(P, E), Var<Z>> { /// Recurse to the environment on the top of the environment stack. #[must_use] pub fn zero(self) -> Chan<(P, E), P> { unsafe { self.cast() } } } impl<E, P, N> Chan<(P, E), Var<S<N>>> { /// Pop the top environment from the environment stack. #[must_use] pub fn succ(self) -> Chan<E, Var<N>> { unsafe { self.cast() } } } /// Homogeneous select. We have a vector of channels, all obeying the same /// protocol (and in the exact same point of the protocol), wait for one of them /// to receive. Removes the receiving channel from the vector and returns both /// the channel and the new vector. #[must_use] pub fn hselect<E, P, A>( mut chans: Vec<Chan<E, Recv<A, P>>>, ) -> (Chan<E, Recv<A, P>>, Vec<Chan<E, Recv<A, P>>>) { let i = iselect(&chans); let c = chans.remove(i); (c, chans) } /// An alternative version of homogeneous select, returning the index of the Chan /// that is ready to receive. pub fn iselect<E, P, A>(chans: &[Chan<E, Recv<A, P>>]) -> usize { let mut map = HashMap::new(); let id = { let mut sel = Select::new(); let mut handles = Vec::with_capacity(chans.len()); // collect all the handles for (i, chan) in chans.iter().enumerate() { let &Chan(_, ref rx, _) = chan; let handle = sel.recv(rx); map.insert(handle, i); handles.push(handle); } sel.ready() }; map.remove(&id).unwrap() } /// Heterogeneous selection structure for channels /// /// This builds a structure of channels that we wish to select over. This is /// structured in a way such that the channels selected over cannot be /// interacted with (consumed) as long as the borrowing ChanSelect object /// exists. This is necessary to ensure memory safety. /// /// The type parameter T is a return type, ie we store a value of some type T /// that is returned in case its associated channels is selected on `wait()` pub struct ChanSelect<'c> { receivers: Vec<&'c Receiver<*mut u8>>, } impl<'c> ChanSelect<'c> { pub fn new() -> ChanSelect<'c> { ChanSelect { receivers: Vec::new(), } } /// Add a channel whose next step is `Recv` /// /// Once a channel has been added it cannot be interacted with as long as it /// is borrowed here (by virtue of borrow checking and lifetimes). pub fn add_recv<E, P, A: marker::Send>(&mut self, chan: &'c Chan<E, Recv<A, P>>) { let &Chan(_, ref rx, _) = chan; let _ = self.receivers.push(rx); } pub fn add_offer<E, P, Q>(&mut self, chan: &'c Chan<E, Offer<P, Q>>) { let &Chan(_, ref rx, _) = chan; let _ = self.receivers.push(rx); } /// Find a Receiver (and hence a Chan) that is ready to receive. /// /// This method consumes the ChanSelect, freeing up the borrowed Receivers /// to be consumed. pub fn wait(self) -> usize { let mut sel = Select::new(); for rx in self.receivers.into_iter() { sel.recv(rx); } sel.ready() } /// How many channels are there in the structure? pub fn len(&self) -> usize { self.receivers.len() } pub fn is_empty(&self) -> bool { self.receivers.is_empty() } } impl<'c> Default for ChanSelect<'c> { fn default() -> Self { Self::new() } } /// Returns two session channels #[must_use] pub fn session_channel<P: HasDual>() -> (Chan<(), P>, Chan<(), P::Dual>) { let (tx1, rx1) = unbounded(); let (tx2, rx2) = unbounded(); let c1 = Chan(tx1, rx2, PhantomData); let c2 = Chan(tx2, rx1, PhantomData); (c1, c2) } /// Connect two functions using a session typed channel. pub fn connect<F1, F2, P>(srv: F1, cli: F2) where F1: Fn(Chan<(), P>) + marker::Send +'static, F2: Fn(Chan<(), P::Dual>) + marker::Send, P: HasDual + marker::Send +'static, P::Dual: HasDual + marker::Send +'static, { let (c1, c2) = session_channel(); let t = spawn(move || srv(c1)); cli(c2); t.join().unwrap(); } mod private { use super::*; pub trait Sealed {} // Impl for all exported protocol types impl Sealed for Eps {} impl<A, P> Sealed for Send<A, P> {} impl<A, P> Sealed for Recv<A, P> {} impl<P, Q> Sealed for Choose<P, Q> {} impl<P, Q> Sealed for Offer<P, Q> {} impl<Z> Sealed for Var<Z> {} impl<P> Sealed for Rec<P> {} } /// This macro is convenient for server-like protocols of the form: /// /// `Offer<A, Offer<B, Offer<C,... >>>` /// /// # Examples /// /// Assume we have a protocol `Offer<Recv<u64, Eps>, Offer<Recv<String, Eps>,Eps>>>` /// we can use the `offer!` macro as follows: /// /// ```rust /// extern crate session_types; /// use session_types::*; /// use std::thread::spawn; /// /// fn srv(c: Chan<(), Offer<Recv<u64, Eps>, Offer<Recv<String, Eps>, Eps>>>) { /// offer! { c, /// Number => { /// let (c, n) = c.recv(); /// assert_eq!(42, n); /// c.close(); /// }, /// String => { /// c.recv().0.close(); /// }, /// Quit => { /// c.close(); /// } /// } /// } /// /// fn cli(c: Chan<(), Choose<Send<u64, Eps>, Choose<Send<String, Eps>, Eps>>>) { /// c.sel1().send(42).close(); /// } /// /// fn main() { /// let (s, c) = session_channel(); /// spawn(move|| cli(c)); /// srv(s); /// } /// ``` /// /// The identifiers on the left-hand side of the arrows have no semantic /// meaning, they only provide a meaningful name for the reader. #[macro_export] macro_rules! offer { ( $id:ident, $branch:ident => $code:expr, $($t:tt)+ ) => ( match $id.offer() { $crate::Left($id) => $code, $crate::Right($id) => offer!{ $id, $($t)+ } } ); ( $id:ident, $branch:ident => $code:expr ) => ( $code ) } /// Returns the channel unchanged on `TryRecvError::Empty`. #[macro_export] macro_rules! try_offer { ( $id:ident, $branch:ident => $code:expr, $($t:tt)+ ) => ( match $id.try_offer() { Ok($crate::Left($id)) => $code, Ok($crate::Right($id)) => try_offer!{ $id, $($t)+ }, Err($id) => Err($id) } ); ( $id:ident, $branch:ident => $code:expr ) => ( $code ) } /// This macro plays the same role as the `select!` macro does for `Receiver`s. /// /// It also supports a second form with `Offer`s (see the example below). /// /// # Examples /// /// ```rust /// extern crate session_types; /// use session_types::*; /// use std::thread::spawn; /// /// fn send_str(c: Chan<(), Send<String, Eps>>) { /// c.send("Hello, World!".to_string()).close(); /// } /// /// fn send_usize(c: Chan<(), Send<usize, Eps>>) { /// c.send(42).close(); /// } /// /// fn main() { /// let (tcs, rcs) = session_channel(); /// let (tcu, rcu) = session_channel(); /// /// // Spawn threads /// spawn(move|| send_str(tcs)); /// spawn(move|| send_usize(tcu)); /// /// chan_select! { /// (c, s) = rcs.recv() => { /// assert_eq!("Hello, World!".to_string(), s); /// c.close(); /// rcu.recv().0.close(); /// }, /// (c, i) = rcu.recv() => { /// assert_eq!(42, i); /// c.close(); /// rcs.recv().0.close(); /// } /// } /// } /// ``` /// /// ```rust /// extern crate session_types; /// extern crate rand; /// /// use std::thread::spawn; /// use session_types::*; /// /// type Igo = Choose<Send<String, Eps>, Send<u64, Eps>>; /// type Ugo = Offer<Recv<String, Eps>, Recv<u64, Eps>>; /// /// fn srv(chan_one: Chan<(), Ugo>, chan_two: Chan<(), Ugo>) { /// let _ign; /// chan_select! { /// _ign = chan_one.offer() => { /// String => { /// let (c, s) = chan_one.recv(); /// assert_eq!("Hello, World!".to_string(), s); /// c.close(); /// match chan_two.offer() { /// Left(c) => c.recv().0.close(), /// Right(c) => c.recv().0.close(), /// } /// }, /// Number => { /// chan_one.recv().0.close(); /// match chan_two.offer() { /// Left(c) => c.recv().0.close(), /// Right(c) => c.recv().0.close(), /// } /// } /// }, /// _ign = chan_two.offer() => { /// String => { /// chan_two.recv().0.close(); /// match chan_one.offer() { /// Left(c) => c.recv().0.close(), /// Right(c) => c.recv().0.close(), /// } /// }, /// Number => { /// chan_two.recv().0.close(); /// match chan_one.offer() { /// Left(c) => c.recv().0.close(), /// Right(c) => c.recv().0.close(), /// } /// } /// } /// } /// } /// /// fn cli(c: Chan<(), Igo>) { /// c.sel1().send("Hello, World!".to_string()).close(); /// } /// /// fn main() { /// let (ca1, ca2) = session_channel(); ///
} } impl<E, P, A: marker::Send + 'static> Chan<E, Send<A, P>> { /// Send a value of type `A` over the channel. Returns a channel with
random_line_split
lib.rs
where `t! r` //! is the protocol "send something of type `t` then proceed with //! protocol `r`", the protocol `t? r` is "receive something of type `t` then proceed //! with protocol `r`, and `eps` is a special marker indicating the end of a //! communication session. //! //! Our session type library allows the user to create channels that adhere to a //! specified protocol. For example, a channel like the above would have the type //! `Chan<(), Send<i64, Recv<bool, Eps>>>`, and the full program could look like this: //! //! ``` //! extern crate session_types; //! use session_types::*; //! //! type Server = Recv<i64, Send<bool, Eps>>; //! type Client = Send<i64, Recv<bool, Eps>>; //! //! fn srv(c: Chan<(), Server>) { //! let (c, n) = c.recv(); //! if n % 2 == 0 { //! c.send(true).close() //! } else { //! c.send(false).close() //! } //! } //! //! fn cli(c: Chan<(), Client>) { //! let n = 42; //! let c = c.send(n); //! let (c, b) = c.recv(); //! //! if b { //! println!("{} is even", n); //! } else { //! println!("{} is odd", n); //! } //! //! c.close(); //! } //! //! fn main() { //! connect(srv, cli); //! } //! ``` #![cfg_attr(feature = "cargo-clippy", allow(clippy::double_must_use))] #![cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] extern crate crossbeam_channel; use std::marker::PhantomData; use std::thread::spawn; use std::{marker, mem, ptr}; use std::collections::HashMap; use crossbeam_channel::{unbounded, Receiver, Sender}; use crossbeam_channel::Select; pub use Branch::*; /// A session typed channel. `P` is the protocol and `E` is the environment, /// containing potential recursion targets #[must_use] pub struct Chan<E, P>(Sender<*mut u8>, Receiver<*mut u8>, PhantomData<(E, P)>); unsafe impl<E: marker::Send, P: marker::Send> marker::Send for Chan<E, P> {} unsafe fn write_chan<A: marker::Send +'static, E, P>(&Chan(ref tx, _, _): &Chan<E, P>, x: A) { tx.send(Box::into_raw(Box::new(x)) as *mut _).unwrap() } unsafe fn read_chan<A: marker::Send +'static, E, P>(&Chan(_, ref rx, _): &Chan<E, P>) -> A { *Box::from_raw(rx.recv().unwrap() as *mut A) } unsafe fn try_read_chan<A: marker::Send +'static, E, P>( &Chan(_, ref rx, _): &Chan<E, P>, ) -> Option<A> { match rx.try_recv() { Ok(a) => Some(*Box::from_raw(a as *mut A)), Err(_) => None, } } /// Peano numbers: Zero #[allow(missing_copy_implementations)] pub struct Z; /// Peano numbers: Increment pub struct S<N>(PhantomData<N>); /// End of communication session (epsilon) #[allow(missing_copy_implementations)] pub struct Eps; /// Receive `A`, then `P` pub struct Recv<A, P>(PhantomData<(A, P)>); /// Send `A`, then `P` pub struct Send<A, P>(PhantomData<(A, P)>); /// Active choice between `P` and `Q` pub struct Choose<P, Q>(PhantomData<(P, Q)>); /// Passive choice (offer) between `P` and `Q` pub struct Offer<P, Q>(PhantomData<(P, Q)>); /// Enter a recursive environment pub struct Rec<P>(PhantomData<P>); /// Recurse. N indicates how many layers of the recursive environment we recurse /// out of. pub struct Var<N>(PhantomData<N>); /// The HasDual trait defines the dual relationship between protocols. /// /// Any valid protocol has a corresponding dual. /// /// This trait is sealed and cannot be implemented outside of session-types pub trait HasDual: private::Sealed { type Dual; } impl HasDual for Eps { type Dual = Eps; } impl<A, P: HasDual> HasDual for Send<A, P> { type Dual = Recv<A, P::Dual>; } impl<A, P: HasDual> HasDual for Recv<A, P> { type Dual = Send<A, P::Dual>; } impl<P: HasDual, Q: HasDual> HasDual for Choose<P, Q> { type Dual = Offer<P::Dual, Q::Dual>; } impl<P: HasDual, Q: HasDual> HasDual for Offer<P, Q> { type Dual = Choose<P::Dual, Q::Dual>; } impl HasDual for Var<Z> { type Dual = Var<Z>; } impl<N> HasDual for Var<S<N>> { type Dual = Var<S<N>>; } impl<P: HasDual> HasDual for Rec<P> { type Dual = Rec<P::Dual>; } pub enum Branch<L, R> { Left(L), Right(R), } impl<E, P> Drop for Chan<E, P> { fn drop(&mut self) { panic!("Session channel prematurely dropped"); } } impl<E> Chan<E, Eps> { /// Close a channel. Should always be used at the end of your program. pub fn close(self) { // This method cleans up the channel without running the panicky destructor // In essence, it calls the drop glue bypassing the `Drop::drop` method let this = mem::ManuallyDrop::new(self); let sender = unsafe { ptr::read(&(this).0 as *const _) }; let receiver = unsafe { ptr::read(&(this).1 as *const _) }; drop(sender); drop(receiver); // drop them } } impl<E, P> Chan<E, P> { unsafe fn cast<E2, P2>(self) -> Chan<E2, P2> { let this = mem::ManuallyDrop::new(self); Chan( ptr::read(&(this).0 as *const _), ptr::read(&(this).1 as *const _), PhantomData, ) } } impl<E, P, A: marker::Send +'static> Chan<E, Send<A, P>> { /// Send a value of type `A` over the channel. Returns a channel with /// protocol `P` #[must_use] pub fn send(self, v: A) -> Chan<E, P> { unsafe { write_chan(&self, v); self.cast() } } } impl<E, P, A: marker::Send +'static> Chan<E, Recv<A, P>> { /// Receives a value of type `A` from the channel. Returns a tuple /// containing the resulting channel and the received value. #[must_use] pub fn recv(self) -> (Chan<E, P>, A) { unsafe { let v = read_chan(&self); (self.cast(), v) } } /// Non-blocking receive. #[must_use] pub fn try_recv(self) -> Result<(Chan<E, P>, A), Self> { unsafe { if let Some(v) = try_read_chan(&self) { Ok((self.cast(), v)) } else { Err(self) } } } } impl<E, P, Q> Chan<E, Choose<P, Q>> { /// Perform an active choice, selecting protocol `P`. #[must_use] pub fn sel1(self) -> Chan<E, P> { unsafe { write_chan(&self, true); self.cast() } } /// Perform an active choice, selecting protocol `Q`. #[must_use] pub fn sel2(self) -> Chan<E, Q> { unsafe { write_chan(&self, false); self.cast() } } } /// Convenience function. This is identical to `.sel2()` impl<Z, A, B> Chan<Z, Choose<A, B>> { #[must_use] pub fn skip(self) -> Chan<Z, B> { self.sel2() } } /// Convenience function. This is identical to `.sel2().sel2()` impl<Z, A, B, C> Chan<Z, Choose<A, Choose<B, C>>> { #[must_use] pub fn skip2(self) -> Chan<Z, C> { self.sel2().sel2() } } /// Convenience function. This is identical to `.sel2().sel2().sel2()` impl<Z, A, B, C, D> Chan<Z, Choose<A, Choose<B, Choose<C, D>>>> { #[must_use] pub fn skip3(self) -> Chan<Z, D> { self.sel2().sel2().sel2() } } /// Convenience function. This is identical to `.sel2().sel2().sel2().sel2()` impl<Z, A, B, C, D, E> Chan<Z, Choose<A, Choose<B, Choose<C, Choose<D, E>>>>> { #[must_use] pub fn skip4(self) -> Chan<Z, E> { self.sel2().sel2().sel2().sel2() } } /// Convenience function. This is identical to `.sel2().sel2().sel2().sel2().sel2()` impl<Z, A, B, C, D, E, F> Chan<Z, Choose<A, Choose<B, Choose<C, Choose<D, Choose<E, F>>>>>> { #[must_use] pub fn skip5(self) -> Chan<Z, F> { self.sel2().sel2().sel2().sel2().sel2() } } /// Convenience function. impl<Z, A, B, C, D, E, F, G> Chan<Z, Choose<A, Choose<B, Choose<C, Choose<D, Choose<E, Choose<F, G>>>>>>> { #[must_use] pub fn skip6(self) -> Chan<Z, G> { self.sel2().sel2().sel2().sel2().sel2().sel2() } } /// Convenience function. impl<Z, A, B, C, D, E, F, G, H> Chan<Z, Choose<A, Choose<B, Choose<C, Choose<D, Choose<E, Choose<F, Choose<G, H>>>>>>>> { #[must_use] pub fn skip7(self) -> Chan<Z, H> { self.sel2().sel2().sel2().sel2().sel2().sel2().sel2() } } impl<E, P, Q> Chan<E, Offer<P, Q>> { /// Passive choice. This allows the other end of the channel to select one /// of two options for continuing the protocol: either `P` or `Q`. #[must_use] pub fn offer(self) -> Branch<Chan<E, P>, Chan<E, Q>> { unsafe { let b = read_chan(&self); if b { Left(self.cast()) } else { Right(self.cast()) } } } /// Poll for choice. #[must_use] pub fn try_offer(self) -> Result<Branch<Chan<E, P>, Chan<E, Q>>, Self> { unsafe { if let Some(b) = try_read_chan(&self) { if b { Ok(Left(self.cast())) } else { Ok(Right(self.cast())) } } else { Err(self) } } } } impl<E, P> Chan<E, Rec<P>> { /// Enter a recursive environment, putting the current environment on the /// top of the environment stack. #[must_use] pub fn enter(self) -> Chan<(P, E), P> { unsafe { self.cast() } } } impl<E, P> Chan<(P, E), Var<Z>> { /// Recurse to the environment on the top of the environment stack. #[must_use] pub fn zero(self) -> Chan<(P, E), P> { unsafe { self.cast() } } } impl<E, P, N> Chan<(P, E), Var<S<N>>> { /// Pop the top environment from the environment stack. #[must_use] pub fn succ(self) -> Chan<E, Var<N>> { unsafe { self.cast() } } } /// Homogeneous select. We have a vector of channels, all obeying the same /// protocol (and in the exact same point of the protocol), wait for one of them /// to receive. Removes the receiving channel from the vector and returns both /// the channel and the new vector. #[must_use] pub fn hselect<E, P, A>( mut chans: Vec<Chan<E, Recv<A, P>>>, ) -> (Chan<E, Recv<A, P>>, Vec<Chan<E, Recv<A, P>>>) { let i = iselect(&chans); let c = chans.remove(i); (c, chans) } /// An alternative version of homogeneous select, returning the index of the Chan /// that is ready to receive. pub fn iselect<E, P, A>(chans: &[Chan<E, Recv<A, P>>]) -> usize { let mut map = HashMap::new(); let id = { let mut sel = Select::new(); let mut handles = Vec::with_capacity(chans.len()); // collect all the handles for (i, chan) in chans.iter().enumerate() { let &Chan(_, ref rx, _) = chan; let handle = sel.recv(rx); map.insert(handle, i); handles.push(handle); } sel.ready() }; map.remove(&id).unwrap() } /// Heterogeneous selection structure for channels /// /// This builds a structure of channels that we wish to select over. This is /// structured in a way such that the channels selected over cannot be /// interacted with (consumed) as long as the borrowing ChanSelect object /// exists. This is necessary to ensure memory safety. /// /// The type parameter T is a return type, ie we store a value of some type T /// that is returned in case its associated channels is selected on `wait()` pub struct
<'c> { receivers: Vec<&'c Receiver<*mut u8>>, } impl<'c> ChanSelect<'c> { pub fn new() -> ChanSelect<'c> { ChanSelect { receivers: Vec::new(), } } /// Add a channel whose next step is `Recv` /// /// Once a channel has been added it cannot be interacted with as long as it /// is borrowed here (by virtue of borrow checking and lifetimes). pub fn add_recv<E, P, A: marker::Send>(&mut self, chan: &'c Chan<E, Recv<A, P>>) { let &Chan(_, ref rx, _) = chan; let _ = self.receivers.push(rx); } pub fn add_offer<E, P, Q>(&mut self, chan: &'c Chan<E, Offer<P, Q>>) { let &Chan(_, ref rx, _) = chan; let _ = self.receivers.push(rx); } /// Find a Receiver (and hence a Chan) that is ready to receive. /// /// This method consumes the ChanSelect, freeing up the borrowed Receivers /// to be consumed. pub fn wait(self) -> usize { let mut sel = Select::new(); for rx in self.receivers.into_iter() { sel.recv(rx); } sel.ready() } /// How many channels are there in the structure? pub fn len(&self) -> usize { self.receivers.len() } pub fn is_empty(&self) -> bool { self.receivers.is_empty() } } impl<'c> Default for ChanSelect<'c> { fn default() -> Self { Self::new() } } /// Returns two session channels #[must_use] pub fn session_channel<P: HasDual>() -> (Chan<(), P>, Chan<(), P::Dual>) { let (tx1, rx1) = unbounded(); let (tx2, rx2) = unbounded(); let c1 = Chan(tx1, rx2, PhantomData); let c2 = Chan(tx2, rx1, PhantomData); (c1, c2) } /// Connect two functions using a session typed channel. pub fn connect<F1, F2, P>(srv: F1, cli: F2) where F1: Fn(Chan<(), P>) + marker::Send +'static, F2: Fn(Chan<(), P::Dual>) + marker::Send, P: HasDual + marker::Send +'static, P::Dual: HasDual + marker::Send +'static, { let (c1, c2) = session_channel(); let t = spawn(move || srv(c1)); cli(c2); t.join().unwrap(); } mod private { use super::*; pub trait Sealed {} // Impl for all exported protocol types impl Sealed for Eps {} impl<A, P> Sealed for Send<A, P> {} impl<A, P> Sealed for Recv<A, P> {} impl<P, Q> Sealed for Choose<P, Q> {} impl<P, Q> Sealed for Offer<P, Q> {} impl<Z> Sealed for Var<Z> {} impl<P> Sealed for Rec<P> {} } /// This macro is convenient for server-like protocols of the form: /// /// `Offer<A, Offer<B, Offer<C,... >>>` /// /// # Examples /// /// Assume we have a protocol `Offer<Recv<u64, Eps>, Offer<Recv<String, Eps>,Eps>>>` /// we can use the `offer!` macro as follows: /// /// ```rust /// extern crate session_types; /// use session_types::*; /// use std::thread::spawn; /// /// fn srv(c: Chan<(), Offer<Recv<u64, Eps>, Offer<Recv<String, Eps>, Eps>>>) { /// offer! { c, /// Number => { /// let (c, n) = c.recv(); /// assert_eq!(42, n); /// c.close(); /// }, /// String => { /// c.recv().0.close(); /// }, /// Quit => { /// c.close(); /// } /// } /// } /// /// fn cli(c: Chan<(), Choose<Send<u64, Eps>, Choose<Send<String, Eps>, Eps>>>) { /// c.sel1().send(42).close(); /// } /// /// fn main() { /// let (s, c) = session_channel(); /// spawn(move|| cli(c)); /// srv(s); /// } /// ``` /// /// The identifiers on the left-hand side of the arrows have no semantic /// meaning, they only provide a meaningful name for the reader. #[macro_export] macro_rules! offer { ( $id:ident, $branch:ident => $code:expr, $($t:tt)+ ) => ( match $id.offer() { $crate::Left($id) => $code, $crate::Right($id) => offer!{ $id, $($t)+ } } ); ( $id:ident, $branch:ident => $code:expr ) => ( $code ) } /// Returns the channel unchanged on `TryRecvError::Empty`. #[macro_export] macro_rules! try_offer { ( $id:ident, $branch:ident => $code:expr, $($t:tt)+ ) => ( match $id.try_offer() { Ok($crate::Left($id)) => $code, Ok($crate::Right($id)) => try_offer!{ $id, $($t)+ }, Err($id) => Err($id) } ); ( $id:ident, $branch:ident => $code:expr ) => ( $code ) } /// This macro plays the same role as the `select!` macro does for `Receiver`s. /// /// It also supports a second form with `Offer`s (see the example below). /// /// # Examples /// /// ```rust /// extern crate session_types; /// use session_types::*; /// use std::thread::spawn; /// /// fn send_str(c: Chan<(), Send<String, Eps>>) { /// c.send("Hello, World!".to_string()).close(); /// } /// /// fn send_usize(c: Chan<(), Send<usize, Eps>>) { /// c.send(42).close(); /// } /// /// fn main() { /// let (tcs, rcs) = session_channel(); /// let (tcu, rcu) = session_channel(); /// /// // Spawn threads /// spawn(move|| send_str(tcs)); /// spawn(move|| send_usize(tcu)); /// /// chan_select! { /// (c, s) = rcs.recv() => { /// assert_eq!("Hello, World!".to_string(), s); /// c.close(); /// rcu.recv().0.close(); /// }, /// (c, i) = rcu.recv() => { /// assert_eq!(42, i); /// c.close(); /// rcs.recv().0.close(); /// } /// } /// } /// ``` /// /// ```rust /// extern crate session_types; /// extern crate rand; /// /// use std::thread::spawn; /// use session_types::*; /// /// type Igo = Choose<Send<String, Eps>, Send<u64, Eps>>; /// type Ugo = Offer<Recv<String, Eps>, Recv<u64, Eps>>; /// /// fn srv(chan_one: Chan<(), Ugo>, chan_two: Chan<(), Ugo>) { /// let _ign; /// chan_select! { /// _ign = chan_one.offer() => { /// String => { /// let (c, s) = chan_one.recv(); /// assert_eq!("Hello, World!".to_string(), s); /// c.close(); /// match chan_two.offer() { /// Left(c) => c.recv().0.close(), /// Right(c) => c.recv().0.close(), /// } /// }, /// Number => { /// chan_one.recv().0.close(); /// match chan_two.offer() { /// Left(c) => c.recv().0.close(), /// Right(c) => c.recv().0.close(), /// } /// } /// }, /// _ign = chan_two.offer() => { /// String => { /// chan_two.recv().0.close(); /// match chan_one.offer() { /// Left(c) => c.recv().0.close(), /// Right(c) => c.recv().0.close(), /// } /// }, /// Number => { /// chan_two.recv().0.close(); /// match chan_one.offer() { /// Left(c) => c.recv().0.close(), /// Right(c) => c.recv().0.close(), /// } /// } /// } /// } /// } /// /// fn cli(c: Chan<(), Igo>) { /// c.sel1().send("Hello, World!".to_string()).close(); /// } /// /// fn main() { /// let (ca1, ca2) = session_channel(); ///
ChanSelect
identifier_name
foreach-nested.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. // -*- rust -*- fn two(it: &fn(int)) { it(0); it(1); } pub fn main()
{ let mut a: ~[int] = ~[-1, -1, -1, -1]; let mut p: int = 0; do two |i| { do two |j| { a[p] = 10 * i + j; p += 1; } } assert_eq!(a[0], 0); assert_eq!(a[1], 1); assert_eq!(a[2], 10); assert_eq!(a[3], 11); }
identifier_body
foreach-nested.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.
pub fn main() { let mut a: ~[int] = ~[-1, -1, -1, -1]; let mut p: int = 0; do two |i| { do two |j| { a[p] = 10 * i + j; p += 1; } } assert_eq!(a[0], 0); assert_eq!(a[1], 1); assert_eq!(a[2], 10); assert_eq!(a[3], 11); }
// -*- rust -*- fn two(it: &fn(int)) { it(0); it(1); }
random_line_split
foreach-nested.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. // -*- rust -*- fn two(it: &fn(int)) { it(0); it(1); } pub fn
() { let mut a: ~[int] = ~[-1, -1, -1, -1]; let mut p: int = 0; do two |i| { do two |j| { a[p] = 10 * i + j; p += 1; } } assert_eq!(a[0], 0); assert_eq!(a[1], 1); assert_eq!(a[2], 10); assert_eq!(a[3], 11); }
main
identifier_name
result.rs
use std::num; use std::io; use std::result::Result; use rusqlite::SqliteError; use std::convert::From; use db; use git2; use url; use rs_es; pub type RepoResult<T> = Result<T, RepoError>; #[derive(Debug)] pub enum RepoError { InvalidArgs(String), EnumParseError(String), DbError(db::DbError), SqlError(SqliteError), NoRemote, NoElasticSearch, NotCloned, PathUnicodeError, StringUnicodeError, GitError(git2::Error), InvalidState(String), FromUtf8Error, UrlParseError(url::ParseError), ElasticSearchError(rs_es::error::EsError), ParseIntError(num::ParseIntError), NoTreeEntryName, HeadRefHasNoDirectTarget, IoError(io::Error), BranchNotFound, } impl From<SqliteError> for RepoError { fn from(err: SqliteError) -> RepoError { RepoError::SqlError(err) } } impl From<db::DbError> for RepoError { fn from(err: db::DbError) -> RepoError { RepoError::DbError(err) } } impl From<git2::Error> for RepoError { fn from(err: git2::Error) -> RepoError { RepoError::GitError(err) } } impl From<url::ParseError> for RepoError { fn from(err: url::ParseError) -> RepoError { RepoError::UrlParseError(err) } } impl From<rs_es::error::EsError> for RepoError { fn from(err: rs_es::error::EsError) -> RepoError { RepoError::ElasticSearchError(err) } } impl From<num::ParseIntError> for RepoError { fn from(err: num::ParseIntError) -> RepoError { RepoError::ParseIntError(err) } } impl From<io::Error> for RepoError { fn
(err: io::Error) -> RepoError { RepoError::IoError(err) } }
from
identifier_name
result.rs
use std::num; use std::io; use std::result::Result; use rusqlite::SqliteError; use std::convert::From; use db; use git2; use url; use rs_es; pub type RepoResult<T> = Result<T, RepoError>; #[derive(Debug)] pub enum RepoError { InvalidArgs(String), EnumParseError(String), DbError(db::DbError), SqlError(SqliteError), NoRemote, NoElasticSearch, NotCloned, PathUnicodeError, StringUnicodeError, GitError(git2::Error), InvalidState(String), FromUtf8Error, UrlParseError(url::ParseError), ElasticSearchError(rs_es::error::EsError), ParseIntError(num::ParseIntError), NoTreeEntryName, HeadRefHasNoDirectTarget, IoError(io::Error), BranchNotFound, } impl From<SqliteError> for RepoError { fn from(err: SqliteError) -> RepoError { RepoError::SqlError(err) } } impl From<db::DbError> for RepoError { fn from(err: db::DbError) -> RepoError { RepoError::DbError(err) } } impl From<git2::Error> for RepoError { fn from(err: git2::Error) -> RepoError
} impl From<url::ParseError> for RepoError { fn from(err: url::ParseError) -> RepoError { RepoError::UrlParseError(err) } } impl From<rs_es::error::EsError> for RepoError { fn from(err: rs_es::error::EsError) -> RepoError { RepoError::ElasticSearchError(err) } } impl From<num::ParseIntError> for RepoError { fn from(err: num::ParseIntError) -> RepoError { RepoError::ParseIntError(err) } } impl From<io::Error> for RepoError { fn from(err: io::Error) -> RepoError { RepoError::IoError(err) } }
{ RepoError::GitError(err) }
identifier_body
result.rs
use std::num; use std::io; use std::result::Result; use rusqlite::SqliteError; use std::convert::From; use db; use git2; use url; use rs_es; pub type RepoResult<T> = Result<T, RepoError>; #[derive(Debug)] pub enum RepoError { InvalidArgs(String), EnumParseError(String), DbError(db::DbError), SqlError(SqliteError), NoRemote, NoElasticSearch, NotCloned, PathUnicodeError, StringUnicodeError, GitError(git2::Error), InvalidState(String), FromUtf8Error, UrlParseError(url::ParseError), ElasticSearchError(rs_es::error::EsError), ParseIntError(num::ParseIntError), NoTreeEntryName, HeadRefHasNoDirectTarget, IoError(io::Error), BranchNotFound, } impl From<SqliteError> for RepoError { fn from(err: SqliteError) -> RepoError { RepoError::SqlError(err) } } impl From<db::DbError> for RepoError { fn from(err: db::DbError) -> RepoError { RepoError::DbError(err) } } impl From<git2::Error> for RepoError { fn from(err: git2::Error) -> RepoError { RepoError::GitError(err) } } impl From<url::ParseError> for RepoError { fn from(err: url::ParseError) -> RepoError { RepoError::UrlParseError(err) } } impl From<rs_es::error::EsError> for RepoError { fn from(err: rs_es::error::EsError) -> RepoError { RepoError::ElasticSearchError(err) } } impl From<num::ParseIntError> for RepoError { fn from(err: num::ParseIntError) -> RepoError {
fn from(err: io::Error) -> RepoError { RepoError::IoError(err) } }
RepoError::ParseIntError(err) } } impl From<io::Error> for RepoError {
random_line_split
test.rs
use std::time::{Instant, Duration}; use scheduler::{oneshot_ms, periodic_ms}; struct ElapsedChecker { start: Instant } impl ElapsedChecker { fn new() -> ElapsedChecker { ElapsedChecker { start: Instant::now() } } fn check(&self, expected_ms: u64) { let actual_elapsed = self.start.elapsed(); let expected = Duration::from_millis(expected_ms); assert!(actual_elapsed > Duration::from_millis(100), "Less than 100ms elapsed"); assert!(actual_elapsed-Duration::from_millis(100) < expected, "Elapsed too late: {:?} instead of {:?}", actual_elapsed, expected); assert!(actual_elapsed+Duration::from_millis(100) > expected, "Elapsed too soon: {:?} instead of {:?}", actual_elapsed, expected); } } #[test] fn simple_wait() { let checker = ElapsedChecker::new(); let timer = oneshot_ms(1400); timer.recv().unwrap(); checker.check(1400); } #[test] fn several_concurrent_waits() { let checker = ElapsedChecker::new(); let medium = oneshot_ms(1400); let short = oneshot_ms(300); let long = oneshot_ms(2000); short.recv().unwrap(); checker.check(300); medium.recv().unwrap(); checker.check(1400); long.recv().unwrap(); checker.check(2000); } #[test] fn several_concurrent_waits_misordered() { let checker = ElapsedChecker::new(); let medium = oneshot_ms(1400); let short = oneshot_ms(300); let long = oneshot_ms(2000); // We wait for the last timer before we check the others, // so they should all recv immediately after the first one. long.recv().unwrap(); checker.check(2000); short.recv().unwrap(); checker.check(2000); medium.recv().unwrap(); checker.check(2000); } #[test] fn
() { let checker = ElapsedChecker::new(); let p = periodic_ms(200); for i in 1..10 { p.recv().unwrap(); checker.check(i*200); } }
simple_periodic
identifier_name
test.rs
use std::time::{Instant, Duration}; use scheduler::{oneshot_ms, periodic_ms}; struct ElapsedChecker { start: Instant } impl ElapsedChecker { fn new() -> ElapsedChecker { ElapsedChecker { start: Instant::now() } } fn check(&self, expected_ms: u64) { let actual_elapsed = self.start.elapsed(); let expected = Duration::from_millis(expected_ms);
assert!(actual_elapsed+Duration::from_millis(100) > expected, "Elapsed too soon: {:?} instead of {:?}", actual_elapsed, expected); } } #[test] fn simple_wait() { let checker = ElapsedChecker::new(); let timer = oneshot_ms(1400); timer.recv().unwrap(); checker.check(1400); } #[test] fn several_concurrent_waits() { let checker = ElapsedChecker::new(); let medium = oneshot_ms(1400); let short = oneshot_ms(300); let long = oneshot_ms(2000); short.recv().unwrap(); checker.check(300); medium.recv().unwrap(); checker.check(1400); long.recv().unwrap(); checker.check(2000); } #[test] fn several_concurrent_waits_misordered() { let checker = ElapsedChecker::new(); let medium = oneshot_ms(1400); let short = oneshot_ms(300); let long = oneshot_ms(2000); // We wait for the last timer before we check the others, // so they should all recv immediately after the first one. long.recv().unwrap(); checker.check(2000); short.recv().unwrap(); checker.check(2000); medium.recv().unwrap(); checker.check(2000); } #[test] fn simple_periodic() { let checker = ElapsedChecker::new(); let p = periodic_ms(200); for i in 1..10 { p.recv().unwrap(); checker.check(i*200); } }
assert!(actual_elapsed > Duration::from_millis(100), "Less than 100ms elapsed"); assert!(actual_elapsed-Duration::from_millis(100) < expected, "Elapsed too late: {:?} instead of {:?}", actual_elapsed, expected);
random_line_split
test.rs
use std::time::{Instant, Duration}; use scheduler::{oneshot_ms, periodic_ms}; struct ElapsedChecker { start: Instant } impl ElapsedChecker { fn new() -> ElapsedChecker { ElapsedChecker { start: Instant::now() } } fn check(&self, expected_ms: u64) { let actual_elapsed = self.start.elapsed(); let expected = Duration::from_millis(expected_ms); assert!(actual_elapsed > Duration::from_millis(100), "Less than 100ms elapsed"); assert!(actual_elapsed-Duration::from_millis(100) < expected, "Elapsed too late: {:?} instead of {:?}", actual_elapsed, expected); assert!(actual_elapsed+Duration::from_millis(100) > expected, "Elapsed too soon: {:?} instead of {:?}", actual_elapsed, expected); } } #[test] fn simple_wait() { let checker = ElapsedChecker::new(); let timer = oneshot_ms(1400); timer.recv().unwrap(); checker.check(1400); } #[test] fn several_concurrent_waits()
#[test] fn several_concurrent_waits_misordered() { let checker = ElapsedChecker::new(); let medium = oneshot_ms(1400); let short = oneshot_ms(300); let long = oneshot_ms(2000); // We wait for the last timer before we check the others, // so they should all recv immediately after the first one. long.recv().unwrap(); checker.check(2000); short.recv().unwrap(); checker.check(2000); medium.recv().unwrap(); checker.check(2000); } #[test] fn simple_periodic() { let checker = ElapsedChecker::new(); let p = periodic_ms(200); for i in 1..10 { p.recv().unwrap(); checker.check(i*200); } }
{ let checker = ElapsedChecker::new(); let medium = oneshot_ms(1400); let short = oneshot_ms(300); let long = oneshot_ms(2000); short.recv().unwrap(); checker.check(300); medium.recv().unwrap(); checker.check(1400); long.recv().unwrap(); checker.check(2000); }
identifier_body
builders.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
// specific language governing permissions and limitations // under the License. ///! Many builders are available to easily create different types of arrow arrays extern crate arrow; use arrow::array::Int32Builder; fn main() { // Primitive Arrays // // Primitive arrays are arrays of fixed-width primitive types (bool, u8, u16, u32, // u64, i8, i16, i32, i64, f32, f64) // Create a new builder with a capacity of 100 let mut primitive_array_builder = Int32Builder::new(100); // Append an individual primitive value primitive_array_builder.append_value(55).unwrap(); // Append a null value primitive_array_builder.append_null().unwrap(); // Append a slice of primitive values primitive_array_builder.append_slice(&[39, 89, 12]).unwrap(); // Build the `PrimitiveArray` let _primitive_array = primitive_array_builder.finish(); }
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the
random_line_split
builders.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. ///! Many builders are available to easily create different types of arrow arrays extern crate arrow; use arrow::array::Int32Builder; fn main()
}
{ // Primitive Arrays // // Primitive arrays are arrays of fixed-width primitive types (bool, u8, u16, u32, // u64, i8, i16, i32, i64, f32, f64) // Create a new builder with a capacity of 100 let mut primitive_array_builder = Int32Builder::new(100); // Append an individual primitive value primitive_array_builder.append_value(55).unwrap(); // Append a null value primitive_array_builder.append_null().unwrap(); // Append a slice of primitive values primitive_array_builder.append_slice(&[39, 89, 12]).unwrap(); // Build the `PrimitiveArray` let _primitive_array = primitive_array_builder.finish();
identifier_body
builders.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. ///! Many builders are available to easily create different types of arrow arrays extern crate arrow; use arrow::array::Int32Builder; fn
() { // Primitive Arrays // // Primitive arrays are arrays of fixed-width primitive types (bool, u8, u16, u32, // u64, i8, i16, i32, i64, f32, f64) // Create a new builder with a capacity of 100 let mut primitive_array_builder = Int32Builder::new(100); // Append an individual primitive value primitive_array_builder.append_value(55).unwrap(); // Append a null value primitive_array_builder.append_null().unwrap(); // Append a slice of primitive values primitive_array_builder.append_slice(&[39, 89, 12]).unwrap(); // Build the `PrimitiveArray` let _primitive_array = primitive_array_builder.finish(); }
main
identifier_name
build.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. extern crate build_helper; extern crate cmake; use std::env; use build_helper::sanitizer_lib_boilerplate; use cmake::Config; fn
() { if let Some(llvm_config) = env::var_os("LLVM_CONFIG") { let (native, target) = match sanitizer_lib_boilerplate("msan") { Ok(native) => native, _ => return, }; Config::new(&native.src_dir) .define("COMPILER_RT_BUILD_SANITIZERS", "ON") .define("COMPILER_RT_BUILD_BUILTINS", "OFF") .define("COMPILER_RT_BUILD_XRAY", "OFF") .define("LLVM_CONFIG_PATH", llvm_config) .out_dir(&native.out_dir) .build_target(&target) .build(); } println!("cargo:rerun-if-env-changed=LLVM_CONFIG"); }
main
identifier_name
build.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. extern crate build_helper; extern crate cmake; use std::env; use build_helper::sanitizer_lib_boilerplate; use cmake::Config; fn main()
{ if let Some(llvm_config) = env::var_os("LLVM_CONFIG") { let (native, target) = match sanitizer_lib_boilerplate("msan") { Ok(native) => native, _ => return, }; Config::new(&native.src_dir) .define("COMPILER_RT_BUILD_SANITIZERS", "ON") .define("COMPILER_RT_BUILD_BUILTINS", "OFF") .define("COMPILER_RT_BUILD_XRAY", "OFF") .define("LLVM_CONFIG_PATH", llvm_config) .out_dir(&native.out_dir) .build_target(&target) .build(); } println!("cargo:rerun-if-env-changed=LLVM_CONFIG"); }
identifier_body
build.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.
use build_helper::sanitizer_lib_boilerplate; use cmake::Config; fn main() { if let Some(llvm_config) = env::var_os("LLVM_CONFIG") { let (native, target) = match sanitizer_lib_boilerplate("msan") { Ok(native) => native, _ => return, }; Config::new(&native.src_dir) .define("COMPILER_RT_BUILD_SANITIZERS", "ON") .define("COMPILER_RT_BUILD_BUILTINS", "OFF") .define("COMPILER_RT_BUILD_XRAY", "OFF") .define("LLVM_CONFIG_PATH", llvm_config) .out_dir(&native.out_dir) .build_target(&target) .build(); } println!("cargo:rerun-if-env-changed=LLVM_CONFIG"); }
extern crate build_helper; extern crate cmake; use std::env;
random_line_split
numeric-method-autoexport.rs
// xfail-pretty // 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 file is intended to test only that methods are automatically // reachable for each numeric type, for each exported impl, with no imports // necessary. Testing the methods of the impls is done within the source // file for each numeric type. pub fn main() { // ints // num assert!(15i.add(&6) == 21); assert!(15i8.add(&6i8) == 21i8);
// uints // num assert!(15u.add(&6u) == 21u); assert!(15u8.add(&6u8) == 21u8); assert!(15u16.add(&6u16) == 21u16); assert!(15u32.add(&6u32) == 21u32); assert!(15u64.add(&6u64) == 21u64); // times 15u.times(|| false); // floats // num assert!(10f.to_int() == 10); assert!(10f32.to_int() == 10); assert!(10f64.to_int() == 10); }
assert!(15i16.add(&6i16) == 21i16); assert!(15i32.add(&6i32) == 21i32); assert!(15i64.add(&6i64) == 21i64);
random_line_split
numeric-method-autoexport.rs
// xfail-pretty // 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 file is intended to test only that methods are automatically // reachable for each numeric type, for each exported impl, with no imports // necessary. Testing the methods of the impls is done within the source // file for each numeric type. pub fn main()
// floats // num assert!(10f.to_int() == 10); assert!(10f32.to_int() == 10); assert!(10f64.to_int() == 10); }
{ // ints // num assert!(15i.add(&6) == 21); assert!(15i8.add(&6i8) == 21i8); assert!(15i16.add(&6i16) == 21i16); assert!(15i32.add(&6i32) == 21i32); assert!(15i64.add(&6i64) == 21i64); // uints // num assert!(15u.add(&6u) == 21u); assert!(15u8.add(&6u8) == 21u8); assert!(15u16.add(&6u16) == 21u16); assert!(15u32.add(&6u32) == 21u32); assert!(15u64.add(&6u64) == 21u64); // times 15u.times(|| false);
identifier_body
numeric-method-autoexport.rs
// xfail-pretty // 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 file is intended to test only that methods are automatically // reachable for each numeric type, for each exported impl, with no imports // necessary. Testing the methods of the impls is done within the source // file for each numeric type. pub fn
() { // ints // num assert!(15i.add(&6) == 21); assert!(15i8.add(&6i8) == 21i8); assert!(15i16.add(&6i16) == 21i16); assert!(15i32.add(&6i32) == 21i32); assert!(15i64.add(&6i64) == 21i64); // uints // num assert!(15u.add(&6u) == 21u); assert!(15u8.add(&6u8) == 21u8); assert!(15u16.add(&6u16) == 21u16); assert!(15u32.add(&6u32) == 21u32); assert!(15u64.add(&6u64) == 21u64); // times 15u.times(|| false); // floats // num assert!(10f.to_int() == 10); assert!(10f32.to_int() == 10); assert!(10f64.to_int() == 10); }
main
identifier_name
image_test.rs
extern crate glium; extern crate glium_graphics; extern crate graphics; extern crate image; extern crate piston; use glium_graphics::{Flip, Glium2d, GliumWindow, OpenGL, Texture, TextureSettings}; use piston::event_loop::EventLoop; use piston::input::RenderEvent; use piston::window::WindowSettings; fn
() { let opengl = OpenGL::V3_2; let (w, h) = (300, 300); let ref mut window: GliumWindow = WindowSettings::new("glium_graphics: image_test", [w, h]) .exit_on_esc(true) .graphics_api(opengl) .build() .unwrap(); let rust_logo = Texture::from_path( window, "assets/rust.png", Flip::None, &TextureSettings::new(), ) .unwrap(); let mut g2d = Glium2d::new(opengl, window); window.set_lazy(true); while let Some(e) = window.next() { use graphics::*; if let Some(args) = e.render_args() { let mut target = window.draw(); g2d.draw(&mut target, args.viewport(), |c, g| { clear(color::WHITE, g); rectangle( [1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 100.0, 100.0], c.transform, g, ); rectangle( [0.0, 1.0, 0.0, 0.3], [50.0, 50.0, 100.0, 100.0], c.transform, g, ); image(&rust_logo, c.transform.trans(100.0, 100.0), g); }); target.finish().unwrap(); } } }
main
identifier_name
image_test.rs
extern crate glium; extern crate glium_graphics; extern crate graphics; extern crate image; extern crate piston; use glium_graphics::{Flip, Glium2d, GliumWindow, OpenGL, Texture, TextureSettings}; use piston::event_loop::EventLoop; use piston::input::RenderEvent; use piston::window::WindowSettings; fn main() { let opengl = OpenGL::V3_2; let (w, h) = (300, 300); let ref mut window: GliumWindow = WindowSettings::new("glium_graphics: image_test", [w, h]) .exit_on_esc(true) .graphics_api(opengl) .build() .unwrap(); let rust_logo = Texture::from_path( window, "assets/rust.png", Flip::None, &TextureSettings::new(), ) .unwrap(); let mut g2d = Glium2d::new(opengl, window); window.set_lazy(true); while let Some(e) = window.next() { use graphics::*; if let Some(args) = e.render_args()
} }
{ let mut target = window.draw(); g2d.draw(&mut target, args.viewport(), |c, g| { clear(color::WHITE, g); rectangle( [1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 100.0, 100.0], c.transform, g, ); rectangle( [0.0, 1.0, 0.0, 0.3], [50.0, 50.0, 100.0, 100.0], c.transform, g, ); image(&rust_logo, c.transform.trans(100.0, 100.0), g); }); target.finish().unwrap(); }
conditional_block
image_test.rs
extern crate glium; extern crate glium_graphics; extern crate graphics; extern crate image; extern crate piston; use glium_graphics::{Flip, Glium2d, GliumWindow, OpenGL, Texture, TextureSettings}; use piston::event_loop::EventLoop; use piston::input::RenderEvent; use piston::window::WindowSettings; fn main()
use graphics::*; if let Some(args) = e.render_args() { let mut target = window.draw(); g2d.draw(&mut target, args.viewport(), |c, g| { clear(color::WHITE, g); rectangle( [1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 100.0, 100.0], c.transform, g, ); rectangle( [0.0, 1.0, 0.0, 0.3], [50.0, 50.0, 100.0, 100.0], c.transform, g, ); image(&rust_logo, c.transform.trans(100.0, 100.0), g); }); target.finish().unwrap(); } } }
{ let opengl = OpenGL::V3_2; let (w, h) = (300, 300); let ref mut window: GliumWindow = WindowSettings::new("glium_graphics: image_test", [w, h]) .exit_on_esc(true) .graphics_api(opengl) .build() .unwrap(); let rust_logo = Texture::from_path( window, "assets/rust.png", Flip::None, &TextureSettings::new(), ) .unwrap(); let mut g2d = Glium2d::new(opengl, window); window.set_lazy(true); while let Some(e) = window.next() {
identifier_body
image_test.rs
extern crate glium; extern crate glium_graphics; extern crate graphics; extern crate image; extern crate piston; use glium_graphics::{Flip, Glium2d, GliumWindow, OpenGL, Texture, TextureSettings}; use piston::event_loop::EventLoop; use piston::input::RenderEvent; use piston::window::WindowSettings;
let ref mut window: GliumWindow = WindowSettings::new("glium_graphics: image_test", [w, h]) .exit_on_esc(true) .graphics_api(opengl) .build() .unwrap(); let rust_logo = Texture::from_path( window, "assets/rust.png", Flip::None, &TextureSettings::new(), ) .unwrap(); let mut g2d = Glium2d::new(opengl, window); window.set_lazy(true); while let Some(e) = window.next() { use graphics::*; if let Some(args) = e.render_args() { let mut target = window.draw(); g2d.draw(&mut target, args.viewport(), |c, g| { clear(color::WHITE, g); rectangle( [1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 100.0, 100.0], c.transform, g, ); rectangle( [0.0, 1.0, 0.0, 0.3], [50.0, 50.0, 100.0, 100.0], c.transform, g, ); image(&rust_logo, c.transform.trans(100.0, 100.0), g); }); target.finish().unwrap(); } } }
fn main() { let opengl = OpenGL::V3_2; let (w, h) = (300, 300);
random_line_split
monad.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. trait vec_monad<A> { fn bind<B>(&self, f: |&A| -> Vec<B> ) -> Vec<B> ; } impl<A> vec_monad<A> for Vec<A> { fn bind<B>(&self, f: |&A| -> Vec<B> ) -> Vec<B> { let mut r = Vec::new(); for elt in self.iter() { r.push_all_move(f(elt)); } r } } trait option_monad<A> { fn bind<B>(&self, f: |&A| -> Option<B>) -> Option<B>; } impl<A> option_monad<A> for Option<A> { fn bind<B>(&self, f: |&A| -> Option<B>) -> Option<B> { match *self { Some(ref a) => { f(a) } None => { None } } } } fn transform(x: Option<int>) -> Option<String> { x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_str()) ) } pub fn main()
{ assert_eq!(transform(Some(10)), Some("11".to_string())); assert_eq!(transform(None), None); assert!((vec!("hi".to_string())) .bind(|x| vec!(x.clone(), format!("{}!", x)) ) .bind(|x| vec!(x.clone(), format!("{}?", x)) ) == vec!("hi".to_string(), "hi?".to_string(), "hi!".to_string(), "hi!?".to_string())); }
identifier_body
monad.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. trait vec_monad<A> { fn bind<B>(&self, f: |&A| -> Vec<B> ) -> Vec<B> ; } impl<A> vec_monad<A> for Vec<A> { fn bind<B>(&self, f: |&A| -> Vec<B> ) -> Vec<B> { let mut r = Vec::new(); for elt in self.iter() { r.push_all_move(f(elt)); } r } } trait option_monad<A> { fn bind<B>(&self, f: |&A| -> Option<B>) -> Option<B>; } impl<A> option_monad<A> for Option<A> { fn
<B>(&self, f: |&A| -> Option<B>) -> Option<B> { match *self { Some(ref a) => { f(a) } None => { None } } } } fn transform(x: Option<int>) -> Option<String> { x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_str()) ) } pub fn main() { assert_eq!(transform(Some(10)), Some("11".to_string())); assert_eq!(transform(None), None); assert!((vec!("hi".to_string())) .bind(|x| vec!(x.clone(), format!("{}!", x)) ) .bind(|x| vec!(x.clone(), format!("{}?", x)) ) == vec!("hi".to_string(), "hi?".to_string(), "hi!".to_string(), "hi!?".to_string())); }
bind
identifier_name
monad.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. trait vec_monad<A> { fn bind<B>(&self, f: |&A| -> Vec<B> ) -> Vec<B> ; } impl<A> vec_monad<A> for Vec<A> { fn bind<B>(&self, f: |&A| -> Vec<B> ) -> Vec<B> { let mut r = Vec::new(); for elt in self.iter() { r.push_all_move(f(elt)); } r } } trait option_monad<A> { fn bind<B>(&self, f: |&A| -> Option<B>) -> Option<B>; } impl<A> option_monad<A> for Option<A> { fn bind<B>(&self, f: |&A| -> Option<B>) -> Option<B> { match *self { Some(ref a) => { f(a) } None => { None } } } } fn transform(x: Option<int>) -> Option<String> { x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_str()) ) } pub fn main() { assert_eq!(transform(Some(10)), Some("11".to_string())); assert_eq!(transform(None), None); assert!((vec!("hi".to_string())) .bind(|x| vec!(x.clone(), format!("{}!", x)) )
vec!("hi".to_string(), "hi?".to_string(), "hi!".to_string(), "hi!?".to_string())); }
.bind(|x| vec!(x.clone(), format!("{}?", x)) ) ==
random_line_split
lib.rs
pub use self::{animal::*, food::*, world::*}; mod animal; mod food; mod world; use lib_simulation as sim; use rand::prelude::*; use serde::Serialize; use wasm_bindgen::prelude::*; #[wasm_bindgen] pub struct Simulation { rng: ThreadRng, sim: sim::Simulation, } #[wasm_bindgen] impl Simulation { #[wasm_bindgen(constructor)] pub fn new(config: JsValue) -> Self { let config: sim::Config = config.into_serde().unwrap(); let mut rng = thread_rng(); let sim = sim::Simulation::random(config, &mut rng); Self { rng, sim } } pub fn default_config() -> JsValue { JsValue::from_serde(&sim::Config::default()).unwrap() } pub fn config(&self) -> JsValue { JsValue::from_serde(self.sim.config()).unwrap() }
JsValue::from_serde(&world).unwrap() } pub fn step(&mut self) -> Option<String> { self.sim.step(&mut self.rng).map(|stats| stats.to_string()) } pub fn train(&mut self) -> String { self.sim.train(&mut self.rng).to_string() } }
pub fn world(&self) -> JsValue { let world = World::from(self.sim.world());
random_line_split
lib.rs
pub use self::{animal::*, food::*, world::*}; mod animal; mod food; mod world; use lib_simulation as sim; use rand::prelude::*; use serde::Serialize; use wasm_bindgen::prelude::*; #[wasm_bindgen] pub struct Simulation { rng: ThreadRng, sim: sim::Simulation, } #[wasm_bindgen] impl Simulation { #[wasm_bindgen(constructor)] pub fn new(config: JsValue) -> Self { let config: sim::Config = config.into_serde().unwrap(); let mut rng = thread_rng(); let sim = sim::Simulation::random(config, &mut rng); Self { rng, sim } } pub fn default_config() -> JsValue { JsValue::from_serde(&sim::Config::default()).unwrap() } pub fn
(&self) -> JsValue { JsValue::from_serde(self.sim.config()).unwrap() } pub fn world(&self) -> JsValue { let world = World::from(self.sim.world()); JsValue::from_serde(&world).unwrap() } pub fn step(&mut self) -> Option<String> { self.sim.step(&mut self.rng).map(|stats| stats.to_string()) } pub fn train(&mut self) -> String { self.sim.train(&mut self.rng).to_string() } }
config
identifier_name
shootout-mandelbrot.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. extern crate sync; use std::io; use sync::Future; static ITER: int = 50; static LIMIT: f64 = 2.0;
fn write_line(init_i: f64, vec_init_r: &[f64], res: &mut Vec<u8>) { for chunk_init_r in vec_init_r.chunks(8) { let mut cur_byte = 0xff; let mut cur_bitmask = 0x80; for &init_r in chunk_init_r.iter() { let mut cur_r = init_r; let mut cur_i = init_i; for _ in range(0, ITER) { let r = cur_r; let i = cur_i; cur_r = r * r - i * i + init_r; cur_i = 2.0 * r * i + init_i; if r * r + i * i > LIMIT * LIMIT { cur_byte &=!cur_bitmask; break; } } cur_bitmask >>= 1; } res.push(cur_byte); } } fn mandelbrot<W: io::Writer>(w: uint, mut out: W) -> io::IoResult<()> { // Ensure w and h are multiples of 8. let w = (w + 7) / 8 * 8; let h = w; let chunk_size = h / 8; let data: Vec<Future<Vec<u8>>> = range(0u, 8).map(|i| Future::spawn(proc () { let vec_init_r = Vec::from_fn(w, |x| 2.0 * (x as f64) / (w as f64) - 1.5); let mut res: Vec<u8> = Vec::with_capacity((chunk_size * w) / 8); for y in range(i * chunk_size, (i + 1) * chunk_size) { let init_i = 2.0 * (y as f64) / (h as f64) - 1.0; write_line(init_i, vec_init_r.as_slice(), &mut res); } res })).collect(); try!(writeln!(&mut out as &mut Writer, "P4\n{} {}", w, h)); for res in data.move_iter() { try!(out.write(res.unwrap().as_slice())); } out.flush() } fn main() { let args = std::os::args(); let args = args.as_slice(); let res = if args.len() < 2 { println!("Test mode: do not dump the image because it's not utf8, \ which interferes with the test runner."); mandelbrot(1000, std::io::util::NullWriter) } else { mandelbrot(from_str(args[1]).unwrap(), std::io::stdout()) }; res.unwrap(); }
random_line_split
shootout-mandelbrot.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. extern crate sync; use std::io; use sync::Future; static ITER: int = 50; static LIMIT: f64 = 2.0; fn write_line(init_i: f64, vec_init_r: &[f64], res: &mut Vec<u8>)
res.push(cur_byte); } } fn mandelbrot<W: io::Writer>(w: uint, mut out: W) -> io::IoResult<()> { // Ensure w and h are multiples of 8. let w = (w + 7) / 8 * 8; let h = w; let chunk_size = h / 8; let data: Vec<Future<Vec<u8>>> = range(0u, 8).map(|i| Future::spawn(proc () { let vec_init_r = Vec::from_fn(w, |x| 2.0 * (x as f64) / (w as f64) - 1.5); let mut res: Vec<u8> = Vec::with_capacity((chunk_size * w) / 8); for y in range(i * chunk_size, (i + 1) * chunk_size) { let init_i = 2.0 * (y as f64) / (h as f64) - 1.0; write_line(init_i, vec_init_r.as_slice(), &mut res); } res })).collect(); try!(writeln!(&mut out as &mut Writer, "P4\n{} {}", w, h)); for res in data.move_iter() { try!(out.write(res.unwrap().as_slice())); } out.flush() } fn main() { let args = std::os::args(); let args = args.as_slice(); let res = if args.len() < 2 { println!("Test mode: do not dump the image because it's not utf8, \ which interferes with the test runner."); mandelbrot(1000, std::io::util::NullWriter) } else { mandelbrot(from_str(args[1]).unwrap(), std::io::stdout()) }; res.unwrap(); }
{ for chunk_init_r in vec_init_r.chunks(8) { let mut cur_byte = 0xff; let mut cur_bitmask = 0x80; for &init_r in chunk_init_r.iter() { let mut cur_r = init_r; let mut cur_i = init_i; for _ in range(0, ITER) { let r = cur_r; let i = cur_i; cur_r = r * r - i * i + init_r; cur_i = 2.0 * r * i + init_i; if r * r + i * i > LIMIT * LIMIT { cur_byte &= !cur_bitmask; break; } } cur_bitmask >>= 1; }
identifier_body
shootout-mandelbrot.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. extern crate sync; use std::io; use sync::Future; static ITER: int = 50; static LIMIT: f64 = 2.0; fn write_line(init_i: f64, vec_init_r: &[f64], res: &mut Vec<u8>) { for chunk_init_r in vec_init_r.chunks(8) { let mut cur_byte = 0xff; let mut cur_bitmask = 0x80; for &init_r in chunk_init_r.iter() { let mut cur_r = init_r; let mut cur_i = init_i; for _ in range(0, ITER) { let r = cur_r; let i = cur_i; cur_r = r * r - i * i + init_r; cur_i = 2.0 * r * i + init_i; if r * r + i * i > LIMIT * LIMIT { cur_byte &=!cur_bitmask; break; } } cur_bitmask >>= 1; } res.push(cur_byte); } } fn
<W: io::Writer>(w: uint, mut out: W) -> io::IoResult<()> { // Ensure w and h are multiples of 8. let w = (w + 7) / 8 * 8; let h = w; let chunk_size = h / 8; let data: Vec<Future<Vec<u8>>> = range(0u, 8).map(|i| Future::spawn(proc () { let vec_init_r = Vec::from_fn(w, |x| 2.0 * (x as f64) / (w as f64) - 1.5); let mut res: Vec<u8> = Vec::with_capacity((chunk_size * w) / 8); for y in range(i * chunk_size, (i + 1) * chunk_size) { let init_i = 2.0 * (y as f64) / (h as f64) - 1.0; write_line(init_i, vec_init_r.as_slice(), &mut res); } res })).collect(); try!(writeln!(&mut out as &mut Writer, "P4\n{} {}", w, h)); for res in data.move_iter() { try!(out.write(res.unwrap().as_slice())); } out.flush() } fn main() { let args = std::os::args(); let args = args.as_slice(); let res = if args.len() < 2 { println!("Test mode: do not dump the image because it's not utf8, \ which interferes with the test runner."); mandelbrot(1000, std::io::util::NullWriter) } else { mandelbrot(from_str(args[1]).unwrap(), std::io::stdout()) }; res.unwrap(); }
mandelbrot
identifier_name
shootout-mandelbrot.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. extern crate sync; use std::io; use sync::Future; static ITER: int = 50; static LIMIT: f64 = 2.0; fn write_line(init_i: f64, vec_init_r: &[f64], res: &mut Vec<u8>) { for chunk_init_r in vec_init_r.chunks(8) { let mut cur_byte = 0xff; let mut cur_bitmask = 0x80; for &init_r in chunk_init_r.iter() { let mut cur_r = init_r; let mut cur_i = init_i; for _ in range(0, ITER) { let r = cur_r; let i = cur_i; cur_r = r * r - i * i + init_r; cur_i = 2.0 * r * i + init_i; if r * r + i * i > LIMIT * LIMIT
} cur_bitmask >>= 1; } res.push(cur_byte); } } fn mandelbrot<W: io::Writer>(w: uint, mut out: W) -> io::IoResult<()> { // Ensure w and h are multiples of 8. let w = (w + 7) / 8 * 8; let h = w; let chunk_size = h / 8; let data: Vec<Future<Vec<u8>>> = range(0u, 8).map(|i| Future::spawn(proc () { let vec_init_r = Vec::from_fn(w, |x| 2.0 * (x as f64) / (w as f64) - 1.5); let mut res: Vec<u8> = Vec::with_capacity((chunk_size * w) / 8); for y in range(i * chunk_size, (i + 1) * chunk_size) { let init_i = 2.0 * (y as f64) / (h as f64) - 1.0; write_line(init_i, vec_init_r.as_slice(), &mut res); } res })).collect(); try!(writeln!(&mut out as &mut Writer, "P4\n{} {}", w, h)); for res in data.move_iter() { try!(out.write(res.unwrap().as_slice())); } out.flush() } fn main() { let args = std::os::args(); let args = args.as_slice(); let res = if args.len() < 2 { println!("Test mode: do not dump the image because it's not utf8, \ which interferes with the test runner."); mandelbrot(1000, std::io::util::NullWriter) } else { mandelbrot(from_str(args[1]).unwrap(), std::io::stdout()) }; res.unwrap(); }
{ cur_byte &= !cur_bitmask; break; }
conditional_block
module.rs
use std::collections::{HashMap, HashSet}; use super::{Expression, Call, TreePrinter, TypeDeclaration, Import, ImportName, Symbol, SymbolType, GlobalBinding, Function, ExternalFunction, prefix}; use target::Target; use compileerror::CompileResult; pub struct Module { pub name: String, pub globals: HashMap<String, GlobalBinding>, pub functions: HashMap<String, Function>, pub externals: HashMap<String, ExternalFunction>, pub types: HashMap<String, TypeDeclaration>, pub import_names: HashSet<ImportName>, pub type_checked: bool, } impl Module { pub fn new(name: &str) -> Module { Module{ name: name.into(), globals: HashMap::new(), functions: HashMap::new(), externals: HashMap::new(), types: HashMap::new(), import_names: HashSet::new(), type_checked: false, } } fn
(&self, call: &Call) -> bool { !self.functions.contains_key(&call.callee.name) && !self.externals.contains_key(&call.callee.name) } fn get_imported_symbols(&self, target: &Target) -> HashMap<String, Symbol> { let mut symbols = HashMap::new(); for func in self.functions.values() { let mut find_imported_calls = |e: &Expression| -> CompileResult<()> { match *e { Expression::Call(ref call) if self.is_imported_call(call) => { let typ = call.callee_type(target.int_size); let symbol = Symbol::new(&call.callee.name, &typ, false, &call.span, SymbolType::External); symbols.insert(call.callee.name.clone(), symbol); } _ => (), } Ok(()) }; let _ = func.expression.visit(&mut find_imported_calls); } symbols } pub fn get_exported_symbols(&self, target: &Target) -> Import { let mut import = Import::new(self.name.clone()); for (name, binding) in &self.globals { import.symbols.insert(name.clone(), Symbol::new(name, &binding.typ, binding.mutable, &binding.span, SymbolType::Global)); } for (name, function) in &self.functions { import.symbols.insert(name.clone(), Symbol::new(name, &function.sig.typ, false, &function.span, SymbolType::Normal)); if function.is_generic() { import.generics.insert(name.clone(), function.clone()); } } for (name, function) in &self.externals { import.symbols.insert(name.clone(), Symbol::new(name, &function.sig.typ, false, &function.span, SymbolType::External)); } for (name, type_decl) in &self.types { import.symbols.insert(name.clone(), Symbol::new(name, &type_decl.get_type(), false, &type_decl.span(), SymbolType::Normal)); } import.imported_symbols = self.get_imported_symbols(target); import } } impl TreePrinter for Module { fn print(&self, level: usize) { let p = prefix(level); println!("{}Module: {}", p, self.name); for i in &self.import_names { println!("{} import {}", p, i.to_namespace_string()); } println!("{}", p); for t in self.types.values() { t.print(level + 1); println!("{}", p); } for global in self.globals.values() { global.print(level + 1); println!("{}", p); } for func in self.externals.values() { func.print(level + 1); println!("{}", p); } for func in self.functions.values() { func.print(level + 1); println!("{}", p); } } }
is_imported_call
identifier_name
module.rs
use std::collections::{HashMap, HashSet}; use super::{Expression, Call, TreePrinter, TypeDeclaration, Import, ImportName, Symbol, SymbolType, GlobalBinding, Function, ExternalFunction, prefix}; use target::Target; use compileerror::CompileResult; pub struct Module { pub name: String, pub globals: HashMap<String, GlobalBinding>, pub functions: HashMap<String, Function>, pub externals: HashMap<String, ExternalFunction>, pub types: HashMap<String, TypeDeclaration>, pub import_names: HashSet<ImportName>, pub type_checked: bool, } impl Module { pub fn new(name: &str) -> Module { Module{ name: name.into(), globals: HashMap::new(), functions: HashMap::new(), externals: HashMap::new(), types: HashMap::new(), import_names: HashSet::new(), type_checked: false, } } fn is_imported_call(&self, call: &Call) -> bool { !self.functions.contains_key(&call.callee.name) && !self.externals.contains_key(&call.callee.name) } fn get_imported_symbols(&self, target: &Target) -> HashMap<String, Symbol> { let mut symbols = HashMap::new(); for func in self.functions.values() { let mut find_imported_calls = |e: &Expression| -> CompileResult<()> {
let symbol = Symbol::new(&call.callee.name, &typ, false, &call.span, SymbolType::External); symbols.insert(call.callee.name.clone(), symbol); } _ => (), } Ok(()) }; let _ = func.expression.visit(&mut find_imported_calls); } symbols } pub fn get_exported_symbols(&self, target: &Target) -> Import { let mut import = Import::new(self.name.clone()); for (name, binding) in &self.globals { import.symbols.insert(name.clone(), Symbol::new(name, &binding.typ, binding.mutable, &binding.span, SymbolType::Global)); } for (name, function) in &self.functions { import.symbols.insert(name.clone(), Symbol::new(name, &function.sig.typ, false, &function.span, SymbolType::Normal)); if function.is_generic() { import.generics.insert(name.clone(), function.clone()); } } for (name, function) in &self.externals { import.symbols.insert(name.clone(), Symbol::new(name, &function.sig.typ, false, &function.span, SymbolType::External)); } for (name, type_decl) in &self.types { import.symbols.insert(name.clone(), Symbol::new(name, &type_decl.get_type(), false, &type_decl.span(), SymbolType::Normal)); } import.imported_symbols = self.get_imported_symbols(target); import } } impl TreePrinter for Module { fn print(&self, level: usize) { let p = prefix(level); println!("{}Module: {}", p, self.name); for i in &self.import_names { println!("{} import {}", p, i.to_namespace_string()); } println!("{}", p); for t in self.types.values() { t.print(level + 1); println!("{}", p); } for global in self.globals.values() { global.print(level + 1); println!("{}", p); } for func in self.externals.values() { func.print(level + 1); println!("{}", p); } for func in self.functions.values() { func.print(level + 1); println!("{}", p); } } }
match *e { Expression::Call(ref call) if self.is_imported_call(call) => { let typ = call.callee_type(target.int_size);
random_line_split
module.rs
use std::collections::{HashMap, HashSet}; use super::{Expression, Call, TreePrinter, TypeDeclaration, Import, ImportName, Symbol, SymbolType, GlobalBinding, Function, ExternalFunction, prefix}; use target::Target; use compileerror::CompileResult; pub struct Module { pub name: String, pub globals: HashMap<String, GlobalBinding>, pub functions: HashMap<String, Function>, pub externals: HashMap<String, ExternalFunction>, pub types: HashMap<String, TypeDeclaration>, pub import_names: HashSet<ImportName>, pub type_checked: bool, } impl Module { pub fn new(name: &str) -> Module
fn is_imported_call(&self, call: &Call) -> bool { !self.functions.contains_key(&call.callee.name) && !self.externals.contains_key(&call.callee.name) } fn get_imported_symbols(&self, target: &Target) -> HashMap<String, Symbol> { let mut symbols = HashMap::new(); for func in self.functions.values() { let mut find_imported_calls = |e: &Expression| -> CompileResult<()> { match *e { Expression::Call(ref call) if self.is_imported_call(call) => { let typ = call.callee_type(target.int_size); let symbol = Symbol::new(&call.callee.name, &typ, false, &call.span, SymbolType::External); symbols.insert(call.callee.name.clone(), symbol); } _ => (), } Ok(()) }; let _ = func.expression.visit(&mut find_imported_calls); } symbols } pub fn get_exported_symbols(&self, target: &Target) -> Import { let mut import = Import::new(self.name.clone()); for (name, binding) in &self.globals { import.symbols.insert(name.clone(), Symbol::new(name, &binding.typ, binding.mutable, &binding.span, SymbolType::Global)); } for (name, function) in &self.functions { import.symbols.insert(name.clone(), Symbol::new(name, &function.sig.typ, false, &function.span, SymbolType::Normal)); if function.is_generic() { import.generics.insert(name.clone(), function.clone()); } } for (name, function) in &self.externals { import.symbols.insert(name.clone(), Symbol::new(name, &function.sig.typ, false, &function.span, SymbolType::External)); } for (name, type_decl) in &self.types { import.symbols.insert(name.clone(), Symbol::new(name, &type_decl.get_type(), false, &type_decl.span(), SymbolType::Normal)); } import.imported_symbols = self.get_imported_symbols(target); import } } impl TreePrinter for Module { fn print(&self, level: usize) { let p = prefix(level); println!("{}Module: {}", p, self.name); for i in &self.import_names { println!("{} import {}", p, i.to_namespace_string()); } println!("{}", p); for t in self.types.values() { t.print(level + 1); println!("{}", p); } for global in self.globals.values() { global.print(level + 1); println!("{}", p); } for func in self.externals.values() { func.print(level + 1); println!("{}", p); } for func in self.functions.values() { func.print(level + 1); println!("{}", p); } } }
{ Module{ name: name.into(), globals: HashMap::new(), functions: HashMap::new(), externals: HashMap::new(), types: HashMap::new(), import_names: HashSet::new(), type_checked: false, } }
identifier_body
audioclient.rs
// 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms //! this ALWAYS GENERATED file contains the definitions for the interfaces use ctypes::c_float; use shared::basetsd::{UINT32, UINT64}; use shared::guiddef::{LPCGUID, REFIID}; use shared::minwindef::{BYTE, DWORD, LPVOID}; use shared::mmreg::WAVEFORMATEX; use shared::winerror::{FACILITY_AUDCLNT, SEVERITY_ERROR, SEVERITY_SUCCESS}; use shared::wtypesbase::SCODE; use um::audiosessiontypes::AUDCLNT_SHAREMODE; use um::strmif::REFERENCE_TIME; use um::unknwnbase::{IUnknown, IUnknownVtbl}; use um::winnt::{HANDLE, HRESULT}; //1627 pub const AUDCLNT_E_NOT_INITIALIZED: HRESULT = AUDCLNT_ERR!(0x001); pub const AUDCLNT_E_ALREADY_INITIALIZED: HRESULT = AUDCLNT_ERR!(0x002); pub const AUDCLNT_E_WRONG_ENDPOINT_TYPE: HRESULT = AUDCLNT_ERR!(0x003); pub const AUDCLNT_E_DEVICE_INVALIDATED: HRESULT = AUDCLNT_ERR!(0x004); pub const AUDCLNT_E_NOT_STOPPED: HRESULT = AUDCLNT_ERR!(0x005); pub const AUDCLNT_E_BUFFER_TOO_LARGE: HRESULT = AUDCLNT_ERR!(0x006); pub const AUDCLNT_E_OUT_OF_ORDER: HRESULT = AUDCLNT_ERR!(0x007); pub const AUDCLNT_E_UNSUPPORTED_FORMAT: HRESULT = AUDCLNT_ERR!(0x008); pub const AUDCLNT_E_INVALID_SIZE: HRESULT = AUDCLNT_ERR!(0x009); pub const AUDCLNT_E_DEVICE_IN_USE: HRESULT = AUDCLNT_ERR!(0x00a);
pub const AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: HRESULT = AUDCLNT_ERR!(0x00e); pub const AUDCLNT_E_ENDPOINT_CREATE_FAILED: HRESULT = AUDCLNT_ERR!(0x00f); pub const AUDCLNT_E_SERVICE_NOT_RUNNING: HRESULT = AUDCLNT_ERR!(0x010); pub const AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: HRESULT = AUDCLNT_ERR!(0x011); pub const AUDCLNT_E_EXCLUSIVE_MODE_ONLY: HRESULT = AUDCLNT_ERR!(0x012); pub const AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: HRESULT = AUDCLNT_ERR!(0x013); pub const AUDCLNT_E_EVENTHANDLE_NOT_SET: HRESULT = AUDCLNT_ERR!(0x014); pub const AUDCLNT_E_INCORRECT_BUFFER_SIZE: HRESULT = AUDCLNT_ERR!(0x015); pub const AUDCLNT_E_BUFFER_SIZE_ERROR: HRESULT = AUDCLNT_ERR!(0x016); pub const AUDCLNT_E_CPUUSAGE_EXCEEDED: HRESULT = AUDCLNT_ERR!(0x017); pub const AUDCLNT_E_BUFFER_ERROR: HRESULT = AUDCLNT_ERR!(0x018); pub const AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED: HRESULT = AUDCLNT_ERR!(0x019); pub const AUDCLNT_E_INVALID_DEVICE_PERIOD: HRESULT = AUDCLNT_ERR!(0x020); pub const AUDCLNT_E_INVALID_STREAM_FLAG: HRESULT = AUDCLNT_ERR!(0x021); pub const AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE: HRESULT = AUDCLNT_ERR!(0x022); pub const AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES: HRESULT = AUDCLNT_ERR!(0x023); pub const AUDCLNT_E_OFFLOAD_MODE_ONLY: HRESULT = AUDCLNT_ERR!(0x024); pub const AUDCLNT_E_NONOFFLOAD_MODE_ONLY: HRESULT = AUDCLNT_ERR!(0x025); pub const AUDCLNT_E_RESOURCES_INVALIDATED: HRESULT = AUDCLNT_ERR!(0x026); pub const AUDCLNT_E_RAW_MODE_UNSUPPORTED: HRESULT = AUDCLNT_ERR!(0x027); pub const AUDCLNT_S_BUFFER_EMPTY: SCODE = AUDCLNT_SUCCESS!(0x001); pub const AUDCLNT_S_THREAD_ALREADY_REGISTERED: SCODE = AUDCLNT_SUCCESS!(0x002); pub const AUDCLNT_S_POSITION_STALLED: SCODE = AUDCLNT_SUCCESS!(0x003); ENUM!{enum AUDCLNT_BUFFERFLAGS { AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY = 0x1, AUDCLNT_BUFFERFLAGS_SILENT = 0x2, AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR = 0x4, }} DEFINE_GUID!{IID_IAudioClient, 0x1CB9AD4C, 0xDBFA, 0x4c32, 0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2} DEFINE_GUID!{IID_IAudioRenderClient, 0xF294ACFC, 0x3146, 0x4483, 0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2} DEFINE_GUID!{IID_IAudioCaptureClient, 0xc8adbd64, 0xe71e, 0x48a0, 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17} DEFINE_GUID!{IID_IAudioClock, 0xcd63314f, 0x3fba, 0x4a1b, 0x81, 0x2c, 0xef, 0x96, 0x35, 0x87, 0x28, 0xe7} DEFINE_GUID!{IID_IAudioStreamVolume, 0x93014887, 0x242d, 0x4068, 0x8a, 0x15, 0xcf, 0x5e, 0x93, 0xb9, 0x0f, 0xe3} RIDL!{#[uuid(0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2)] interface IAudioClient(IAudioClientVtbl): IUnknown(IUnknownVtbl) { fn Initialize( ShareMode: AUDCLNT_SHAREMODE, StreamFlags: DWORD, hnsBufferDuration: REFERENCE_TIME, hnsPeriodicity: REFERENCE_TIME, pFormat: *const WAVEFORMATEX, AudioSessionGuid: LPCGUID, ) -> HRESULT, fn GetBufferSize( pNumBufferFrames: *mut UINT32, ) -> HRESULT, fn GetStreamLatency( phnsLatency: *mut REFERENCE_TIME, ) -> HRESULT, fn GetCurrentPadding( pNumPaddingFrames: *mut UINT32, ) -> HRESULT, fn IsFormatSupported( ShareMode: AUDCLNT_SHAREMODE, pFormat: *const WAVEFORMATEX, ppClosestMatch: *mut *mut WAVEFORMATEX, ) -> HRESULT, fn GetMixFormat( ppDeviceFormat: *mut *mut WAVEFORMATEX, ) -> HRESULT, fn GetDevicePeriod( phnsDefaultDevicePeriod: *mut REFERENCE_TIME, phnsMinimumDevicePeriod: *mut REFERENCE_TIME, ) -> HRESULT, fn Start() -> HRESULT, fn Stop() -> HRESULT, fn Reset() -> HRESULT, fn SetEventHandle( eventHandle: HANDLE, ) -> HRESULT, fn GetService( riid: REFIID, ppv: *mut LPVOID, ) -> HRESULT, }} RIDL!{#[uuid(0xf294acfc, 0x3146, 0x4483, 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2)] interface IAudioRenderClient(IAudioRenderClientVtbl): IUnknown(IUnknownVtbl) { fn GetBuffer( NumFramesRequested: UINT32, ppData: *mut *mut BYTE, ) -> HRESULT, fn ReleaseBuffer( NumFramesWritten: UINT32, dwFlags: DWORD, ) -> HRESULT, }} RIDL!{#[uuid(0xc8adbd64, 0xe71e, 0x48a0, 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17)] interface IAudioCaptureClient(IAudioCaptureClientVtbl): IUnknown(IUnknownVtbl) { fn GetBuffer( ppData: *mut *mut BYTE, pNumFramesToRead: *mut UINT32, pdwFlags: *mut DWORD, pu64DevicePosition: *mut UINT64, pu64QPCPosition: *mut UINT64, ) -> HRESULT, fn ReleaseBuffer( NumFramesRead: UINT32, ) -> HRESULT, fn GetNextPacketSize( pNumFramesInNextPacket: *mut UINT32, ) -> HRESULT, }} RIDL!{#[uuid(0xcd63314f, 0x3fba, 0x4a1b, 0x81, 0x2c, 0xef, 0x96, 0x35, 0x87, 0x28, 0xe7)] interface IAudioClock(IAudioClockVtbl): IUnknown(IUnknownVtbl) { fn GetFrequency( pu64Frequency: *mut UINT64, ) -> HRESULT, fn GetPosition( pu64Position: *mut UINT64, pu64QPCPosition: *mut UINT64, ) -> HRESULT, fn GetCharacteristics( pdwCharacteristics: *mut DWORD, ) -> HRESULT, }} RIDL!{#[uuid(0x93014887, 0x242d, 0x4068, 0x8a, 0x15, 0xcf, 0x5e, 0x93, 0xb9, 0x0f, 0xe3)] interface IAudioStreamVolume(IAudioStreamVolumeVtbl): IUnknown(IUnknownVtbl) { fn GetChannelCount( pdwCount: *mut UINT32, ) -> HRESULT, fn SetChannelVolume( dwIndex: UINT32, fLevel: c_float, ) -> HRESULT, fn GetChannelVolume( dwIndex: UINT32, pfLevel: *mut c_float, ) -> HRESULT, fn SetAllVolumes( dwCount: UINT32, pfVolumes: *const c_float, ) -> HRESULT, fn GetAllVolumes( dwCount: UINT32, pfVolumes: *mut c_float, ) -> HRESULT, }}
pub const AUDCLNT_E_BUFFER_OPERATION_PENDING: HRESULT = AUDCLNT_ERR!(0x00b); pub const AUDCLNT_E_THREAD_NOT_REGISTERED: HRESULT = AUDCLNT_ERR!(0x00c);
random_line_split
inprocess.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 canvas_traits::webgl::webgl_channel; use canvas_traits::webgl::DOMToTextureCommand; use canvas_traits::webgl::{WebGLChan, WebGLContextId, WebGLMsg, WebGLPipeline, WebGLReceiver}; use canvas_traits::webgl::{WebGLSender, WebVRCommand, WebVRRenderHandler}; use crate::gl_context::GLContextFactory; use crate::webgl_thread::{WebGLExternalImageApi, WebGLExternalImageHandler, WebGLThread}; use euclid::Size2D; use fnv::FnvHashMap; use gleam::gl; use servo_config::prefs::PREFS; use std::rc::Rc; /// WebGL Threading API entry point that lives in the constellation. pub struct WebGLThreads(WebGLSender<WebGLMsg>); impl WebGLThreads { /// Creates a new WebGLThreads object pub fn new( gl_factory: GLContextFactory, webrender_gl: Rc<dyn gl::Gl>, webrender_api_sender: webrender_api::RenderApiSender, webvr_compositor: Option<Box<dyn WebVRRenderHandler>>, ) -> ( WebGLThreads, Box<dyn webrender::ExternalImageHandler>, Option<Box<dyn webrender::OutputImageHandler>>, ) { // This implementation creates a single `WebGLThread` for all the pipelines. let channel = WebGLThread::start( gl_factory, webrender_api_sender, webvr_compositor.map(|c| WebVRRenderWrapper(c)), ); let output_handler = if PREFS.is_dom_to_texture_enabled() { Some(Box::new(OutputHandler::new( webrender_gl.clone(), channel.clone(), ))) } else { None }; let external = WebGLExternalImageHandler::new(WebGLExternalImages::new(webrender_gl, channel.clone())); ( WebGLThreads(channel), Box::new(external), output_handler.map(|b| b as Box<_>), ) } /// Gets the WebGLThread handle for each script pipeline. pub fn pipeline(&self) -> WebGLPipeline { // This mode creates a single thread, so the existing WebGLChan is just cloned. WebGLPipeline(WebGLChan(self.0.clone())) } /// Sends a exit message to close the WebGLThreads and release all WebGLContexts. pub fn exit(&self) -> Result<(), &'static str> { self.0 .send(WebGLMsg::Exit) .map_err(|_| "Failed to send Exit message") } } /// Bridge between the webrender::ExternalImage callbacks and the WebGLThreads. struct WebGLExternalImages { webrender_gl: Rc<dyn gl::Gl>, webgl_channel: WebGLSender<WebGLMsg>, // Used to avoid creating a new channel on each received WebRender request. lock_channel: ( WebGLSender<(u32, Size2D<i32>, usize)>, WebGLReceiver<(u32, Size2D<i32>, usize)>, ), } impl WebGLExternalImages { fn new(webrender_gl: Rc<dyn gl::Gl>, channel: WebGLSender<WebGLMsg>) -> Self { Self { webrender_gl, webgl_channel: channel, lock_channel: webgl_channel().unwrap(), } } } impl WebGLExternalImageApi for WebGLExternalImages { fn lock(&mut self, ctx_id: WebGLContextId) -> (u32, Size2D<i32>) { // WebGL Thread has it's own GL command queue that we need to synchronize with the WR GL command queue. // The WebGLMsg::Lock message inserts a fence in the WebGL command queue. self.webgl_channel .send(WebGLMsg::Lock(ctx_id, self.lock_channel.0.clone())) .unwrap(); let (image_id, size, gl_sync) = self.lock_channel.1.recv().unwrap(); // The next glWaitSync call is run on the WR thread and it's used to synchronize the two // flows of OpenGL commands in order to avoid WR using a semi-ready WebGL texture. // glWaitSync doesn't block WR thread, it affects only internal OpenGL subsystem. self.webrender_gl .wait_sync(gl_sync as gl::GLsync, 0, gl::TIMEOUT_IGNORED); (image_id, size) } fn unlock(&mut self, ctx_id: WebGLContextId) { self.webgl_channel.send(WebGLMsg::Unlock(ctx_id)).unwrap(); } } /// Wrapper to send WebVR commands used in `WebGLThread`. struct WebVRRenderWrapper(Box<dyn WebVRRenderHandler>); impl WebVRRenderHandler for WebVRRenderWrapper { fn handle(&mut self, command: WebVRCommand, texture: Option<(u32, Size2D<i32>)>) { self.0.handle(command, texture); } } /// struct used to implement DOMToTexture feature and webrender::OutputImageHandler trait. type OutputHandlerData = Option<(u32, Size2D<i32>)>; struct OutputHandler { webrender_gl: Rc<dyn gl::Gl>, webgl_channel: WebGLSender<WebGLMsg>, // Used to avoid creating a new channel on each received WebRender request. lock_channel: ( WebGLSender<OutputHandlerData>, WebGLReceiver<OutputHandlerData>, ), sync_objects: FnvHashMap<webrender_api::PipelineId, gl::GLsync>, } impl OutputHandler { fn new(webrender_gl: Rc<dyn gl::Gl>, channel: WebGLSender<WebGLMsg>) -> Self { Self { webrender_gl, webgl_channel: channel,
} } /// Bridge between the WR frame outputs and WebGL to implement DOMToTexture synchronization. impl webrender::OutputImageHandler for OutputHandler { fn lock( &mut self, id: webrender_api::PipelineId, ) -> Option<(u32, webrender_api::DeviceIntSize)> { // Insert a fence in the WR command queue let gl_sync = self .webrender_gl .fence_sync(gl::SYNC_GPU_COMMANDS_COMPLETE, 0); // The lock command adds a WaitSync call on the WebGL command flow. let command = DOMToTextureCommand::Lock(id, gl_sync as usize, self.lock_channel.0.clone()); self.webgl_channel .send(WebGLMsg::DOMToTextureCommand(command)) .unwrap(); self.lock_channel.1.recv().unwrap().map(|(tex_id, size)| { ( tex_id, webrender_api::DeviceIntSize::new(size.width, size.height), ) }) } fn unlock(&mut self, id: webrender_api::PipelineId) { if let Some(gl_sync) = self.sync_objects.remove(&id) { // Flush the Sync object into the GPU's command queue to guarantee that it it's signaled. self.webrender_gl.flush(); // Mark the sync object for deletion. self.webrender_gl.delete_sync(gl_sync); } } }
lock_channel: webgl_channel().unwrap(), sync_objects: Default::default(), }
random_line_split
inprocess.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 canvas_traits::webgl::webgl_channel; use canvas_traits::webgl::DOMToTextureCommand; use canvas_traits::webgl::{WebGLChan, WebGLContextId, WebGLMsg, WebGLPipeline, WebGLReceiver}; use canvas_traits::webgl::{WebGLSender, WebVRCommand, WebVRRenderHandler}; use crate::gl_context::GLContextFactory; use crate::webgl_thread::{WebGLExternalImageApi, WebGLExternalImageHandler, WebGLThread}; use euclid::Size2D; use fnv::FnvHashMap; use gleam::gl; use servo_config::prefs::PREFS; use std::rc::Rc; /// WebGL Threading API entry point that lives in the constellation. pub struct WebGLThreads(WebGLSender<WebGLMsg>); impl WebGLThreads { /// Creates a new WebGLThreads object pub fn new( gl_factory: GLContextFactory, webrender_gl: Rc<dyn gl::Gl>, webrender_api_sender: webrender_api::RenderApiSender, webvr_compositor: Option<Box<dyn WebVRRenderHandler>>, ) -> ( WebGLThreads, Box<dyn webrender::ExternalImageHandler>, Option<Box<dyn webrender::OutputImageHandler>>, ) { // This implementation creates a single `WebGLThread` for all the pipelines. let channel = WebGLThread::start( gl_factory, webrender_api_sender, webvr_compositor.map(|c| WebVRRenderWrapper(c)), ); let output_handler = if PREFS.is_dom_to_texture_enabled() { Some(Box::new(OutputHandler::new( webrender_gl.clone(), channel.clone(), ))) } else { None }; let external = WebGLExternalImageHandler::new(WebGLExternalImages::new(webrender_gl, channel.clone())); ( WebGLThreads(channel), Box::new(external), output_handler.map(|b| b as Box<_>), ) } /// Gets the WebGLThread handle for each script pipeline. pub fn pipeline(&self) -> WebGLPipeline { // This mode creates a single thread, so the existing WebGLChan is just cloned. WebGLPipeline(WebGLChan(self.0.clone())) } /// Sends a exit message to close the WebGLThreads and release all WebGLContexts. pub fn exit(&self) -> Result<(), &'static str> { self.0 .send(WebGLMsg::Exit) .map_err(|_| "Failed to send Exit message") } } /// Bridge between the webrender::ExternalImage callbacks and the WebGLThreads. struct
{ webrender_gl: Rc<dyn gl::Gl>, webgl_channel: WebGLSender<WebGLMsg>, // Used to avoid creating a new channel on each received WebRender request. lock_channel: ( WebGLSender<(u32, Size2D<i32>, usize)>, WebGLReceiver<(u32, Size2D<i32>, usize)>, ), } impl WebGLExternalImages { fn new(webrender_gl: Rc<dyn gl::Gl>, channel: WebGLSender<WebGLMsg>) -> Self { Self { webrender_gl, webgl_channel: channel, lock_channel: webgl_channel().unwrap(), } } } impl WebGLExternalImageApi for WebGLExternalImages { fn lock(&mut self, ctx_id: WebGLContextId) -> (u32, Size2D<i32>) { // WebGL Thread has it's own GL command queue that we need to synchronize with the WR GL command queue. // The WebGLMsg::Lock message inserts a fence in the WebGL command queue. self.webgl_channel .send(WebGLMsg::Lock(ctx_id, self.lock_channel.0.clone())) .unwrap(); let (image_id, size, gl_sync) = self.lock_channel.1.recv().unwrap(); // The next glWaitSync call is run on the WR thread and it's used to synchronize the two // flows of OpenGL commands in order to avoid WR using a semi-ready WebGL texture. // glWaitSync doesn't block WR thread, it affects only internal OpenGL subsystem. self.webrender_gl .wait_sync(gl_sync as gl::GLsync, 0, gl::TIMEOUT_IGNORED); (image_id, size) } fn unlock(&mut self, ctx_id: WebGLContextId) { self.webgl_channel.send(WebGLMsg::Unlock(ctx_id)).unwrap(); } } /// Wrapper to send WebVR commands used in `WebGLThread`. struct WebVRRenderWrapper(Box<dyn WebVRRenderHandler>); impl WebVRRenderHandler for WebVRRenderWrapper { fn handle(&mut self, command: WebVRCommand, texture: Option<(u32, Size2D<i32>)>) { self.0.handle(command, texture); } } /// struct used to implement DOMToTexture feature and webrender::OutputImageHandler trait. type OutputHandlerData = Option<(u32, Size2D<i32>)>; struct OutputHandler { webrender_gl: Rc<dyn gl::Gl>, webgl_channel: WebGLSender<WebGLMsg>, // Used to avoid creating a new channel on each received WebRender request. lock_channel: ( WebGLSender<OutputHandlerData>, WebGLReceiver<OutputHandlerData>, ), sync_objects: FnvHashMap<webrender_api::PipelineId, gl::GLsync>, } impl OutputHandler { fn new(webrender_gl: Rc<dyn gl::Gl>, channel: WebGLSender<WebGLMsg>) -> Self { Self { webrender_gl, webgl_channel: channel, lock_channel: webgl_channel().unwrap(), sync_objects: Default::default(), } } } /// Bridge between the WR frame outputs and WebGL to implement DOMToTexture synchronization. impl webrender::OutputImageHandler for OutputHandler { fn lock( &mut self, id: webrender_api::PipelineId, ) -> Option<(u32, webrender_api::DeviceIntSize)> { // Insert a fence in the WR command queue let gl_sync = self .webrender_gl .fence_sync(gl::SYNC_GPU_COMMANDS_COMPLETE, 0); // The lock command adds a WaitSync call on the WebGL command flow. let command = DOMToTextureCommand::Lock(id, gl_sync as usize, self.lock_channel.0.clone()); self.webgl_channel .send(WebGLMsg::DOMToTextureCommand(command)) .unwrap(); self.lock_channel.1.recv().unwrap().map(|(tex_id, size)| { ( tex_id, webrender_api::DeviceIntSize::new(size.width, size.height), ) }) } fn unlock(&mut self, id: webrender_api::PipelineId) { if let Some(gl_sync) = self.sync_objects.remove(&id) { // Flush the Sync object into the GPU's command queue to guarantee that it it's signaled. self.webrender_gl.flush(); // Mark the sync object for deletion. self.webrender_gl.delete_sync(gl_sync); } } }
WebGLExternalImages
identifier_name
inprocess.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 canvas_traits::webgl::webgl_channel; use canvas_traits::webgl::DOMToTextureCommand; use canvas_traits::webgl::{WebGLChan, WebGLContextId, WebGLMsg, WebGLPipeline, WebGLReceiver}; use canvas_traits::webgl::{WebGLSender, WebVRCommand, WebVRRenderHandler}; use crate::gl_context::GLContextFactory; use crate::webgl_thread::{WebGLExternalImageApi, WebGLExternalImageHandler, WebGLThread}; use euclid::Size2D; use fnv::FnvHashMap; use gleam::gl; use servo_config::prefs::PREFS; use std::rc::Rc; /// WebGL Threading API entry point that lives in the constellation. pub struct WebGLThreads(WebGLSender<WebGLMsg>); impl WebGLThreads { /// Creates a new WebGLThreads object pub fn new( gl_factory: GLContextFactory, webrender_gl: Rc<dyn gl::Gl>, webrender_api_sender: webrender_api::RenderApiSender, webvr_compositor: Option<Box<dyn WebVRRenderHandler>>, ) -> ( WebGLThreads, Box<dyn webrender::ExternalImageHandler>, Option<Box<dyn webrender::OutputImageHandler>>, ) { // This implementation creates a single `WebGLThread` for all the pipelines. let channel = WebGLThread::start( gl_factory, webrender_api_sender, webvr_compositor.map(|c| WebVRRenderWrapper(c)), ); let output_handler = if PREFS.is_dom_to_texture_enabled()
else { None }; let external = WebGLExternalImageHandler::new(WebGLExternalImages::new(webrender_gl, channel.clone())); ( WebGLThreads(channel), Box::new(external), output_handler.map(|b| b as Box<_>), ) } /// Gets the WebGLThread handle for each script pipeline. pub fn pipeline(&self) -> WebGLPipeline { // This mode creates a single thread, so the existing WebGLChan is just cloned. WebGLPipeline(WebGLChan(self.0.clone())) } /// Sends a exit message to close the WebGLThreads and release all WebGLContexts. pub fn exit(&self) -> Result<(), &'static str> { self.0 .send(WebGLMsg::Exit) .map_err(|_| "Failed to send Exit message") } } /// Bridge between the webrender::ExternalImage callbacks and the WebGLThreads. struct WebGLExternalImages { webrender_gl: Rc<dyn gl::Gl>, webgl_channel: WebGLSender<WebGLMsg>, // Used to avoid creating a new channel on each received WebRender request. lock_channel: ( WebGLSender<(u32, Size2D<i32>, usize)>, WebGLReceiver<(u32, Size2D<i32>, usize)>, ), } impl WebGLExternalImages { fn new(webrender_gl: Rc<dyn gl::Gl>, channel: WebGLSender<WebGLMsg>) -> Self { Self { webrender_gl, webgl_channel: channel, lock_channel: webgl_channel().unwrap(), } } } impl WebGLExternalImageApi for WebGLExternalImages { fn lock(&mut self, ctx_id: WebGLContextId) -> (u32, Size2D<i32>) { // WebGL Thread has it's own GL command queue that we need to synchronize with the WR GL command queue. // The WebGLMsg::Lock message inserts a fence in the WebGL command queue. self.webgl_channel .send(WebGLMsg::Lock(ctx_id, self.lock_channel.0.clone())) .unwrap(); let (image_id, size, gl_sync) = self.lock_channel.1.recv().unwrap(); // The next glWaitSync call is run on the WR thread and it's used to synchronize the two // flows of OpenGL commands in order to avoid WR using a semi-ready WebGL texture. // glWaitSync doesn't block WR thread, it affects only internal OpenGL subsystem. self.webrender_gl .wait_sync(gl_sync as gl::GLsync, 0, gl::TIMEOUT_IGNORED); (image_id, size) } fn unlock(&mut self, ctx_id: WebGLContextId) { self.webgl_channel.send(WebGLMsg::Unlock(ctx_id)).unwrap(); } } /// Wrapper to send WebVR commands used in `WebGLThread`. struct WebVRRenderWrapper(Box<dyn WebVRRenderHandler>); impl WebVRRenderHandler for WebVRRenderWrapper { fn handle(&mut self, command: WebVRCommand, texture: Option<(u32, Size2D<i32>)>) { self.0.handle(command, texture); } } /// struct used to implement DOMToTexture feature and webrender::OutputImageHandler trait. type OutputHandlerData = Option<(u32, Size2D<i32>)>; struct OutputHandler { webrender_gl: Rc<dyn gl::Gl>, webgl_channel: WebGLSender<WebGLMsg>, // Used to avoid creating a new channel on each received WebRender request. lock_channel: ( WebGLSender<OutputHandlerData>, WebGLReceiver<OutputHandlerData>, ), sync_objects: FnvHashMap<webrender_api::PipelineId, gl::GLsync>, } impl OutputHandler { fn new(webrender_gl: Rc<dyn gl::Gl>, channel: WebGLSender<WebGLMsg>) -> Self { Self { webrender_gl, webgl_channel: channel, lock_channel: webgl_channel().unwrap(), sync_objects: Default::default(), } } } /// Bridge between the WR frame outputs and WebGL to implement DOMToTexture synchronization. impl webrender::OutputImageHandler for OutputHandler { fn lock( &mut self, id: webrender_api::PipelineId, ) -> Option<(u32, webrender_api::DeviceIntSize)> { // Insert a fence in the WR command queue let gl_sync = self .webrender_gl .fence_sync(gl::SYNC_GPU_COMMANDS_COMPLETE, 0); // The lock command adds a WaitSync call on the WebGL command flow. let command = DOMToTextureCommand::Lock(id, gl_sync as usize, self.lock_channel.0.clone()); self.webgl_channel .send(WebGLMsg::DOMToTextureCommand(command)) .unwrap(); self.lock_channel.1.recv().unwrap().map(|(tex_id, size)| { ( tex_id, webrender_api::DeviceIntSize::new(size.width, size.height), ) }) } fn unlock(&mut self, id: webrender_api::PipelineId) { if let Some(gl_sync) = self.sync_objects.remove(&id) { // Flush the Sync object into the GPU's command queue to guarantee that it it's signaled. self.webrender_gl.flush(); // Mark the sync object for deletion. self.webrender_gl.delete_sync(gl_sync); } } }
{ Some(Box::new(OutputHandler::new( webrender_gl.clone(), channel.clone(), ))) }
conditional_block
choose.rs
//! depends: rand = "0.3" //! depends: regex = "0.2" extern crate zaldinar_core; extern crate regex; extern crate rand; use rand::Rng; use zaldinar_core::client::PluginRegister; use zaldinar_core::events::CommandEvent; macro_rules! regex { ($s:expr) => (::regex::Regex::new($s).unwrap()) } fn choose(event: &CommandEvent) { let content = event.args.join(" "); let mut rng = rand::thread_rng(); let split = if content.contains(",") { regex!(r"\s*,\s*").split(&content).collect::<Vec<&str>>() } else { regex!(r"\s+").split(&content).collect::<Vec<&str>>() }; let message = match rng.choose(&split) { Some(v) => *v, None => "I don't have anything to choose from.", }; event.client.send_message(event.channel(), message); } fn coin(event: &CommandEvent) { let mut rng = rand::thread_rng(); let message = format!("\x01ACTION flips a coin... \x02{}\x02\x01", rng.choose(&["heads", "tails"]).unwrap()); event.client.send_message(event.channel(), message); } fn rand_command(event: &CommandEvent) { if event.args.len()!= 1 { event.client.send_message(event.channel(), "Please specify exactly one argument."); return; } let max = match event.args[0].parse::<u64>() { Ok(v) => v, Err(_) =>
, }; let mut rng = rand::thread_rng(); event.client.send_message(event.channel(), format!("{}", rng.gen_range(0, max) + 1)); } pub fn register(register: &mut PluginRegister) { register.register_command("choose", choose); register.register_command("coin", coin); register.register_command("rand", rand_command); }
{ event.client.send_message(event.channel(), format!("Invalid number '{}'", event.args[0])); return; }
conditional_block
choose.rs
//! depends: rand = "0.3" //! depends: regex = "0.2" extern crate zaldinar_core; extern crate regex; extern crate rand; use rand::Rng; use zaldinar_core::client::PluginRegister; use zaldinar_core::events::CommandEvent; macro_rules! regex { ($s:expr) => (::regex::Regex::new($s).unwrap()) } fn choose(event: &CommandEvent)
fn coin(event: &CommandEvent) { let mut rng = rand::thread_rng(); let message = format!("\x01ACTION flips a coin... \x02{}\x02\x01", rng.choose(&["heads", "tails"]).unwrap()); event.client.send_message(event.channel(), message); } fn rand_command(event: &CommandEvent) { if event.args.len()!= 1 { event.client.send_message(event.channel(), "Please specify exactly one argument."); return; } let max = match event.args[0].parse::<u64>() { Ok(v) => v, Err(_) => { event.client.send_message(event.channel(), format!("Invalid number '{}'", event.args[0])); return; }, }; let mut rng = rand::thread_rng(); event.client.send_message(event.channel(), format!("{}", rng.gen_range(0, max) + 1)); } pub fn register(register: &mut PluginRegister) { register.register_command("choose", choose); register.register_command("coin", coin); register.register_command("rand", rand_command); }
{ let content = event.args.join(" "); let mut rng = rand::thread_rng(); let split = if content.contains(",") { regex!(r"\s*,\s*").split(&content).collect::<Vec<&str>>() } else { regex!(r"\s+").split(&content).collect::<Vec<&str>>() }; let message = match rng.choose(&split) { Some(v) => *v, None => "I don't have anything to choose from.", }; event.client.send_message(event.channel(), message); }
identifier_body
choose.rs
//! depends: rand = "0.3" //! depends: regex = "0.2" extern crate zaldinar_core; extern crate regex; extern crate rand; use rand::Rng; use zaldinar_core::client::PluginRegister; use zaldinar_core::events::CommandEvent; macro_rules! regex { ($s:expr) => (::regex::Regex::new($s).unwrap()) } fn choose(event: &CommandEvent) { let content = event.args.join(" "); let mut rng = rand::thread_rng(); let split = if content.contains(",") { regex!(r"\s*,\s*").split(&content).collect::<Vec<&str>>() } else { regex!(r"\s+").split(&content).collect::<Vec<&str>>() }; let message = match rng.choose(&split) { Some(v) => *v, None => "I don't have anything to choose from.", }; event.client.send_message(event.channel(), message); } fn coin(event: &CommandEvent) { let mut rng = rand::thread_rng(); let message = format!("\x01ACTION flips a coin... \x02{}\x02\x01", rng.choose(&["heads", "tails"]).unwrap()); event.client.send_message(event.channel(), message); } fn rand_command(event: &CommandEvent) { if event.args.len()!= 1 { event.client.send_message(event.channel(), "Please specify exactly one argument."); return; } let max = match event.args[0].parse::<u64>() { Ok(v) => v, Err(_) => { event.client.send_message(event.channel(), format!("Invalid number '{}'", event.args[0])); return; }, }; let mut rng = rand::thread_rng(); event.client.send_message(event.channel(), format!("{}", rng.gen_range(0, max) + 1)); } pub fn
(register: &mut PluginRegister) { register.register_command("choose", choose); register.register_command("coin", coin); register.register_command("rand", rand_command); }
register
identifier_name
choose.rs
//! depends: rand = "0.3" //! depends: regex = "0.2" extern crate zaldinar_core; extern crate regex; extern crate rand; use rand::Rng; use zaldinar_core::client::PluginRegister; use zaldinar_core::events::CommandEvent; macro_rules! regex { ($s:expr) => (::regex::Regex::new($s).unwrap()) } fn choose(event: &CommandEvent) { let content = event.args.join(" "); let mut rng = rand::thread_rng(); let split = if content.contains(",") { regex!(r"\s*,\s*").split(&content).collect::<Vec<&str>>() } else { regex!(r"\s+").split(&content).collect::<Vec<&str>>() }; let message = match rng.choose(&split) {
event.client.send_message(event.channel(), message); } fn coin(event: &CommandEvent) { let mut rng = rand::thread_rng(); let message = format!("\x01ACTION flips a coin... \x02{}\x02\x01", rng.choose(&["heads", "tails"]).unwrap()); event.client.send_message(event.channel(), message); } fn rand_command(event: &CommandEvent) { if event.args.len()!= 1 { event.client.send_message(event.channel(), "Please specify exactly one argument."); return; } let max = match event.args[0].parse::<u64>() { Ok(v) => v, Err(_) => { event.client.send_message(event.channel(), format!("Invalid number '{}'", event.args[0])); return; }, }; let mut rng = rand::thread_rng(); event.client.send_message(event.channel(), format!("{}", rng.gen_range(0, max) + 1)); } pub fn register(register: &mut PluginRegister) { register.register_command("choose", choose); register.register_command("coin", coin); register.register_command("rand", rand_command); }
Some(v) => *v, None => "I don't have anything to choose from.", };
random_line_split
type_of.rs
, RegionEscape, Ty}; use util::ppaux; use util::ppaux::Repr; use trans::type_::Type; use std::num::Int; use syntax::abi; use syntax::ast; // LLVM doesn't like objects that are too big. Issue #17913 fn ensure_array_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, llet: Type, size: machine::llsize, scapegoat: Ty<'tcx>) { let esz = machine::llsize_of_alloc(ccx, llet); match esz.checked_mul(size) { Some(n) if n < ccx.obj_size_bound() => {} _ => { ccx.report_overbig_object(scapegoat) } } } pub fn arg_is_indirect<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg_ty: Ty<'tcx>) -> bool { !type_is_immediate(ccx, arg_ty) } pub fn return_uses_outptr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { !type_is_immediate(ccx, ty) } pub fn type_of_explicit_arg<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg_ty: Ty<'tcx>) -> Type { let llty = arg_type_of(ccx, arg_ty); if arg_is_indirect(ccx, arg_ty) { llty.ptr_to() } else { llty } } /// Yields the types of the "real" arguments for this function. For most /// functions, these are simply the types of the arguments. For functions with /// the `RustCall` ABI, however, this untuples the arguments of the function. pub fn untuple_arguments_if_necessary<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, inputs: &[Ty<'tcx>], abi: abi::Abi) -> Vec<Ty<'tcx>> { if abi!= abi::RustCall { return inputs.iter().map(|x| (*x).clone()).collect() } if inputs.len() == 0 { return Vec::new() } let mut result = Vec::new(); for (i, &arg_prior_to_tuple) in inputs.iter().enumerate() { if i < inputs.len() - 1 { result.push(arg_prior_to_tuple); } } match inputs[inputs.len() - 1].sty { ty::ty_tup(ref tupled_arguments) => { debug!("untuple_arguments_if_necessary(): untupling arguments"); for &tupled_argument in tupled_arguments.iter() { result.push(tupled_argument); } } _ => { ccx.tcx().sess.bug("argument to function with \"rust-call\" ABI \ is neither a tuple nor unit") } } result } pub fn type_of_rust_fn<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, llenvironment_type: Option<Type>, sig: &ty::Binder<ty::FnSig<'tcx>>, abi: abi::Abi) -> Type { let sig = ty::erase_late_bound_regions(cx.tcx(), sig); assert!(!sig.variadic); // rust fns are never variadic let mut atys: Vec<Type> = Vec::new(); // First, munge the inputs, if this has the `rust-call` ABI. let inputs = untuple_arguments_if_necessary(cx, sig.inputs.as_slice(), abi); // Arg 0: Output pointer. // (if the output type is non-immediate) let lloutputtype = match sig.output { ty::FnConverging(output) => { let use_out_pointer = return_uses_outptr(cx, output); let lloutputtype = arg_type_of(cx, output); // Use the output as the actual return value if it's immediate. if use_out_pointer { atys.push(lloutputtype.ptr_to()); Type::void(cx) } else if return_type_is_void(cx, output) { Type::void(cx) } else { lloutputtype } } ty::FnDiverging => Type::void(cx) }; // Arg 1: Environment match llenvironment_type { None => {} Some(llenvironment_type) => atys.push(llenvironment_type), } //... then explicit args. let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty)); atys.extend(input_tys); Type::func(&atys[], &lloutputtype) } // Given a function type and a count of ty params, construct an llvm type pub fn type_of_fn_from_ty<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, fty: Ty<'tcx>) -> Type { match fty.sty { ty::ty_bare_fn(_, ref f) => { // FIXME(#19925) once fn item types are // zero-sized, we'll need to do something here if f.abi == abi::Rust || f.abi == abi::RustCall { type_of_rust_fn(cx, None, &f.sig, f.abi) } else { foreign::lltype_for_foreign_fn(cx, fty) } } _ => { cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn") } } } // A "sizing type" is an LLVM type, the size and alignment of which are // guaranteed to be equivalent to what you would get out of `type_of()`. It's // useful because: // // (1) It may be cheaper to compute the sizing type than the full type if all // you're interested in is the size and/or alignment; // // (2) It won't make any recursive calls to determine the structure of the // type behind pointers. This can help prevent infinite loops for // recursive types. For example, enum types rely on this behavior. pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { match cx.llsizingtypes().borrow().get(&t).cloned() { Some(t) => return t, None => () } let llsizingty = match t.sty { _ if!lltype_is_sized(cx.tcx(), t) => { cx.sess().bug(&format!("trying to take the sizing type of {}, an unsized type", ppaux::ty_to_string(cx.tcx(), t))[]) } ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty,..}) | ty::ty_ptr(ty::mt{ty,..}) => { if type_is_sized(cx.tcx(), ty) { Type::i8p(cx) } else { Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false) } } ty::ty_bare_fn(..) => Type::i8p(cx), ty::ty_vec(ty, Some(size)) => { let llty = sizing_type_of(cx, ty); let size = size as u64; ensure_array_fits_in_address_space(cx, llty, size, t); Type::array(&llty, size) } ty::ty_tup(ref tys) if tys.is_empty() => { Type::nil(cx) } ty::ty_tup(..) | ty::ty_enum(..) | ty::ty_unboxed_closure(..) => { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr, false) } ty::ty_struct(..) => { if ty::type_is_simd(cx.tcx(), t) { let llet = type_of(cx, ty::simd_type(cx.tcx(), t)); let n = ty::simd_size(cx.tcx(), t) as u64; ensure_array_fits_in_address_space(cx, llet, n, t); Type::vector(&llet, n) } else { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr, false) } } ty::ty_open(_) => { Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false) } ty::ty_projection(..) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) => { cx.sess().bug(&format!("fictitious type {} in sizing_type_of()", ppaux::ty_to_string(cx.tcx(), t))[]) } ty::ty_vec(_, None) | ty::ty_trait(..) | ty::ty_str => panic!("unreachable") }; cx.llsizingtypes().borrow_mut().insert(t, llsizingty); llsizingty } pub fn foreign_arg_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type
pub fn arg_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { if ty::type_is_bool(t) { Type::i1(cx) } else if type_is_immediate(cx, t) && type_of(cx, t).is_aggregate() { // We want to pass small aggregates as immediate values, but using an aggregate LLVM type // for this leads to bad optimizations, so its arg type is an appropriately sized integer match machine::llsize_of_alloc(cx, sizing_type_of(cx, t)) { 0 => type_of(cx, t), n => Type::ix(cx, n * 8), } } else { type_of(cx, t) } } // NB: If you update this, be sure to update `sizing_type_of()` as well. pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { fn type_of_unsize_info<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { // It is possible to end up here with a sized type. This happens with a // struct which might be unsized, but is monomorphised to a sized type. // In this case we'll fake a fat pointer with no unsize info (we use 0). // However, its still a fat pointer, so we need some type use. if type_is_sized(cx.tcx(), t) { return Type::i8p(cx); } match unsized_part_of_type(cx.tcx(), t).sty { ty::ty_str | ty::ty_vec(..) => Type::uint_from_ty(cx, ast::TyUs(false)), ty::ty_trait(_) => Type::vtable_ptr(cx), _ => panic!("Unexpected type returned from unsized_part_of_type : {}", t.repr(cx.tcx())) } } // Check the cache. match cx.lltypes().borrow().get(&t) { Some(&llty) => return llty, None => () } debug!("type_of {} {:?}", t.repr(cx.tcx()), t.sty); assert!(!t.has_escaping_regions()); // Replace any typedef'd types with their equivalent non-typedef // type. This ensures that all LLVM nominal types that contain // Rust types are defined as the same LLVM types. If we don't do // this then, e.g. `Option<{myfield: bool}>` would be a different // type than `Option<myrec>`. let t_norm = erase_regions(cx.tcx(), &t); if t!= t_norm { let llty = type_of(cx, t_norm); debug!("--> normalized {} {:?} to {} {:?} llty={}", t.repr(cx.tcx()), t, t_norm.repr(cx.tcx()), t_norm, cx.tn().type_to_string(llty)); cx.lltypes().borrow_mut().insert(t, llty); return llty; } let mut llty = match t.sty { ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_enum(did, ref substs) => { // Only create the named struct, but don't fill it in. We // fill it in *after* placing it into the type cache. This // avoids creating more than one copy of the enum when one // of the enum's variants refers to the enum itself. let repr = adt::represent_type(cx, t); let tps = substs.types.get_slice(subst::TypeSpace); let name = llvm_type_name(cx, an_enum, did, tps); adt::incomplete_type_of(cx, &*repr, &name[]) } ty::ty_unboxed_closure(did, _, ref substs) => { // Only create the named struct, but don't fill it in. We // fill it in *after* placing it into the type cache. let repr = adt::represent_type(cx, t); // Unboxed closures can have substitutions in all spaces // inherited from their environment, so we use entire // contents of the VecPerParamSpace to to construct the llvm // name let name = llvm_type_name(cx, an_unboxed_closure, did, substs.types.as_slice()); adt::incomplete_type_of(cx, &*repr, &name[]) } ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty,..}) | ty::ty_ptr(ty::mt{ty,..}) => { match ty.sty { ty::ty_str => { // This means we get a nicer name in the output (str is always // unsized). cx.tn().find_type("str_slice").unwrap() } ty::ty_trait(..) => Type::opaque_trait(cx), _ if!type_is_sized(cx.tcx(), ty) => { let p_ty = type_of(cx, ty).ptr_to(); Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, ty)], false) } _ => type_of(cx, ty).ptr_to(), } } ty::ty_vec(ty, Some(size)) => { let size = size as u64; let llty = type_of(cx, ty); ensure_array_fits_in_address_space(cx, llty, size, t); Type::array(&llty, size) } ty::ty_vec(ty, None) => { type_of(cx, ty) } ty::ty_trait(..) => { Type::opaque_trait_data(cx) } ty::ty_str => Type::i8(cx), ty::ty_bare_fn(..) => { type_of_fn_from_ty(cx, t).ptr_to() } ty::ty_tup(ref tys) if tys.is_empty() => Type::nil(cx), ty::ty_tup(..) => { let repr = adt::represent_type(cx, t); adt::type_of(cx, &*repr) } ty::ty_struct(did, ref substs) => { if ty::type_is_simd(cx.tcx(), t) { let llet = type_of(cx, ty::simd_type(cx.tcx(), t)); let n = ty::simd_size(cx.tcx(), t) as u64; ensure_array_fits_in_address_space(cx, llet, n, t); Type::vector(&llet, n) } else { // Only create the named struct, but don't fill it in. We fill it // in *after* placing it into the type cache. This prevents // infinite recursion with recursive struct types. let repr = adt::represent_type(cx, t); let tps = substs.types.get_slice(subst::TypeSpace); let name = llvm_type_name(cx, a_struct, did, tps); adt::incomplete_type_of(cx, &*repr, &name[]) } } ty::ty_open(t) => match t.sty { ty::ty_struct(..) => { let p_ty = type_of(cx, t).ptr_to(); Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false) } ty::ty_vec(ty, None) => { let p_ty = type_of(cx, ty).ptr_to(); Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false) } ty::ty_str => { let p_ty = Type::i8p(cx); Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false) } ty::ty_trait(..) => Type::opaque_trait(cx), _ => cx.sess().bug(&format!("ty_open with sized type: {}", ppaux::ty_to_string(cx.tcx(), t))[]) }, ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"), ty::ty_projection(..) => cx.sess().bug("type_of with ty_projection"), ty::ty_param(..) => cx.sess().bug("type_of with ty_param"), ty::ty_err(..) => cx.sess().bug("type_of with ty_err"), }; debug!("--> mapped t={} {:?} to llty={}", t.repr(cx.tcx()), t, cx.tn().type_to_string(llty)); cx.lltypes().borrow_mut().insert(t, llty); // If this was an enum or struct, fill in the type now. match t.sty { ty::ty_enum(..) | ty::ty_struct(..) | ty::ty_unboxed_closure(..) if!ty::type_is_simd(cx.tcx(), t) => { let repr = adt::represent_type(cx, t); adt::finish_type_of(cx, &*repr, &mut llty); } _ => () } return llty; } pub fn align_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> machine::llalign { let llty = sizing_type_of(cx, t); machine::llalign_of_min(cx, llty) } // Want refinements! (Or case classes, I guess #[derive(Copy)] pub enum named_ty { a_struct, an_enum, an_unboxed_closure, } pub fn llvm_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, what: named_ty,
{ if ty::type_is_bool(t) { Type::i1(cx) } else { type_of(cx, t) } }
identifier_body
type_of.rs
::{self, RegionEscape, Ty}; use util::ppaux; use util::ppaux::Repr; use trans::type_::Type; use std::num::Int; use syntax::abi; use syntax::ast; // LLVM doesn't like objects that are too big. Issue #17913 fn ensure_array_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, llet: Type, size: machine::llsize, scapegoat: Ty<'tcx>) { let esz = machine::llsize_of_alloc(ccx, llet); match esz.checked_mul(size) { Some(n) if n < ccx.obj_size_bound() => {} _ => { ccx.report_overbig_object(scapegoat) } } } pub fn arg_is_indirect<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg_ty: Ty<'tcx>) -> bool { !type_is_immediate(ccx, arg_ty) } pub fn return_uses_outptr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { !type_is_immediate(ccx, ty) } pub fn type_of_explicit_arg<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg_ty: Ty<'tcx>) -> Type { let llty = arg_type_of(ccx, arg_ty); if arg_is_indirect(ccx, arg_ty) { llty.ptr_to() } else { llty } } /// Yields the types of the "real" arguments for this function. For most /// functions, these are simply the types of the arguments. For functions with /// the `RustCall` ABI, however, this untuples the arguments of the function. pub fn untuple_arguments_if_necessary<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, inputs: &[Ty<'tcx>], abi: abi::Abi) -> Vec<Ty<'tcx>> { if abi!= abi::RustCall { return inputs.iter().map(|x| (*x).clone()).collect() } if inputs.len() == 0 { return Vec::new() } let mut result = Vec::new(); for (i, &arg_prior_to_tuple) in inputs.iter().enumerate() { if i < inputs.len() - 1 { result.push(arg_prior_to_tuple); } } match inputs[inputs.len() - 1].sty { ty::ty_tup(ref tupled_arguments) => { debug!("untuple_arguments_if_necessary(): untupling arguments"); for &tupled_argument in tupled_arguments.iter() { result.push(tupled_argument); } } _ => { ccx.tcx().sess.bug("argument to function with \"rust-call\" ABI \ is neither a tuple nor unit") } } result } pub fn type_of_rust_fn<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, llenvironment_type: Option<Type>, sig: &ty::Binder<ty::FnSig<'tcx>>, abi: abi::Abi) -> Type { let sig = ty::erase_late_bound_regions(cx.tcx(), sig); assert!(!sig.variadic); // rust fns are never variadic let mut atys: Vec<Type> = Vec::new(); // First, munge the inputs, if this has the `rust-call` ABI. let inputs = untuple_arguments_if_necessary(cx, sig.inputs.as_slice(), abi); // Arg 0: Output pointer. // (if the output type is non-immediate) let lloutputtype = match sig.output { ty::FnConverging(output) => { let use_out_pointer = return_uses_outptr(cx, output); let lloutputtype = arg_type_of(cx, output); // Use the output as the actual return value if it's immediate. if use_out_pointer { atys.push(lloutputtype.ptr_to()); Type::void(cx) } else if return_type_is_void(cx, output) { Type::void(cx) } else { lloutputtype } } ty::FnDiverging => Type::void(cx) }; // Arg 1: Environment match llenvironment_type { None => {} Some(llenvironment_type) => atys.push(llenvironment_type), }
//... then explicit args. let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty)); atys.extend(input_tys); Type::func(&atys[], &lloutputtype) } // Given a function type and a count of ty params, construct an llvm type pub fn type_of_fn_from_ty<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, fty: Ty<'tcx>) -> Type { match fty.sty { ty::ty_bare_fn(_, ref f) => { // FIXME(#19925) once fn item types are // zero-sized, we'll need to do something here if f.abi == abi::Rust || f.abi == abi::RustCall { type_of_rust_fn(cx, None, &f.sig, f.abi) } else { foreign::lltype_for_foreign_fn(cx, fty) } } _ => { cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn") } } } // A "sizing type" is an LLVM type, the size and alignment of which are // guaranteed to be equivalent to what you would get out of `type_of()`. It's // useful because: // // (1) It may be cheaper to compute the sizing type than the full type if all // you're interested in is the size and/or alignment; // // (2) It won't make any recursive calls to determine the structure of the // type behind pointers. This can help prevent infinite loops for // recursive types. For example, enum types rely on this behavior. pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { match cx.llsizingtypes().borrow().get(&t).cloned() { Some(t) => return t, None => () } let llsizingty = match t.sty { _ if!lltype_is_sized(cx.tcx(), t) => { cx.sess().bug(&format!("trying to take the sizing type of {}, an unsized type", ppaux::ty_to_string(cx.tcx(), t))[]) } ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty,..}) | ty::ty_ptr(ty::mt{ty,..}) => { if type_is_sized(cx.tcx(), ty) { Type::i8p(cx) } else { Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false) } } ty::ty_bare_fn(..) => Type::i8p(cx), ty::ty_vec(ty, Some(size)) => { let llty = sizing_type_of(cx, ty); let size = size as u64; ensure_array_fits_in_address_space(cx, llty, size, t); Type::array(&llty, size) } ty::ty_tup(ref tys) if tys.is_empty() => { Type::nil(cx) } ty::ty_tup(..) | ty::ty_enum(..) | ty::ty_unboxed_closure(..) => { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr, false) } ty::ty_struct(..) => { if ty::type_is_simd(cx.tcx(), t) { let llet = type_of(cx, ty::simd_type(cx.tcx(), t)); let n = ty::simd_size(cx.tcx(), t) as u64; ensure_array_fits_in_address_space(cx, llet, n, t); Type::vector(&llet, n) } else { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr, false) } } ty::ty_open(_) => { Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false) } ty::ty_projection(..) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) => { cx.sess().bug(&format!("fictitious type {} in sizing_type_of()", ppaux::ty_to_string(cx.tcx(), t))[]) } ty::ty_vec(_, None) | ty::ty_trait(..) | ty::ty_str => panic!("unreachable") }; cx.llsizingtypes().borrow_mut().insert(t, llsizingty); llsizingty } pub fn foreign_arg_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { if ty::type_is_bool(t) { Type::i1(cx) } else { type_of(cx, t) } } pub fn arg_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { if ty::type_is_bool(t) { Type::i1(cx) } else if type_is_immediate(cx, t) && type_of(cx, t).is_aggregate() { // We want to pass small aggregates as immediate values, but using an aggregate LLVM type // for this leads to bad optimizations, so its arg type is an appropriately sized integer match machine::llsize_of_alloc(cx, sizing_type_of(cx, t)) { 0 => type_of(cx, t), n => Type::ix(cx, n * 8), } } else { type_of(cx, t) } } // NB: If you update this, be sure to update `sizing_type_of()` as well. pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { fn type_of_unsize_info<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { // It is possible to end up here with a sized type. This happens with a // struct which might be unsized, but is monomorphised to a sized type. // In this case we'll fake a fat pointer with no unsize info (we use 0). // However, its still a fat pointer, so we need some type use. if type_is_sized(cx.tcx(), t) { return Type::i8p(cx); } match unsized_part_of_type(cx.tcx(), t).sty { ty::ty_str | ty::ty_vec(..) => Type::uint_from_ty(cx, ast::TyUs(false)), ty::ty_trait(_) => Type::vtable_ptr(cx), _ => panic!("Unexpected type returned from unsized_part_of_type : {}", t.repr(cx.tcx())) } } // Check the cache. match cx.lltypes().borrow().get(&t) { Some(&llty) => return llty, None => () } debug!("type_of {} {:?}", t.repr(cx.tcx()), t.sty); assert!(!t.has_escaping_regions()); // Replace any typedef'd types with their equivalent non-typedef // type. This ensures that all LLVM nominal types that contain // Rust types are defined as the same LLVM types. If we don't do // this then, e.g. `Option<{myfield: bool}>` would be a different // type than `Option<myrec>`. let t_norm = erase_regions(cx.tcx(), &t); if t!= t_norm { let llty = type_of(cx, t_norm); debug!("--> normalized {} {:?} to {} {:?} llty={}", t.repr(cx.tcx()), t, t_norm.repr(cx.tcx()), t_norm, cx.tn().type_to_string(llty)); cx.lltypes().borrow_mut().insert(t, llty); return llty; } let mut llty = match t.sty { ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_enum(did, ref substs) => { // Only create the named struct, but don't fill it in. We // fill it in *after* placing it into the type cache. This // avoids creating more than one copy of the enum when one // of the enum's variants refers to the enum itself. let repr = adt::represent_type(cx, t); let tps = substs.types.get_slice(subst::TypeSpace); let name = llvm_type_name(cx, an_enum, did, tps); adt::incomplete_type_of(cx, &*repr, &name[]) } ty::ty_unboxed_closure(did, _, ref substs) => { // Only create the named struct, but don't fill it in. We // fill it in *after* placing it into the type cache. let repr = adt::represent_type(cx, t); // Unboxed closures can have substitutions in all spaces // inherited from their environment, so we use entire // contents of the VecPerParamSpace to to construct the llvm // name let name = llvm_type_name(cx, an_unboxed_closure, did, substs.types.as_slice()); adt::incomplete_type_of(cx, &*repr, &name[]) } ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty,..}) | ty::ty_ptr(ty::mt{ty,..}) => { match ty.sty { ty::ty_str => { // This means we get a nicer name in the output (str is always // unsized). cx.tn().find_type("str_slice").unwrap() } ty::ty_trait(..) => Type::opaque_trait(cx), _ if!type_is_sized(cx.tcx(), ty) => { let p_ty = type_of(cx, ty).ptr_to(); Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, ty)], false) } _ => type_of(cx, ty).ptr_to(), } } ty::ty_vec(ty, Some(size)) => { let size = size as u64; let llty = type_of(cx, ty); ensure_array_fits_in_address_space(cx, llty, size, t); Type::array(&llty, size) } ty::ty_vec(ty, None) => { type_of(cx, ty) } ty::ty_trait(..) => { Type::opaque_trait_data(cx) } ty::ty_str => Type::i8(cx), ty::ty_bare_fn(..) => { type_of_fn_from_ty(cx, t).ptr_to() } ty::ty_tup(ref tys) if tys.is_empty() => Type::nil(cx), ty::ty_tup(..) => { let repr = adt::represent_type(cx, t); adt::type_of(cx, &*repr) } ty::ty_struct(did, ref substs) => { if ty::type_is_simd(cx.tcx(), t) { let llet = type_of(cx, ty::simd_type(cx.tcx(), t)); let n = ty::simd_size(cx.tcx(), t) as u64; ensure_array_fits_in_address_space(cx, llet, n, t); Type::vector(&llet, n) } else { // Only create the named struct, but don't fill it in. We fill it // in *after* placing it into the type cache. This prevents // infinite recursion with recursive struct types. let repr = adt::represent_type(cx, t); let tps = substs.types.get_slice(subst::TypeSpace); let name = llvm_type_name(cx, a_struct, did, tps); adt::incomplete_type_of(cx, &*repr, &name[]) } } ty::ty_open(t) => match t.sty { ty::ty_struct(..) => { let p_ty = type_of(cx, t).ptr_to(); Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false) } ty::ty_vec(ty, None) => { let p_ty = type_of(cx, ty).ptr_to(); Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false) } ty::ty_str => { let p_ty = Type::i8p(cx); Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false) } ty::ty_trait(..) => Type::opaque_trait(cx), _ => cx.sess().bug(&format!("ty_open with sized type: {}", ppaux::ty_to_string(cx.tcx(), t))[]) }, ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"), ty::ty_projection(..) => cx.sess().bug("type_of with ty_projection"), ty::ty_param(..) => cx.sess().bug("type_of with ty_param"), ty::ty_err(..) => cx.sess().bug("type_of with ty_err"), }; debug!("--> mapped t={} {:?} to llty={}", t.repr(cx.tcx()), t, cx.tn().type_to_string(llty)); cx.lltypes().borrow_mut().insert(t, llty); // If this was an enum or struct, fill in the type now. match t.sty { ty::ty_enum(..) | ty::ty_struct(..) | ty::ty_unboxed_closure(..) if!ty::type_is_simd(cx.tcx(), t) => { let repr = adt::represent_type(cx, t); adt::finish_type_of(cx, &*repr, &mut llty); } _ => () } return llty; } pub fn align_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> machine::llalign { let llty = sizing_type_of(cx, t); machine::llalign_of_min(cx, llty) } // Want refinements! (Or case classes, I guess #[derive(Copy)] pub enum named_ty { a_struct, an_enum, an_unboxed_closure, } pub fn llvm_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, what: named_ty,
random_line_split
type_of.rs
(scapegoat) } } } pub fn arg_is_indirect<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg_ty: Ty<'tcx>) -> bool { !type_is_immediate(ccx, arg_ty) } pub fn return_uses_outptr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { !type_is_immediate(ccx, ty) } pub fn type_of_explicit_arg<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg_ty: Ty<'tcx>) -> Type { let llty = arg_type_of(ccx, arg_ty); if arg_is_indirect(ccx, arg_ty) { llty.ptr_to() } else { llty } } /// Yields the types of the "real" arguments for this function. For most /// functions, these are simply the types of the arguments. For functions with /// the `RustCall` ABI, however, this untuples the arguments of the function. pub fn untuple_arguments_if_necessary<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, inputs: &[Ty<'tcx>], abi: abi::Abi) -> Vec<Ty<'tcx>> { if abi!= abi::RustCall { return inputs.iter().map(|x| (*x).clone()).collect() } if inputs.len() == 0 { return Vec::new() } let mut result = Vec::new(); for (i, &arg_prior_to_tuple) in inputs.iter().enumerate() { if i < inputs.len() - 1 { result.push(arg_prior_to_tuple); } } match inputs[inputs.len() - 1].sty { ty::ty_tup(ref tupled_arguments) => { debug!("untuple_arguments_if_necessary(): untupling arguments"); for &tupled_argument in tupled_arguments.iter() { result.push(tupled_argument); } } _ => { ccx.tcx().sess.bug("argument to function with \"rust-call\" ABI \ is neither a tuple nor unit") } } result } pub fn type_of_rust_fn<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, llenvironment_type: Option<Type>, sig: &ty::Binder<ty::FnSig<'tcx>>, abi: abi::Abi) -> Type { let sig = ty::erase_late_bound_regions(cx.tcx(), sig); assert!(!sig.variadic); // rust fns are never variadic let mut atys: Vec<Type> = Vec::new(); // First, munge the inputs, if this has the `rust-call` ABI. let inputs = untuple_arguments_if_necessary(cx, sig.inputs.as_slice(), abi); // Arg 0: Output pointer. // (if the output type is non-immediate) let lloutputtype = match sig.output { ty::FnConverging(output) => { let use_out_pointer = return_uses_outptr(cx, output); let lloutputtype = arg_type_of(cx, output); // Use the output as the actual return value if it's immediate. if use_out_pointer { atys.push(lloutputtype.ptr_to()); Type::void(cx) } else if return_type_is_void(cx, output) { Type::void(cx) } else { lloutputtype } } ty::FnDiverging => Type::void(cx) }; // Arg 1: Environment match llenvironment_type { None => {} Some(llenvironment_type) => atys.push(llenvironment_type), } //... then explicit args. let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty)); atys.extend(input_tys); Type::func(&atys[], &lloutputtype) } // Given a function type and a count of ty params, construct an llvm type pub fn type_of_fn_from_ty<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, fty: Ty<'tcx>) -> Type { match fty.sty { ty::ty_bare_fn(_, ref f) => { // FIXME(#19925) once fn item types are // zero-sized, we'll need to do something here if f.abi == abi::Rust || f.abi == abi::RustCall { type_of_rust_fn(cx, None, &f.sig, f.abi) } else { foreign::lltype_for_foreign_fn(cx, fty) } } _ => { cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn") } } } // A "sizing type" is an LLVM type, the size and alignment of which are // guaranteed to be equivalent to what you would get out of `type_of()`. It's // useful because: // // (1) It may be cheaper to compute the sizing type than the full type if all // you're interested in is the size and/or alignment; // // (2) It won't make any recursive calls to determine the structure of the // type behind pointers. This can help prevent infinite loops for // recursive types. For example, enum types rely on this behavior. pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { match cx.llsizingtypes().borrow().get(&t).cloned() { Some(t) => return t, None => () } let llsizingty = match t.sty { _ if!lltype_is_sized(cx.tcx(), t) => { cx.sess().bug(&format!("trying to take the sizing type of {}, an unsized type", ppaux::ty_to_string(cx.tcx(), t))[]) } ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty,..}) | ty::ty_ptr(ty::mt{ty,..}) => { if type_is_sized(cx.tcx(), ty) { Type::i8p(cx) } else { Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false) } } ty::ty_bare_fn(..) => Type::i8p(cx), ty::ty_vec(ty, Some(size)) => { let llty = sizing_type_of(cx, ty); let size = size as u64; ensure_array_fits_in_address_space(cx, llty, size, t); Type::array(&llty, size) } ty::ty_tup(ref tys) if tys.is_empty() => { Type::nil(cx) } ty::ty_tup(..) | ty::ty_enum(..) | ty::ty_unboxed_closure(..) => { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr, false) } ty::ty_struct(..) => { if ty::type_is_simd(cx.tcx(), t) { let llet = type_of(cx, ty::simd_type(cx.tcx(), t)); let n = ty::simd_size(cx.tcx(), t) as u64; ensure_array_fits_in_address_space(cx, llet, n, t); Type::vector(&llet, n) } else { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr, false) } } ty::ty_open(_) => { Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false) } ty::ty_projection(..) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) => { cx.sess().bug(&format!("fictitious type {} in sizing_type_of()", ppaux::ty_to_string(cx.tcx(), t))[]) } ty::ty_vec(_, None) | ty::ty_trait(..) | ty::ty_str => panic!("unreachable") }; cx.llsizingtypes().borrow_mut().insert(t, llsizingty); llsizingty } pub fn foreign_arg_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { if ty::type_is_bool(t) { Type::i1(cx) } else { type_of(cx, t) } } pub fn arg_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { if ty::type_is_bool(t) { Type::i1(cx) } else if type_is_immediate(cx, t) && type_of(cx, t).is_aggregate() { // We want to pass small aggregates as immediate values, but using an aggregate LLVM type // for this leads to bad optimizations, so its arg type is an appropriately sized integer match machine::llsize_of_alloc(cx, sizing_type_of(cx, t)) { 0 => type_of(cx, t), n => Type::ix(cx, n * 8), } } else { type_of(cx, t) } } // NB: If you update this, be sure to update `sizing_type_of()` as well. pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { fn type_of_unsize_info<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { // It is possible to end up here with a sized type. This happens with a // struct which might be unsized, but is monomorphised to a sized type. // In this case we'll fake a fat pointer with no unsize info (we use 0). // However, its still a fat pointer, so we need some type use. if type_is_sized(cx.tcx(), t) { return Type::i8p(cx); } match unsized_part_of_type(cx.tcx(), t).sty { ty::ty_str | ty::ty_vec(..) => Type::uint_from_ty(cx, ast::TyUs(false)), ty::ty_trait(_) => Type::vtable_ptr(cx), _ => panic!("Unexpected type returned from unsized_part_of_type : {}", t.repr(cx.tcx())) } } // Check the cache. match cx.lltypes().borrow().get(&t) { Some(&llty) => return llty, None => () } debug!("type_of {} {:?}", t.repr(cx.tcx()), t.sty); assert!(!t.has_escaping_regions()); // Replace any typedef'd types with their equivalent non-typedef // type. This ensures that all LLVM nominal types that contain // Rust types are defined as the same LLVM types. If we don't do // this then, e.g. `Option<{myfield: bool}>` would be a different // type than `Option<myrec>`. let t_norm = erase_regions(cx.tcx(), &t); if t!= t_norm { let llty = type_of(cx, t_norm); debug!("--> normalized {} {:?} to {} {:?} llty={}", t.repr(cx.tcx()), t, t_norm.repr(cx.tcx()), t_norm, cx.tn().type_to_string(llty)); cx.lltypes().borrow_mut().insert(t, llty); return llty; } let mut llty = match t.sty { ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_enum(did, ref substs) => { // Only create the named struct, but don't fill it in. We // fill it in *after* placing it into the type cache. This // avoids creating more than one copy of the enum when one // of the enum's variants refers to the enum itself. let repr = adt::represent_type(cx, t); let tps = substs.types.get_slice(subst::TypeSpace); let name = llvm_type_name(cx, an_enum, did, tps); adt::incomplete_type_of(cx, &*repr, &name[]) } ty::ty_unboxed_closure(did, _, ref substs) => { // Only create the named struct, but don't fill it in. We // fill it in *after* placing it into the type cache. let repr = adt::represent_type(cx, t); // Unboxed closures can have substitutions in all spaces // inherited from their environment, so we use entire // contents of the VecPerParamSpace to to construct the llvm // name let name = llvm_type_name(cx, an_unboxed_closure, did, substs.types.as_slice()); adt::incomplete_type_of(cx, &*repr, &name[]) } ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty,..}) | ty::ty_ptr(ty::mt{ty,..}) => { match ty.sty { ty::ty_str => { // This means we get a nicer name in the output (str is always // unsized). cx.tn().find_type("str_slice").unwrap() } ty::ty_trait(..) => Type::opaque_trait(cx), _ if!type_is_sized(cx.tcx(), ty) => { let p_ty = type_of(cx, ty).ptr_to(); Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, ty)], false) } _ => type_of(cx, ty).ptr_to(), } } ty::ty_vec(ty, Some(size)) => { let size = size as u64; let llty = type_of(cx, ty); ensure_array_fits_in_address_space(cx, llty, size, t); Type::array(&llty, size) } ty::ty_vec(ty, None) => { type_of(cx, ty) } ty::ty_trait(..) => { Type::opaque_trait_data(cx) } ty::ty_str => Type::i8(cx), ty::ty_bare_fn(..) => { type_of_fn_from_ty(cx, t).ptr_to() } ty::ty_tup(ref tys) if tys.is_empty() => Type::nil(cx), ty::ty_tup(..) => { let repr = adt::represent_type(cx, t); adt::type_of(cx, &*repr) } ty::ty_struct(did, ref substs) => { if ty::type_is_simd(cx.tcx(), t) { let llet = type_of(cx, ty::simd_type(cx.tcx(), t)); let n = ty::simd_size(cx.tcx(), t) as u64; ensure_array_fits_in_address_space(cx, llet, n, t); Type::vector(&llet, n) } else { // Only create the named struct, but don't fill it in. We fill it // in *after* placing it into the type cache. This prevents // infinite recursion with recursive struct types. let repr = adt::represent_type(cx, t); let tps = substs.types.get_slice(subst::TypeSpace); let name = llvm_type_name(cx, a_struct, did, tps); adt::incomplete_type_of(cx, &*repr, &name[]) } } ty::ty_open(t) => match t.sty { ty::ty_struct(..) => { let p_ty = type_of(cx, t).ptr_to(); Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false) } ty::ty_vec(ty, None) => { let p_ty = type_of(cx, ty).ptr_to(); Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false) } ty::ty_str => { let p_ty = Type::i8p(cx); Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false) } ty::ty_trait(..) => Type::opaque_trait(cx), _ => cx.sess().bug(&format!("ty_open with sized type: {}", ppaux::ty_to_string(cx.tcx(), t))[]) }, ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"), ty::ty_projection(..) => cx.sess().bug("type_of with ty_projection"), ty::ty_param(..) => cx.sess().bug("type_of with ty_param"), ty::ty_err(..) => cx.sess().bug("type_of with ty_err"), }; debug!("--> mapped t={} {:?} to llty={}", t.repr(cx.tcx()), t, cx.tn().type_to_string(llty)); cx.lltypes().borrow_mut().insert(t, llty); // If this was an enum or struct, fill in the type now. match t.sty { ty::ty_enum(..) | ty::ty_struct(..) | ty::ty_unboxed_closure(..) if!ty::type_is_simd(cx.tcx(), t) => { let repr = adt::represent_type(cx, t); adt::finish_type_of(cx, &*repr, &mut llty); } _ => () } return llty; } pub fn align_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> machine::llalign { let llty = sizing_type_of(cx, t); machine::llalign_of_min(cx, llty) } // Want refinements! (Or case classes, I guess #[derive(Copy)] pub enum named_ty { a_struct, an_enum, an_unboxed_closure, } pub fn llvm_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, what: named_ty, did: ast::DefId, tps: &[Ty<'tcx>]) -> String { let name = match what { a_struct => "struct", an_enum => "enum", an_unboxed_closure => return "closure".to_string(), }; let base = ty::item_path_str(cx.tcx(), did); let strings: Vec<String> = tps.iter().map(|t| t.repr(cx.tcx())).collect(); let tstr = if strings.is_empty() { base } else { format!("{}<{:?}>", base, strings) }; if did.krate == 0 { format!("{}.{}", name, tstr) } else { format!("{}.{}[{}{}]", name, tstr, "#", did.krate) } } pub fn
type_of_dtor
identifier_name
action.rs
use RawFd;
} impl Action { #[inline] pub fn encode(action: Action) -> u64 { match action { Action::Notify(data, fd) => ((fd as u64) << 31) | ((data as u64) << 15), Action::New(data) => data, } } #[inline] pub fn decode(data: u64) -> Action { let arg1 = ((data >> 15) & 0xffff) as usize; let fd = (data >> 31) as i32; match data & 0x7fff { 0 => Action::Notify(arg1, fd), _ => Action::New(data), } } } #[cfg(test)] mod tests { use super::Action; #[test] fn decode_encode_new_action() { let data = Action::encode(Action::New(::std::u64::MAX)); if let Action::New(fd) = Action::decode(data) { assert!(fd == ::std::u64::MAX); } else { panic!("action is not Action::New") } } #[test] fn decode_encode_notify_action() { let data = Action::encode(Action::Notify(10110, 0)); if let Action::Notify(data, fd) = Action::decode(data) { assert!(data == 10110); assert!(fd == 0); } else { panic!("action is not Action::Notify") } } }
pub enum Action { Notify(usize, RawFd), New(u64),
random_line_split
action.rs
use RawFd; pub enum Action { Notify(usize, RawFd), New(u64), } impl Action { #[inline] pub fn
(action: Action) -> u64 { match action { Action::Notify(data, fd) => ((fd as u64) << 31) | ((data as u64) << 15), Action::New(data) => data, } } #[inline] pub fn decode(data: u64) -> Action { let arg1 = ((data >> 15) & 0xffff) as usize; let fd = (data >> 31) as i32; match data & 0x7fff { 0 => Action::Notify(arg1, fd), _ => Action::New(data), } } } #[cfg(test)] mod tests { use super::Action; #[test] fn decode_encode_new_action() { let data = Action::encode(Action::New(::std::u64::MAX)); if let Action::New(fd) = Action::decode(data) { assert!(fd == ::std::u64::MAX); } else { panic!("action is not Action::New") } } #[test] fn decode_encode_notify_action() { let data = Action::encode(Action::Notify(10110, 0)); if let Action::Notify(data, fd) = Action::decode(data) { assert!(data == 10110); assert!(fd == 0); } else { panic!("action is not Action::Notify") } } }
encode
identifier_name
action.rs
use RawFd; pub enum Action { Notify(usize, RawFd), New(u64), } impl Action { #[inline] pub fn encode(action: Action) -> u64
#[inline] pub fn decode(data: u64) -> Action { let arg1 = ((data >> 15) & 0xffff) as usize; let fd = (data >> 31) as i32; match data & 0x7fff { 0 => Action::Notify(arg1, fd), _ => Action::New(data), } } } #[cfg(test)] mod tests { use super::Action; #[test] fn decode_encode_new_action() { let data = Action::encode(Action::New(::std::u64::MAX)); if let Action::New(fd) = Action::decode(data) { assert!(fd == ::std::u64::MAX); } else { panic!("action is not Action::New") } } #[test] fn decode_encode_notify_action() { let data = Action::encode(Action::Notify(10110, 0)); if let Action::Notify(data, fd) = Action::decode(data) { assert!(data == 10110); assert!(fd == 0); } else { panic!("action is not Action::Notify") } } }
{ match action { Action::Notify(data, fd) => ((fd as u64) << 31) | ((data as u64) << 15), Action::New(data) => data, } }
identifier_body
servoxmlparser.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::ServoXMLParserBinding; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::trace::JSTraceable; use dom::document::Document; use dom::node::Node; use dom::window::Window; use js::jsapi::JSTracer; use msg::constellation_msg::PipelineId; use parse::{Parser, ParserRef}; use script_thread::ScriptThread; use std::cell::Cell; use url::Url; use xml5ever::tokenizer; use xml5ever::tree_builder::{self, XmlTreeBuilder}; pub type Tokenizer = tokenizer::XmlTokenizer<XmlTreeBuilder<JS<Node>, Sink>>; #[must_root] #[derive(JSTraceable, HeapSizeOf)] pub struct Sink { pub base_url: Option<Url>, pub document: JS<Document>, } #[must_root] #[dom_struct] pub struct ServoXMLParser { reflector_: Reflector, #[ignore_heap_size_of = "Defined in xml5ever"] tokenizer: DOMRefCell<Tokenizer>, /// Input chunks received but not yet passed to the parser. pending_input: DOMRefCell<Vec<String>>, /// The document associated with this parser. document: JS<Document>, /// True if this parser should avoid passing any further data to the tokenizer. suspended: Cell<bool>, /// Whether to expect any further input from the associated network request. last_chunk_received: Cell<bool>, /// The pipeline associated with this parse, unavailable if this parse does not /// correspond to a page load. pipeline: Option<PipelineId>, } impl<'a> Parser for &'a ServoXMLParser { fn parse_chunk(self, input: String) { self.document.set_current_parser(Some(ParserRef::XML(self))); self.pending_input.borrow_mut().push(input); if!self.is_suspended() { self.parse_sync(); } } fn finish(self) { assert!(!self.suspended.get()); assert!(self.pending_input.borrow().is_empty()); self.tokenizer.borrow_mut().end(); debug!("finished parsing"); self.document.set_current_parser(None); if let Some(pipeline) = self.pipeline { ScriptThread::parsing_complete(pipeline); } } } impl ServoXMLParser { #[allow(unrooted_must_root)] pub fn new(base_url: Option<Url>, document: &Document, pipeline: Option<PipelineId>) -> Root<ServoXMLParser> { let sink = Sink { base_url: base_url, document: JS::from_ref(document), }; let tb = XmlTreeBuilder::new(sink); let tok = tokenizer::XmlTokenizer::new(tb, Default::default()); let parser = ServoXMLParser { reflector_: Reflector::new(), tokenizer: DOMRefCell::new(tok), pending_input: DOMRefCell::new(vec!()), document: JS::from_ref(document), suspended: Cell::new(false), last_chunk_received: Cell::new(false), pipeline: pipeline, }; reflect_dom_object(box parser, document.window(), ServoXMLParserBinding::Wrap) } pub fn window(&self) -> &Window { self.document.window() } pub fn resume(&self) { assert!(self.suspended.get()); self.suspended.set(false); self.parse_sync(); } pub fn suspend(&self) { assert!(!self.suspended.get()); self.suspended.set(true); } pub fn is_suspended(&self) -> bool { self.suspended.get() } pub fn parse_sync(&self) { // This parser will continue to parse while there is either pending input or // the parser remains unsuspended. loop { self.document.reflow_if_reflow_timer_expired(); let mut pending_input = self.pending_input.borrow_mut(); if!pending_input.is_empty() { let chunk = pending_input.remove(0); self.tokenizer.borrow_mut().feed(chunk.into()); } else { self.tokenizer.borrow_mut().run(); } // Document parsing is blocked on an external resource. if self.suspended.get() { return; } if pending_input.is_empty() { break; } } if self.last_chunk_received.get() { self.finish(); } } pub fn pending_input(&self) -> &DOMRefCell<Vec<String>> { &self.pending_input } pub fn set_plaintext_state(&self) { //self.tokenizer.borrow_mut().set_plaintext_state() } pub fn end_tokenizer(&self) { self.tokenizer.borrow_mut().end() } pub fn document(&self) -> &Document { &self.document } pub fn last_chunk_received(&self) -> &Cell<bool> { &self.last_chunk_received } pub fn tokenizer(&self) -> &DOMRefCell<Tokenizer> { &self.tokenizer } } struct Tracer { trc: *mut JSTracer, } impl tree_builder::Tracer for Tracer { type Handle = JS<Node>; #[allow(unrooted_must_root)] fn trace_handle(&self, node: JS<Node>) { node.trace(self.trc); } } impl JSTraceable for Tokenizer { fn trace(&self, trc: *mut JSTracer) { let tracer = Tracer { trc: trc, };
let tree_builder = self.sink(); tree_builder.trace_handles(tracer); tree_builder.sink().trace(trc); } }
let tracer = &tracer as &tree_builder::Tracer<Handle=JS<Node>>;
random_line_split
servoxmlparser.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::ServoXMLParserBinding; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::trace::JSTraceable; use dom::document::Document; use dom::node::Node; use dom::window::Window; use js::jsapi::JSTracer; use msg::constellation_msg::PipelineId; use parse::{Parser, ParserRef}; use script_thread::ScriptThread; use std::cell::Cell; use url::Url; use xml5ever::tokenizer; use xml5ever::tree_builder::{self, XmlTreeBuilder}; pub type Tokenizer = tokenizer::XmlTokenizer<XmlTreeBuilder<JS<Node>, Sink>>; #[must_root] #[derive(JSTraceable, HeapSizeOf)] pub struct Sink { pub base_url: Option<Url>, pub document: JS<Document>, } #[must_root] #[dom_struct] pub struct ServoXMLParser { reflector_: Reflector, #[ignore_heap_size_of = "Defined in xml5ever"] tokenizer: DOMRefCell<Tokenizer>, /// Input chunks received but not yet passed to the parser. pending_input: DOMRefCell<Vec<String>>, /// The document associated with this parser. document: JS<Document>, /// True if this parser should avoid passing any further data to the tokenizer. suspended: Cell<bool>, /// Whether to expect any further input from the associated network request. last_chunk_received: Cell<bool>, /// The pipeline associated with this parse, unavailable if this parse does not /// correspond to a page load. pipeline: Option<PipelineId>, } impl<'a> Parser for &'a ServoXMLParser { fn parse_chunk(self, input: String) { self.document.set_current_parser(Some(ParserRef::XML(self))); self.pending_input.borrow_mut().push(input); if!self.is_suspended() { self.parse_sync(); } } fn finish(self) { assert!(!self.suspended.get()); assert!(self.pending_input.borrow().is_empty()); self.tokenizer.borrow_mut().end(); debug!("finished parsing"); self.document.set_current_parser(None); if let Some(pipeline) = self.pipeline { ScriptThread::parsing_complete(pipeline); } } } impl ServoXMLParser { #[allow(unrooted_must_root)] pub fn new(base_url: Option<Url>, document: &Document, pipeline: Option<PipelineId>) -> Root<ServoXMLParser> { let sink = Sink { base_url: base_url, document: JS::from_ref(document), }; let tb = XmlTreeBuilder::new(sink); let tok = tokenizer::XmlTokenizer::new(tb, Default::default()); let parser = ServoXMLParser { reflector_: Reflector::new(), tokenizer: DOMRefCell::new(tok), pending_input: DOMRefCell::new(vec!()), document: JS::from_ref(document), suspended: Cell::new(false), last_chunk_received: Cell::new(false), pipeline: pipeline, }; reflect_dom_object(box parser, document.window(), ServoXMLParserBinding::Wrap) } pub fn window(&self) -> &Window { self.document.window() } pub fn resume(&self)
pub fn suspend(&self) { assert!(!self.suspended.get()); self.suspended.set(true); } pub fn is_suspended(&self) -> bool { self.suspended.get() } pub fn parse_sync(&self) { // This parser will continue to parse while there is either pending input or // the parser remains unsuspended. loop { self.document.reflow_if_reflow_timer_expired(); let mut pending_input = self.pending_input.borrow_mut(); if!pending_input.is_empty() { let chunk = pending_input.remove(0); self.tokenizer.borrow_mut().feed(chunk.into()); } else { self.tokenizer.borrow_mut().run(); } // Document parsing is blocked on an external resource. if self.suspended.get() { return; } if pending_input.is_empty() { break; } } if self.last_chunk_received.get() { self.finish(); } } pub fn pending_input(&self) -> &DOMRefCell<Vec<String>> { &self.pending_input } pub fn set_plaintext_state(&self) { //self.tokenizer.borrow_mut().set_plaintext_state() } pub fn end_tokenizer(&self) { self.tokenizer.borrow_mut().end() } pub fn document(&self) -> &Document { &self.document } pub fn last_chunk_received(&self) -> &Cell<bool> { &self.last_chunk_received } pub fn tokenizer(&self) -> &DOMRefCell<Tokenizer> { &self.tokenizer } } struct Tracer { trc: *mut JSTracer, } impl tree_builder::Tracer for Tracer { type Handle = JS<Node>; #[allow(unrooted_must_root)] fn trace_handle(&self, node: JS<Node>) { node.trace(self.trc); } } impl JSTraceable for Tokenizer { fn trace(&self, trc: *mut JSTracer) { let tracer = Tracer { trc: trc, }; let tracer = &tracer as &tree_builder::Tracer<Handle=JS<Node>>; let tree_builder = self.sink(); tree_builder.trace_handles(tracer); tree_builder.sink().trace(trc); } }
{ assert!(self.suspended.get()); self.suspended.set(false); self.parse_sync(); }
identifier_body
servoxmlparser.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::ServoXMLParserBinding; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::trace::JSTraceable; use dom::document::Document; use dom::node::Node; use dom::window::Window; use js::jsapi::JSTracer; use msg::constellation_msg::PipelineId; use parse::{Parser, ParserRef}; use script_thread::ScriptThread; use std::cell::Cell; use url::Url; use xml5ever::tokenizer; use xml5ever::tree_builder::{self, XmlTreeBuilder}; pub type Tokenizer = tokenizer::XmlTokenizer<XmlTreeBuilder<JS<Node>, Sink>>; #[must_root] #[derive(JSTraceable, HeapSizeOf)] pub struct Sink { pub base_url: Option<Url>, pub document: JS<Document>, } #[must_root] #[dom_struct] pub struct ServoXMLParser { reflector_: Reflector, #[ignore_heap_size_of = "Defined in xml5ever"] tokenizer: DOMRefCell<Tokenizer>, /// Input chunks received but not yet passed to the parser. pending_input: DOMRefCell<Vec<String>>, /// The document associated with this parser. document: JS<Document>, /// True if this parser should avoid passing any further data to the tokenizer. suspended: Cell<bool>, /// Whether to expect any further input from the associated network request. last_chunk_received: Cell<bool>, /// The pipeline associated with this parse, unavailable if this parse does not /// correspond to a page load. pipeline: Option<PipelineId>, } impl<'a> Parser for &'a ServoXMLParser { fn parse_chunk(self, input: String) { self.document.set_current_parser(Some(ParserRef::XML(self))); self.pending_input.borrow_mut().push(input); if!self.is_suspended() { self.parse_sync(); } } fn finish(self) { assert!(!self.suspended.get()); assert!(self.pending_input.borrow().is_empty()); self.tokenizer.borrow_mut().end(); debug!("finished parsing"); self.document.set_current_parser(None); if let Some(pipeline) = self.pipeline { ScriptThread::parsing_complete(pipeline); } } } impl ServoXMLParser { #[allow(unrooted_must_root)] pub fn new(base_url: Option<Url>, document: &Document, pipeline: Option<PipelineId>) -> Root<ServoXMLParser> { let sink = Sink { base_url: base_url, document: JS::from_ref(document), }; let tb = XmlTreeBuilder::new(sink); let tok = tokenizer::XmlTokenizer::new(tb, Default::default()); let parser = ServoXMLParser { reflector_: Reflector::new(), tokenizer: DOMRefCell::new(tok), pending_input: DOMRefCell::new(vec!()), document: JS::from_ref(document), suspended: Cell::new(false), last_chunk_received: Cell::new(false), pipeline: pipeline, }; reflect_dom_object(box parser, document.window(), ServoXMLParserBinding::Wrap) } pub fn
(&self) -> &Window { self.document.window() } pub fn resume(&self) { assert!(self.suspended.get()); self.suspended.set(false); self.parse_sync(); } pub fn suspend(&self) { assert!(!self.suspended.get()); self.suspended.set(true); } pub fn is_suspended(&self) -> bool { self.suspended.get() } pub fn parse_sync(&self) { // This parser will continue to parse while there is either pending input or // the parser remains unsuspended. loop { self.document.reflow_if_reflow_timer_expired(); let mut pending_input = self.pending_input.borrow_mut(); if!pending_input.is_empty() { let chunk = pending_input.remove(0); self.tokenizer.borrow_mut().feed(chunk.into()); } else { self.tokenizer.borrow_mut().run(); } // Document parsing is blocked on an external resource. if self.suspended.get() { return; } if pending_input.is_empty() { break; } } if self.last_chunk_received.get() { self.finish(); } } pub fn pending_input(&self) -> &DOMRefCell<Vec<String>> { &self.pending_input } pub fn set_plaintext_state(&self) { //self.tokenizer.borrow_mut().set_plaintext_state() } pub fn end_tokenizer(&self) { self.tokenizer.borrow_mut().end() } pub fn document(&self) -> &Document { &self.document } pub fn last_chunk_received(&self) -> &Cell<bool> { &self.last_chunk_received } pub fn tokenizer(&self) -> &DOMRefCell<Tokenizer> { &self.tokenizer } } struct Tracer { trc: *mut JSTracer, } impl tree_builder::Tracer for Tracer { type Handle = JS<Node>; #[allow(unrooted_must_root)] fn trace_handle(&self, node: JS<Node>) { node.trace(self.trc); } } impl JSTraceable for Tokenizer { fn trace(&self, trc: *mut JSTracer) { let tracer = Tracer { trc: trc, }; let tracer = &tracer as &tree_builder::Tracer<Handle=JS<Node>>; let tree_builder = self.sink(); tree_builder.trace_handles(tracer); tree_builder.sink().trace(trc); } }
window
identifier_name
servoxmlparser.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::ServoXMLParserBinding; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::trace::JSTraceable; use dom::document::Document; use dom::node::Node; use dom::window::Window; use js::jsapi::JSTracer; use msg::constellation_msg::PipelineId; use parse::{Parser, ParserRef}; use script_thread::ScriptThread; use std::cell::Cell; use url::Url; use xml5ever::tokenizer; use xml5ever::tree_builder::{self, XmlTreeBuilder}; pub type Tokenizer = tokenizer::XmlTokenizer<XmlTreeBuilder<JS<Node>, Sink>>; #[must_root] #[derive(JSTraceable, HeapSizeOf)] pub struct Sink { pub base_url: Option<Url>, pub document: JS<Document>, } #[must_root] #[dom_struct] pub struct ServoXMLParser { reflector_: Reflector, #[ignore_heap_size_of = "Defined in xml5ever"] tokenizer: DOMRefCell<Tokenizer>, /// Input chunks received but not yet passed to the parser. pending_input: DOMRefCell<Vec<String>>, /// The document associated with this parser. document: JS<Document>, /// True if this parser should avoid passing any further data to the tokenizer. suspended: Cell<bool>, /// Whether to expect any further input from the associated network request. last_chunk_received: Cell<bool>, /// The pipeline associated with this parse, unavailable if this parse does not /// correspond to a page load. pipeline: Option<PipelineId>, } impl<'a> Parser for &'a ServoXMLParser { fn parse_chunk(self, input: String) { self.document.set_current_parser(Some(ParserRef::XML(self))); self.pending_input.borrow_mut().push(input); if!self.is_suspended() { self.parse_sync(); } } fn finish(self) { assert!(!self.suspended.get()); assert!(self.pending_input.borrow().is_empty()); self.tokenizer.borrow_mut().end(); debug!("finished parsing"); self.document.set_current_parser(None); if let Some(pipeline) = self.pipeline { ScriptThread::parsing_complete(pipeline); } } } impl ServoXMLParser { #[allow(unrooted_must_root)] pub fn new(base_url: Option<Url>, document: &Document, pipeline: Option<PipelineId>) -> Root<ServoXMLParser> { let sink = Sink { base_url: base_url, document: JS::from_ref(document), }; let tb = XmlTreeBuilder::new(sink); let tok = tokenizer::XmlTokenizer::new(tb, Default::default()); let parser = ServoXMLParser { reflector_: Reflector::new(), tokenizer: DOMRefCell::new(tok), pending_input: DOMRefCell::new(vec!()), document: JS::from_ref(document), suspended: Cell::new(false), last_chunk_received: Cell::new(false), pipeline: pipeline, }; reflect_dom_object(box parser, document.window(), ServoXMLParserBinding::Wrap) } pub fn window(&self) -> &Window { self.document.window() } pub fn resume(&self) { assert!(self.suspended.get()); self.suspended.set(false); self.parse_sync(); } pub fn suspend(&self) { assert!(!self.suspended.get()); self.suspended.set(true); } pub fn is_suspended(&self) -> bool { self.suspended.get() } pub fn parse_sync(&self) { // This parser will continue to parse while there is either pending input or // the parser remains unsuspended. loop { self.document.reflow_if_reflow_timer_expired(); let mut pending_input = self.pending_input.borrow_mut(); if!pending_input.is_empty() { let chunk = pending_input.remove(0); self.tokenizer.borrow_mut().feed(chunk.into()); } else { self.tokenizer.borrow_mut().run(); } // Document parsing is blocked on an external resource. if self.suspended.get() { return; } if pending_input.is_empty()
} if self.last_chunk_received.get() { self.finish(); } } pub fn pending_input(&self) -> &DOMRefCell<Vec<String>> { &self.pending_input } pub fn set_plaintext_state(&self) { //self.tokenizer.borrow_mut().set_plaintext_state() } pub fn end_tokenizer(&self) { self.tokenizer.borrow_mut().end() } pub fn document(&self) -> &Document { &self.document } pub fn last_chunk_received(&self) -> &Cell<bool> { &self.last_chunk_received } pub fn tokenizer(&self) -> &DOMRefCell<Tokenizer> { &self.tokenizer } } struct Tracer { trc: *mut JSTracer, } impl tree_builder::Tracer for Tracer { type Handle = JS<Node>; #[allow(unrooted_must_root)] fn trace_handle(&self, node: JS<Node>) { node.trace(self.trc); } } impl JSTraceable for Tokenizer { fn trace(&self, trc: *mut JSTracer) { let tracer = Tracer { trc: trc, }; let tracer = &tracer as &tree_builder::Tracer<Handle=JS<Node>>; let tree_builder = self.sink(); tree_builder.trace_handles(tracer); tree_builder.sink().trace(trc); } }
{ break; }
conditional_block
repr-transparent-other-reprs.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(repr_align)] // See also repr-transparent.rs #[repr(transparent, C)] //~ ERROR cannot have other repr struct TransparentPlusC { ptr: *const u8 } #[repr(transparent, packed)] //~ ERROR cannot have other repr struct TransparentPlusPacked(*const u8); #[repr(transparent, align(2))] //~ ERROR cannot have other repr
#[repr(transparent)] //~ ERROR cannot have other repr #[repr(C)] struct SeparateAttributes(*mut u8); fn main() {}
struct TransparentPlusAlign(u8);
random_line_split
repr-transparent-other-reprs.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(repr_align)] // See also repr-transparent.rs #[repr(transparent, C)] //~ ERROR cannot have other repr struct
{ ptr: *const u8 } #[repr(transparent, packed)] //~ ERROR cannot have other repr struct TransparentPlusPacked(*const u8); #[repr(transparent, align(2))] //~ ERROR cannot have other repr struct TransparentPlusAlign(u8); #[repr(transparent)] //~ ERROR cannot have other repr #[repr(C)] struct SeparateAttributes(*mut u8); fn main() {}
TransparentPlusC
identifier_name
cssnamespacerule.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::CSSNamespaceRuleBinding; use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding::CSSNamespaceRuleMethods; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use parking_lot::RwLock; use std::sync::Arc; use style::stylesheets::NamespaceRule; use style_traits::ToCss; #[dom_struct] pub struct
{ cssrule: CSSRule, #[ignore_heap_size_of = "Arc"] namespacerule: Arc<RwLock<NamespaceRule>>, } impl CSSNamespaceRule { fn new_inherited(parent: Option<&CSSStyleSheet>, namespacerule: Arc<RwLock<NamespaceRule>>) -> CSSNamespaceRule { CSSNamespaceRule { cssrule: CSSRule::new_inherited(parent), namespacerule: namespacerule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent: Option<&CSSStyleSheet>, namespacerule: Arc<RwLock<NamespaceRule>>) -> Root<CSSNamespaceRule> { reflect_dom_object(box CSSNamespaceRule::new_inherited(parent, namespacerule), window, CSSNamespaceRuleBinding::Wrap) } } impl CSSNamespaceRuleMethods for CSSNamespaceRule { // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-prefix fn Prefix(&self) -> DOMString { self.namespacerule.read().prefix .as_ref().map(|s| s.to_string().into()) .unwrap_or(DOMString::new()) } // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-namespaceuri fn NamespaceURI(&self) -> DOMString { (*self.namespacerule.read().url).into() } } impl SpecificCSSRule for CSSNamespaceRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::NAMESPACE_RULE } fn get_css(&self) -> DOMString { self.namespacerule.read().to_css_string().into() } }
CSSNamespaceRule
identifier_name
cssnamespacerule.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::CSSNamespaceRuleBinding; use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding::CSSNamespaceRuleMethods; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use parking_lot::RwLock; use std::sync::Arc; use style::stylesheets::NamespaceRule; use style_traits::ToCss; #[dom_struct] pub struct CSSNamespaceRule { cssrule: CSSRule, #[ignore_heap_size_of = "Arc"] namespacerule: Arc<RwLock<NamespaceRule>>, } impl CSSNamespaceRule { fn new_inherited(parent: Option<&CSSStyleSheet>, namespacerule: Arc<RwLock<NamespaceRule>>) -> CSSNamespaceRule { CSSNamespaceRule { cssrule: CSSRule::new_inherited(parent), namespacerule: namespacerule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent: Option<&CSSStyleSheet>, namespacerule: Arc<RwLock<NamespaceRule>>) -> Root<CSSNamespaceRule>
} impl CSSNamespaceRuleMethods for CSSNamespaceRule { // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-prefix fn Prefix(&self) -> DOMString { self.namespacerule.read().prefix .as_ref().map(|s| s.to_string().into()) .unwrap_or(DOMString::new()) } // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-namespaceuri fn NamespaceURI(&self) -> DOMString { (*self.namespacerule.read().url).into() } } impl SpecificCSSRule for CSSNamespaceRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::NAMESPACE_RULE } fn get_css(&self) -> DOMString { self.namespacerule.read().to_css_string().into() } }
{ reflect_dom_object(box CSSNamespaceRule::new_inherited(parent, namespacerule), window, CSSNamespaceRuleBinding::Wrap) }
identifier_body
cssnamespacerule.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::CSSNamespaceRuleBinding; use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding::CSSNamespaceRuleMethods; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use parking_lot::RwLock; use std::sync::Arc; use style::stylesheets::NamespaceRule; use style_traits::ToCss; #[dom_struct] pub struct CSSNamespaceRule { cssrule: CSSRule, #[ignore_heap_size_of = "Arc"] namespacerule: Arc<RwLock<NamespaceRule>>, } impl CSSNamespaceRule { fn new_inherited(parent: Option<&CSSStyleSheet>, namespacerule: Arc<RwLock<NamespaceRule>>) -> CSSNamespaceRule { CSSNamespaceRule { cssrule: CSSRule::new_inherited(parent), namespacerule: namespacerule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent: Option<&CSSStyleSheet>, namespacerule: Arc<RwLock<NamespaceRule>>) -> Root<CSSNamespaceRule> {
} } impl CSSNamespaceRuleMethods for CSSNamespaceRule { // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-prefix fn Prefix(&self) -> DOMString { self.namespacerule.read().prefix .as_ref().map(|s| s.to_string().into()) .unwrap_or(DOMString::new()) } // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-namespaceuri fn NamespaceURI(&self) -> DOMString { (*self.namespacerule.read().url).into() } } impl SpecificCSSRule for CSSNamespaceRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::NAMESPACE_RULE } fn get_css(&self) -> DOMString { self.namespacerule.read().to_css_string().into() } }
reflect_dom_object(box CSSNamespaceRule::new_inherited(parent, namespacerule), window, CSSNamespaceRuleBinding::Wrap)
random_line_split
p22.rs
use std::time::{SystemTime, UNIX_EPOCH}; use rand::{Rng, SeedableRng, weak_rng}; use util::MT19937Rng; fn epoch_time() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH).unwrap() .as_secs() } #[test] fn run() { let mut w_rng = weak_rng(); let mut mt_rng = MT19937Rng::new_unseeded(); let mut t = epoch_time(); //// Oracle let wait1: u64 = w_rng.gen_range(10, 1000); t += wait1; let seed: u32 = (t & 0xFFFFFFFF) as u32; mt_rng.reseed(seed); let wait2: u64 = w_rng.gen_range(10, 1000); t += wait2; let out = mt_rng.next_u32(); // Attacker // We simply step backward from our current time until a freshly seeded // rng produces the same out value. let mut recovered_seed = None; for i in 0..2000 { let seed2: u32 = ((t - i) & 0xFFFFFFFF) as u32; mt_rng.reseed(seed2); let out2 = mt_rng.next_u32(); if out == out2
} assert!(recovered_seed.is_some()); assert_eq!(seed, recovered_seed.unwrap()); }
{ recovered_seed = Some(seed2); }
conditional_block
p22.rs
use std::time::{SystemTime, UNIX_EPOCH}; use rand::{Rng, SeedableRng, weak_rng}; use util::MT19937Rng; fn epoch_time() -> u64
#[test] fn run() { let mut w_rng = weak_rng(); let mut mt_rng = MT19937Rng::new_unseeded(); let mut t = epoch_time(); //// Oracle let wait1: u64 = w_rng.gen_range(10, 1000); t += wait1; let seed: u32 = (t & 0xFFFFFFFF) as u32; mt_rng.reseed(seed); let wait2: u64 = w_rng.gen_range(10, 1000); t += wait2; let out = mt_rng.next_u32(); // Attacker // We simply step backward from our current time until a freshly seeded // rng produces the same out value. let mut recovered_seed = None; for i in 0..2000 { let seed2: u32 = ((t - i) & 0xFFFFFFFF) as u32; mt_rng.reseed(seed2); let out2 = mt_rng.next_u32(); if out == out2 { recovered_seed = Some(seed2); } } assert!(recovered_seed.is_some()); assert_eq!(seed, recovered_seed.unwrap()); }
{ SystemTime::now() .duration_since(UNIX_EPOCH).unwrap() .as_secs() }
identifier_body
p22.rs
use std::time::{SystemTime, UNIX_EPOCH}; use rand::{Rng, SeedableRng, weak_rng}; use util::MT19937Rng; fn epoch_time() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH).unwrap() .as_secs() } #[test] fn run() { let mut w_rng = weak_rng(); let mut mt_rng = MT19937Rng::new_unseeded(); let mut t = epoch_time(); //// Oracle
let wait1: u64 = w_rng.gen_range(10, 1000); t += wait1; let seed: u32 = (t & 0xFFFFFFFF) as u32; mt_rng.reseed(seed); let wait2: u64 = w_rng.gen_range(10, 1000); t += wait2; let out = mt_rng.next_u32(); // Attacker // We simply step backward from our current time until a freshly seeded // rng produces the same out value. let mut recovered_seed = None; for i in 0..2000 { let seed2: u32 = ((t - i) & 0xFFFFFFFF) as u32; mt_rng.reseed(seed2); let out2 = mt_rng.next_u32(); if out == out2 { recovered_seed = Some(seed2); } } assert!(recovered_seed.is_some()); assert_eq!(seed, recovered_seed.unwrap()); }
random_line_split
p22.rs
use std::time::{SystemTime, UNIX_EPOCH}; use rand::{Rng, SeedableRng, weak_rng}; use util::MT19937Rng; fn
() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH).unwrap() .as_secs() } #[test] fn run() { let mut w_rng = weak_rng(); let mut mt_rng = MT19937Rng::new_unseeded(); let mut t = epoch_time(); //// Oracle let wait1: u64 = w_rng.gen_range(10, 1000); t += wait1; let seed: u32 = (t & 0xFFFFFFFF) as u32; mt_rng.reseed(seed); let wait2: u64 = w_rng.gen_range(10, 1000); t += wait2; let out = mt_rng.next_u32(); // Attacker // We simply step backward from our current time until a freshly seeded // rng produces the same out value. let mut recovered_seed = None; for i in 0..2000 { let seed2: u32 = ((t - i) & 0xFFFFFFFF) as u32; mt_rng.reseed(seed2); let out2 = mt_rng.next_u32(); if out == out2 { recovered_seed = Some(seed2); } } assert!(recovered_seed.is_some()); assert_eq!(seed, recovered_seed.unwrap()); }
epoch_time
identifier_name
buffer.rs
/* gl/src/gl_wrapper/buffer.rs, 2017-07-19 Copyright (c) 2017 Juuso Tuononen This file is licensed under Apache License, Version 2.0 or MIT License */ //! Send data to GPU. use super::gl_raw; use self::gl_raw::types::*; use std::mem::size_of; use std::os::raw::c_void; use std::ptr; /// Send static data to GPU with Vertex Buffer Object struct VertexBufferStatic { id: GLuint, attribute_component_count: GLint, } impl VertexBufferStatic { /// Sends static data to GPU. /// /// # Arguments /// * `data` - Float data which is sent to GPU. /// * `attribute_component_count` - Number of floats in one vertex attribute. /// /// # Safety /// This function does not check if data length and `attribute_component_count` match. unsafe fn new(data: &[f32], attribute_component_count: GLint) -> VertexBufferStatic
/// Set vertex attribute to match buffer data. /// /// # Arguments /// * `attribute_index` - Index of vertex attribute. fn set_vertex_attributes(&mut self, attribute_index: GLuint) { unsafe { gl_raw::BindBuffer(gl_raw::ARRAY_BUFFER, self.id); let stride = (self.attribute_component_count * size_of::<f32>() as GLint) as GLsizei; gl_raw::VertexAttribPointer(attribute_index, self.attribute_component_count, gl_raw::FLOAT, gl_raw::FALSE, stride, ptr::null()); gl_raw::EnableVertexAttribArray(attribute_index); } } } impl Drop for VertexBufferStatic { /// Deletes OpenGL's buffer object. fn drop(&mut self) { unsafe { gl_raw::DeleteBuffers(1, &self.id); } } } /// Send multiple buffers of data to GPU. /// /// OpenGL 3.3 version of this struct is implemented /// with OpenGL's Vertex Array Object. /// /// OpenGL ES 2.0 does not support Vertex Array Objects, so vertex /// attributes are set for every buffer /// when `draw` method is called if using OpenGL ES version of this struct. #[cfg(not(feature = "gles"))] pub struct VertexArray { id: GLuint, vertex_buffers: Vec<VertexBufferStatic>, vertex_count: GLsizei, } #[cfg(feature = "gles")] pub struct VertexArray { vertex_buffers: Vec<(VertexBufferStatic, GLuint)>, vertex_count: GLsizei, } impl VertexArray { /// Creates new Vertex Array Object #[cfg(not(feature = "gles"))] pub fn new(vertex_count: GLsizei) -> VertexArray { let mut id: GLuint = 0; let vertex_buffers = vec![]; unsafe { gl_raw::GenVertexArrays(1, &mut id); VertexArray {id, vertex_buffers, vertex_count} } } #[cfg(feature = "gles")] pub fn new(vertex_count: GLsizei) -> VertexArray { let vertex_buffers = vec![]; VertexArray {vertex_buffers, vertex_count} } /// Adds new buffer to Vertex Array Object /// /// # Arguments /// * `data` - Float data to send to the GPU. /// * `attribute_component_count` - Number of floats in one attribute. /// * `attribute_index` - Index of vertex attribute. /// /// # Panics /// * If buffer length doesn't match with `VertexArray`'s vertex count. /// * If buffer length doesn't match with attribute_component_count. pub fn add_static_buffer(&mut self, data: &[f32], attribute_component_count: GLint, attribute_index: GLuint) { if data.len() / attribute_component_count as usize!= self.vertex_count as usize { panic!("buffer length doesn't match with VertexArray's vertex count"); } if data.len() % attribute_component_count as usize!= 0 { panic!("buffer length doesn't match with attribute_component_count"); } #[cfg(not(feature = "gles"))] { let mut buffer; unsafe { buffer = VertexBufferStatic::new(data, attribute_component_count); } self.bind(); buffer.set_vertex_attributes(attribute_index); self.vertex_buffers.push(buffer); } #[cfg(feature = "gles")] { let buffer; unsafe { buffer = VertexBufferStatic::new(data, attribute_component_count); } self.vertex_buffers.push((buffer, attribute_index)); } } /// Bind OpenGL's Vertex Array Object. This method /// only exists for OpenGL 3.3 version of `VertexArray` struct. #[cfg(not(feature = "gles"))] fn bind(&self) { unsafe { gl_raw::BindVertexArray(self.id); } } /// Draw with buffers currently existing buffers in `VertexArray`. Remember to enable /// correct shader `Program` with it's `use_program` method before calling this method. pub fn draw(&mut self) { #[cfg(not(feature = "gles"))] { self.bind(); } #[cfg(feature = "gles")] { for &mut (ref mut buffer, attribute_index) in &mut self.vertex_buffers { buffer.set_vertex_attributes(attribute_index); } } unsafe { gl_raw::DrawArrays(gl_raw::TRIANGLES, 0, self.vertex_count); } } } #[cfg(not(feature = "gles"))] impl Drop for VertexArray { /// Delete OpenGL's Vertex Array Object. This implementation of Drop trait /// only exists for OpenGL 3.3 version of `VertexArray` struct. fn drop(&mut self) { unsafe { gl_raw::DeleteVertexArrays(1, &self.id); } } }
{ let mut id: GLuint = 0; gl_raw::GenBuffers(1, &mut id); gl_raw::BindBuffer(gl_raw::ARRAY_BUFFER, id); let size: GLsizeiptr = (size_of::<f32>() * data.len()) as GLsizeiptr; let data_ptr = data.as_ptr() as *const c_void; gl_raw::BufferData(gl_raw::ARRAY_BUFFER, size, data_ptr, gl_raw::STATIC_DRAW); VertexBufferStatic {id, attribute_component_count} }
identifier_body
buffer.rs
/* gl/src/gl_wrapper/buffer.rs, 2017-07-19 Copyright (c) 2017 Juuso Tuononen This file is licensed under Apache License, Version 2.0 or MIT License */ //! Send data to GPU. use super::gl_raw; use self::gl_raw::types::*; use std::mem::size_of; use std::os::raw::c_void; use std::ptr; /// Send static data to GPU with Vertex Buffer Object struct VertexBufferStatic { id: GLuint, attribute_component_count: GLint, } impl VertexBufferStatic { /// Sends static data to GPU. /// /// # Arguments /// * `data` - Float data which is sent to GPU. /// * `attribute_component_count` - Number of floats in one vertex attribute. /// /// # Safety /// This function does not check if data length and `attribute_component_count` match. unsafe fn new(data: &[f32], attribute_component_count: GLint) -> VertexBufferStatic { let mut id: GLuint = 0; gl_raw::GenBuffers(1, &mut id); gl_raw::BindBuffer(gl_raw::ARRAY_BUFFER, id); let size: GLsizeiptr = (size_of::<f32>() * data.len()) as GLsizeiptr; let data_ptr = data.as_ptr() as *const c_void; gl_raw::BufferData(gl_raw::ARRAY_BUFFER, size, data_ptr, gl_raw::STATIC_DRAW); VertexBufferStatic {id, attribute_component_count} } /// Set vertex attribute to match buffer data. /// /// # Arguments /// * `attribute_index` - Index of vertex attribute. fn set_vertex_attributes(&mut self, attribute_index: GLuint) { unsafe { gl_raw::BindBuffer(gl_raw::ARRAY_BUFFER, self.id); let stride = (self.attribute_component_count * size_of::<f32>() as GLint) as GLsizei; gl_raw::VertexAttribPointer(attribute_index, self.attribute_component_count, gl_raw::FLOAT, gl_raw::FALSE, stride, ptr::null()); gl_raw::EnableVertexAttribArray(attribute_index); } } } impl Drop for VertexBufferStatic { /// Deletes OpenGL's buffer object. fn drop(&mut self) { unsafe { gl_raw::DeleteBuffers(1, &self.id); } } } /// Send multiple buffers of data to GPU. /// /// OpenGL 3.3 version of this struct is implemented /// with OpenGL's Vertex Array Object. /// /// OpenGL ES 2.0 does not support Vertex Array Objects, so vertex /// attributes are set for every buffer /// when `draw` method is called if using OpenGL ES version of this struct. #[cfg(not(feature = "gles"))] pub struct VertexArray { id: GLuint, vertex_buffers: Vec<VertexBufferStatic>, vertex_count: GLsizei, } #[cfg(feature = "gles")] pub struct VertexArray { vertex_buffers: Vec<(VertexBufferStatic, GLuint)>, vertex_count: GLsizei, } impl VertexArray { /// Creates new Vertex Array Object #[cfg(not(feature = "gles"))] pub fn new(vertex_count: GLsizei) -> VertexArray { let mut id: GLuint = 0; let vertex_buffers = vec![]; unsafe { gl_raw::GenVertexArrays(1, &mut id); VertexArray {id, vertex_buffers, vertex_count} } } #[cfg(feature = "gles")] pub fn new(vertex_count: GLsizei) -> VertexArray { let vertex_buffers = vec![]; VertexArray {vertex_buffers, vertex_count} } /// Adds new buffer to Vertex Array Object /// /// # Arguments /// * `data` - Float data to send to the GPU. /// * `attribute_component_count` - Number of floats in one attribute. /// * `attribute_index` - Index of vertex attribute. /// /// # Panics /// * If buffer length doesn't match with `VertexArray`'s vertex count. /// * If buffer length doesn't match with attribute_component_count. pub fn add_static_buffer(&mut self, data: &[f32], attribute_component_count: GLint, attribute_index: GLuint) { if data.len() / attribute_component_count as usize!= self.vertex_count as usize { panic!("buffer length doesn't match with VertexArray's vertex count"); } if data.len() % attribute_component_count as usize!= 0
#[cfg(not(feature = "gles"))] { let mut buffer; unsafe { buffer = VertexBufferStatic::new(data, attribute_component_count); } self.bind(); buffer.set_vertex_attributes(attribute_index); self.vertex_buffers.push(buffer); } #[cfg(feature = "gles")] { let buffer; unsafe { buffer = VertexBufferStatic::new(data, attribute_component_count); } self.vertex_buffers.push((buffer, attribute_index)); } } /// Bind OpenGL's Vertex Array Object. This method /// only exists for OpenGL 3.3 version of `VertexArray` struct. #[cfg(not(feature = "gles"))] fn bind(&self) { unsafe { gl_raw::BindVertexArray(self.id); } } /// Draw with buffers currently existing buffers in `VertexArray`. Remember to enable /// correct shader `Program` with it's `use_program` method before calling this method. pub fn draw(&mut self) { #[cfg(not(feature = "gles"))] { self.bind(); } #[cfg(feature = "gles")] { for &mut (ref mut buffer, attribute_index) in &mut self.vertex_buffers { buffer.set_vertex_attributes(attribute_index); } } unsafe { gl_raw::DrawArrays(gl_raw::TRIANGLES, 0, self.vertex_count); } } } #[cfg(not(feature = "gles"))] impl Drop for VertexArray { /// Delete OpenGL's Vertex Array Object. This implementation of Drop trait /// only exists for OpenGL 3.3 version of `VertexArray` struct. fn drop(&mut self) { unsafe { gl_raw::DeleteVertexArrays(1, &self.id); } } }
{ panic!("buffer length doesn't match with attribute_component_count"); }
conditional_block
buffer.rs
/* gl/src/gl_wrapper/buffer.rs, 2017-07-19 Copyright (c) 2017 Juuso Tuononen This file is licensed under Apache License, Version 2.0 or MIT License */ //! Send data to GPU. use super::gl_raw; use self::gl_raw::types::*; use std::mem::size_of; use std::os::raw::c_void; use std::ptr; /// Send static data to GPU with Vertex Buffer Object struct VertexBufferStatic { id: GLuint, attribute_component_count: GLint, } impl VertexBufferStatic { /// Sends static data to GPU. /// /// # Arguments /// * `data` - Float data which is sent to GPU. /// * `attribute_component_count` - Number of floats in one vertex attribute. /// /// # Safety /// This function does not check if data length and `attribute_component_count` match. unsafe fn new(data: &[f32], attribute_component_count: GLint) -> VertexBufferStatic { let mut id: GLuint = 0; gl_raw::GenBuffers(1, &mut id); gl_raw::BindBuffer(gl_raw::ARRAY_BUFFER, id); let size: GLsizeiptr = (size_of::<f32>() * data.len()) as GLsizeiptr; let data_ptr = data.as_ptr() as *const c_void; gl_raw::BufferData(gl_raw::ARRAY_BUFFER, size, data_ptr, gl_raw::STATIC_DRAW); VertexBufferStatic {id, attribute_component_count} } /// Set vertex attribute to match buffer data. /// /// # Arguments /// * `attribute_index` - Index of vertex attribute. fn
(&mut self, attribute_index: GLuint) { unsafe { gl_raw::BindBuffer(gl_raw::ARRAY_BUFFER, self.id); let stride = (self.attribute_component_count * size_of::<f32>() as GLint) as GLsizei; gl_raw::VertexAttribPointer(attribute_index, self.attribute_component_count, gl_raw::FLOAT, gl_raw::FALSE, stride, ptr::null()); gl_raw::EnableVertexAttribArray(attribute_index); } } } impl Drop for VertexBufferStatic { /// Deletes OpenGL's buffer object. fn drop(&mut self) { unsafe { gl_raw::DeleteBuffers(1, &self.id); } } } /// Send multiple buffers of data to GPU. /// /// OpenGL 3.3 version of this struct is implemented /// with OpenGL's Vertex Array Object. /// /// OpenGL ES 2.0 does not support Vertex Array Objects, so vertex /// attributes are set for every buffer /// when `draw` method is called if using OpenGL ES version of this struct. #[cfg(not(feature = "gles"))] pub struct VertexArray { id: GLuint, vertex_buffers: Vec<VertexBufferStatic>, vertex_count: GLsizei, } #[cfg(feature = "gles")] pub struct VertexArray { vertex_buffers: Vec<(VertexBufferStatic, GLuint)>, vertex_count: GLsizei, } impl VertexArray { /// Creates new Vertex Array Object #[cfg(not(feature = "gles"))] pub fn new(vertex_count: GLsizei) -> VertexArray { let mut id: GLuint = 0; let vertex_buffers = vec![]; unsafe { gl_raw::GenVertexArrays(1, &mut id); VertexArray {id, vertex_buffers, vertex_count} } } #[cfg(feature = "gles")] pub fn new(vertex_count: GLsizei) -> VertexArray { let vertex_buffers = vec![]; VertexArray {vertex_buffers, vertex_count} } /// Adds new buffer to Vertex Array Object /// /// # Arguments /// * `data` - Float data to send to the GPU. /// * `attribute_component_count` - Number of floats in one attribute. /// * `attribute_index` - Index of vertex attribute. /// /// # Panics /// * If buffer length doesn't match with `VertexArray`'s vertex count. /// * If buffer length doesn't match with attribute_component_count. pub fn add_static_buffer(&mut self, data: &[f32], attribute_component_count: GLint, attribute_index: GLuint) { if data.len() / attribute_component_count as usize!= self.vertex_count as usize { panic!("buffer length doesn't match with VertexArray's vertex count"); } if data.len() % attribute_component_count as usize!= 0 { panic!("buffer length doesn't match with attribute_component_count"); } #[cfg(not(feature = "gles"))] { let mut buffer; unsafe { buffer = VertexBufferStatic::new(data, attribute_component_count); } self.bind(); buffer.set_vertex_attributes(attribute_index); self.vertex_buffers.push(buffer); } #[cfg(feature = "gles")] { let buffer; unsafe { buffer = VertexBufferStatic::new(data, attribute_component_count); } self.vertex_buffers.push((buffer, attribute_index)); } } /// Bind OpenGL's Vertex Array Object. This method /// only exists for OpenGL 3.3 version of `VertexArray` struct. #[cfg(not(feature = "gles"))] fn bind(&self) { unsafe { gl_raw::BindVertexArray(self.id); } } /// Draw with buffers currently existing buffers in `VertexArray`. Remember to enable /// correct shader `Program` with it's `use_program` method before calling this method. pub fn draw(&mut self) { #[cfg(not(feature = "gles"))] { self.bind(); } #[cfg(feature = "gles")] { for &mut (ref mut buffer, attribute_index) in &mut self.vertex_buffers { buffer.set_vertex_attributes(attribute_index); } } unsafe { gl_raw::DrawArrays(gl_raw::TRIANGLES, 0, self.vertex_count); } } } #[cfg(not(feature = "gles"))] impl Drop for VertexArray { /// Delete OpenGL's Vertex Array Object. This implementation of Drop trait /// only exists for OpenGL 3.3 version of `VertexArray` struct. fn drop(&mut self) { unsafe { gl_raw::DeleteVertexArrays(1, &self.id); } } }
set_vertex_attributes
identifier_name