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
ascii.rs
// This is a part of rust-encoding. // Copyright (c) 2013-2015, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! 7-bit ASCII encoding. use libtww::std::mem; use libtww::std::convert::Into; use types::*; /** * ASCII, also known as ISO/IEC 646:US. * * It is both a basis and a lowest common denominator of many other encodings * including UTF-8, which Rust internally assumes. */ #[derive(Clone, Copy)] pub struct ASCIIEncoding; impl Encoding for ASCIIEncoding { fn name(&self) -> &'static str
fn raw_encoder(&self) -> Box<RawEncoder> { ASCIIEncoder::new() } fn raw_decoder(&self) -> Box<RawDecoder> { ASCIIDecoder::new() } } /// An encoder for ASCII. #[derive(Clone, Copy)] pub struct ASCIIEncoder; impl ASCIIEncoder { pub fn new() -> Box<RawEncoder> { Box::new(ASCIIEncoder) } } impl RawEncoder for ASCIIEncoder { fn from_self(&self) -> Box<RawEncoder> { ASCIIEncoder::new() } fn is_ascii_compatible(&self) -> bool { true } fn raw_feed(&mut self, input: &str, output: &mut ByteWriter) -> (usize, Option<CodecError>) { output.writer_hint(input.len()); match input.as_bytes().iter().position(|&ch| ch >= 0x80) { Some(first_error) => { output.write_bytes(&input.as_bytes()[..first_error]); let len = input[first_error..].chars().next().unwrap().len_utf8(); (first_error, Some(CodecError { upto: (first_error + len) as isize, cause: "unrepresentable character".into(), })) } None => { output.write_bytes(input.as_bytes()); (input.len(), None) } } } fn raw_finish(&mut self, _output: &mut ByteWriter) -> Option<CodecError> { None } } /// A decoder for ASCII. #[derive(Clone, Copy)] pub struct ASCIIDecoder; impl ASCIIDecoder { pub fn new() -> Box<RawDecoder> { Box::new(ASCIIDecoder) } } impl RawDecoder for ASCIIDecoder { fn from_self(&self) -> Box<RawDecoder> { ASCIIDecoder::new() } fn is_ascii_compatible(&self) -> bool { true } fn raw_feed(&mut self, input: &[u8], output: &mut StringWriter) -> (usize, Option<CodecError>) { output.writer_hint(input.len()); fn write_ascii_bytes(output: &mut StringWriter, buf: &[u8]) { output.write_str(unsafe { mem::transmute(buf) }); } match input.iter().position(|&ch| ch >= 0x80) { Some(first_error) => { write_ascii_bytes(output, &input[..first_error]); (first_error, Some(CodecError { upto: first_error as isize + 1, cause: "invalid sequence".into(), })) } None => { write_ascii_bytes(output, input); (input.len(), None) } } } fn raw_finish(&mut self, _output: &mut StringWriter) -> Option<CodecError> { None } } #[cfg(test)] mod tests { extern crate test; use super::ASCIIEncoding; use testutils; use types::*; #[test] fn test_encoder() { let mut e = ASCIIEncoding.raw_encoder(); assert_feed_ok!(e, "A", "", [0x41]); assert_feed_ok!(e, "BC", "", [0x42, 0x43]); assert_feed_ok!(e, "", "", []); assert_feed_err!(e, "", "\u{a0}", "", []); assert_feed_err!(e, "X", "\u{a0}", "Z", [0x58]); assert_finish_ok!(e, []); } #[test] fn test_decoder() { let mut d = ASCIIEncoding.raw_decoder(); assert_feed_ok!(d, [0x41], [], "A"); assert_feed_ok!(d, [0x42, 0x43], [], "BC"); assert_feed_ok!(d, [], [], ""); assert_feed_err!(d, [], [0xa0], [], ""); assert_feed_err!(d, [0x58], [0xa0], [0x5a], "X"); assert_finish_ok!(d, ""); } #[bench] fn bench_encode(bencher: &mut test::Bencher) { let s = testutils::ASCII_TEXT; bencher.bytes = s.len() as u64; bencher.iter(|| { test::black_box({ ASCIIEncoding.encode(s, EncoderTrap::Strict) }) }) } #[bench] fn bench_decode(bencher: &mut test::Bencher) { let s = testutils::ASCII_TEXT.as_bytes(); bencher.bytes = s.len() as u64; bencher.iter(|| { test::black_box({ ASCIIEncoding.decode(s, DecoderTrap::Strict) }) }) } #[bench] fn bench_encode_replace(bencher: &mut test::Bencher) { let s = testutils::KOREAN_TEXT; bencher.bytes = s.len() as u64; bencher.iter(|| { test::black_box({ ASCIIEncoding.encode(s, EncoderTrap::Replace) }) }) } #[bench] fn bench_decode_replace(bencher: &mut test::Bencher) { let s = testutils::KOREAN_TEXT.as_bytes(); bencher.bytes = s.len() as u64; bencher.iter(|| { test::black_box({ ASCIIEncoding.decode(s, DecoderTrap::Replace) }) }) } }
{ "ascii" }
identifier_body
ascii.rs
// This is a part of rust-encoding. // Copyright (c) 2013-2015, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! 7-bit ASCII encoding. use libtww::std::mem; use libtww::std::convert::Into; use types::*; /** * ASCII, also known as ISO/IEC 646:US. * * It is both a basis and a lowest common denominator of many other encodings * including UTF-8, which Rust internally assumes. */ #[derive(Clone, Copy)] pub struct ASCIIEncoding; impl Encoding for ASCIIEncoding { fn name(&self) -> &'static str { "ascii" } fn
(&self) -> Box<RawEncoder> { ASCIIEncoder::new() } fn raw_decoder(&self) -> Box<RawDecoder> { ASCIIDecoder::new() } } /// An encoder for ASCII. #[derive(Clone, Copy)] pub struct ASCIIEncoder; impl ASCIIEncoder { pub fn new() -> Box<RawEncoder> { Box::new(ASCIIEncoder) } } impl RawEncoder for ASCIIEncoder { fn from_self(&self) -> Box<RawEncoder> { ASCIIEncoder::new() } fn is_ascii_compatible(&self) -> bool { true } fn raw_feed(&mut self, input: &str, output: &mut ByteWriter) -> (usize, Option<CodecError>) { output.writer_hint(input.len()); match input.as_bytes().iter().position(|&ch| ch >= 0x80) { Some(first_error) => { output.write_bytes(&input.as_bytes()[..first_error]); let len = input[first_error..].chars().next().unwrap().len_utf8(); (first_error, Some(CodecError { upto: (first_error + len) as isize, cause: "unrepresentable character".into(), })) } None => { output.write_bytes(input.as_bytes()); (input.len(), None) } } } fn raw_finish(&mut self, _output: &mut ByteWriter) -> Option<CodecError> { None } } /// A decoder for ASCII. #[derive(Clone, Copy)] pub struct ASCIIDecoder; impl ASCIIDecoder { pub fn new() -> Box<RawDecoder> { Box::new(ASCIIDecoder) } } impl RawDecoder for ASCIIDecoder { fn from_self(&self) -> Box<RawDecoder> { ASCIIDecoder::new() } fn is_ascii_compatible(&self) -> bool { true } fn raw_feed(&mut self, input: &[u8], output: &mut StringWriter) -> (usize, Option<CodecError>) { output.writer_hint(input.len()); fn write_ascii_bytes(output: &mut StringWriter, buf: &[u8]) { output.write_str(unsafe { mem::transmute(buf) }); } match input.iter().position(|&ch| ch >= 0x80) { Some(first_error) => { write_ascii_bytes(output, &input[..first_error]); (first_error, Some(CodecError { upto: first_error as isize + 1, cause: "invalid sequence".into(), })) } None => { write_ascii_bytes(output, input); (input.len(), None) } } } fn raw_finish(&mut self, _output: &mut StringWriter) -> Option<CodecError> { None } } #[cfg(test)] mod tests { extern crate test; use super::ASCIIEncoding; use testutils; use types::*; #[test] fn test_encoder() { let mut e = ASCIIEncoding.raw_encoder(); assert_feed_ok!(e, "A", "", [0x41]); assert_feed_ok!(e, "BC", "", [0x42, 0x43]); assert_feed_ok!(e, "", "", []); assert_feed_err!(e, "", "\u{a0}", "", []); assert_feed_err!(e, "X", "\u{a0}", "Z", [0x58]); assert_finish_ok!(e, []); } #[test] fn test_decoder() { let mut d = ASCIIEncoding.raw_decoder(); assert_feed_ok!(d, [0x41], [], "A"); assert_feed_ok!(d, [0x42, 0x43], [], "BC"); assert_feed_ok!(d, [], [], ""); assert_feed_err!(d, [], [0xa0], [], ""); assert_feed_err!(d, [0x58], [0xa0], [0x5a], "X"); assert_finish_ok!(d, ""); } #[bench] fn bench_encode(bencher: &mut test::Bencher) { let s = testutils::ASCII_TEXT; bencher.bytes = s.len() as u64; bencher.iter(|| { test::black_box({ ASCIIEncoding.encode(s, EncoderTrap::Strict) }) }) } #[bench] fn bench_decode(bencher: &mut test::Bencher) { let s = testutils::ASCII_TEXT.as_bytes(); bencher.bytes = s.len() as u64; bencher.iter(|| { test::black_box({ ASCIIEncoding.decode(s, DecoderTrap::Strict) }) }) } #[bench] fn bench_encode_replace(bencher: &mut test::Bencher) { let s = testutils::KOREAN_TEXT; bencher.bytes = s.len() as u64; bencher.iter(|| { test::black_box({ ASCIIEncoding.encode(s, EncoderTrap::Replace) }) }) } #[bench] fn bench_decode_replace(bencher: &mut test::Bencher) { let s = testutils::KOREAN_TEXT.as_bytes(); bencher.bytes = s.len() as u64; bencher.iter(|| { test::black_box({ ASCIIEncoding.decode(s, DecoderTrap::Replace) }) }) } }
raw_encoder
identifier_name
mod.rs
//! Trait Resolution. See the [rustc-dev-guide] for more information on how this works. //! //! [rustc-dev-guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html mod engine; pub mod error_reporting; mod project; mod structural_impls; pub mod util; use rustc_hir as hir; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::{self, Const, Ty}; use rustc_span::Span; pub use self::FulfillmentErrorCode::*; pub use self::ImplSource::*; pub use self::ObligationCauseCode::*; pub use self::SelectionError::*; pub use self::engine::{TraitEngine, TraitEngineExt}; pub use self::project::MismatchedProjectionTypes; pub(crate) use self::project::UndoLog; pub use self::project::{ Normalized, NormalizedTy, ProjectionCache, ProjectionCacheEntry, ProjectionCacheKey, ProjectionCacheStorage, Reveal, }; pub use rustc_middle::traits::*; /// An `Obligation` represents some trait reference (e.g., `i32: Eq`) for /// which the "impl_source" must be found. The process of finding an "impl_source" is /// called "resolving" the `Obligation`. This process consists of /// either identifying an `impl` (e.g., `impl Eq for i32`) that /// satisfies the obligation, or else finding a bound that is in /// scope. The eventual result is usually a `Selection` (defined below). #[derive(Clone, PartialEq, Eq, Hash)] pub struct Obligation<'tcx, T> { /// The reason we have to prove this thing. pub cause: ObligationCause<'tcx>, /// The environment in which we should prove this thing. pub param_env: ty::ParamEnv<'tcx>, /// The thing we are trying to prove. pub predicate: T, /// If we started proving this as a result of trying to prove /// something else, track the total depth to ensure termination. /// If this goes over a certain threshold, we abort compilation -- /// in such cases, we can not say whether or not the predicate /// holds for certain. Stupid halting problem; such a drag. pub recursion_depth: usize, } pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>; pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>; // `PredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] static_assert_size!(PredicateObligation<'_>, 32); pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>; pub type Selection<'tcx> = ImplSource<'tcx, PredicateObligation<'tcx>>; pub struct FulfillmentError<'tcx> { pub obligation: PredicateObligation<'tcx>, pub code: FulfillmentErrorCode<'tcx>, /// Diagnostics only: we opportunistically change the `code.span` when we encounter an /// obligation error caused by a call argument. When this is the case, we also signal that in /// this field to ensure accuracy of suggestions. pub points_at_arg_span: bool, /// Diagnostics only: the 'root' obligation which resulted in /// the failure to process `obligation`. This is the obligation /// that was initially passed to `register_predicate_obligation` pub root_obligation: PredicateObligation<'tcx>, } #[derive(Clone)] pub enum FulfillmentErrorCode<'tcx> { CodeSelectionError(SelectionError<'tcx>), CodeProjectionError(MismatchedProjectionTypes<'tcx>), CodeSubtypeError(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate CodeConstEquateError(ExpectedFound<&'tcx Const<'tcx>>, TypeError<'tcx>), CodeAmbiguity, } impl<'tcx, O> Obligation<'tcx, O> { pub fn
( cause: ObligationCause<'tcx>, param_env: ty::ParamEnv<'tcx>, predicate: O, ) -> Obligation<'tcx, O> { Obligation { cause, param_env, recursion_depth: 0, predicate } } pub fn with_depth( cause: ObligationCause<'tcx>, recursion_depth: usize, param_env: ty::ParamEnv<'tcx>, predicate: O, ) -> Obligation<'tcx, O> { Obligation { cause, param_env, recursion_depth, predicate } } pub fn misc( span: Span, body_id: hir::HirId, param_env: ty::ParamEnv<'tcx>, trait_ref: O, ) -> Obligation<'tcx, O> { Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref) } pub fn with<P>(&self, value: P) -> Obligation<'tcx, P> { Obligation { cause: self.cause.clone(), param_env: self.param_env, recursion_depth: self.recursion_depth, predicate: value, } } } impl<'tcx> FulfillmentError<'tcx> { pub fn new( obligation: PredicateObligation<'tcx>, code: FulfillmentErrorCode<'tcx>, root_obligation: PredicateObligation<'tcx>, ) -> FulfillmentError<'tcx> { FulfillmentError { obligation, code, points_at_arg_span: false, root_obligation } } } impl<'tcx> TraitObligation<'tcx> { pub fn self_ty(&self) -> ty::Binder<'tcx, Ty<'tcx>> { self.predicate.map_bound(|p| p.self_ty()) } }
new
identifier_name
mod.rs
//! Trait Resolution. See the [rustc-dev-guide] for more information on how this works. //! //! [rustc-dev-guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html mod engine; pub mod error_reporting; mod project; mod structural_impls; pub mod util; use rustc_hir as hir; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::{self, Const, Ty}; use rustc_span::Span; pub use self::FulfillmentErrorCode::*; pub use self::ImplSource::*; pub use self::ObligationCauseCode::*; pub use self::SelectionError::*; pub use self::engine::{TraitEngine, TraitEngineExt}; pub use self::project::MismatchedProjectionTypes; pub(crate) use self::project::UndoLog; pub use self::project::{ Normalized, NormalizedTy, ProjectionCache, ProjectionCacheEntry, ProjectionCacheKey, ProjectionCacheStorage, Reveal, }; pub use rustc_middle::traits::*; /// An `Obligation` represents some trait reference (e.g., `i32: Eq`) for /// which the "impl_source" must be found. The process of finding an "impl_source" is /// called "resolving" the `Obligation`. This process consists of /// either identifying an `impl` (e.g., `impl Eq for i32`) that /// satisfies the obligation, or else finding a bound that is in /// scope. The eventual result is usually a `Selection` (defined below). #[derive(Clone, PartialEq, Eq, Hash)] pub struct Obligation<'tcx, T> { /// The reason we have to prove this thing. pub cause: ObligationCause<'tcx>, /// The environment in which we should prove this thing. pub param_env: ty::ParamEnv<'tcx>, /// The thing we are trying to prove. pub predicate: T,
/// something else, track the total depth to ensure termination. /// If this goes over a certain threshold, we abort compilation -- /// in such cases, we can not say whether or not the predicate /// holds for certain. Stupid halting problem; such a drag. pub recursion_depth: usize, } pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>; pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>; // `PredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] static_assert_size!(PredicateObligation<'_>, 32); pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>; pub type Selection<'tcx> = ImplSource<'tcx, PredicateObligation<'tcx>>; pub struct FulfillmentError<'tcx> { pub obligation: PredicateObligation<'tcx>, pub code: FulfillmentErrorCode<'tcx>, /// Diagnostics only: we opportunistically change the `code.span` when we encounter an /// obligation error caused by a call argument. When this is the case, we also signal that in /// this field to ensure accuracy of suggestions. pub points_at_arg_span: bool, /// Diagnostics only: the 'root' obligation which resulted in /// the failure to process `obligation`. This is the obligation /// that was initially passed to `register_predicate_obligation` pub root_obligation: PredicateObligation<'tcx>, } #[derive(Clone)] pub enum FulfillmentErrorCode<'tcx> { CodeSelectionError(SelectionError<'tcx>), CodeProjectionError(MismatchedProjectionTypes<'tcx>), CodeSubtypeError(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate CodeConstEquateError(ExpectedFound<&'tcx Const<'tcx>>, TypeError<'tcx>), CodeAmbiguity, } impl<'tcx, O> Obligation<'tcx, O> { pub fn new( cause: ObligationCause<'tcx>, param_env: ty::ParamEnv<'tcx>, predicate: O, ) -> Obligation<'tcx, O> { Obligation { cause, param_env, recursion_depth: 0, predicate } } pub fn with_depth( cause: ObligationCause<'tcx>, recursion_depth: usize, param_env: ty::ParamEnv<'tcx>, predicate: O, ) -> Obligation<'tcx, O> { Obligation { cause, param_env, recursion_depth, predicate } } pub fn misc( span: Span, body_id: hir::HirId, param_env: ty::ParamEnv<'tcx>, trait_ref: O, ) -> Obligation<'tcx, O> { Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref) } pub fn with<P>(&self, value: P) -> Obligation<'tcx, P> { Obligation { cause: self.cause.clone(), param_env: self.param_env, recursion_depth: self.recursion_depth, predicate: value, } } } impl<'tcx> FulfillmentError<'tcx> { pub fn new( obligation: PredicateObligation<'tcx>, code: FulfillmentErrorCode<'tcx>, root_obligation: PredicateObligation<'tcx>, ) -> FulfillmentError<'tcx> { FulfillmentError { obligation, code, points_at_arg_span: false, root_obligation } } } impl<'tcx> TraitObligation<'tcx> { pub fn self_ty(&self) -> ty::Binder<'tcx, Ty<'tcx>> { self.predicate.map_bound(|p| p.self_ty()) } }
/// If we started proving this as a result of trying to prove
random_line_split
mod.rs
//! Trait Resolution. See the [rustc-dev-guide] for more information on how this works. //! //! [rustc-dev-guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html mod engine; pub mod error_reporting; mod project; mod structural_impls; pub mod util; use rustc_hir as hir; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::{self, Const, Ty}; use rustc_span::Span; pub use self::FulfillmentErrorCode::*; pub use self::ImplSource::*; pub use self::ObligationCauseCode::*; pub use self::SelectionError::*; pub use self::engine::{TraitEngine, TraitEngineExt}; pub use self::project::MismatchedProjectionTypes; pub(crate) use self::project::UndoLog; pub use self::project::{ Normalized, NormalizedTy, ProjectionCache, ProjectionCacheEntry, ProjectionCacheKey, ProjectionCacheStorage, Reveal, }; pub use rustc_middle::traits::*; /// An `Obligation` represents some trait reference (e.g., `i32: Eq`) for /// which the "impl_source" must be found. The process of finding an "impl_source" is /// called "resolving" the `Obligation`. This process consists of /// either identifying an `impl` (e.g., `impl Eq for i32`) that /// satisfies the obligation, or else finding a bound that is in /// scope. The eventual result is usually a `Selection` (defined below). #[derive(Clone, PartialEq, Eq, Hash)] pub struct Obligation<'tcx, T> { /// The reason we have to prove this thing. pub cause: ObligationCause<'tcx>, /// The environment in which we should prove this thing. pub param_env: ty::ParamEnv<'tcx>, /// The thing we are trying to prove. pub predicate: T, /// If we started proving this as a result of trying to prove /// something else, track the total depth to ensure termination. /// If this goes over a certain threshold, we abort compilation -- /// in such cases, we can not say whether or not the predicate /// holds for certain. Stupid halting problem; such a drag. pub recursion_depth: usize, } pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>; pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>; // `PredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] static_assert_size!(PredicateObligation<'_>, 32); pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>; pub type Selection<'tcx> = ImplSource<'tcx, PredicateObligation<'tcx>>; pub struct FulfillmentError<'tcx> { pub obligation: PredicateObligation<'tcx>, pub code: FulfillmentErrorCode<'tcx>, /// Diagnostics only: we opportunistically change the `code.span` when we encounter an /// obligation error caused by a call argument. When this is the case, we also signal that in /// this field to ensure accuracy of suggestions. pub points_at_arg_span: bool, /// Diagnostics only: the 'root' obligation which resulted in /// the failure to process `obligation`. This is the obligation /// that was initially passed to `register_predicate_obligation` pub root_obligation: PredicateObligation<'tcx>, } #[derive(Clone)] pub enum FulfillmentErrorCode<'tcx> { CodeSelectionError(SelectionError<'tcx>), CodeProjectionError(MismatchedProjectionTypes<'tcx>), CodeSubtypeError(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate CodeConstEquateError(ExpectedFound<&'tcx Const<'tcx>>, TypeError<'tcx>), CodeAmbiguity, } impl<'tcx, O> Obligation<'tcx, O> { pub fn new( cause: ObligationCause<'tcx>, param_env: ty::ParamEnv<'tcx>, predicate: O, ) -> Obligation<'tcx, O> { Obligation { cause, param_env, recursion_depth: 0, predicate } } pub fn with_depth( cause: ObligationCause<'tcx>, recursion_depth: usize, param_env: ty::ParamEnv<'tcx>, predicate: O, ) -> Obligation<'tcx, O> { Obligation { cause, param_env, recursion_depth, predicate } } pub fn misc( span: Span, body_id: hir::HirId, param_env: ty::ParamEnv<'tcx>, trait_ref: O, ) -> Obligation<'tcx, O>
pub fn with<P>(&self, value: P) -> Obligation<'tcx, P> { Obligation { cause: self.cause.clone(), param_env: self.param_env, recursion_depth: self.recursion_depth, predicate: value, } } } impl<'tcx> FulfillmentError<'tcx> { pub fn new( obligation: PredicateObligation<'tcx>, code: FulfillmentErrorCode<'tcx>, root_obligation: PredicateObligation<'tcx>, ) -> FulfillmentError<'tcx> { FulfillmentError { obligation, code, points_at_arg_span: false, root_obligation } } } impl<'tcx> TraitObligation<'tcx> { pub fn self_ty(&self) -> ty::Binder<'tcx, Ty<'tcx>> { self.predicate.map_bound(|p| p.self_ty()) } }
{ Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref) }
identifier_body
errors.rs
use primitives::*; error_chain!{ errors { /// Error when trying trying to call `Expr::get()`, but the index is invalid. InvalidExprAccess(index: usize) { description("Trying to access an invalid expression index.") display("Trying to access the invalid expression index {}.", index) } /// Error when attempting to perform an operation on tensors whose shapes are /// not compatible (none of them is broadcastable to the other) InvalidShapes(op_name: String, shape1: String, shape2: String) { description("The shapes given are incompatible.") display("The shapes {} and {} given to operator {} are incompatible", shape1, shape2, op_name) } InvalidArguments(op: String, args: Vec<usize>, msg: String) {
display("Invalid arguments: {:?}. '{}' message: {}", args, op, msg) } Downcast(from: FundamentalType, to: FundamentalType) { description("Down casting tensor.") display("Down casting tensor from {} to {}.", from, to) } } // foreign_links { // LibUsb(::libusb::Error); // Io(::std::io::Error); // } }
description("Invalid arguments.")
random_line_split
super_simplex.rs
//! An example of using Super Simplex noise extern crate noise; use noise::{utils::*, Seedable, SuperSimplex}; fn main() { let mut lookup_2d: [([i8; 2], [f64; 2]); 8 * 4] = [([0; 2], [0.0; 2]); 8 * 4]; let mut lookup_3d: [[i8; 3]; 16 * 4] = [[0; 3]; 16 * 4]; let skew_constant = -0.211324865405187; for i in 0..8 { let (i1, j1, i2, j2); if i & 1 == 0 { if i & 2 == 0 { i1 = -1; j1 = 0; } else
if i & 4 == 0 { i2 = 0; j2 = -1; } else { i2 = 0; j2 = 1; } } else { if i & 2!= 0 { i1 = 2; j1 = 1; } else { i1 = 0; j1 = 1; } if i & 4!= 0 { i2 = 1; j2 = 2; } else { i2 = 1; j2 = 0; } } lookup_2d[i * 4] = ([0, 0], [0.0, 0.0]); let skew_factor = -1.0 - 2.0 * skew_constant; lookup_2d[i * 4 + 1] = ([1, 1], [skew_factor, skew_factor]); let skew_factor = (i1 as f64 + j1 as f64) * skew_constant; lookup_2d[i * 4 + 2] = ( [i1, j1], [-i1 as f64 - skew_factor, -j1 as f64 - skew_factor], ); let skew_factor = (i2 as f64 + j2 as f64) * skew_constant; lookup_2d[i * 4 + 3] = ( [i2, j2], [-i2 as f64 - skew_factor, -j2 as f64 - skew_factor], ); } print!("lookup_2d = ["); for x in &lookup_2d { print!( "([{}, {}], [{}f64, {}f64]),", x.0[0], x.0[1], x.1[0], x.1[1] ); } println!("\x08]"); for i in 0..16 { let (i1, j1, k1, i2, j2, k2, i3, j3, k3, i4, j4, k4); if i & 1!= 0 { i1 = 1; j1 = 1; k1 = 1; } else { i1 = 0; j1 = 0; k1 = 0; } if i & 2!= 0 { i2 = 0; j2 = 1; k2 = 1; } else { i2 = 1; j2 = 0; k2 = 0; } if i & 4!= 0 { j3 = 0; i3 = 1; k3 = 1; } else { j3 = 1; i3 = 0; k3 = 0; } if i & 8!= 0 { k4 = 0; i4 = 1; j4 = 1; } else { k4 = 1; i4 = 0; j4 = 0; } lookup_3d[i * 4] = [i1, j1, k1]; lookup_3d[i * 4 + 1] = [i2, j2, k2]; lookup_3d[i * 4 + 2] = [i3, j3, k3]; lookup_3d[i * 4 + 3] = [i4, j4, k4]; } print!("lookup_3d = ["); for x in lookup_3d.iter() { print!("[{}, {}, {}],", x[0], x[1], x[2]); } println!("\x08]"); // Calculation of maximum value: // x => real_rel_coords[0], y => real_rel_coords[1] // a-h, components of gradient vectors for 4 closest points // One contribution: (a*x + b*y) * (2/3 - x^2 - y^2)^4 // Limit per contribution: 0 <= x^2 + y^2 < 2/3 // skew = ((1 / sqrt(2 + 1) - 1) / 2) // (a*x + b*y) * (2/3 - x^2 - y^2)^4 + (c*(x - 1 - 2 * skew) + d*(y - 1 - 2 * skew)) * (2/3 - (x - 1 - 2 * skew)^2 - (y - 1 - 2 * skew)^2)^4 + (e*(x - skew) + f*(y - 1 - skew)) * (2/3 - (x - skew)^2 - (y - 1 - skew)^2)^4 + (g*(x - 1 - skew) + h*(y - skew)) * (2/3 - (x - 1 - skew)^2 - (y - skew)^2)^4 // 0 <= x^2 + y^2 < 2/3 && 0 <= (x - 1 - 2 * skew)^2 + (y - 1 - 2 * skew)^2 < 2/3 && 0 <= (x - skew)^2 + (y - 1 - skew)^2 < 2/3 && 0 <= (x - 1 - skew)^2 + (y - skew)^2 < 2/3 // a^2 + b^2 == 1 && c^2 + d^2 == 1 && e^2 + f^2 == 1 && g^2 + h^2 == 1 // Note: Maximum value is dependent on gradients. In the example below the gradients were [0,1] at [0,0], [-1,0] at [1,1], and [1/sqrt(2),-1/sqrt(2)] at [0,1] (on the simplex grid) // The maximum possible value is achieved when the dot product of the delta position to the gradient is 1.0. As such, the gradients used below were picked because they produced the maximum possible dot product when sampled at the centroid of the simplex. // Mathematica code for finding maximum of 2D Super Simplex noise: // Clear["Global`*"]; // skew = (1/Sqrt[2 + 1] - 1)/2 // eq[a_, b_, x_, y_] = (a*x + b*y)*(2/3 - x^2 - y^2)^4 // eq5[x_, y_] = eq[0, 1, x, y] + eq[-1, 0, x - 1 - 2*skew, y - 1 - 2*skew] + eq[1/Sqrt[2], -1/Sqrt[2], x - skew, y - 1 - skew] // F[{x_, y_}] = eq5[x, y]; // Fx[x_, y_] = D[eq5[x, y], x]; // Fy[x_, y_] = D[eq5[x, y], y]; // Fxx[x_, y_] = D[D[eq5[x, y], x], x]; // Fyy[x_, y_] = D[D[eq5[x, y], y], y]; // Fxy[x_, y_] = D[D[eq5[x, y], x], y]; // X0 = {1/3 + skew, 2/3 + skew}; // P0 = N[X0]; // gradF[{x_, y_}] = {Fx[x, y], Fy[x, y]}; // H[{x_, y_}] = {{Fxx[x, y], Fxy[x, y]}, {Fxy[x, y], Fyy[x, y]}}; // Print["f[", PaddedForm[P0, {13, 12}], "]=", // PaddedForm[F[P0], {13, 12}]] // For[i = 1, i <= 10, i++, P0 = P0 - gradF[P0].Inverse[H[P0]]; // Print["f[", PaddedForm[P0, {21, 20}], "]=", // PaddedForm[F[P0], {21, 20}]]] // P0; // {xout, yout} = P0; // eq5[xout, yout] // The computation for the maximum in 3D is shown below. // As it turns out, the maximum is at [1/4,1/4,1/4], so iteration is unnecessary in this case. // The most likely cause for this is that the gradient vectors lined up much better in 3D than they did in 2D, and so the "center" of one of the simplices also turned out to be the maxima. // All gradient vectors were chosen pointing towards the center of the simplex cube. // Clear["Global`*"]; // skew3d = 2/3; // norm = 1/Sqrt[2]; // norm2 = 1/Sqrt[3]; // eq3d[a_, b_, c_, x_, y_, // z_] = (a*x + b*y + c*z)*(3/4 - x^2 - y^2 - z^2)^4; // (*first lattice: [0,0,0], [1,0,0], [0,1,0], [0,0,1]*) // (*second lattice: [1,1,1], [0,1,1], [1,0,1], [1,1,0]*) // eq3dsp[x_, y_, z_] = // eq3d[norm2, norm2, norm2, x, y, z] + // eq3d[-norm2, norm2, norm2, x - 1, y, z] + // eq3d[norm2, -norm2, norm2, x, y - 1, z] + // eq3d[norm2, norm2, -norm2, x, y, z - 1] + // eq3d[-norm2, -norm2, -norm2, x + 1/2 - 1, y + 1/2 - 1, z + 1/2 - 1] + // eq3d[norm2, -norm2, -norm2, x + 1/2, y + 1/2 - 1, z + 1/2 - 1] + // eq3d[-norm2, norm2, -norm2, x + 1/2 - 1, y + 1/2, z + 1/2 - 1] + // eq3d[-norm2, -norm2, norm2, x + 1/2 - 1, y + 1/2 - 1, z + 1/2]; // F[{x_, y_, z_}] = eq3dsp[x, y, z]; // Fx[x_, y_, z_] = D[eq3dsp[x, y, z], x]; // Fy[x_, y_, z_] = D[eq3dsp[x, y, z], y]; // Fz[x_, y_, z_] = D[eq3dsp[x, y, z], z]; // Fxx[x_, y_, z_] = D[D[eq3dsp[x, y, z], x], x]; // Fyy[x_, y_, z_] = D[D[eq3dsp[x, y, z], y], y]; // Fzz[x_, y_, z_] = D[D[eq3dsp[x, y, z], z], z]; // Fxy[x_, y_, z_] = D[D[eq3dsp[x, y, z], x], y]; // Fxz[x_, y_, z_] = D[D[eq3dsp[x, y, z], x], z]; // Fyz[x_, y_, z_] = D[D[eq3dsp[x, y, z], y], z]; // X0 = {1/4, 1/4, 1/4}; // P0 = N[X0]; // gradF[{x_, y_, z_}] = {Fx[x, y, z], Fy[x, y, z], Fz[x, y, z]}; // H[{x_, y_, z_}] = {{Fxx[x, y, z], Fxy[x, y, z], // Fxz[x, y, z]}, {Fxy[x, y, z], Fyy[x, y, z], // Fyz[x, y, z]}, {Fxz[x, y, z], Fyz[x, y, z], Fzz[x, y, z]}}; // Print["f[", PaddedForm[P0, {13, 12}], "]=", // PaddedForm[F[P0], {13, 12}]] // For[i = 1, i <= 10, i++, P0 = P0 - gradF[P0].Inverse[H[P0]]; // Print["f[", PaddedForm[P0, {21, 20}], "]=", // PaddedForm[F[P0], {21, 20}]]] // P0; // {xout, yout, zout} = P0; // eq3dsp[xout, yout, zout] let super_simplex = SuperSimplex::new(); PlaneMapBuilder::new(&super_simplex) .build() .write_to_file("super_simplex.png"); let super_simplex = super_simplex.set_seed(1); PlaneMapBuilder::new(&super_simplex) .build() .write_to_file("super_simplex_seed=1.png"); }
{ i1 = 1; j1 = 0; }
conditional_block
super_simplex.rs
//! An example of using Super Simplex noise extern crate noise; use noise::{utils::*, Seedable, SuperSimplex}; fn main()
j2 = 1; } } else { if i & 2!= 0 { i1 = 2; j1 = 1; } else { i1 = 0; j1 = 1; } if i & 4!= 0 { i2 = 1; j2 = 2; } else { i2 = 1; j2 = 0; } } lookup_2d[i * 4] = ([0, 0], [0.0, 0.0]); let skew_factor = -1.0 - 2.0 * skew_constant; lookup_2d[i * 4 + 1] = ([1, 1], [skew_factor, skew_factor]); let skew_factor = (i1 as f64 + j1 as f64) * skew_constant; lookup_2d[i * 4 + 2] = ( [i1, j1], [-i1 as f64 - skew_factor, -j1 as f64 - skew_factor], ); let skew_factor = (i2 as f64 + j2 as f64) * skew_constant; lookup_2d[i * 4 + 3] = ( [i2, j2], [-i2 as f64 - skew_factor, -j2 as f64 - skew_factor], ); } print!("lookup_2d = ["); for x in &lookup_2d { print!( "([{}, {}], [{}f64, {}f64]),", x.0[0], x.0[1], x.1[0], x.1[1] ); } println!("\x08]"); for i in 0..16 { let (i1, j1, k1, i2, j2, k2, i3, j3, k3, i4, j4, k4); if i & 1!= 0 { i1 = 1; j1 = 1; k1 = 1; } else { i1 = 0; j1 = 0; k1 = 0; } if i & 2!= 0 { i2 = 0; j2 = 1; k2 = 1; } else { i2 = 1; j2 = 0; k2 = 0; } if i & 4!= 0 { j3 = 0; i3 = 1; k3 = 1; } else { j3 = 1; i3 = 0; k3 = 0; } if i & 8!= 0 { k4 = 0; i4 = 1; j4 = 1; } else { k4 = 1; i4 = 0; j4 = 0; } lookup_3d[i * 4] = [i1, j1, k1]; lookup_3d[i * 4 + 1] = [i2, j2, k2]; lookup_3d[i * 4 + 2] = [i3, j3, k3]; lookup_3d[i * 4 + 3] = [i4, j4, k4]; } print!("lookup_3d = ["); for x in lookup_3d.iter() { print!("[{}, {}, {}],", x[0], x[1], x[2]); } println!("\x08]"); // Calculation of maximum value: // x => real_rel_coords[0], y => real_rel_coords[1] // a-h, components of gradient vectors for 4 closest points // One contribution: (a*x + b*y) * (2/3 - x^2 - y^2)^4 // Limit per contribution: 0 <= x^2 + y^2 < 2/3 // skew = ((1 / sqrt(2 + 1) - 1) / 2) // (a*x + b*y) * (2/3 - x^2 - y^2)^4 + (c*(x - 1 - 2 * skew) + d*(y - 1 - 2 * skew)) * (2/3 - (x - 1 - 2 * skew)^2 - (y - 1 - 2 * skew)^2)^4 + (e*(x - skew) + f*(y - 1 - skew)) * (2/3 - (x - skew)^2 - (y - 1 - skew)^2)^4 + (g*(x - 1 - skew) + h*(y - skew)) * (2/3 - (x - 1 - skew)^2 - (y - skew)^2)^4 // 0 <= x^2 + y^2 < 2/3 && 0 <= (x - 1 - 2 * skew)^2 + (y - 1 - 2 * skew)^2 < 2/3 && 0 <= (x - skew)^2 + (y - 1 - skew)^2 < 2/3 && 0 <= (x - 1 - skew)^2 + (y - skew)^2 < 2/3 // a^2 + b^2 == 1 && c^2 + d^2 == 1 && e^2 + f^2 == 1 && g^2 + h^2 == 1 // Note: Maximum value is dependent on gradients. In the example below the gradients were [0,1] at [0,0], [-1,0] at [1,1], and [1/sqrt(2),-1/sqrt(2)] at [0,1] (on the simplex grid) // The maximum possible value is achieved when the dot product of the delta position to the gradient is 1.0. As such, the gradients used below were picked because they produced the maximum possible dot product when sampled at the centroid of the simplex. // Mathematica code for finding maximum of 2D Super Simplex noise: // Clear["Global`*"]; // skew = (1/Sqrt[2 + 1] - 1)/2 // eq[a_, b_, x_, y_] = (a*x + b*y)*(2/3 - x^2 - y^2)^4 // eq5[x_, y_] = eq[0, 1, x, y] + eq[-1, 0, x - 1 - 2*skew, y - 1 - 2*skew] + eq[1/Sqrt[2], -1/Sqrt[2], x - skew, y - 1 - skew] // F[{x_, y_}] = eq5[x, y]; // Fx[x_, y_] = D[eq5[x, y], x]; // Fy[x_, y_] = D[eq5[x, y], y]; // Fxx[x_, y_] = D[D[eq5[x, y], x], x]; // Fyy[x_, y_] = D[D[eq5[x, y], y], y]; // Fxy[x_, y_] = D[D[eq5[x, y], x], y]; // X0 = {1/3 + skew, 2/3 + skew}; // P0 = N[X0]; // gradF[{x_, y_}] = {Fx[x, y], Fy[x, y]}; // H[{x_, y_}] = {{Fxx[x, y], Fxy[x, y]}, {Fxy[x, y], Fyy[x, y]}}; // Print["f[", PaddedForm[P0, {13, 12}], "]=", // PaddedForm[F[P0], {13, 12}]] // For[i = 1, i <= 10, i++, P0 = P0 - gradF[P0].Inverse[H[P0]]; // Print["f[", PaddedForm[P0, {21, 20}], "]=", // PaddedForm[F[P0], {21, 20}]]] // P0; // {xout, yout} = P0; // eq5[xout, yout] // The computation for the maximum in 3D is shown below. // As it turns out, the maximum is at [1/4,1/4,1/4], so iteration is unnecessary in this case. // The most likely cause for this is that the gradient vectors lined up much better in 3D than they did in 2D, and so the "center" of one of the simplices also turned out to be the maxima. // All gradient vectors were chosen pointing towards the center of the simplex cube. // Clear["Global`*"]; // skew3d = 2/3; // norm = 1/Sqrt[2]; // norm2 = 1/Sqrt[3]; // eq3d[a_, b_, c_, x_, y_, // z_] = (a*x + b*y + c*z)*(3/4 - x^2 - y^2 - z^2)^4; // (*first lattice: [0,0,0], [1,0,0], [0,1,0], [0,0,1]*) // (*second lattice: [1,1,1], [0,1,1], [1,0,1], [1,1,0]*) // eq3dsp[x_, y_, z_] = // eq3d[norm2, norm2, norm2, x, y, z] + // eq3d[-norm2, norm2, norm2, x - 1, y, z] + // eq3d[norm2, -norm2, norm2, x, y - 1, z] + // eq3d[norm2, norm2, -norm2, x, y, z - 1] + // eq3d[-norm2, -norm2, -norm2, x + 1/2 - 1, y + 1/2 - 1, z + 1/2 - 1] + // eq3d[norm2, -norm2, -norm2, x + 1/2, y + 1/2 - 1, z + 1/2 - 1] + // eq3d[-norm2, norm2, -norm2, x + 1/2 - 1, y + 1/2, z + 1/2 - 1] + // eq3d[-norm2, -norm2, norm2, x + 1/2 - 1, y + 1/2 - 1, z + 1/2]; // F[{x_, y_, z_}] = eq3dsp[x, y, z]; // Fx[x_, y_, z_] = D[eq3dsp[x, y, z], x]; // Fy[x_, y_, z_] = D[eq3dsp[x, y, z], y]; // Fz[x_, y_, z_] = D[eq3dsp[x, y, z], z]; // Fxx[x_, y_, z_] = D[D[eq3dsp[x, y, z], x], x]; // Fyy[x_, y_, z_] = D[D[eq3dsp[x, y, z], y], y]; // Fzz[x_, y_, z_] = D[D[eq3dsp[x, y, z], z], z]; // Fxy[x_, y_, z_] = D[D[eq3dsp[x, y, z], x], y]; // Fxz[x_, y_, z_] = D[D[eq3dsp[x, y, z], x], z]; // Fyz[x_, y_, z_] = D[D[eq3dsp[x, y, z], y], z]; // X0 = {1/4, 1/4, 1/4}; // P0 = N[X0]; // gradF[{x_, y_, z_}] = {Fx[x, y, z], Fy[x, y, z], Fz[x, y, z]}; // H[{x_, y_, z_}] = {{Fxx[x, y, z], Fxy[x, y, z], // Fxz[x, y, z]}, {Fxy[x, y, z], Fyy[x, y, z], // Fyz[x, y, z]}, {Fxz[x, y, z], Fyz[x, y, z], Fzz[x, y, z]}}; // Print["f[", PaddedForm[P0, {13, 12}], "]=", // PaddedForm[F[P0], {13, 12}]] // For[i = 1, i <= 10, i++, P0 = P0 - gradF[P0].Inverse[H[P0]]; // Print["f[", PaddedForm[P0, {21, 20}], "]=", // PaddedForm[F[P0], {21, 20}]]] // P0; // {xout, yout, zout} = P0; // eq3dsp[xout, yout, zout] let super_simplex = SuperSimplex::new(); PlaneMapBuilder::new(&super_simplex) .build() .write_to_file("super_simplex.png"); let super_simplex = super_simplex.set_seed(1); PlaneMapBuilder::new(&super_simplex) .build() .write_to_file("super_simplex_seed=1.png"); }
{ let mut lookup_2d: [([i8; 2], [f64; 2]); 8 * 4] = [([0; 2], [0.0; 2]); 8 * 4]; let mut lookup_3d: [[i8; 3]; 16 * 4] = [[0; 3]; 16 * 4]; let skew_constant = -0.211324865405187; for i in 0..8 { let (i1, j1, i2, j2); if i & 1 == 0 { if i & 2 == 0 { i1 = -1; j1 = 0; } else { i1 = 1; j1 = 0; } if i & 4 == 0 { i2 = 0; j2 = -1; } else { i2 = 0;
identifier_body
super_simplex.rs
//! An example of using Super Simplex noise extern crate noise; use noise::{utils::*, Seedable, SuperSimplex}; fn
() { let mut lookup_2d: [([i8; 2], [f64; 2]); 8 * 4] = [([0; 2], [0.0; 2]); 8 * 4]; let mut lookup_3d: [[i8; 3]; 16 * 4] = [[0; 3]; 16 * 4]; let skew_constant = -0.211324865405187; for i in 0..8 { let (i1, j1, i2, j2); if i & 1 == 0 { if i & 2 == 0 { i1 = -1; j1 = 0; } else { i1 = 1; j1 = 0; } if i & 4 == 0 { i2 = 0; j2 = -1; } else { i2 = 0; j2 = 1; } } else { if i & 2!= 0 { i1 = 2; j1 = 1; } else { i1 = 0; j1 = 1; } if i & 4!= 0 { i2 = 1; j2 = 2; } else { i2 = 1; j2 = 0; } } lookup_2d[i * 4] = ([0, 0], [0.0, 0.0]); let skew_factor = -1.0 - 2.0 * skew_constant; lookup_2d[i * 4 + 1] = ([1, 1], [skew_factor, skew_factor]); let skew_factor = (i1 as f64 + j1 as f64) * skew_constant; lookup_2d[i * 4 + 2] = ( [i1, j1], [-i1 as f64 - skew_factor, -j1 as f64 - skew_factor], ); let skew_factor = (i2 as f64 + j2 as f64) * skew_constant; lookup_2d[i * 4 + 3] = ( [i2, j2], [-i2 as f64 - skew_factor, -j2 as f64 - skew_factor], ); } print!("lookup_2d = ["); for x in &lookup_2d { print!( "([{}, {}], [{}f64, {}f64]),", x.0[0], x.0[1], x.1[0], x.1[1] ); } println!("\x08]"); for i in 0..16 { let (i1, j1, k1, i2, j2, k2, i3, j3, k3, i4, j4, k4); if i & 1!= 0 { i1 = 1; j1 = 1; k1 = 1; } else { i1 = 0; j1 = 0; k1 = 0; } if i & 2!= 0 { i2 = 0; j2 = 1; k2 = 1; } else { i2 = 1; j2 = 0; k2 = 0; } if i & 4!= 0 { j3 = 0; i3 = 1; k3 = 1; } else { j3 = 1; i3 = 0; k3 = 0; } if i & 8!= 0 { k4 = 0; i4 = 1; j4 = 1; } else { k4 = 1; i4 = 0; j4 = 0; } lookup_3d[i * 4] = [i1, j1, k1]; lookup_3d[i * 4 + 1] = [i2, j2, k2]; lookup_3d[i * 4 + 2] = [i3, j3, k3]; lookup_3d[i * 4 + 3] = [i4, j4, k4]; } print!("lookup_3d = ["); for x in lookup_3d.iter() { print!("[{}, {}, {}],", x[0], x[1], x[2]); } println!("\x08]"); // Calculation of maximum value: // x => real_rel_coords[0], y => real_rel_coords[1] // a-h, components of gradient vectors for 4 closest points // One contribution: (a*x + b*y) * (2/3 - x^2 - y^2)^4 // Limit per contribution: 0 <= x^2 + y^2 < 2/3 // skew = ((1 / sqrt(2 + 1) - 1) / 2) // (a*x + b*y) * (2/3 - x^2 - y^2)^4 + (c*(x - 1 - 2 * skew) + d*(y - 1 - 2 * skew)) * (2/3 - (x - 1 - 2 * skew)^2 - (y - 1 - 2 * skew)^2)^4 + (e*(x - skew) + f*(y - 1 - skew)) * (2/3 - (x - skew)^2 - (y - 1 - skew)^2)^4 + (g*(x - 1 - skew) + h*(y - skew)) * (2/3 - (x - 1 - skew)^2 - (y - skew)^2)^4 // 0 <= x^2 + y^2 < 2/3 && 0 <= (x - 1 - 2 * skew)^2 + (y - 1 - 2 * skew)^2 < 2/3 && 0 <= (x - skew)^2 + (y - 1 - skew)^2 < 2/3 && 0 <= (x - 1 - skew)^2 + (y - skew)^2 < 2/3 // a^2 + b^2 == 1 && c^2 + d^2 == 1 && e^2 + f^2 == 1 && g^2 + h^2 == 1 // Note: Maximum value is dependent on gradients. In the example below the gradients were [0,1] at [0,0], [-1,0] at [1,1], and [1/sqrt(2),-1/sqrt(2)] at [0,1] (on the simplex grid) // The maximum possible value is achieved when the dot product of the delta position to the gradient is 1.0. As such, the gradients used below were picked because they produced the maximum possible dot product when sampled at the centroid of the simplex. // Mathematica code for finding maximum of 2D Super Simplex noise: // Clear["Global`*"]; // skew = (1/Sqrt[2 + 1] - 1)/2 // eq[a_, b_, x_, y_] = (a*x + b*y)*(2/3 - x^2 - y^2)^4 // eq5[x_, y_] = eq[0, 1, x, y] + eq[-1, 0, x - 1 - 2*skew, y - 1 - 2*skew] + eq[1/Sqrt[2], -1/Sqrt[2], x - skew, y - 1 - skew] // F[{x_, y_}] = eq5[x, y]; // Fx[x_, y_] = D[eq5[x, y], x]; // Fy[x_, y_] = D[eq5[x, y], y]; // Fxx[x_, y_] = D[D[eq5[x, y], x], x]; // Fyy[x_, y_] = D[D[eq5[x, y], y], y]; // Fxy[x_, y_] = D[D[eq5[x, y], x], y]; // X0 = {1/3 + skew, 2/3 + skew}; // P0 = N[X0]; // gradF[{x_, y_}] = {Fx[x, y], Fy[x, y]}; // H[{x_, y_}] = {{Fxx[x, y], Fxy[x, y]}, {Fxy[x, y], Fyy[x, y]}}; // Print["f[", PaddedForm[P0, {13, 12}], "]=", // PaddedForm[F[P0], {13, 12}]] // For[i = 1, i <= 10, i++, P0 = P0 - gradF[P0].Inverse[H[P0]]; // Print["f[", PaddedForm[P0, {21, 20}], "]=", // PaddedForm[F[P0], {21, 20}]]] // P0; // {xout, yout} = P0; // eq5[xout, yout] // The computation for the maximum in 3D is shown below. // As it turns out, the maximum is at [1/4,1/4,1/4], so iteration is unnecessary in this case. // The most likely cause for this is that the gradient vectors lined up much better in 3D than they did in 2D, and so the "center" of one of the simplices also turned out to be the maxima. // All gradient vectors were chosen pointing towards the center of the simplex cube. // Clear["Global`*"]; // skew3d = 2/3; // norm = 1/Sqrt[2]; // norm2 = 1/Sqrt[3]; // eq3d[a_, b_, c_, x_, y_, // z_] = (a*x + b*y + c*z)*(3/4 - x^2 - y^2 - z^2)^4; // (*first lattice: [0,0,0], [1,0,0], [0,1,0], [0,0,1]*) // (*second lattice: [1,1,1], [0,1,1], [1,0,1], [1,1,0]*) // eq3dsp[x_, y_, z_] = // eq3d[norm2, norm2, norm2, x, y, z] + // eq3d[-norm2, norm2, norm2, x - 1, y, z] + // eq3d[norm2, -norm2, norm2, x, y - 1, z] + // eq3d[norm2, norm2, -norm2, x, y, z - 1] + // eq3d[-norm2, -norm2, -norm2, x + 1/2 - 1, y + 1/2 - 1, z + 1/2 - 1] + // eq3d[norm2, -norm2, -norm2, x + 1/2, y + 1/2 - 1, z + 1/2 - 1] + // eq3d[-norm2, norm2, -norm2, x + 1/2 - 1, y + 1/2, z + 1/2 - 1] + // eq3d[-norm2, -norm2, norm2, x + 1/2 - 1, y + 1/2 - 1, z + 1/2]; // F[{x_, y_, z_}] = eq3dsp[x, y, z]; // Fx[x_, y_, z_] = D[eq3dsp[x, y, z], x]; // Fy[x_, y_, z_] = D[eq3dsp[x, y, z], y]; // Fz[x_, y_, z_] = D[eq3dsp[x, y, z], z]; // Fxx[x_, y_, z_] = D[D[eq3dsp[x, y, z], x], x]; // Fyy[x_, y_, z_] = D[D[eq3dsp[x, y, z], y], y]; // Fzz[x_, y_, z_] = D[D[eq3dsp[x, y, z], z], z]; // Fxy[x_, y_, z_] = D[D[eq3dsp[x, y, z], x], y]; // Fxz[x_, y_, z_] = D[D[eq3dsp[x, y, z], x], z]; // Fyz[x_, y_, z_] = D[D[eq3dsp[x, y, z], y], z]; // X0 = {1/4, 1/4, 1/4}; // P0 = N[X0]; // gradF[{x_, y_, z_}] = {Fx[x, y, z], Fy[x, y, z], Fz[x, y, z]}; // H[{x_, y_, z_}] = {{Fxx[x, y, z], Fxy[x, y, z], // Fxz[x, y, z]}, {Fxy[x, y, z], Fyy[x, y, z], // Fyz[x, y, z]}, {Fxz[x, y, z], Fyz[x, y, z], Fzz[x, y, z]}}; // Print["f[", PaddedForm[P0, {13, 12}], "]=", // PaddedForm[F[P0], {13, 12}]] // For[i = 1, i <= 10, i++, P0 = P0 - gradF[P0].Inverse[H[P0]]; // Print["f[", PaddedForm[P0, {21, 20}], "]=", // PaddedForm[F[P0], {21, 20}]]] // P0; // {xout, yout, zout} = P0; // eq3dsp[xout, yout, zout] let super_simplex = SuperSimplex::new(); PlaneMapBuilder::new(&super_simplex) .build() .write_to_file("super_simplex.png"); let super_simplex = super_simplex.set_seed(1); PlaneMapBuilder::new(&super_simplex) .build() .write_to_file("super_simplex_seed=1.png"); }
main
identifier_name
super_simplex.rs
//! An example of using Super Simplex noise extern crate noise; use noise::{utils::*, Seedable, SuperSimplex}; fn main() { let mut lookup_2d: [([i8; 2], [f64; 2]); 8 * 4] = [([0; 2], [0.0; 2]); 8 * 4]; let mut lookup_3d: [[i8; 3]; 16 * 4] = [[0; 3]; 16 * 4]; let skew_constant = -0.211324865405187; for i in 0..8 { let (i1, j1, i2, j2); if i & 1 == 0 { if i & 2 == 0 { i1 = -1; j1 = 0; } else { i1 = 1; j1 = 0; } if i & 4 == 0 { i2 = 0; j2 = -1; } else { i2 = 0; j2 = 1; } } else { if i & 2!= 0 { i1 = 2; j1 = 1;
if i & 4!= 0 { i2 = 1; j2 = 2; } else { i2 = 1; j2 = 0; } } lookup_2d[i * 4] = ([0, 0], [0.0, 0.0]); let skew_factor = -1.0 - 2.0 * skew_constant; lookup_2d[i * 4 + 1] = ([1, 1], [skew_factor, skew_factor]); let skew_factor = (i1 as f64 + j1 as f64) * skew_constant; lookup_2d[i * 4 + 2] = ( [i1, j1], [-i1 as f64 - skew_factor, -j1 as f64 - skew_factor], ); let skew_factor = (i2 as f64 + j2 as f64) * skew_constant; lookup_2d[i * 4 + 3] = ( [i2, j2], [-i2 as f64 - skew_factor, -j2 as f64 - skew_factor], ); } print!("lookup_2d = ["); for x in &lookup_2d { print!( "([{}, {}], [{}f64, {}f64]),", x.0[0], x.0[1], x.1[0], x.1[1] ); } println!("\x08]"); for i in 0..16 { let (i1, j1, k1, i2, j2, k2, i3, j3, k3, i4, j4, k4); if i & 1!= 0 { i1 = 1; j1 = 1; k1 = 1; } else { i1 = 0; j1 = 0; k1 = 0; } if i & 2!= 0 { i2 = 0; j2 = 1; k2 = 1; } else { i2 = 1; j2 = 0; k2 = 0; } if i & 4!= 0 { j3 = 0; i3 = 1; k3 = 1; } else { j3 = 1; i3 = 0; k3 = 0; } if i & 8!= 0 { k4 = 0; i4 = 1; j4 = 1; } else { k4 = 1; i4 = 0; j4 = 0; } lookup_3d[i * 4] = [i1, j1, k1]; lookup_3d[i * 4 + 1] = [i2, j2, k2]; lookup_3d[i * 4 + 2] = [i3, j3, k3]; lookup_3d[i * 4 + 3] = [i4, j4, k4]; } print!("lookup_3d = ["); for x in lookup_3d.iter() { print!("[{}, {}, {}],", x[0], x[1], x[2]); } println!("\x08]"); // Calculation of maximum value: // x => real_rel_coords[0], y => real_rel_coords[1] // a-h, components of gradient vectors for 4 closest points // One contribution: (a*x + b*y) * (2/3 - x^2 - y^2)^4 // Limit per contribution: 0 <= x^2 + y^2 < 2/3 // skew = ((1 / sqrt(2 + 1) - 1) / 2) // (a*x + b*y) * (2/3 - x^2 - y^2)^4 + (c*(x - 1 - 2 * skew) + d*(y - 1 - 2 * skew)) * (2/3 - (x - 1 - 2 * skew)^2 - (y - 1 - 2 * skew)^2)^4 + (e*(x - skew) + f*(y - 1 - skew)) * (2/3 - (x - skew)^2 - (y - 1 - skew)^2)^4 + (g*(x - 1 - skew) + h*(y - skew)) * (2/3 - (x - 1 - skew)^2 - (y - skew)^2)^4 // 0 <= x^2 + y^2 < 2/3 && 0 <= (x - 1 - 2 * skew)^2 + (y - 1 - 2 * skew)^2 < 2/3 && 0 <= (x - skew)^2 + (y - 1 - skew)^2 < 2/3 && 0 <= (x - 1 - skew)^2 + (y - skew)^2 < 2/3 // a^2 + b^2 == 1 && c^2 + d^2 == 1 && e^2 + f^2 == 1 && g^2 + h^2 == 1 // Note: Maximum value is dependent on gradients. In the example below the gradients were [0,1] at [0,0], [-1,0] at [1,1], and [1/sqrt(2),-1/sqrt(2)] at [0,1] (on the simplex grid) // The maximum possible value is achieved when the dot product of the delta position to the gradient is 1.0. As such, the gradients used below were picked because they produced the maximum possible dot product when sampled at the centroid of the simplex. // Mathematica code for finding maximum of 2D Super Simplex noise: // Clear["Global`*"]; // skew = (1/Sqrt[2 + 1] - 1)/2 // eq[a_, b_, x_, y_] = (a*x + b*y)*(2/3 - x^2 - y^2)^4 // eq5[x_, y_] = eq[0, 1, x, y] + eq[-1, 0, x - 1 - 2*skew, y - 1 - 2*skew] + eq[1/Sqrt[2], -1/Sqrt[2], x - skew, y - 1 - skew] // F[{x_, y_}] = eq5[x, y]; // Fx[x_, y_] = D[eq5[x, y], x]; // Fy[x_, y_] = D[eq5[x, y], y]; // Fxx[x_, y_] = D[D[eq5[x, y], x], x]; // Fyy[x_, y_] = D[D[eq5[x, y], y], y]; // Fxy[x_, y_] = D[D[eq5[x, y], x], y]; // X0 = {1/3 + skew, 2/3 + skew}; // P0 = N[X0]; // gradF[{x_, y_}] = {Fx[x, y], Fy[x, y]}; // H[{x_, y_}] = {{Fxx[x, y], Fxy[x, y]}, {Fxy[x, y], Fyy[x, y]}}; // Print["f[", PaddedForm[P0, {13, 12}], "]=", // PaddedForm[F[P0], {13, 12}]] // For[i = 1, i <= 10, i++, P0 = P0 - gradF[P0].Inverse[H[P0]]; // Print["f[", PaddedForm[P0, {21, 20}], "]=", // PaddedForm[F[P0], {21, 20}]]] // P0; // {xout, yout} = P0; // eq5[xout, yout] // The computation for the maximum in 3D is shown below. // As it turns out, the maximum is at [1/4,1/4,1/4], so iteration is unnecessary in this case. // The most likely cause for this is that the gradient vectors lined up much better in 3D than they did in 2D, and so the "center" of one of the simplices also turned out to be the maxima. // All gradient vectors were chosen pointing towards the center of the simplex cube. // Clear["Global`*"]; // skew3d = 2/3; // norm = 1/Sqrt[2]; // norm2 = 1/Sqrt[3]; // eq3d[a_, b_, c_, x_, y_, // z_] = (a*x + b*y + c*z)*(3/4 - x^2 - y^2 - z^2)^4; // (*first lattice: [0,0,0], [1,0,0], [0,1,0], [0,0,1]*) // (*second lattice: [1,1,1], [0,1,1], [1,0,1], [1,1,0]*) // eq3dsp[x_, y_, z_] = // eq3d[norm2, norm2, norm2, x, y, z] + // eq3d[-norm2, norm2, norm2, x - 1, y, z] + // eq3d[norm2, -norm2, norm2, x, y - 1, z] + // eq3d[norm2, norm2, -norm2, x, y, z - 1] + // eq3d[-norm2, -norm2, -norm2, x + 1/2 - 1, y + 1/2 - 1, z + 1/2 - 1] + // eq3d[norm2, -norm2, -norm2, x + 1/2, y + 1/2 - 1, z + 1/2 - 1] + // eq3d[-norm2, norm2, -norm2, x + 1/2 - 1, y + 1/2, z + 1/2 - 1] + // eq3d[-norm2, -norm2, norm2, x + 1/2 - 1, y + 1/2 - 1, z + 1/2]; // F[{x_, y_, z_}] = eq3dsp[x, y, z]; // Fx[x_, y_, z_] = D[eq3dsp[x, y, z], x]; // Fy[x_, y_, z_] = D[eq3dsp[x, y, z], y]; // Fz[x_, y_, z_] = D[eq3dsp[x, y, z], z]; // Fxx[x_, y_, z_] = D[D[eq3dsp[x, y, z], x], x]; // Fyy[x_, y_, z_] = D[D[eq3dsp[x, y, z], y], y]; // Fzz[x_, y_, z_] = D[D[eq3dsp[x, y, z], z], z]; // Fxy[x_, y_, z_] = D[D[eq3dsp[x, y, z], x], y]; // Fxz[x_, y_, z_] = D[D[eq3dsp[x, y, z], x], z]; // Fyz[x_, y_, z_] = D[D[eq3dsp[x, y, z], y], z]; // X0 = {1/4, 1/4, 1/4}; // P0 = N[X0]; // gradF[{x_, y_, z_}] = {Fx[x, y, z], Fy[x, y, z], Fz[x, y, z]}; // H[{x_, y_, z_}] = {{Fxx[x, y, z], Fxy[x, y, z], // Fxz[x, y, z]}, {Fxy[x, y, z], Fyy[x, y, z], // Fyz[x, y, z]}, {Fxz[x, y, z], Fyz[x, y, z], Fzz[x, y, z]}}; // Print["f[", PaddedForm[P0, {13, 12}], "]=", // PaddedForm[F[P0], {13, 12}]] // For[i = 1, i <= 10, i++, P0 = P0 - gradF[P0].Inverse[H[P0]]; // Print["f[", PaddedForm[P0, {21, 20}], "]=", // PaddedForm[F[P0], {21, 20}]]] // P0; // {xout, yout, zout} = P0; // eq3dsp[xout, yout, zout] let super_simplex = SuperSimplex::new(); PlaneMapBuilder::new(&super_simplex) .build() .write_to_file("super_simplex.png"); let super_simplex = super_simplex.set_seed(1); PlaneMapBuilder::new(&super_simplex) .build() .write_to_file("super_simplex_seed=1.png"); }
} else { i1 = 0; j1 = 1; }
random_line_split
lib.rs
#![cfg_attr(test, feature(plugin))] #![warn( clippy::empty_enum, clippy::filter_map, clippy::if_not_else, clippy::invalid_upcast_comparisons, clippy::items_after_statements, clippy::mut_mut, clippy::nonminimal_bool, clippy::option_map_unwrap_or, clippy::option_map_unwrap_or_else, clippy::pub_enum_variant_names, clippy::shadow_same, clippy::single_match_else, clippy::string_add_assign, clippy::unicode_not_nfc, clippy::unseparated_literal_suffix, clippy::used_underscore_binding, clippy::wrong_pub_self_convention )] #[macro_use] extern crate log; #[macro_use] extern crate failure; #[macro_use] extern crate serde_derive; #[macro_use] extern crate lazy_static; #[cfg(test)] extern crate quickcheck; #[cfg(test)] #[macro_use] extern crate quickcheck_macros; mod collection; mod command; mod current_level; mod direction; mod event; mod game; mod level; mod macros; mod move_; mod position; pub mod save; mod undo; mod util; use std::fs; use std::path::PathBuf; use ansi_term::Colour::{Blue, Green, White, Yellow}; pub use crate::collection::*; pub use crate::command::*; pub use crate::current_level::*; pub use crate::direction::*; pub use crate::event::*; pub use crate::game::*; pub use crate::level::*; pub use crate::macros::*; pub use crate::move_::*; pub use crate::position::*; use crate::save::CollectionState; pub use crate::util::*; fn file_stem(p: &PathBuf) -> &str { p.file_stem().unwrap().to_str().unwrap() } pub fn convert_savegames() { use std::ffi::OsStr; for entry in fs::read_dir(DATA_DIR.as_path()).unwrap() { let entry = entry.unwrap(); let path = entry.path(); if path.is_file() && path.extension() == Some(OsStr::new("json")) { let collection_name = file_stem(&path); let mut state = save::CollectionState::load(collection_name); state.save(collection_name).unwrap(); } } } struct CollectionStats { pub short_name: String, pub name: String, pub total_levels: usize, pub solved_levels: usize, } impl CollectionStats { fn solved(&self) -> bool { self.total_levels == self.solved_levels } fn started(&self) -> bool { self.solved_levels > 0 } } fn gather_stats() -> Vec<CollectionStats> { // Find all level set files let mut paths: Vec<PathBuf> = fs::read_dir(ASSETS.join("levels")) .unwrap() .map(|x| x.unwrap().path()) .collect(); paths.sort_by(|x, y| ::natord::compare(file_stem(x), file_stem(y))); let mut result = vec![]; for path in paths { if let Some(ext) = path.extension() { use std::ffi::OsStr; if ext == OsStr::new("lvl") || ext == OsStr::new("slc") { let name = path.file_stem().and_then(|x| x.to_str()).unwrap(); let collection = Collection::parse_metadata(name).unwrap(); let state = CollectionState::load(collection.short_name()); result.push(CollectionStats { short_name: name.to_string(), name: collection.name().to_string(), total_levels: collection.number_of_levels(), solved_levels: state.number_of_solved_levels(), }); } } } result } pub fn print_collections_table() { let stats = gather_stats(); println!( " {} {}", Yellow.bold().paint("File name"), Yellow.bold().paint("Collection name") ); println!("--------------------------------------------------------------------------------"); for collection in stats { let padded_short_name = format!("{:<24}", collection.short_name); let padded_full_name = format!("{:<36}", collection.name); if collection.solved() { println!( " {}{} {}", Green.paint(padded_short_name), Green.bold().paint(padded_full_name), Green.paint("done") ); } else { let solved = if collection.started() { Blue.paint("solved") } else { White.paint("solved") }; println!( " {}{}{:>10} {}", padded_short_name, White.bold().paint(padded_full_name), format!("{}/{}", collection.solved_levels, collection.total_levels), solved ); } } } pub fn print_stats() { let stats = gather_stats(); let num_collections = stats.len(); let num_levels: usize = stats.iter().map(|x| x.total_levels).sum();
let finished_levels: usize = stats.iter().map(|x| x.solved_levels).sum(); let collections_started = stats.iter().filter(|x| x.started() &&!x.solved()).count(); println!( "{}", Yellow.bold().paint(" Collections Levels") ); println!("------------------------------------"); println!("Total {:>11} {:>11}", num_collections, num_levels); println!( "Finished {:>11} {:>11}", finished_collections, finished_levels ); println!("Started {:>11}", collections_started); }
let finished_collections = stats.iter().filter(|x| x.solved()).count();
random_line_split
lib.rs
#![cfg_attr(test, feature(plugin))] #![warn( clippy::empty_enum, clippy::filter_map, clippy::if_not_else, clippy::invalid_upcast_comparisons, clippy::items_after_statements, clippy::mut_mut, clippy::nonminimal_bool, clippy::option_map_unwrap_or, clippy::option_map_unwrap_or_else, clippy::pub_enum_variant_names, clippy::shadow_same, clippy::single_match_else, clippy::string_add_assign, clippy::unicode_not_nfc, clippy::unseparated_literal_suffix, clippy::used_underscore_binding, clippy::wrong_pub_self_convention )] #[macro_use] extern crate log; #[macro_use] extern crate failure; #[macro_use] extern crate serde_derive; #[macro_use] extern crate lazy_static; #[cfg(test)] extern crate quickcheck; #[cfg(test)] #[macro_use] extern crate quickcheck_macros; mod collection; mod command; mod current_level; mod direction; mod event; mod game; mod level; mod macros; mod move_; mod position; pub mod save; mod undo; mod util; use std::fs; use std::path::PathBuf; use ansi_term::Colour::{Blue, Green, White, Yellow}; pub use crate::collection::*; pub use crate::command::*; pub use crate::current_level::*; pub use crate::direction::*; pub use crate::event::*; pub use crate::game::*; pub use crate::level::*; pub use crate::macros::*; pub use crate::move_::*; pub use crate::position::*; use crate::save::CollectionState; pub use crate::util::*; fn file_stem(p: &PathBuf) -> &str { p.file_stem().unwrap().to_str().unwrap() } pub fn convert_savegames() { use std::ffi::OsStr; for entry in fs::read_dir(DATA_DIR.as_path()).unwrap() { let entry = entry.unwrap(); let path = entry.path(); if path.is_file() && path.extension() == Some(OsStr::new("json")) { let collection_name = file_stem(&path); let mut state = save::CollectionState::load(collection_name); state.save(collection_name).unwrap(); } } } struct CollectionStats { pub short_name: String, pub name: String, pub total_levels: usize, pub solved_levels: usize, } impl CollectionStats { fn solved(&self) -> bool { self.total_levels == self.solved_levels } fn started(&self) -> bool { self.solved_levels > 0 } } fn gather_stats() -> Vec<CollectionStats> { // Find all level set files let mut paths: Vec<PathBuf> = fs::read_dir(ASSETS.join("levels")) .unwrap() .map(|x| x.unwrap().path()) .collect(); paths.sort_by(|x, y| ::natord::compare(file_stem(x), file_stem(y))); let mut result = vec![]; for path in paths { if let Some(ext) = path.extension() { use std::ffi::OsStr; if ext == OsStr::new("lvl") || ext == OsStr::new("slc") { let name = path.file_stem().and_then(|x| x.to_str()).unwrap(); let collection = Collection::parse_metadata(name).unwrap(); let state = CollectionState::load(collection.short_name()); result.push(CollectionStats { short_name: name.to_string(), name: collection.name().to_string(), total_levels: collection.number_of_levels(), solved_levels: state.number_of_solved_levels(), }); } } } result } pub fn print_collections_table()
); } else { let solved = if collection.started() { Blue.paint("solved") } else { White.paint("solved") }; println!( " {}{}{:>10} {}", padded_short_name, White.bold().paint(padded_full_name), format!("{}/{}", collection.solved_levels, collection.total_levels), solved ); } } } pub fn print_stats() { let stats = gather_stats(); let num_collections = stats.len(); let num_levels: usize = stats.iter().map(|x| x.total_levels).sum(); let finished_collections = stats.iter().filter(|x| x.solved()).count(); let finished_levels: usize = stats.iter().map(|x| x.solved_levels).sum(); let collections_started = stats.iter().filter(|x| x.started() &&!x.solved()).count(); println!( "{}", Yellow.bold().paint(" Collections Levels") ); println!("------------------------------------"); println!("Total {:>11} {:>11}", num_collections, num_levels); println!( "Finished {:>11} {:>11}", finished_collections, finished_levels ); println!("Started {:>11}", collections_started); }
{ let stats = gather_stats(); println!( " {} {}", Yellow.bold().paint("File name"), Yellow.bold().paint("Collection name") ); println!("--------------------------------------------------------------------------------"); for collection in stats { let padded_short_name = format!("{:<24}", collection.short_name); let padded_full_name = format!("{:<36}", collection.name); if collection.solved() { println!( " {}{} {}", Green.paint(padded_short_name), Green.bold().paint(padded_full_name), Green.paint("done")
identifier_body
lib.rs
#![cfg_attr(test, feature(plugin))] #![warn( clippy::empty_enum, clippy::filter_map, clippy::if_not_else, clippy::invalid_upcast_comparisons, clippy::items_after_statements, clippy::mut_mut, clippy::nonminimal_bool, clippy::option_map_unwrap_or, clippy::option_map_unwrap_or_else, clippy::pub_enum_variant_names, clippy::shadow_same, clippy::single_match_else, clippy::string_add_assign, clippy::unicode_not_nfc, clippy::unseparated_literal_suffix, clippy::used_underscore_binding, clippy::wrong_pub_self_convention )] #[macro_use] extern crate log; #[macro_use] extern crate failure; #[macro_use] extern crate serde_derive; #[macro_use] extern crate lazy_static; #[cfg(test)] extern crate quickcheck; #[cfg(test)] #[macro_use] extern crate quickcheck_macros; mod collection; mod command; mod current_level; mod direction; mod event; mod game; mod level; mod macros; mod move_; mod position; pub mod save; mod undo; mod util; use std::fs; use std::path::PathBuf; use ansi_term::Colour::{Blue, Green, White, Yellow}; pub use crate::collection::*; pub use crate::command::*; pub use crate::current_level::*; pub use crate::direction::*; pub use crate::event::*; pub use crate::game::*; pub use crate::level::*; pub use crate::macros::*; pub use crate::move_::*; pub use crate::position::*; use crate::save::CollectionState; pub use crate::util::*; fn file_stem(p: &PathBuf) -> &str { p.file_stem().unwrap().to_str().unwrap() } pub fn convert_savegames() { use std::ffi::OsStr; for entry in fs::read_dir(DATA_DIR.as_path()).unwrap() { let entry = entry.unwrap(); let path = entry.path(); if path.is_file() && path.extension() == Some(OsStr::new("json")) { let collection_name = file_stem(&path); let mut state = save::CollectionState::load(collection_name); state.save(collection_name).unwrap(); } } } struct CollectionStats { pub short_name: String, pub name: String, pub total_levels: usize, pub solved_levels: usize, } impl CollectionStats { fn solved(&self) -> bool { self.total_levels == self.solved_levels } fn started(&self) -> bool { self.solved_levels > 0 } } fn gather_stats() -> Vec<CollectionStats> { // Find all level set files let mut paths: Vec<PathBuf> = fs::read_dir(ASSETS.join("levels")) .unwrap() .map(|x| x.unwrap().path()) .collect(); paths.sort_by(|x, y| ::natord::compare(file_stem(x), file_stem(y))); let mut result = vec![]; for path in paths { if let Some(ext) = path.extension() { use std::ffi::OsStr; if ext == OsStr::new("lvl") || ext == OsStr::new("slc") { let name = path.file_stem().and_then(|x| x.to_str()).unwrap(); let collection = Collection::parse_metadata(name).unwrap(); let state = CollectionState::load(collection.short_name()); result.push(CollectionStats { short_name: name.to_string(), name: collection.name().to_string(), total_levels: collection.number_of_levels(), solved_levels: state.number_of_solved_levels(), }); } } } result } pub fn print_collections_table() { let stats = gather_stats(); println!( " {} {}", Yellow.bold().paint("File name"), Yellow.bold().paint("Collection name") ); println!("--------------------------------------------------------------------------------"); for collection in stats { let padded_short_name = format!("{:<24}", collection.short_name); let padded_full_name = format!("{:<36}", collection.name); if collection.solved() { println!( " {}{} {}", Green.paint(padded_short_name), Green.bold().paint(padded_full_name), Green.paint("done") ); } else { let solved = if collection.started()
else { White.paint("solved") }; println!( " {}{}{:>10} {}", padded_short_name, White.bold().paint(padded_full_name), format!("{}/{}", collection.solved_levels, collection.total_levels), solved ); } } } pub fn print_stats() { let stats = gather_stats(); let num_collections = stats.len(); let num_levels: usize = stats.iter().map(|x| x.total_levels).sum(); let finished_collections = stats.iter().filter(|x| x.solved()).count(); let finished_levels: usize = stats.iter().map(|x| x.solved_levels).sum(); let collections_started = stats.iter().filter(|x| x.started() &&!x.solved()).count(); println!( "{}", Yellow.bold().paint(" Collections Levels") ); println!("------------------------------------"); println!("Total {:>11} {:>11}", num_collections, num_levels); println!( "Finished {:>11} {:>11}", finished_collections, finished_levels ); println!("Started {:>11}", collections_started); }
{ Blue.paint("solved") }
conditional_block
lib.rs
#![cfg_attr(test, feature(plugin))] #![warn( clippy::empty_enum, clippy::filter_map, clippy::if_not_else, clippy::invalid_upcast_comparisons, clippy::items_after_statements, clippy::mut_mut, clippy::nonminimal_bool, clippy::option_map_unwrap_or, clippy::option_map_unwrap_or_else, clippy::pub_enum_variant_names, clippy::shadow_same, clippy::single_match_else, clippy::string_add_assign, clippy::unicode_not_nfc, clippy::unseparated_literal_suffix, clippy::used_underscore_binding, clippy::wrong_pub_self_convention )] #[macro_use] extern crate log; #[macro_use] extern crate failure; #[macro_use] extern crate serde_derive; #[macro_use] extern crate lazy_static; #[cfg(test)] extern crate quickcheck; #[cfg(test)] #[macro_use] extern crate quickcheck_macros; mod collection; mod command; mod current_level; mod direction; mod event; mod game; mod level; mod macros; mod move_; mod position; pub mod save; mod undo; mod util; use std::fs; use std::path::PathBuf; use ansi_term::Colour::{Blue, Green, White, Yellow}; pub use crate::collection::*; pub use crate::command::*; pub use crate::current_level::*; pub use crate::direction::*; pub use crate::event::*; pub use crate::game::*; pub use crate::level::*; pub use crate::macros::*; pub use crate::move_::*; pub use crate::position::*; use crate::save::CollectionState; pub use crate::util::*; fn file_stem(p: &PathBuf) -> &str { p.file_stem().unwrap().to_str().unwrap() } pub fn convert_savegames() { use std::ffi::OsStr; for entry in fs::read_dir(DATA_DIR.as_path()).unwrap() { let entry = entry.unwrap(); let path = entry.path(); if path.is_file() && path.extension() == Some(OsStr::new("json")) { let collection_name = file_stem(&path); let mut state = save::CollectionState::load(collection_name); state.save(collection_name).unwrap(); } } } struct CollectionStats { pub short_name: String, pub name: String, pub total_levels: usize, pub solved_levels: usize, } impl CollectionStats { fn solved(&self) -> bool { self.total_levels == self.solved_levels } fn started(&self) -> bool { self.solved_levels > 0 } } fn gather_stats() -> Vec<CollectionStats> { // Find all level set files let mut paths: Vec<PathBuf> = fs::read_dir(ASSETS.join("levels")) .unwrap() .map(|x| x.unwrap().path()) .collect(); paths.sort_by(|x, y| ::natord::compare(file_stem(x), file_stem(y))); let mut result = vec![]; for path in paths { if let Some(ext) = path.extension() { use std::ffi::OsStr; if ext == OsStr::new("lvl") || ext == OsStr::new("slc") { let name = path.file_stem().and_then(|x| x.to_str()).unwrap(); let collection = Collection::parse_metadata(name).unwrap(); let state = CollectionState::load(collection.short_name()); result.push(CollectionStats { short_name: name.to_string(), name: collection.name().to_string(), total_levels: collection.number_of_levels(), solved_levels: state.number_of_solved_levels(), }); } } } result } pub fn print_collections_table() { let stats = gather_stats(); println!( " {} {}", Yellow.bold().paint("File name"), Yellow.bold().paint("Collection name") ); println!("--------------------------------------------------------------------------------"); for collection in stats { let padded_short_name = format!("{:<24}", collection.short_name); let padded_full_name = format!("{:<36}", collection.name); if collection.solved() { println!( " {}{} {}", Green.paint(padded_short_name), Green.bold().paint(padded_full_name), Green.paint("done") ); } else { let solved = if collection.started() { Blue.paint("solved") } else { White.paint("solved") }; println!( " {}{}{:>10} {}", padded_short_name, White.bold().paint(padded_full_name), format!("{}/{}", collection.solved_levels, collection.total_levels), solved ); } } } pub fn
() { let stats = gather_stats(); let num_collections = stats.len(); let num_levels: usize = stats.iter().map(|x| x.total_levels).sum(); let finished_collections = stats.iter().filter(|x| x.solved()).count(); let finished_levels: usize = stats.iter().map(|x| x.solved_levels).sum(); let collections_started = stats.iter().filter(|x| x.started() &&!x.solved()).count(); println!( "{}", Yellow.bold().paint(" Collections Levels") ); println!("------------------------------------"); println!("Total {:>11} {:>11}", num_collections, num_levels); println!( "Finished {:>11} {:>11}", finished_collections, finished_levels ); println!("Started {:>11}", collections_started); }
print_stats
identifier_name
HowMuch.rs
fn how_much(mut m: i32, mut n: i32) -> Vec<(String, String, String)> { if m > n { std::mem::swap(&mut m, &mut n); } let mut result: Vec<(String, String, String)> = Vec::new(); let mut c: f32; let mut b: f32; for i in m..n+1 { c = (i as f32-1f32)/9f32; b = (i as f32-2f32)/7f32; if c < 0f32 || b < 0f32
if c.fract() == 0f32 && b.fract() == 0f32 { let r_tuple = (format!("M: {}", i), format!("B: {}", b as i32), format!("C: {}", c as i32)); result.push(r_tuple); } } return result; } fn testing(m: i32, n: i32, exp: Vec<(&str, &str, &str)>) -> () { let ans: String = format!("{:?}", how_much(m, n)); let sol: String = format!("{:?}", exp); assert_eq!(ans, sol) } fn tests() { testing(1, 100, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11")]); testing(1000, 1100, vec![("M: 1045", "B: 149", "C: 116")]); testing(10000, 9950, vec![("M: 9991", "B: 1427", "C: 1110")]); testing(0, 200, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11"), ("M: 163", "B: 23", "C: 18")]); testing(2950, 2950, vec![]); } fn main() { tests(); }
{ continue; }
conditional_block
HowMuch.rs
fn how_much(mut m: i32, mut n: i32) -> Vec<(String, String, String)> { if m > n { std::mem::swap(&mut m, &mut n); } let mut result: Vec<(String, String, String)> = Vec::new(); let mut c: f32; let mut b: f32; for i in m..n+1 { c = (i as f32-1f32)/9f32; b = (i as f32-2f32)/7f32; if c < 0f32 || b < 0f32 { continue; } if c.fract() == 0f32 && b.fract() == 0f32 { let r_tuple = (format!("M: {}", i), format!("B: {}", b as i32), format!("C: {}", c as i32)); result.push(r_tuple); } } return result; } fn testing(m: i32, n: i32, exp: Vec<(&str, &str, &str)>) -> ()
fn tests() { testing(1, 100, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11")]); testing(1000, 1100, vec![("M: 1045", "B: 149", "C: 116")]); testing(10000, 9950, vec![("M: 9991", "B: 1427", "C: 1110")]); testing(0, 200, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11"), ("M: 163", "B: 23", "C: 18")]); testing(2950, 2950, vec![]); } fn main() { tests(); }
{ let ans: String = format!("{:?}", how_much(m, n)); let sol: String = format!("{:?}", exp); assert_eq!(ans, sol) }
identifier_body
HowMuch.rs
fn
(mut m: i32, mut n: i32) -> Vec<(String, String, String)> { if m > n { std::mem::swap(&mut m, &mut n); } let mut result: Vec<(String, String, String)> = Vec::new(); let mut c: f32; let mut b: f32; for i in m..n+1 { c = (i as f32-1f32)/9f32; b = (i as f32-2f32)/7f32; if c < 0f32 || b < 0f32 { continue; } if c.fract() == 0f32 && b.fract() == 0f32 { let r_tuple = (format!("M: {}", i), format!("B: {}", b as i32), format!("C: {}", c as i32)); result.push(r_tuple); } } return result; } fn testing(m: i32, n: i32, exp: Vec<(&str, &str, &str)>) -> () { let ans: String = format!("{:?}", how_much(m, n)); let sol: String = format!("{:?}", exp); assert_eq!(ans, sol) } fn tests() { testing(1, 100, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11")]); testing(1000, 1100, vec![("M: 1045", "B: 149", "C: 116")]); testing(10000, 9950, vec![("M: 9991", "B: 1427", "C: 1110")]); testing(0, 200, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11"), ("M: 163", "B: 23", "C: 18")]); testing(2950, 2950, vec![]); } fn main() { tests(); }
how_much
identifier_name
HowMuch.rs
fn how_much(mut m: i32, mut n: i32) -> Vec<(String, String, String)> { if m > n { std::mem::swap(&mut m, &mut n); } let mut result: Vec<(String, String, String)> = Vec::new(); let mut c: f32; let mut b: f32; for i in m..n+1 { c = (i as f32-1f32)/9f32;
if c.fract() == 0f32 && b.fract() == 0f32 { let r_tuple = (format!("M: {}", i), format!("B: {}", b as i32), format!("C: {}", c as i32)); result.push(r_tuple); } } return result; } fn testing(m: i32, n: i32, exp: Vec<(&str, &str, &str)>) -> () { let ans: String = format!("{:?}", how_much(m, n)); let sol: String = format!("{:?}", exp); assert_eq!(ans, sol) } fn tests() { testing(1, 100, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11")]); testing(1000, 1100, vec![("M: 1045", "B: 149", "C: 116")]); testing(10000, 9950, vec![("M: 9991", "B: 1427", "C: 1110")]); testing(0, 200, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11"), ("M: 163", "B: 23", "C: 18")]); testing(2950, 2950, vec![]); } fn main() { tests(); }
b = (i as f32-2f32)/7f32; if c < 0f32 || b < 0f32 { continue; }
random_line_split
trivial-bounds-lint.rs
#![feature(trivial_bounds)] #![allow(unused)] #![deny(trivial_bounds)] struct A where i32: Copy; //~ ERROR trait X<T: Copy> {} trait Y<T>: Copy {} trait Z { type S: Copy; } // Check only the bound the user writes trigger the lint fn trivial_elaboration<T>() where T: X<i32> + Z<S = i32>, i32: Y<T> {} // OK fn global_param() where i32: X<()> {} //~ ERROR // Should only error on the trait bound, not the implicit // projection bound <i32 as Z>::S == i32. fn global_projection() where i32: Z<S = i32> {} //~ ERROR impl A { fn new() -> A { A } } // Lifetime bounds should be linted as well fn global_lifetimes() where i32:'static, &'static str:'static {} //~^ ERROR //~| ERROR fn local_lifetimes<'a>() where i32: 'a, &'a str: 'a
// OK fn global_outlives() where'static:'static {} //~ ERROR // Check that each bound is checked individually fn mixed_bounds<T: Copy>() where i32: X<T> + Copy {} //~ ERROR fn main() {}
{}
identifier_body
trivial-bounds-lint.rs
#![feature(trivial_bounds)] #![allow(unused)] #![deny(trivial_bounds)] struct A where i32: Copy; //~ ERROR trait X<T: Copy> {} trait Y<T>: Copy {} trait Z { type S: Copy;
fn global_param() where i32: X<()> {} //~ ERROR // Should only error on the trait bound, not the implicit // projection bound <i32 as Z>::S == i32. fn global_projection() where i32: Z<S = i32> {} //~ ERROR impl A { fn new() -> A { A } } // Lifetime bounds should be linted as well fn global_lifetimes() where i32:'static, &'static str:'static {} //~^ ERROR //~| ERROR fn local_lifetimes<'a>() where i32: 'a, &'a str: 'a {} // OK fn global_outlives() where'static:'static {} //~ ERROR // Check that each bound is checked individually fn mixed_bounds<T: Copy>() where i32: X<T> + Copy {} //~ ERROR fn main() {}
} // Check only the bound the user writes trigger the lint fn trivial_elaboration<T>() where T: X<i32> + Z<S = i32>, i32: Y<T> {} // OK
random_line_split
trivial-bounds-lint.rs
#![feature(trivial_bounds)] #![allow(unused)] #![deny(trivial_bounds)] struct
where i32: Copy; //~ ERROR trait X<T: Copy> {} trait Y<T>: Copy {} trait Z { type S: Copy; } // Check only the bound the user writes trigger the lint fn trivial_elaboration<T>() where T: X<i32> + Z<S = i32>, i32: Y<T> {} // OK fn global_param() where i32: X<()> {} //~ ERROR // Should only error on the trait bound, not the implicit // projection bound <i32 as Z>::S == i32. fn global_projection() where i32: Z<S = i32> {} //~ ERROR impl A { fn new() -> A { A } } // Lifetime bounds should be linted as well fn global_lifetimes() where i32:'static, &'static str:'static {} //~^ ERROR //~| ERROR fn local_lifetimes<'a>() where i32: 'a, &'a str: 'a {} // OK fn global_outlives() where'static:'static {} //~ ERROR // Check that each bound is checked individually fn mixed_bounds<T: Copy>() where i32: X<T> + Copy {} //~ ERROR fn main() {}
A
identifier_name
debug.rs
/* This Source Code Form is subject to the terms of the Mozilla Public
use std::cast::transmute; use std::mem::size_of; fn hexdump_slice(buf: &[u8]) { let stderr = io::stderr(); stderr.write_str(" "); for (i, &v) in buf.iter().enumerate() { stderr.write_str(fmt!("%02X ", v as uint)); match i % 16 { 15 => stderr.write_str("\n "), 7 => stderr.write_str(" "), _ => () } stderr.flush(); } stderr.write_char('\n'); } pub fn hexdump<T>(obj: &T) { unsafe { let buf: *u8 = transmute(obj); debug!("dumping at %p", buf); buf_as_slice(buf, size_of::<T>(), hexdump_slice); } }
* 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 std::io; use std::vec::raw::buf_as_slice;
random_line_split
debug.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 std::io; use std::vec::raw::buf_as_slice; use std::cast::transmute; use std::mem::size_of; fn hexdump_slice(buf: &[u8])
pub fn hexdump<T>(obj: &T) { unsafe { let buf: *u8 = transmute(obj); debug!("dumping at %p", buf); buf_as_slice(buf, size_of::<T>(), hexdump_slice); } }
{ let stderr = io::stderr(); stderr.write_str(" "); for (i, &v) in buf.iter().enumerate() { stderr.write_str(fmt!("%02X ", v as uint)); match i % 16 { 15 => stderr.write_str("\n "), 7 => stderr.write_str(" "), _ => () } stderr.flush(); } stderr.write_char('\n'); }
identifier_body
debug.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 std::io; use std::vec::raw::buf_as_slice; use std::cast::transmute; use std::mem::size_of; fn
(buf: &[u8]) { let stderr = io::stderr(); stderr.write_str(" "); for (i, &v) in buf.iter().enumerate() { stderr.write_str(fmt!("%02X ", v as uint)); match i % 16 { 15 => stderr.write_str("\n "), 7 => stderr.write_str(" "), _ => () } stderr.flush(); } stderr.write_char('\n'); } pub fn hexdump<T>(obj: &T) { unsafe { let buf: *u8 = transmute(obj); debug!("dumping at %p", buf); buf_as_slice(buf, size_of::<T>(), hexdump_slice); } }
hexdump_slice
identifier_name
numbers.rs
//! Functions operating on numbers. use rand::{Rng, SeedableRng, StdRng}; use std::sync::Mutex; use remacs_macros::lisp_fn; use remacs_sys::{EmacsInt, INTMASK}; use lisp::LispObject; use lisp::defsubr; lazy_static! { static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap()); } /// Return t if OBJECT is a floating point number. #[lisp_fn] pub fn floatp(object: LispObject) -> bool { object.is_float() } /// Return t if OBJECT is an integer. #[lisp_fn] pub fn integerp(object: LispObject) -> bool { object.is_integer() }
pub fn integer_or_marker_p(object: LispObject) -> bool { object.is_marker() || object.is_integer() } /// Return t if OBJECT is a non-negative integer. #[lisp_fn] pub fn natnump(object: LispObject) -> bool { object.is_natnum() } /// Return t if OBJECT is a number (floating point or integer). #[lisp_fn] pub fn numberp(object: LispObject) -> bool { object.is_number() } /// Return t if OBJECT is a number or a marker (editor pointer). #[lisp_fn] pub fn number_or_marker_p(object: LispObject) -> bool { object.is_number() || object.is_marker() } /// Return a pseudo-random number. /// All integers representable in Lisp, i.e. between `most-negative-fixnum' /// and `most-positive-fixnum', inclusive, are equally likely. /// /// With positive integer LIMIT, return random number in interval [0,LIMIT). /// With argument t, set the random number seed from the system's entropy /// pool if available, otherwise from less-random volatile data such as the time. /// With a string argument, set the seed based on the string's contents. /// Other values of LIMIT are ignored. /// /// See Info node `(elisp)Random Numbers' for more details. // NOTE(db48x): does not return an EmacsInt, because it relies on the // truncating behavior of from_fixnum_truncated. #[lisp_fn(min = "0")] pub fn random(limit: LispObject) -> LispObject { let mut rng = RNG.lock().unwrap(); if limit.is_t() { *rng = StdRng::new().unwrap(); } else if let Some(s) = limit.as_string() { let values: Vec<usize> = s.as_slice().iter().map(|&x| x as usize).collect(); rng.reseed(&values); } if let Some(limit) = limit.as_fixnum() { // Return the remainder, except reject the rare case where // get_random returns a number so close to INTMASK that the // remainder isn't random. loop { let val: EmacsInt = rng.gen(); let remainder = val.abs() % limit; if val - remainder <= INTMASK - limit + 1 { return LispObject::from_fixnum(remainder); } } } else { LispObject::from_fixnum_truncated(rng.gen()) } } include!(concat!(env!("OUT_DIR"), "/numbers_exports.rs"));
/// Return t if OBJECT is an integer or a marker (editor pointer). #[lisp_fn]
random_line_split
numbers.rs
//! Functions operating on numbers. use rand::{Rng, SeedableRng, StdRng}; use std::sync::Mutex; use remacs_macros::lisp_fn; use remacs_sys::{EmacsInt, INTMASK}; use lisp::LispObject; use lisp::defsubr; lazy_static! { static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap()); } /// Return t if OBJECT is a floating point number. #[lisp_fn] pub fn floatp(object: LispObject) -> bool { object.is_float() } /// Return t if OBJECT is an integer. #[lisp_fn] pub fn integerp(object: LispObject) -> bool { object.is_integer() } /// Return t if OBJECT is an integer or a marker (editor pointer). #[lisp_fn] pub fn integer_or_marker_p(object: LispObject) -> bool
/// Return t if OBJECT is a non-negative integer. #[lisp_fn] pub fn natnump(object: LispObject) -> bool { object.is_natnum() } /// Return t if OBJECT is a number (floating point or integer). #[lisp_fn] pub fn numberp(object: LispObject) -> bool { object.is_number() } /// Return t if OBJECT is a number or a marker (editor pointer). #[lisp_fn] pub fn number_or_marker_p(object: LispObject) -> bool { object.is_number() || object.is_marker() } /// Return a pseudo-random number. /// All integers representable in Lisp, i.e. between `most-negative-fixnum' /// and `most-positive-fixnum', inclusive, are equally likely. /// /// With positive integer LIMIT, return random number in interval [0,LIMIT). /// With argument t, set the random number seed from the system's entropy /// pool if available, otherwise from less-random volatile data such as the time. /// With a string argument, set the seed based on the string's contents. /// Other values of LIMIT are ignored. /// /// See Info node `(elisp)Random Numbers' for more details. // NOTE(db48x): does not return an EmacsInt, because it relies on the // truncating behavior of from_fixnum_truncated. #[lisp_fn(min = "0")] pub fn random(limit: LispObject) -> LispObject { let mut rng = RNG.lock().unwrap(); if limit.is_t() { *rng = StdRng::new().unwrap(); } else if let Some(s) = limit.as_string() { let values: Vec<usize> = s.as_slice().iter().map(|&x| x as usize).collect(); rng.reseed(&values); } if let Some(limit) = limit.as_fixnum() { // Return the remainder, except reject the rare case where // get_random returns a number so close to INTMASK that the // remainder isn't random. loop { let val: EmacsInt = rng.gen(); let remainder = val.abs() % limit; if val - remainder <= INTMASK - limit + 1 { return LispObject::from_fixnum(remainder); } } } else { LispObject::from_fixnum_truncated(rng.gen()) } } include!(concat!(env!("OUT_DIR"), "/numbers_exports.rs"));
{ object.is_marker() || object.is_integer() }
identifier_body
numbers.rs
//! Functions operating on numbers. use rand::{Rng, SeedableRng, StdRng}; use std::sync::Mutex; use remacs_macros::lisp_fn; use remacs_sys::{EmacsInt, INTMASK}; use lisp::LispObject; use lisp::defsubr; lazy_static! { static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap()); } /// Return t if OBJECT is a floating point number. #[lisp_fn] pub fn floatp(object: LispObject) -> bool { object.is_float() } /// Return t if OBJECT is an integer. #[lisp_fn] pub fn integerp(object: LispObject) -> bool { object.is_integer() } /// Return t if OBJECT is an integer or a marker (editor pointer). #[lisp_fn] pub fn integer_or_marker_p(object: LispObject) -> bool { object.is_marker() || object.is_integer() } /// Return t if OBJECT is a non-negative integer. #[lisp_fn] pub fn natnump(object: LispObject) -> bool { object.is_natnum() } /// Return t if OBJECT is a number (floating point or integer). #[lisp_fn] pub fn numberp(object: LispObject) -> bool { object.is_number() } /// Return t if OBJECT is a number or a marker (editor pointer). #[lisp_fn] pub fn number_or_marker_p(object: LispObject) -> bool { object.is_number() || object.is_marker() } /// Return a pseudo-random number. /// All integers representable in Lisp, i.e. between `most-negative-fixnum' /// and `most-positive-fixnum', inclusive, are equally likely. /// /// With positive integer LIMIT, return random number in interval [0,LIMIT). /// With argument t, set the random number seed from the system's entropy /// pool if available, otherwise from less-random volatile data such as the time. /// With a string argument, set the seed based on the string's contents. /// Other values of LIMIT are ignored. /// /// See Info node `(elisp)Random Numbers' for more details. // NOTE(db48x): does not return an EmacsInt, because it relies on the // truncating behavior of from_fixnum_truncated. #[lisp_fn(min = "0")] pub fn random(limit: LispObject) -> LispObject { let mut rng = RNG.lock().unwrap(); if limit.is_t() { *rng = StdRng::new().unwrap(); } else if let Some(s) = limit.as_string()
if let Some(limit) = limit.as_fixnum() { // Return the remainder, except reject the rare case where // get_random returns a number so close to INTMASK that the // remainder isn't random. loop { let val: EmacsInt = rng.gen(); let remainder = val.abs() % limit; if val - remainder <= INTMASK - limit + 1 { return LispObject::from_fixnum(remainder); } } } else { LispObject::from_fixnum_truncated(rng.gen()) } } include!(concat!(env!("OUT_DIR"), "/numbers_exports.rs"));
{ let values: Vec<usize> = s.as_slice().iter().map(|&x| x as usize).collect(); rng.reseed(&values); }
conditional_block
numbers.rs
//! Functions operating on numbers. use rand::{Rng, SeedableRng, StdRng}; use std::sync::Mutex; use remacs_macros::lisp_fn; use remacs_sys::{EmacsInt, INTMASK}; use lisp::LispObject; use lisp::defsubr; lazy_static! { static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap()); } /// Return t if OBJECT is a floating point number. #[lisp_fn] pub fn floatp(object: LispObject) -> bool { object.is_float() } /// Return t if OBJECT is an integer. #[lisp_fn] pub fn integerp(object: LispObject) -> bool { object.is_integer() } /// Return t if OBJECT is an integer or a marker (editor pointer). #[lisp_fn] pub fn integer_or_marker_p(object: LispObject) -> bool { object.is_marker() || object.is_integer() } /// Return t if OBJECT is a non-negative integer. #[lisp_fn] pub fn natnump(object: LispObject) -> bool { object.is_natnum() } /// Return t if OBJECT is a number (floating point or integer). #[lisp_fn] pub fn numberp(object: LispObject) -> bool { object.is_number() } /// Return t if OBJECT is a number or a marker (editor pointer). #[lisp_fn] pub fn
(object: LispObject) -> bool { object.is_number() || object.is_marker() } /// Return a pseudo-random number. /// All integers representable in Lisp, i.e. between `most-negative-fixnum' /// and `most-positive-fixnum', inclusive, are equally likely. /// /// With positive integer LIMIT, return random number in interval [0,LIMIT). /// With argument t, set the random number seed from the system's entropy /// pool if available, otherwise from less-random volatile data such as the time. /// With a string argument, set the seed based on the string's contents. /// Other values of LIMIT are ignored. /// /// See Info node `(elisp)Random Numbers' for more details. // NOTE(db48x): does not return an EmacsInt, because it relies on the // truncating behavior of from_fixnum_truncated. #[lisp_fn(min = "0")] pub fn random(limit: LispObject) -> LispObject { let mut rng = RNG.lock().unwrap(); if limit.is_t() { *rng = StdRng::new().unwrap(); } else if let Some(s) = limit.as_string() { let values: Vec<usize> = s.as_slice().iter().map(|&x| x as usize).collect(); rng.reseed(&values); } if let Some(limit) = limit.as_fixnum() { // Return the remainder, except reject the rare case where // get_random returns a number so close to INTMASK that the // remainder isn't random. loop { let val: EmacsInt = rng.gen(); let remainder = val.abs() % limit; if val - remainder <= INTMASK - limit + 1 { return LispObject::from_fixnum(remainder); } } } else { LispObject::from_fixnum_truncated(rng.gen()) } } include!(concat!(env!("OUT_DIR"), "/numbers_exports.rs"));
number_or_marker_p
identifier_name
inherited_table.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, gecko_name="TableBorder") %> ${helpers.single_keyword("border-collapse", "separate collapse", gecko_constant_prefix="NS_STYLE_BORDER", animatable=False, spec="https://drafts.csswg.org/css-tables/#propdef-border-collapse")} ${helpers.single_keyword("empty-cells", "show hide", gecko_constant_prefix="NS_STYLE_TABLE_EMPTY_CELLS", animatable=False, spec="https://drafts.csswg.org/css-tables/#propdef-empty-cells")} ${helpers.single_keyword("caption-side", "top bottom", extra_gecko_values="right left top-outside bottom-outside", needs_conversion="True", animatable=False, spec="https://drafts.csswg.org/css-tables/#propdef-caption-side")} <%helpers:longhand name="border-spacing" animatable="False" boxed="True" spec="https://drafts.csswg.org/css-tables/#propdef-border-spacing"> use app_units::Au; use std::fmt; use style_traits::ToCss; use values::HasViewportPercentage; pub mod computed_value { use app_units::Au; use properties::animated_properties::Interpolate; #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct T { pub horizontal: Au, pub vertical: Au, } /// https://drafts.csswg.org/css-transitions/#animtype-simple-list impl Interpolate for T { #[inline] fn interpolate(&self, other: &Self, time: f64) -> Result<Self, ()> { Ok(T { horizontal: try!(self.horizontal.interpolate(&other.horizontal, time)), vertical: try!(self.vertical.interpolate(&other.vertical, time)), }) } } } impl HasViewportPercentage for SpecifiedValue { fn has_viewport_percentage(&self) -> bool { return self.horizontal.has_viewport_percentage() || self.vertical.has_viewport_percentage() } } #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct SpecifiedValue { pub horizontal: specified::Length, pub vertical: specified::Length, } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { horizontal: Au(0), vertical: Au(0), } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { computed_value::T { horizontal: self.horizontal.to_computed_value(context), vertical: self.vertical.to_computed_value(context), } } #[inline] fn from_computed_value(computed: &computed_value::T) -> Self { SpecifiedValue { horizontal: ToComputedValue::from_computed_value(&computed.horizontal), vertical: ToComputedValue::from_computed_value(&computed.vertical), } } } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { let mut first = None; let mut second = None; match specified::Length::parse_non_negative(input) { Err(()) => (), Ok(length) => { first = Some(length); if let Ok(len) = input.try(|input| specified::Length::parse_non_negative(input))
} } match (first, second) { (None, None) => Err(()), (Some(length), None) => { Ok(SpecifiedValue { horizontal: length.clone(), vertical: length, }) } (Some(horizontal), Some(vertical)) => { Ok(SpecifiedValue { horizontal: horizontal, vertical: vertical, }) } (None, Some(_)) => panic!("shouldn't happen"), } } </%helpers:longhand>
{ second = Some(len); }
conditional_block
inherited_table.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, gecko_name="TableBorder") %> ${helpers.single_keyword("border-collapse", "separate collapse", gecko_constant_prefix="NS_STYLE_BORDER", animatable=False, spec="https://drafts.csswg.org/css-tables/#propdef-border-collapse")} ${helpers.single_keyword("empty-cells", "show hide", gecko_constant_prefix="NS_STYLE_TABLE_EMPTY_CELLS", animatable=False, spec="https://drafts.csswg.org/css-tables/#propdef-empty-cells")} ${helpers.single_keyword("caption-side", "top bottom", extra_gecko_values="right left top-outside bottom-outside", needs_conversion="True", animatable=False, spec="https://drafts.csswg.org/css-tables/#propdef-caption-side")} <%helpers:longhand name="border-spacing" animatable="False" boxed="True" spec="https://drafts.csswg.org/css-tables/#propdef-border-spacing"> use app_units::Au; use std::fmt; use style_traits::ToCss; use values::HasViewportPercentage; pub mod computed_value { use app_units::Au; use properties::animated_properties::Interpolate; #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct T { pub horizontal: Au, pub vertical: Au, } /// https://drafts.csswg.org/css-transitions/#animtype-simple-list impl Interpolate for T { #[inline] fn interpolate(&self, other: &Self, time: f64) -> Result<Self, ()> { Ok(T { horizontal: try!(self.horizontal.interpolate(&other.horizontal, time)), vertical: try!(self.vertical.interpolate(&other.vertical, time)), }) } } } impl HasViewportPercentage for SpecifiedValue { fn has_viewport_percentage(&self) -> bool { return self.horizontal.has_viewport_percentage() || self.vertical.has_viewport_percentage() } } #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct SpecifiedValue { pub horizontal: specified::Length, pub vertical: specified::Length, } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { horizontal: Au(0), vertical: Au(0), } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { computed_value::T { horizontal: self.horizontal.to_computed_value(context), vertical: self.vertical.to_computed_value(context), } }
fn from_computed_value(computed: &computed_value::T) -> Self { SpecifiedValue { horizontal: ToComputedValue::from_computed_value(&computed.horizontal), vertical: ToComputedValue::from_computed_value(&computed.vertical), } } } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { let mut first = None; let mut second = None; match specified::Length::parse_non_negative(input) { Err(()) => (), Ok(length) => { first = Some(length); if let Ok(len) = input.try(|input| specified::Length::parse_non_negative(input)) { second = Some(len); } } } match (first, second) { (None, None) => Err(()), (Some(length), None) => { Ok(SpecifiedValue { horizontal: length.clone(), vertical: length, }) } (Some(horizontal), Some(vertical)) => { Ok(SpecifiedValue { horizontal: horizontal, vertical: vertical, }) } (None, Some(_)) => panic!("shouldn't happen"), } } </%helpers:longhand>
#[inline]
random_line_split
inherited_table.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, gecko_name="TableBorder") %> ${helpers.single_keyword("border-collapse", "separate collapse", gecko_constant_prefix="NS_STYLE_BORDER", animatable=False, spec="https://drafts.csswg.org/css-tables/#propdef-border-collapse")} ${helpers.single_keyword("empty-cells", "show hide", gecko_constant_prefix="NS_STYLE_TABLE_EMPTY_CELLS", animatable=False, spec="https://drafts.csswg.org/css-tables/#propdef-empty-cells")} ${helpers.single_keyword("caption-side", "top bottom", extra_gecko_values="right left top-outside bottom-outside", needs_conversion="True", animatable=False, spec="https://drafts.csswg.org/css-tables/#propdef-caption-side")} <%helpers:longhand name="border-spacing" animatable="False" boxed="True" spec="https://drafts.csswg.org/css-tables/#propdef-border-spacing"> use app_units::Au; use std::fmt; use style_traits::ToCss; use values::HasViewportPercentage; pub mod computed_value { use app_units::Au; use properties::animated_properties::Interpolate; #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct T { pub horizontal: Au, pub vertical: Au, } /// https://drafts.csswg.org/css-transitions/#animtype-simple-list impl Interpolate for T { #[inline] fn interpolate(&self, other: &Self, time: f64) -> Result<Self, ()> { Ok(T { horizontal: try!(self.horizontal.interpolate(&other.horizontal, time)), vertical: try!(self.vertical.interpolate(&other.vertical, time)), }) } } } impl HasViewportPercentage for SpecifiedValue { fn has_viewport_percentage(&self) -> bool { return self.horizontal.has_viewport_percentage() || self.vertical.has_viewport_percentage() } } #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct SpecifiedValue { pub horizontal: specified::Length, pub vertical: specified::Length, } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { horizontal: Au(0), vertical: Au(0), } } impl ToCss for SpecifiedValue { fn
<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { computed_value::T { horizontal: self.horizontal.to_computed_value(context), vertical: self.vertical.to_computed_value(context), } } #[inline] fn from_computed_value(computed: &computed_value::T) -> Self { SpecifiedValue { horizontal: ToComputedValue::from_computed_value(&computed.horizontal), vertical: ToComputedValue::from_computed_value(&computed.vertical), } } } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { let mut first = None; let mut second = None; match specified::Length::parse_non_negative(input) { Err(()) => (), Ok(length) => { first = Some(length); if let Ok(len) = input.try(|input| specified::Length::parse_non_negative(input)) { second = Some(len); } } } match (first, second) { (None, None) => Err(()), (Some(length), None) => { Ok(SpecifiedValue { horizontal: length.clone(), vertical: length, }) } (Some(horizontal), Some(vertical)) => { Ok(SpecifiedValue { horizontal: horizontal, vertical: vertical, }) } (None, Some(_)) => panic!("shouldn't happen"), } } </%helpers:longhand>
to_css
identifier_name
os.rs
// Copyright 2013 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. //! Interfaces to the operating system provided random number //! generators. pub use self::imp::OSRng; #[cfg(unix)] mod imp { use Rng; use reader::ReaderRng; use std::io::{IoResult, File}; /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. #[cfg(unix)] pub struct OSRng { inner: ReaderRng<File> } impl OSRng { /// Create a new `OSRng`. pub fn new() -> IoResult<OSRng> { let reader = try!(File::open(&Path::new("/dev/urandom"))); let reader_rng = ReaderRng::new(reader); Ok(OSRng { inner: reader_rng }) } } impl Rng for OSRng { fn next_u32(&mut self) -> u32 { self.inner.next_u32() } fn next_u64(&mut self) -> u64 { self.inner.next_u64() } fn fill_bytes(&mut self, v: &mut [u8]) { self.inner.fill_bytes(v) } } } #[cfg(windows)] mod imp { extern crate libc; use Rng; use std::cast; use std::io::{IoResult, IoError}; use std::os; use std::rt::stack; use self::libc::{c_ulong, DWORD, BYTE, LPCSTR, BOOL}; type HCRYPTPROV = c_ulong; /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. pub struct OSRng { hcryptprov: HCRYPTPROV } static PROV_RSA_FULL: DWORD = 1; static CRYPT_SILENT: DWORD = 64; static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000; static NTE_BAD_SIGNATURE: DWORD = 0x80090006; extern "system" { fn CryptAcquireContextA(phProv: *mut HCRYPTPROV, pszContainer: LPCSTR, pszProvider: LPCSTR, dwProvType: DWORD, dwFlags: DWORD) -> BOOL; fn CryptGenRandom(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: *mut BYTE) -> BOOL; fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL; } impl OSRng { /// Create a new `OSRng`. pub fn new() -> IoResult<OSRng> { let mut hcp = 0; let mut ret = unsafe { CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT) }; // It turns out that if we can't acquire a context with the // NTE_BAD_SIGNATURE error code, the documentation states: // // The provider DLL signature could not be verified. Either the // DLL or the digital signature has been tampered with. // // Sounds fishy, no? As it turns out, our signature can be bad // because our Thread Information Block (TIB) isn't exactly what it // expects. As to why, I have no idea. The only data we store in the // TIB is the stack limit for each thread, but apparently that's // enough to make the signature valid. // // Furthermore, this error only happens the *first* time we call // CryptAcquireContext, so we don't have to worry about future // calls. // // Anyway, the fix employed here is that if we see this error, we // pray that we're not close to the end of the stack, temporarily // set the stack limit to 0 (what the TIB originally was), acquire a // context, and then reset the stack limit. // // Again, I'm not sure why this is the fix, nor why we're getting // this error. All I can say is that this seems to allow libnative // to progress where it otherwise would be hindered. Who knew? if ret == 0 && os::errno() as DWORD == NTE_BAD_SIGNATURE { unsafe { let limit = stack::get_sp_limit(); stack::record_sp_limit(0); ret = CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT); stack::record_sp_limit(limit); } } if ret == 0 { Err(IoError::last_error()) } else
} } impl Rng for OSRng { fn next_u32(&mut self) -> u32 { let mut v = [0u8,.. 4]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn next_u64(&mut self) -> u64 { let mut v = [0u8,.. 8]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn fill_bytes(&mut self, v: &mut [u8]) { let ret = unsafe { CryptGenRandom(self.hcryptprov, v.len() as DWORD, v.as_mut_ptr()) }; if ret == 0 { fail!("couldn't generate random bytes: {}", os::last_os_error()); } } } impl Drop for OSRng { fn drop(&mut self) { let ret = unsafe { CryptReleaseContext(self.hcryptprov, 0) }; if ret == 0 { fail!("couldn't release context: {}", os::last_os_error()); } } } } #[cfg(test)] mod test { use super::OSRng; use Rng; use std::task; #[test] fn test_os_rng() { let mut r = OSRng::new().unwrap(); r.next_u32(); r.next_u64(); let mut v = [0u8,.. 1000]; r.fill_bytes(v); } #[test] fn test_os_rng_tasks() { let mut txs = vec!(); for _ in range(0, 20) { let (tx, rx) = channel(); txs.push(tx); task::spawn(proc() { // wait until all the tasks are ready to go. rx.recv(); // deschedule to attempt to interleave things as much // as possible (XXX: is this a good test?) let mut r = OSRng::new().unwrap(); task::deschedule(); let mut v = [0u8,.. 1000]; for _ in range(0, 100) { r.next_u32(); task::deschedule(); r.next_u64(); task::deschedule(); r.fill_bytes(v); task::deschedule(); } }) } // start all the tasks for tx in txs.iter() { tx.send(()) } } }
{ Ok(OSRng { hcryptprov: hcp }) }
conditional_block
os.rs
// Copyright 2013 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. //! Interfaces to the operating system provided random number //! generators. pub use self::imp::OSRng; #[cfg(unix)] mod imp { use Rng; use reader::ReaderRng; use std::io::{IoResult, File}; /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. #[cfg(unix)] pub struct OSRng { inner: ReaderRng<File> } impl OSRng { /// Create a new `OSRng`. pub fn new() -> IoResult<OSRng> { let reader = try!(File::open(&Path::new("/dev/urandom"))); let reader_rng = ReaderRng::new(reader); Ok(OSRng { inner: reader_rng }) } } impl Rng for OSRng { fn next_u32(&mut self) -> u32 { self.inner.next_u32() } fn next_u64(&mut self) -> u64 { self.inner.next_u64() } fn fill_bytes(&mut self, v: &mut [u8]) { self.inner.fill_bytes(v) } } } #[cfg(windows)] mod imp { extern crate libc; use Rng; use std::cast; use std::io::{IoResult, IoError}; use std::os; use std::rt::stack; use self::libc::{c_ulong, DWORD, BYTE, LPCSTR, BOOL}; type HCRYPTPROV = c_ulong; /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. pub struct OSRng { hcryptprov: HCRYPTPROV } static PROV_RSA_FULL: DWORD = 1; static CRYPT_SILENT: DWORD = 64; static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000; static NTE_BAD_SIGNATURE: DWORD = 0x80090006; extern "system" { fn CryptAcquireContextA(phProv: *mut HCRYPTPROV, pszContainer: LPCSTR, pszProvider: LPCSTR, dwProvType: DWORD, dwFlags: DWORD) -> BOOL; fn CryptGenRandom(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: *mut BYTE) -> BOOL; fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL; } impl OSRng { /// Create a new `OSRng`. pub fn new() -> IoResult<OSRng> { let mut hcp = 0; let mut ret = unsafe { CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT) }; // It turns out that if we can't acquire a context with the // NTE_BAD_SIGNATURE error code, the documentation states: // // The provider DLL signature could not be verified. Either the // DLL or the digital signature has been tampered with. // // Sounds fishy, no? As it turns out, our signature can be bad // because our Thread Information Block (TIB) isn't exactly what it // expects. As to why, I have no idea. The only data we store in the // TIB is the stack limit for each thread, but apparently that's // enough to make the signature valid. // // Furthermore, this error only happens the *first* time we call // CryptAcquireContext, so we don't have to worry about future // calls. // // Anyway, the fix employed here is that if we see this error, we // pray that we're not close to the end of the stack, temporarily // set the stack limit to 0 (what the TIB originally was), acquire a // context, and then reset the stack limit. // // Again, I'm not sure why this is the fix, nor why we're getting // this error. All I can say is that this seems to allow libnative // to progress where it otherwise would be hindered. Who knew? if ret == 0 && os::errno() as DWORD == NTE_BAD_SIGNATURE { unsafe { let limit = stack::get_sp_limit(); stack::record_sp_limit(0); ret = CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT); stack::record_sp_limit(limit); } } if ret == 0 { Err(IoError::last_error()) } else { Ok(OSRng { hcryptprov: hcp }) } } } impl Rng for OSRng { fn next_u32(&mut self) -> u32 { let mut v = [0u8,.. 4]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn next_u64(&mut self) -> u64 { let mut v = [0u8,.. 8]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn fill_bytes(&mut self, v: &mut [u8]) { let ret = unsafe { CryptGenRandom(self.hcryptprov, v.len() as DWORD, v.as_mut_ptr()) }; if ret == 0 { fail!("couldn't generate random bytes: {}", os::last_os_error()); } } } impl Drop for OSRng { fn drop(&mut self)
} } #[cfg(test)] mod test { use super::OSRng; use Rng; use std::task; #[test] fn test_os_rng() { let mut r = OSRng::new().unwrap(); r.next_u32(); r.next_u64(); let mut v = [0u8,.. 1000]; r.fill_bytes(v); } #[test] fn test_os_rng_tasks() { let mut txs = vec!(); for _ in range(0, 20) { let (tx, rx) = channel(); txs.push(tx); task::spawn(proc() { // wait until all the tasks are ready to go. rx.recv(); // deschedule to attempt to interleave things as much // as possible (XXX: is this a good test?) let mut r = OSRng::new().unwrap(); task::deschedule(); let mut v = [0u8,.. 1000]; for _ in range(0, 100) { r.next_u32(); task::deschedule(); r.next_u64(); task::deschedule(); r.fill_bytes(v); task::deschedule(); } }) } // start all the tasks for tx in txs.iter() { tx.send(()) } } }
{ let ret = unsafe { CryptReleaseContext(self.hcryptprov, 0) }; if ret == 0 { fail!("couldn't release context: {}", os::last_os_error()); } }
identifier_body
os.rs
// Copyright 2013 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. //! Interfaces to the operating system provided random number //! generators. pub use self::imp::OSRng; #[cfg(unix)] mod imp { use Rng; use reader::ReaderRng; use std::io::{IoResult, File}; /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. #[cfg(unix)] pub struct OSRng { inner: ReaderRng<File> } impl OSRng { /// Create a new `OSRng`. pub fn new() -> IoResult<OSRng> { let reader = try!(File::open(&Path::new("/dev/urandom"))); let reader_rng = ReaderRng::new(reader); Ok(OSRng { inner: reader_rng }) } } impl Rng for OSRng { fn next_u32(&mut self) -> u32 { self.inner.next_u32() } fn next_u64(&mut self) -> u64 { self.inner.next_u64() } fn fill_bytes(&mut self, v: &mut [u8]) { self.inner.fill_bytes(v) } } } #[cfg(windows)] mod imp { extern crate libc; use Rng; use std::cast; use std::io::{IoResult, IoError}; use std::os; use std::rt::stack; use self::libc::{c_ulong, DWORD, BYTE, LPCSTR, BOOL}; type HCRYPTPROV = c_ulong; /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. pub struct OSRng { hcryptprov: HCRYPTPROV } static PROV_RSA_FULL: DWORD = 1; static CRYPT_SILENT: DWORD = 64; static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000; static NTE_BAD_SIGNATURE: DWORD = 0x80090006; extern "system" { fn CryptAcquireContextA(phProv: *mut HCRYPTPROV, pszContainer: LPCSTR, pszProvider: LPCSTR, dwProvType: DWORD, dwFlags: DWORD) -> BOOL; fn CryptGenRandom(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: *mut BYTE) -> BOOL; fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL; } impl OSRng { /// Create a new `OSRng`. pub fn new() -> IoResult<OSRng> { let mut hcp = 0; let mut ret = unsafe { CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT) }; // It turns out that if we can't acquire a context with the // NTE_BAD_SIGNATURE error code, the documentation states: // // The provider DLL signature could not be verified. Either the // DLL or the digital signature has been tampered with. // // Sounds fishy, no? As it turns out, our signature can be bad // because our Thread Information Block (TIB) isn't exactly what it // expects. As to why, I have no idea. The only data we store in the // TIB is the stack limit for each thread, but apparently that's // enough to make the signature valid. // // Furthermore, this error only happens the *first* time we call // CryptAcquireContext, so we don't have to worry about future // calls. // // Anyway, the fix employed here is that if we see this error, we // pray that we're not close to the end of the stack, temporarily // set the stack limit to 0 (what the TIB originally was), acquire a // context, and then reset the stack limit. // // Again, I'm not sure why this is the fix, nor why we're getting // this error. All I can say is that this seems to allow libnative // to progress where it otherwise would be hindered. Who knew? if ret == 0 && os::errno() as DWORD == NTE_BAD_SIGNATURE { unsafe { let limit = stack::get_sp_limit(); stack::record_sp_limit(0); ret = CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT); stack::record_sp_limit(limit); } } if ret == 0 { Err(IoError::last_error()) } else { Ok(OSRng { hcryptprov: hcp }) } } } impl Rng for OSRng { fn next_u32(&mut self) -> u32 { let mut v = [0u8,.. 4]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn next_u64(&mut self) -> u64 { let mut v = [0u8,.. 8]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn fill_bytes(&mut self, v: &mut [u8]) { let ret = unsafe { CryptGenRandom(self.hcryptprov, v.len() as DWORD, v.as_mut_ptr()) }; if ret == 0 { fail!("couldn't generate random bytes: {}", os::last_os_error()); } } } impl Drop for OSRng { fn drop(&mut self) { let ret = unsafe { CryptReleaseContext(self.hcryptprov, 0) }; if ret == 0 { fail!("couldn't release context: {}", os::last_os_error()); } } } } #[cfg(test)] mod test { use super::OSRng; use Rng; use std::task; #[test] fn test_os_rng() { let mut r = OSRng::new().unwrap(); r.next_u32(); r.next_u64(); let mut v = [0u8,.. 1000]; r.fill_bytes(v); } #[test] fn test_os_rng_tasks() {
txs.push(tx); task::spawn(proc() { // wait until all the tasks are ready to go. rx.recv(); // deschedule to attempt to interleave things as much // as possible (XXX: is this a good test?) let mut r = OSRng::new().unwrap(); task::deschedule(); let mut v = [0u8,.. 1000]; for _ in range(0, 100) { r.next_u32(); task::deschedule(); r.next_u64(); task::deschedule(); r.fill_bytes(v); task::deschedule(); } }) } // start all the tasks for tx in txs.iter() { tx.send(()) } } }
let mut txs = vec!(); for _ in range(0, 20) { let (tx, rx) = channel();
random_line_split
os.rs
// Copyright 2013 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. //! Interfaces to the operating system provided random number //! generators. pub use self::imp::OSRng; #[cfg(unix)] mod imp { use Rng; use reader::ReaderRng; use std::io::{IoResult, File}; /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. #[cfg(unix)] pub struct OSRng { inner: ReaderRng<File> } impl OSRng { /// Create a new `OSRng`. pub fn new() -> IoResult<OSRng> { let reader = try!(File::open(&Path::new("/dev/urandom"))); let reader_rng = ReaderRng::new(reader); Ok(OSRng { inner: reader_rng }) } } impl Rng for OSRng { fn next_u32(&mut self) -> u32 { self.inner.next_u32() } fn next_u64(&mut self) -> u64 { self.inner.next_u64() } fn fill_bytes(&mut self, v: &mut [u8]) { self.inner.fill_bytes(v) } } } #[cfg(windows)] mod imp { extern crate libc; use Rng; use std::cast; use std::io::{IoResult, IoError}; use std::os; use std::rt::stack; use self::libc::{c_ulong, DWORD, BYTE, LPCSTR, BOOL}; type HCRYPTPROV = c_ulong; /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. pub struct OSRng { hcryptprov: HCRYPTPROV } static PROV_RSA_FULL: DWORD = 1; static CRYPT_SILENT: DWORD = 64; static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000; static NTE_BAD_SIGNATURE: DWORD = 0x80090006; extern "system" { fn CryptAcquireContextA(phProv: *mut HCRYPTPROV, pszContainer: LPCSTR, pszProvider: LPCSTR, dwProvType: DWORD, dwFlags: DWORD) -> BOOL; fn CryptGenRandom(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: *mut BYTE) -> BOOL; fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL; } impl OSRng { /// Create a new `OSRng`. pub fn new() -> IoResult<OSRng> { let mut hcp = 0; let mut ret = unsafe { CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT) }; // It turns out that if we can't acquire a context with the // NTE_BAD_SIGNATURE error code, the documentation states: // // The provider DLL signature could not be verified. Either the // DLL or the digital signature has been tampered with. // // Sounds fishy, no? As it turns out, our signature can be bad // because our Thread Information Block (TIB) isn't exactly what it // expects. As to why, I have no idea. The only data we store in the // TIB is the stack limit for each thread, but apparently that's // enough to make the signature valid. // // Furthermore, this error only happens the *first* time we call // CryptAcquireContext, so we don't have to worry about future // calls. // // Anyway, the fix employed here is that if we see this error, we // pray that we're not close to the end of the stack, temporarily // set the stack limit to 0 (what the TIB originally was), acquire a // context, and then reset the stack limit. // // Again, I'm not sure why this is the fix, nor why we're getting // this error. All I can say is that this seems to allow libnative // to progress where it otherwise would be hindered. Who knew? if ret == 0 && os::errno() as DWORD == NTE_BAD_SIGNATURE { unsafe { let limit = stack::get_sp_limit(); stack::record_sp_limit(0); ret = CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT); stack::record_sp_limit(limit); } } if ret == 0 { Err(IoError::last_error()) } else { Ok(OSRng { hcryptprov: hcp }) } } } impl Rng for OSRng { fn next_u32(&mut self) -> u32 { let mut v = [0u8,.. 4]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn
(&mut self) -> u64 { let mut v = [0u8,.. 8]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn fill_bytes(&mut self, v: &mut [u8]) { let ret = unsafe { CryptGenRandom(self.hcryptprov, v.len() as DWORD, v.as_mut_ptr()) }; if ret == 0 { fail!("couldn't generate random bytes: {}", os::last_os_error()); } } } impl Drop for OSRng { fn drop(&mut self) { let ret = unsafe { CryptReleaseContext(self.hcryptprov, 0) }; if ret == 0 { fail!("couldn't release context: {}", os::last_os_error()); } } } } #[cfg(test)] mod test { use super::OSRng; use Rng; use std::task; #[test] fn test_os_rng() { let mut r = OSRng::new().unwrap(); r.next_u32(); r.next_u64(); let mut v = [0u8,.. 1000]; r.fill_bytes(v); } #[test] fn test_os_rng_tasks() { let mut txs = vec!(); for _ in range(0, 20) { let (tx, rx) = channel(); txs.push(tx); task::spawn(proc() { // wait until all the tasks are ready to go. rx.recv(); // deschedule to attempt to interleave things as much // as possible (XXX: is this a good test?) let mut r = OSRng::new().unwrap(); task::deschedule(); let mut v = [0u8,.. 1000]; for _ in range(0, 100) { r.next_u32(); task::deschedule(); r.next_u64(); task::deschedule(); r.fill_bytes(v); task::deschedule(); } }) } // start all the tasks for tx in txs.iter() { tx.send(()) } } }
next_u64
identifier_name
websocket.rs
use std::ptr; use std::thread; use websocket::client::request::Url; use websocket::header::{Headers, WebSocketProtocol}; use websocket::ws::util::url::parse_url; #[derive(JSTraceable, PartialEq, Copy, Clone, Debug, HeapSizeOf)] enum WebSocketRequestState { Connecting = 0, Open = 1, Closing = 2, Closed = 3, } // list of bad ports according to // https://fetch.spec.whatwg.org/#port-blocking const BLOCKED_PORTS_LIST: &'static [u16] = &[ 1, // tcpmux 7, // echo 9, // discard 11, // systat 13, // daytime 15, // netstat 17, // qotd 19, // chargen 20, // ftp-data 21, // ftp 22, // ssh 23, // telnet 25, // smtp 37, // time 42, // name 43, // nicname 53, // domain 77, // priv-rjs 79, // finger 87, // ttylink 95, // supdup 101, // hostriame 102, // iso-tsap 103, // gppitnp 104, // acr-nema 109, // pop2 110, // pop3 111, // sunrpc 113, // auth 115, // sftp 117, // uucp-path 119, // nntp 123, // ntp 135, // loc-srv / epmap 139, // netbios 143, // imap2 179, // bgp 389, // ldap 465, // smtp+ssl 512, // print / exec 513, // login 514, // shell 515, // printer 526, // tempo 530, // courier 531, // chat 532, // netnews 540, // uucp 556, // remotefs 563, // nntp+ssl 587, // smtp 601, // syslog-conn 636, // ldap+ssl 993, // imap+ssl 995, // pop3+ssl 2049, // nfs 3659, // apple-sasl 4045, // lockd 6000, // x11 6665, // irc (alternate) 6666, // irc (alternate) 6667, // irc (default) 6668, // irc (alternate) 6669, // irc (alternate) ]; // Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1 // Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl #[allow(dead_code)] mod close_code { pub const NORMAL: u16 = 1000; pub const GOING_AWAY: u16 = 1001; pub const PROTOCOL_ERROR: u16 = 1002; pub const UNSUPPORTED_DATATYPE: u16 = 1003; pub const NO_STATUS: u16 = 1005; pub const ABNORMAL: u16 = 1006; pub const INVALID_PAYLOAD: u16 = 1007; pub const POLICY_VIOLATION: u16 = 1008; pub const TOO_LARGE: u16 = 1009; pub const EXTENSION_MISSING: u16 = 1010; pub const INTERNAL_ERROR: u16 = 1011; pub const TLS_FAILED: u16 = 1015; } pub fn close_the_websocket_connection(address: Trusted<WebSocket>, sender: Box<ScriptChan>, code: Option<u16>, reason: String) { let close_task = box CloseTask { address: address, failed: false, code: code, reason: Some(reason), }; sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, close_task)).unwrap(); } pub fn fail_the_websocket_connection(address: Trusted<WebSocket>, sender: Box<ScriptChan>) { let close_task = box CloseTask { address: address, failed: true, code: Some(close_code::ABNORMAL), reason: None, }; sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, close_task)).unwrap(); } #[dom_struct] pub struct WebSocket { eventtarget: EventTarget, url: Url, ready_state: Cell<WebSocketRequestState>, buffered_amount: Cell<u64>, clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount #[ignore_heap_size_of = "Defined in std"] sender: DOMRefCell<Option<IpcSender<WebSocketDomAction>>>, binary_type: Cell<BinaryType>, protocol: DOMRefCell<String>, //Subprotocol selected by server } impl WebSocket { fn new_inherited(url: Url) -> WebSocket { WebSocket { eventtarget: EventTarget::new_inherited(), url: url, ready_state: Cell::new(WebSocketRequestState::Connecting), buffered_amount: Cell::new(0), clearing_buffer: Cell::new(false), sender: DOMRefCell::new(None), binary_type: Cell::new(BinaryType::Blob), protocol: DOMRefCell::new("".to_owned()), } } fn new(global: &GlobalScope, url: Url) -> Root<WebSocket> { reflect_dom_object(box WebSocket::new_inherited(url), global, WebSocketBinding::Wrap) } pub fn Constructor(global: &GlobalScope, url: DOMString, protocols: Option<StringOrStringSequence>) -> Fallible<Root<WebSocket>> { // Step 1. let resource_url = try!(Url::parse(&url).map_err(|_| Error::Syntax)); // Although we do this replace and parse operation again in the resource thread, // we try here to be able to immediately throw a syntax error on failure. let _ = try!(parse_url(&replace_hosts(&resource_url)).map_err(|_| Error::Syntax)); // Step 2: Disallow https -> ws connections. // Step 3: Potentially block access to some ports. let port: u16 = resource_url.port_or_known_default().unwrap(); if BLOCKED_PORTS_LIST.iter().any(|&p| p == port) { return Err(Error::Security); } // Step 4. let protocols = match protocols { Some(StringOrStringSequence::String(string)) => vec![String::from(string)], Some(StringOrStringSequence::StringSequence(sequence)) => { sequence.into_iter().map(String::from).collect() }, _ => Vec::new(), }; // Step 5. for (i, protocol) in protocols.iter().enumerate() { // https://tools.ietf.org/html/rfc6455#section-4.1 // Handshake requirements, step 10 if protocols[i + 1..].iter().any(|p| p.eq_ignore_ascii_case(protocol)) { return Err(Error::Syntax); } // https://tools.ietf.org/html/rfc6455#section-4.1 if!is_token(protocol.as_bytes()) { return Err(Error::Syntax); } } // Step 6: Origin. let origin = UrlHelper::Origin(&global.get_url()).0; // Step 7. let ws = WebSocket::new(global, resource_url.clone()); let address = Trusted::new(ws.r()); let connect_data = WebSocketConnectData { resource_url: resource_url.clone(), origin: origin, protocols: protocols, }; // Create the interface for communication with the resource thread let (dom_action_sender, resource_action_receiver): (IpcSender<WebSocketDomAction>, IpcReceiver<WebSocketDomAction>) = ipc::channel().unwrap(); let (resource_event_sender, dom_event_receiver): (IpcSender<WebSocketNetworkEvent>, IpcReceiver<WebSocketNetworkEvent>) = ipc::channel().unwrap(); let connect = WebSocketCommunicate { event_sender: resource_event_sender, action_receiver: resource_action_receiver, }; let _ = global.core_resource_thread().send(WebsocketConnect(connect, connect_data)); *ws.sender.borrow_mut() = Some(dom_action_sender); let moved_address = address.clone(); let sender = global.networking_task_source(); thread::spawn(move || { while let Ok(event) = dom_event_receiver.recv() { match event { WebSocketNetworkEvent::ConnectionEstablished(headers, protocols) => { let open_thread = box ConnectionEstablishedTask { address: moved_address.clone(), headers: headers, protocols: protocols, }; sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, open_thread)).unwrap(); }, WebSocketNetworkEvent::MessageReceived(message) => { let message_thread = box MessageReceivedTask { address: moved_address.clone(), message: message, }; sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, message_thread)).unwrap(); }, WebSocketNetworkEvent::Fail => { fail_the_websocket_connection(moved_address.clone(), sender.clone()); }, WebSocketNetworkEvent::Close(code, reason) => { close_the_websocket_connection(moved_address.clone(), sender.clone(), code, reason); }, } } }); // Step 7. Ok(ws) } // https://html.spec.whatwg.org/multipage/#dom-websocket-send fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> { let return_after_buffer = match self.ready_state.get() { WebSocketRequestState::Connecting => { return Err(Error::InvalidState); }, WebSocketRequestState::Open => false, WebSocketRequestState::Closing | WebSocketRequestState::Closed => true, }; let address = Trusted::new(self); match data_byte_len.checked_add(self.buffered_amount.get()) { None => panic!(), Some(new_amount) => self.buffered_amount.set(new_amount) }; if return_after_buffer { return Ok(false); } if!self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open { self.clearing_buffer.set(true); let task = box BufferedAmountTask { address: address, }; self.global() .script_chan() .send(CommonScriptMsg::RunnableMsg(WebSocketEvent, task)) .unwrap(); } Ok(true) } } impl WebSocketMethods for WebSocket { // https://html.spec.whatwg.org/multipage/#handler-websocket-onopen event_handler!(open, GetOnopen, SetOnopen); // https://html.spec.whatwg.org/multipage/#handler-websocket-onclose event_handler!(close, GetOnclose, SetOnclose); // https://html.spec.whatwg.org/multipage/#handler-websocket-onerror event_handler!(error, GetOnerror, SetOnerror); // https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage event_handler!(message, GetOnmessage, SetOnmessage); // https://html.spec.whatwg.org/multipage/#dom-websocket-url fn Url(&self) -> DOMString { DOMString::from(self.url.as_str()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-readystate fn ReadyState(&self) -> u16 { self.ready_state.get() as u16 } // https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount fn BufferedAmount(&self) -> u64 { self.buffered_amount.get() } // https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype fn BinaryType(&self) -> BinaryType { self.binary_type.get() } // https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype fn SetBinaryType(&self, btype: BinaryType) { self.binary_type.set(btype) } // https://html.spec.whatwg.org/multipage/#dom-websocket-protocol fn Protocol(&self) -> DOMString { DOMString::from(self.protocol.borrow().clone()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-send fn Send(&self, data: USVString) -> ErrorResult { let data_byte_len = data.0.as_bytes().len() as u64; let send_data = try!(self.send_impl(data_byte_len)); if send_data { let mut other_sender = self.sender.borrow_mut(); let my_sender = other_sender.as_mut().unwrap(); let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0))); } Ok(()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-send fn Send_(&self, blob: &Blob) -> ErrorResult { /* As per https://html.spec.whatwg.org/multipage/#websocket the buffered amount needs to be clamped to u32, even though Blob.Size() is u64 If the buffer limit is reached in the first place, there are likely other major problems */ let data_byte_len = blob.Size(); let send_data = try!(self.send_impl(data_byte_len)); if send_data { let mut other_sender = self.sender.borrow_mut(); let my_sender = other_sender.as_mut().unwrap(); let bytes = blob.get_bytes().unwrap_or(vec![]); let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes))); } Ok(()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-close fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult { if let Some(code) = code { //Fail if the supplied code isn't normal and isn't reserved for libraries, frameworks, and applications if code!= close_code::NORMAL && (code < 3000 || code > 4999) { return Err(Error::InvalidAccess); } } if let Some(ref reason) = reason { if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes return Err(Error::Syntax); } } match self.ready_state.get() { WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing WebSocketRequestState::Connecting => { //Connection is not yet established /*By setting the state to closing, the open function will abort connecting the websocket*/ self.ready_state.set(WebSocketRequestState::Closing); let address = Trusted::new(self); let sender = self.global().networking_task_source(); fail_the_websocket_connection(address, sender); } WebSocketRequestState::Open => { self.ready_state.set(WebSocketRequestState::Closing); // Kick off _Start the WebSocket Closing Handshake_ // https://tools.ietf.org/html/rfc6455#section-7.1.2 let reason = reason.map(|reason| reason.0); let mut other_sender = self.sender.borrow_mut(); let my_sender = other_sender.as_mut().unwrap(); let _ = my_sender.send(WebSocketDomAction::Close(code, reason)); } } Ok(()) //Return Ok } } /// Task queued when *the WebSocket connection is established*. struct ConnectionEstablishedTask { address: Trusted<WebSocket>, protocols: Vec<String>, headers: Headers, } impl Runnable for ConnectionEstablishedTask { fn name(&self) -> &'static str { "ConnectionEstablishedTask" } fn handler(self: Box<Self>) { let ws = self.address.root(); // Step 1: Protocols. if!self.protocols.is_empty() && self.headers.get::<WebSocketProtocol>().is_none() { let sender = ws.global().networking_task_source(); fail_the_websocket_connection(self.address, sender); return; } // Step 2. ws.ready_state.set(WebSocketRequestState::Open); // Step 3: Extensions. //TODO: Set extensions to extensions in use // Step 4: Protocols. let protocol_in_use = unwrap_websocket_protocol(self.headers.get::<WebSocketProtocol>()); if let Some(protocol_name) = protocol_in_use { *ws.protocol.borrow_mut() = protocol_name.to_owned(); }; // Step 5: Cookies. if let Some(cookies) = self.headers.get_raw("set-cookie") { for cookie in cookies.iter() { if let Ok(cookie_value) = String::from_utf8(cookie.clone()) { let _ = ws.global().core_resource_thread().send( SetCookiesForUrl(ws.url.clone(), cookie_value, HTTP)); } } } // Step 6. ws.upcast().fire_simple_event("open"); } } struct BufferedAmountTask { address: Trusted<WebSocket>, } impl Runnable for BufferedAmountTask { // See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount // // To be compliant with standards, we need to reset bufferedAmount only when the event loop // reaches step 1. In our implementation, the bytes will already have been sent on a background // thread. fn name(&self) -> &'static str { "BufferedAmountTask" } fn handler(self: Box<Self>) { let ws = self.address.root(); ws.buffered_amount.set(0); ws.clearing_buffer.set(false); } } struct CloseTask { address: Trusted<WebSocket>, failed: bool, code: Option<u16>, reason: Option<String>, } impl Runnable for CloseTask { fn name(&self) -> &'static str { "CloseTask" } fn handler(self: Box<Self>) { let ws = self.address.root(); if ws.ready_state.get() == WebSocketRequestState::Closed { // Do nothing if already closed. return; } // Perform _the WebSocket connection is closed_ steps. // https://html.spec.whatwg.org/multipage/#closeWebSocket // Step 1. ws.ready_state.set(WebSocketRequestState::Closed); // Step 2. if self.failed { ws.upcast().fire_simple_event("error"); } // Step 3. let clean_close =!self.failed; let code = self.code.unwrap_or(close_code::NO_STATUS); let reason = DOMString::from(self.reason.unwrap_or("".to_owned())); let close_event = CloseEvent::new(&ws.global(), atom!("close"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, clean_close, code, reason); close_event.upcast::<Event>().fire(ws.upcast()); } } struct MessageReceivedTask { address: Trusted<WebSocket>, message: MessageData, } impl Runnable for MessageReceivedTask { fn
name
identifier_name
websocket.rs
traits::unwrap_websocket_protocol; use script_runtime::{CommonScriptMsg, ScriptChan}; use script_runtime::ScriptThreadEventCategory::WebSocketEvent; use script_thread::Runnable; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::Cell; use std::ptr; use std::thread; use websocket::client::request::Url; use websocket::header::{Headers, WebSocketProtocol}; use websocket::ws::util::url::parse_url; #[derive(JSTraceable, PartialEq, Copy, Clone, Debug, HeapSizeOf)] enum WebSocketRequestState { Connecting = 0, Open = 1, Closing = 2, Closed = 3, } // list of bad ports according to // https://fetch.spec.whatwg.org/#port-blocking const BLOCKED_PORTS_LIST: &'static [u16] = &[ 1, // tcpmux 7, // echo 9, // discard 11, // systat 13, // daytime 15, // netstat 17, // qotd 19, // chargen 20, // ftp-data 21, // ftp 22, // ssh 23, // telnet 25, // smtp 37, // time 42, // name 43, // nicname 53, // domain 77, // priv-rjs 79, // finger 87, // ttylink 95, // supdup 101, // hostriame 102, // iso-tsap 103, // gppitnp 104, // acr-nema 109, // pop2 110, // pop3 111, // sunrpc 113, // auth 115, // sftp 117, // uucp-path 119, // nntp 123, // ntp 135, // loc-srv / epmap 139, // netbios 143, // imap2 179, // bgp 389, // ldap 465, // smtp+ssl 512, // print / exec 513, // login 514, // shell 515, // printer 526, // tempo 530, // courier 531, // chat 532, // netnews 540, // uucp 556, // remotefs 563, // nntp+ssl 587, // smtp 601, // syslog-conn 636, // ldap+ssl 993, // imap+ssl 995, // pop3+ssl 2049, // nfs 3659, // apple-sasl 4045, // lockd 6000, // x11 6665, // irc (alternate) 6666, // irc (alternate) 6667, // irc (default) 6668, // irc (alternate) 6669, // irc (alternate) ]; // Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1 // Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl #[allow(dead_code)] mod close_code { pub const NORMAL: u16 = 1000; pub const GOING_AWAY: u16 = 1001; pub const PROTOCOL_ERROR: u16 = 1002; pub const UNSUPPORTED_DATATYPE: u16 = 1003; pub const NO_STATUS: u16 = 1005; pub const ABNORMAL: u16 = 1006; pub const INVALID_PAYLOAD: u16 = 1007; pub const POLICY_VIOLATION: u16 = 1008; pub const TOO_LARGE: u16 = 1009; pub const EXTENSION_MISSING: u16 = 1010; pub const INTERNAL_ERROR: u16 = 1011; pub const TLS_FAILED: u16 = 1015; } pub fn close_the_websocket_connection(address: Trusted<WebSocket>, sender: Box<ScriptChan>, code: Option<u16>, reason: String) { let close_task = box CloseTask { address: address, failed: false, code: code, reason: Some(reason), }; sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, close_task)).unwrap(); } pub fn fail_the_websocket_connection(address: Trusted<WebSocket>, sender: Box<ScriptChan>) { let close_task = box CloseTask { address: address, failed: true, code: Some(close_code::ABNORMAL), reason: None, }; sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, close_task)).unwrap(); } #[dom_struct] pub struct WebSocket { eventtarget: EventTarget, url: Url, ready_state: Cell<WebSocketRequestState>, buffered_amount: Cell<u64>, clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount #[ignore_heap_size_of = "Defined in std"] sender: DOMRefCell<Option<IpcSender<WebSocketDomAction>>>, binary_type: Cell<BinaryType>, protocol: DOMRefCell<String>, //Subprotocol selected by server } impl WebSocket { fn new_inherited(url: Url) -> WebSocket { WebSocket { eventtarget: EventTarget::new_inherited(), url: url, ready_state: Cell::new(WebSocketRequestState::Connecting), buffered_amount: Cell::new(0), clearing_buffer: Cell::new(false), sender: DOMRefCell::new(None), binary_type: Cell::new(BinaryType::Blob), protocol: DOMRefCell::new("".to_owned()), } } fn new(global: &GlobalScope, url: Url) -> Root<WebSocket> { reflect_dom_object(box WebSocket::new_inherited(url), global, WebSocketBinding::Wrap) } pub fn Constructor(global: &GlobalScope, url: DOMString, protocols: Option<StringOrStringSequence>) -> Fallible<Root<WebSocket>> { // Step 1. let resource_url = try!(Url::parse(&url).map_err(|_| Error::Syntax)); // Although we do this replace and parse operation again in the resource thread, // we try here to be able to immediately throw a syntax error on failure. let _ = try!(parse_url(&replace_hosts(&resource_url)).map_err(|_| Error::Syntax)); // Step 2: Disallow https -> ws connections. // Step 3: Potentially block access to some ports. let port: u16 = resource_url.port_or_known_default().unwrap(); if BLOCKED_PORTS_LIST.iter().any(|&p| p == port) { return Err(Error::Security); } // Step 4. let protocols = match protocols { Some(StringOrStringSequence::String(string)) => vec![String::from(string)], Some(StringOrStringSequence::StringSequence(sequence)) => { sequence.into_iter().map(String::from).collect() }, _ => Vec::new(), }; // Step 5. for (i, protocol) in protocols.iter().enumerate() { // https://tools.ietf.org/html/rfc6455#section-4.1 // Handshake requirements, step 10 if protocols[i + 1..].iter().any(|p| p.eq_ignore_ascii_case(protocol)) { return Err(Error::Syntax); } // https://tools.ietf.org/html/rfc6455#section-4.1 if!is_token(protocol.as_bytes()) { return Err(Error::Syntax); } } // Step 6: Origin. let origin = UrlHelper::Origin(&global.get_url()).0; // Step 7. let ws = WebSocket::new(global, resource_url.clone()); let address = Trusted::new(ws.r()); let connect_data = WebSocketConnectData { resource_url: resource_url.clone(), origin: origin, protocols: protocols, }; // Create the interface for communication with the resource thread let (dom_action_sender, resource_action_receiver): (IpcSender<WebSocketDomAction>, IpcReceiver<WebSocketDomAction>) = ipc::channel().unwrap(); let (resource_event_sender, dom_event_receiver): (IpcSender<WebSocketNetworkEvent>, IpcReceiver<WebSocketNetworkEvent>) = ipc::channel().unwrap(); let connect = WebSocketCommunicate { event_sender: resource_event_sender, action_receiver: resource_action_receiver, }; let _ = global.core_resource_thread().send(WebsocketConnect(connect, connect_data)); *ws.sender.borrow_mut() = Some(dom_action_sender); let moved_address = address.clone(); let sender = global.networking_task_source(); thread::spawn(move || { while let Ok(event) = dom_event_receiver.recv() { match event { WebSocketNetworkEvent::ConnectionEstablished(headers, protocols) => { let open_thread = box ConnectionEstablishedTask { address: moved_address.clone(), headers: headers, protocols: protocols, }; sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, open_thread)).unwrap(); }, WebSocketNetworkEvent::MessageReceived(message) => { let message_thread = box MessageReceivedTask { address: moved_address.clone(), message: message, }; sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, message_thread)).unwrap(); }, WebSocketNetworkEvent::Fail => { fail_the_websocket_connection(moved_address.clone(), sender.clone()); }, WebSocketNetworkEvent::Close(code, reason) => { close_the_websocket_connection(moved_address.clone(), sender.clone(), code, reason); }, } } }); // Step 7. Ok(ws) } // https://html.spec.whatwg.org/multipage/#dom-websocket-send fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> { let return_after_buffer = match self.ready_state.get() { WebSocketRequestState::Connecting => { return Err(Error::InvalidState); }, WebSocketRequestState::Open => false, WebSocketRequestState::Closing | WebSocketRequestState::Closed => true, }; let address = Trusted::new(self); match data_byte_len.checked_add(self.buffered_amount.get()) { None => panic!(), Some(new_amount) => self.buffered_amount.set(new_amount) }; if return_after_buffer { return Ok(false); } if!self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open { self.clearing_buffer.set(true); let task = box BufferedAmountTask { address: address, }; self.global() .script_chan() .send(CommonScriptMsg::RunnableMsg(WebSocketEvent, task)) .unwrap(); } Ok(true) } } impl WebSocketMethods for WebSocket { // https://html.spec.whatwg.org/multipage/#handler-websocket-onopen event_handler!(open, GetOnopen, SetOnopen); // https://html.spec.whatwg.org/multipage/#handler-websocket-onclose event_handler!(close, GetOnclose, SetOnclose); // https://html.spec.whatwg.org/multipage/#handler-websocket-onerror event_handler!(error, GetOnerror, SetOnerror); // https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage event_handler!(message, GetOnmessage, SetOnmessage); // https://html.spec.whatwg.org/multipage/#dom-websocket-url fn Url(&self) -> DOMString { DOMString::from(self.url.as_str()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-readystate fn ReadyState(&self) -> u16 { self.ready_state.get() as u16 } // https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount fn BufferedAmount(&self) -> u64 { self.buffered_amount.get() } // https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype fn BinaryType(&self) -> BinaryType { self.binary_type.get() } // https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype fn SetBinaryType(&self, btype: BinaryType) { self.binary_type.set(btype) } // https://html.spec.whatwg.org/multipage/#dom-websocket-protocol fn Protocol(&self) -> DOMString { DOMString::from(self.protocol.borrow().clone()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-send fn Send(&self, data: USVString) -> ErrorResult { let data_byte_len = data.0.as_bytes().len() as u64; let send_data = try!(self.send_impl(data_byte_len)); if send_data { let mut other_sender = self.sender.borrow_mut(); let my_sender = other_sender.as_mut().unwrap(); let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0))); } Ok(()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-send fn Send_(&self, blob: &Blob) -> ErrorResult { /* As per https://html.spec.whatwg.org/multipage/#websocket the buffered amount needs to be clamped to u32, even though Blob.Size() is u64 If the buffer limit is reached in the first place, there are likely other major problems */ let data_byte_len = blob.Size(); let send_data = try!(self.send_impl(data_byte_len)); if send_data { let mut other_sender = self.sender.borrow_mut(); let my_sender = other_sender.as_mut().unwrap(); let bytes = blob.get_bytes().unwrap_or(vec![]); let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes))); } Ok(()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-close fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult { if let Some(code) = code { //Fail if the supplied code isn't normal and isn't reserved for libraries, frameworks, and applications if code!= close_code::NORMAL && (code < 3000 || code > 4999) { return Err(Error::InvalidAccess); } } if let Some(ref reason) = reason { if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes return Err(Error::Syntax); } } match self.ready_state.get() { WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing WebSocketRequestState::Connecting => { //Connection is not yet established /*By setting the state to closing, the open function will abort connecting the websocket*/ self.ready_state.set(WebSocketRequestState::Closing); let address = Trusted::new(self); let sender = self.global().networking_task_source(); fail_the_websocket_connection(address, sender); } WebSocketRequestState::Open => { self.ready_state.set(WebSocketRequestState::Closing); // Kick off _Start the WebSocket Closing Handshake_ // https://tools.ietf.org/html/rfc6455#section-7.1.2 let reason = reason.map(|reason| reason.0); let mut other_sender = self.sender.borrow_mut(); let my_sender = other_sender.as_mut().unwrap(); let _ = my_sender.send(WebSocketDomAction::Close(code, reason)); } } Ok(()) //Return Ok } } /// Task queued when *the WebSocket connection is established*. struct ConnectionEstablishedTask { address: Trusted<WebSocket>, protocols: Vec<String>, headers: Headers, } impl Runnable for ConnectionEstablishedTask { fn name(&self) -> &'static str { "ConnectionEstablishedTask" } fn handler(self: Box<Self>) { let ws = self.address.root(); // Step 1: Protocols. if!self.protocols.is_empty() && self.headers.get::<WebSocketProtocol>().is_none() { let sender = ws.global().networking_task_source(); fail_the_websocket_connection(self.address, sender); return; } // Step 2. ws.ready_state.set(WebSocketRequestState::Open); // Step 3: Extensions. //TODO: Set extensions to extensions in use // Step 4: Protocols. let protocol_in_use = unwrap_websocket_protocol(self.headers.get::<WebSocketProtocol>()); if let Some(protocol_name) = protocol_in_use { *ws.protocol.borrow_mut() = protocol_name.to_owned(); }; // Step 5: Cookies. if let Some(cookies) = self.headers.get_raw("set-cookie") { for cookie in cookies.iter() { if let Ok(cookie_value) = String::from_utf8(cookie.clone()) { let _ = ws.global().core_resource_thread().send( SetCookiesForUrl(ws.url.clone(), cookie_value, HTTP)); } } } // Step 6. ws.upcast().fire_simple_event("open"); } } struct BufferedAmountTask { address: Trusted<WebSocket>, } impl Runnable for BufferedAmountTask { // See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount // // To be compliant with standards, we need to reset bufferedAmount only when the event loop // reaches step 1. In our implementation, the bytes will already have been sent on a background // thread. fn name(&self) -> &'static str { "BufferedAmountTask" } fn handler(self: Box<Self>) { let ws = self.address.root(); ws.buffered_amount.set(0); ws.clearing_buffer.set(false); } } struct CloseTask { address: Trusted<WebSocket>, failed: bool, code: Option<u16>, reason: Option<String>, } impl Runnable for CloseTask { fn name(&self) -> &'static str { "CloseTask" } fn handler(self: Box<Self>) { let ws = self.address.root(); if ws.ready_state.get() == WebSocketRequestState::Closed
// Perform _the WebSocket connection is closed_ steps. // https://html.spec.whatwg.org/multipage/#closeWebSocket // Step 1. ws.ready_state.set(WebSocketRequestState::Closed); // Step 2. if self.failed { ws.upcast().fire_simple_event("error"); } // Step 3. let clean_close =!self.failed; let code = self.code.unwrap_or(close_code::NO_STATUS); let reason = DOMString::from(self.reason.unwrap_or("".to_owned())); let close_event = CloseEvent::new(&ws.global(), atom!("close"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, clean_close, code, reason);
{ // Do nothing if already closed. return; }
conditional_block
websocket.rs
_traits::unwrap_websocket_protocol; use script_runtime::{CommonScriptMsg, ScriptChan}; use script_runtime::ScriptThreadEventCategory::WebSocketEvent; use script_thread::Runnable; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::Cell; use std::ptr; use std::thread; use websocket::client::request::Url; use websocket::header::{Headers, WebSocketProtocol}; use websocket::ws::util::url::parse_url; #[derive(JSTraceable, PartialEq, Copy, Clone, Debug, HeapSizeOf)] enum WebSocketRequestState { Connecting = 0, Open = 1, Closing = 2, Closed = 3, } // list of bad ports according to // https://fetch.spec.whatwg.org/#port-blocking const BLOCKED_PORTS_LIST: &'static [u16] = &[ 1, // tcpmux 7, // echo 9, // discard 11, // systat 13, // daytime 15, // netstat 17, // qotd 19, // chargen 20, // ftp-data 21, // ftp 22, // ssh 23, // telnet 25, // smtp 37, // time 42, // name 43, // nicname 53, // domain 77, // priv-rjs 79, // finger 87, // ttylink 95, // supdup 101, // hostriame 102, // iso-tsap 103, // gppitnp 104, // acr-nema 109, // pop2 110, // pop3 111, // sunrpc 113, // auth 115, // sftp 117, // uucp-path 119, // nntp 123, // ntp 135, // loc-srv / epmap 139, // netbios 143, // imap2 179, // bgp 389, // ldap 465, // smtp+ssl 512, // print / exec 513, // login 514, // shell 515, // printer 526, // tempo 530, // courier 531, // chat 532, // netnews 540, // uucp 556, // remotefs 563, // nntp+ssl 587, // smtp 601, // syslog-conn 636, // ldap+ssl 993, // imap+ssl 995, // pop3+ssl 2049, // nfs 3659, // apple-sasl 4045, // lockd 6000, // x11 6665, // irc (alternate) 6666, // irc (alternate) 6667, // irc (default) 6668, // irc (alternate) 6669, // irc (alternate) ]; // Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1 // Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl #[allow(dead_code)] mod close_code { pub const NORMAL: u16 = 1000; pub const GOING_AWAY: u16 = 1001; pub const PROTOCOL_ERROR: u16 = 1002; pub const UNSUPPORTED_DATATYPE: u16 = 1003; pub const NO_STATUS: u16 = 1005; pub const ABNORMAL: u16 = 1006; pub const INVALID_PAYLOAD: u16 = 1007; pub const POLICY_VIOLATION: u16 = 1008; pub const TOO_LARGE: u16 = 1009; pub const EXTENSION_MISSING: u16 = 1010; pub const INTERNAL_ERROR: u16 = 1011; pub const TLS_FAILED: u16 = 1015; } pub fn close_the_websocket_connection(address: Trusted<WebSocket>, sender: Box<ScriptChan>, code: Option<u16>, reason: String) { let close_task = box CloseTask { address: address, failed: false, code: code, reason: Some(reason), }; sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, close_task)).unwrap(); } pub fn fail_the_websocket_connection(address: Trusted<WebSocket>, sender: Box<ScriptChan>) { let close_task = box CloseTask { address: address, failed: true, code: Some(close_code::ABNORMAL), reason: None, }; sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, close_task)).unwrap(); } #[dom_struct] pub struct WebSocket { eventtarget: EventTarget, url: Url, ready_state: Cell<WebSocketRequestState>, buffered_amount: Cell<u64>, clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount #[ignore_heap_size_of = "Defined in std"] sender: DOMRefCell<Option<IpcSender<WebSocketDomAction>>>, binary_type: Cell<BinaryType>, protocol: DOMRefCell<String>, //Subprotocol selected by server } impl WebSocket { fn new_inherited(url: Url) -> WebSocket { WebSocket { eventtarget: EventTarget::new_inherited(), url: url, ready_state: Cell::new(WebSocketRequestState::Connecting), buffered_amount: Cell::new(0), clearing_buffer: Cell::new(false), sender: DOMRefCell::new(None), binary_type: Cell::new(BinaryType::Blob), protocol: DOMRefCell::new("".to_owned()), } } fn new(global: &GlobalScope, url: Url) -> Root<WebSocket> { reflect_dom_object(box WebSocket::new_inherited(url), global, WebSocketBinding::Wrap) } pub fn Constructor(global: &GlobalScope, url: DOMString, protocols: Option<StringOrStringSequence>) -> Fallible<Root<WebSocket>> { // Step 1. let resource_url = try!(Url::parse(&url).map_err(|_| Error::Syntax)); // Although we do this replace and parse operation again in the resource thread, // we try here to be able to immediately throw a syntax error on failure. let _ = try!(parse_url(&replace_hosts(&resource_url)).map_err(|_| Error::Syntax)); // Step 2: Disallow https -> ws connections. // Step 3: Potentially block access to some ports. let port: u16 = resource_url.port_or_known_default().unwrap(); if BLOCKED_PORTS_LIST.iter().any(|&p| p == port) { return Err(Error::Security); } // Step 4. let protocols = match protocols { Some(StringOrStringSequence::String(string)) => vec![String::from(string)], Some(StringOrStringSequence::StringSequence(sequence)) => { sequence.into_iter().map(String::from).collect() }, _ => Vec::new(), }; // Step 5. for (i, protocol) in protocols.iter().enumerate() { // https://tools.ietf.org/html/rfc6455#section-4.1 // Handshake requirements, step 10 if protocols[i + 1..].iter().any(|p| p.eq_ignore_ascii_case(protocol)) { return Err(Error::Syntax); } // https://tools.ietf.org/html/rfc6455#section-4.1 if!is_token(protocol.as_bytes()) { return Err(Error::Syntax); } } // Step 6: Origin. let origin = UrlHelper::Origin(&global.get_url()).0; // Step 7. let ws = WebSocket::new(global, resource_url.clone()); let address = Trusted::new(ws.r()); let connect_data = WebSocketConnectData { resource_url: resource_url.clone(), origin: origin, protocols: protocols, }; // Create the interface for communication with the resource thread let (dom_action_sender, resource_action_receiver): (IpcSender<WebSocketDomAction>, IpcReceiver<WebSocketDomAction>) = ipc::channel().unwrap(); let (resource_event_sender, dom_event_receiver): (IpcSender<WebSocketNetworkEvent>, IpcReceiver<WebSocketNetworkEvent>) = ipc::channel().unwrap(); let connect = WebSocketCommunicate { event_sender: resource_event_sender, action_receiver: resource_action_receiver, }; let _ = global.core_resource_thread().send(WebsocketConnect(connect, connect_data)); *ws.sender.borrow_mut() = Some(dom_action_sender); let moved_address = address.clone(); let sender = global.networking_task_source(); thread::spawn(move || { while let Ok(event) = dom_event_receiver.recv() { match event { WebSocketNetworkEvent::ConnectionEstablished(headers, protocols) => { let open_thread = box ConnectionEstablishedTask { address: moved_address.clone(), headers: headers, protocols: protocols, }; sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, open_thread)).unwrap(); }, WebSocketNetworkEvent::MessageReceived(message) => { let message_thread = box MessageReceivedTask { address: moved_address.clone(), message: message, }; sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, message_thread)).unwrap(); }, WebSocketNetworkEvent::Fail => { fail_the_websocket_connection(moved_address.clone(), sender.clone()); }, WebSocketNetworkEvent::Close(code, reason) => { close_the_websocket_connection(moved_address.clone(), sender.clone(), code, reason); }, } } }); // Step 7. Ok(ws) } // https://html.spec.whatwg.org/multipage/#dom-websocket-send fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> { let return_after_buffer = match self.ready_state.get() { WebSocketRequestState::Connecting => { return Err(Error::InvalidState); }, WebSocketRequestState::Open => false, WebSocketRequestState::Closing | WebSocketRequestState::Closed => true, }; let address = Trusted::new(self); match data_byte_len.checked_add(self.buffered_amount.get()) { None => panic!(), Some(new_amount) => self.buffered_amount.set(new_amount) }; if return_after_buffer { return Ok(false); } if!self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open { self.clearing_buffer.set(true); let task = box BufferedAmountTask { address: address, }; self.global() .script_chan() .send(CommonScriptMsg::RunnableMsg(WebSocketEvent, task)) .unwrap(); } Ok(true) } } impl WebSocketMethods for WebSocket { // https://html.spec.whatwg.org/multipage/#handler-websocket-onopen event_handler!(open, GetOnopen, SetOnopen); // https://html.spec.whatwg.org/multipage/#handler-websocket-onclose event_handler!(close, GetOnclose, SetOnclose); // https://html.spec.whatwg.org/multipage/#handler-websocket-onerror event_handler!(error, GetOnerror, SetOnerror); // https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage event_handler!(message, GetOnmessage, SetOnmessage); // https://html.spec.whatwg.org/multipage/#dom-websocket-url fn Url(&self) -> DOMString { DOMString::from(self.url.as_str()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-readystate fn ReadyState(&self) -> u16 { self.ready_state.get() as u16 } // https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount fn BufferedAmount(&self) -> u64 { self.buffered_amount.get() } // https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype fn BinaryType(&self) -> BinaryType { self.binary_type.get() } // https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype fn SetBinaryType(&self, btype: BinaryType) { self.binary_type.set(btype) } // https://html.spec.whatwg.org/multipage/#dom-websocket-protocol fn Protocol(&self) -> DOMString { DOMString::from(self.protocol.borrow().clone()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-send fn Send(&self, data: USVString) -> ErrorResult { let data_byte_len = data.0.as_bytes().len() as u64; let send_data = try!(self.send_impl(data_byte_len)); if send_data { let mut other_sender = self.sender.borrow_mut(); let my_sender = other_sender.as_mut().unwrap(); let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0))); } Ok(()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-send fn Send_(&self, blob: &Blob) -> ErrorResult { /* As per https://html.spec.whatwg.org/multipage/#websocket the buffered amount needs to be clamped to u32, even though Blob.Size() is u64 If the buffer limit is reached in the first place, there are likely other major problems */ let data_byte_len = blob.Size(); let send_data = try!(self.send_impl(data_byte_len)); if send_data { let mut other_sender = self.sender.borrow_mut(); let my_sender = other_sender.as_mut().unwrap(); let bytes = blob.get_bytes().unwrap_or(vec![]); let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes))); } Ok(()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-close fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult { if let Some(code) = code { //Fail if the supplied code isn't normal and isn't reserved for libraries, frameworks, and applications if code!= close_code::NORMAL && (code < 3000 || code > 4999) { return Err(Error::InvalidAccess); } } if let Some(ref reason) = reason { if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes return Err(Error::Syntax); } } match self.ready_state.get() { WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing WebSocketRequestState::Connecting => { //Connection is not yet established /*By setting the state to closing, the open function will abort connecting the websocket*/ self.ready_state.set(WebSocketRequestState::Closing); let address = Trusted::new(self); let sender = self.global().networking_task_source(); fail_the_websocket_connection(address, sender); } WebSocketRequestState::Open => { self.ready_state.set(WebSocketRequestState::Closing); // Kick off _Start the WebSocket Closing Handshake_ // https://tools.ietf.org/html/rfc6455#section-7.1.2 let reason = reason.map(|reason| reason.0); let mut other_sender = self.sender.borrow_mut(); let my_sender = other_sender.as_mut().unwrap(); let _ = my_sender.send(WebSocketDomAction::Close(code, reason)); } } Ok(()) //Return Ok } } /// Task queued when *the WebSocket connection is established*. struct ConnectionEstablishedTask { address: Trusted<WebSocket>, protocols: Vec<String>, headers: Headers, } impl Runnable for ConnectionEstablishedTask { fn name(&self) -> &'static str { "ConnectionEstablishedTask" } fn handler(self: Box<Self>) { let ws = self.address.root(); // Step 1: Protocols. if!self.protocols.is_empty() && self.headers.get::<WebSocketProtocol>().is_none() { let sender = ws.global().networking_task_source(); fail_the_websocket_connection(self.address, sender); return; } // Step 2. ws.ready_state.set(WebSocketRequestState::Open); // Step 3: Extensions. //TODO: Set extensions to extensions in use // Step 4: Protocols. let protocol_in_use = unwrap_websocket_protocol(self.headers.get::<WebSocketProtocol>()); if let Some(protocol_name) = protocol_in_use { *ws.protocol.borrow_mut() = protocol_name.to_owned(); }; // Step 5: Cookies. if let Some(cookies) = self.headers.get_raw("set-cookie") { for cookie in cookies.iter() { if let Ok(cookie_value) = String::from_utf8(cookie.clone()) { let _ = ws.global().core_resource_thread().send( SetCookiesForUrl(ws.url.clone(), cookie_value, HTTP)); } } } // Step 6. ws.upcast().fire_simple_event("open"); } } struct BufferedAmountTask { address: Trusted<WebSocket>, } impl Runnable for BufferedAmountTask { // See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount // // To be compliant with standards, we need to reset bufferedAmount only when the event loop // reaches step 1. In our implementation, the bytes will already have been sent on a background // thread. fn name(&self) -> &'static str { "BufferedAmountTask" } fn handler(self: Box<Self>) { let ws = self.address.root(); ws.buffered_amount.set(0); ws.clearing_buffer.set(false); } } struct CloseTask { address: Trusted<WebSocket>, failed: bool, code: Option<u16>, reason: Option<String>, } impl Runnable for CloseTask { fn name(&self) -> &'static str { "CloseTask" } fn handler(self: Box<Self>) { let ws = self.address.root(); if ws.ready_state.get() == WebSocketRequestState::Closed { // Do nothing if already closed. return; }
// Perform _the WebSocket connection is closed_ steps. // https://html.spec.whatwg.org/multipage/#closeWebSocket // Step 1. ws.ready_state.set(WebSocketRequestState::Closed); // Step 2. if self.failed { ws.upcast().fire_simple_event("error"); } // Step 3. let clean_close =!self.failed; let code = self.code.unwrap_or(close_code::NO_STATUS); let reason = DOMString::from(self.reason.unwrap_or("".to_owned())); let close_event = CloseEvent::new(&ws.global(), atom!("close"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, clean_close, code, reason);
random_line_split
std-panic-locations.rs
// run-pass // ignore-wasm32-bare compiled with panic=abort by default // revisions: default mir-opt //[mir-opt] compile-flags: -Zmir-opt-level=4 #![allow(unconditional_panic)] //! Test that panic locations for `#[track_caller]` functions in std have the correct //! location reported. use std::cell::RefCell; use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ops::{Index, IndexMut}; use std::panic::{AssertUnwindSafe, UnwindSafe}; fn main() { // inspect the `PanicInfo` we receive to ensure the right file is the source std::panic::set_hook(Box::new(|info| { let actual = info.location().unwrap(); if actual.file()!= file!()
})); fn assert_panicked(f: impl FnOnce() + UnwindSafe) { std::panic::catch_unwind(f).unwrap_err(); } let nope: Option<()> = None; assert_panicked(|| nope.unwrap()); assert_panicked(|| nope.expect("")); let oops: Result<(), ()> = Err(()); assert_panicked(|| oops.unwrap()); assert_panicked(|| oops.expect("")); let fine: Result<(), ()> = Ok(()); assert_panicked(|| fine.unwrap_err()); assert_panicked(|| fine.expect_err("")); let mut small = [0]; // the implementation backing str, vec, etc assert_panicked(move || { small.index(1); }); assert_panicked(move || { small[1]; }); assert_panicked(move || { small.index_mut(1); }); assert_panicked(move || { small[1] += 1; }); let sorted: BTreeMap<bool, bool> = Default::default(); assert_panicked(|| { sorted.index(&false); }); assert_panicked(|| { sorted[&false]; }); let unsorted: HashMap<bool, bool> = Default::default(); assert_panicked(|| { unsorted.index(&false); }); assert_panicked(|| { unsorted[&false]; }); let weirdo: VecDeque<()> = Default::default(); assert_panicked(|| { weirdo.index(1); }); assert_panicked(|| { weirdo[1]; }); let refcell: RefCell<()> = Default::default(); let _conflicting = refcell.borrow_mut(); assert_panicked(AssertUnwindSafe(|| { refcell.borrow(); })); assert_panicked(AssertUnwindSafe(|| { refcell.borrow_mut(); })); }
{ eprintln!("expected a location in the test file, found {:?}", actual); panic!(); }
conditional_block
std-panic-locations.rs
// run-pass // ignore-wasm32-bare compiled with panic=abort by default // revisions: default mir-opt //[mir-opt] compile-flags: -Zmir-opt-level=4 #![allow(unconditional_panic)] //! Test that panic locations for `#[track_caller]` functions in std have the correct //! location reported. use std::cell::RefCell; use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ops::{Index, IndexMut}; use std::panic::{AssertUnwindSafe, UnwindSafe}; fn main() { // inspect the `PanicInfo` we receive to ensure the right file is the source std::panic::set_hook(Box::new(|info| { let actual = info.location().unwrap(); if actual.file()!= file!() { eprintln!("expected a location in the test file, found {:?}", actual); panic!(); } })); fn assert_panicked(f: impl FnOnce() + UnwindSafe)
let nope: Option<()> = None; assert_panicked(|| nope.unwrap()); assert_panicked(|| nope.expect("")); let oops: Result<(), ()> = Err(()); assert_panicked(|| oops.unwrap()); assert_panicked(|| oops.expect("")); let fine: Result<(), ()> = Ok(()); assert_panicked(|| fine.unwrap_err()); assert_panicked(|| fine.expect_err("")); let mut small = [0]; // the implementation backing str, vec, etc assert_panicked(move || { small.index(1); }); assert_panicked(move || { small[1]; }); assert_panicked(move || { small.index_mut(1); }); assert_panicked(move || { small[1] += 1; }); let sorted: BTreeMap<bool, bool> = Default::default(); assert_panicked(|| { sorted.index(&false); }); assert_panicked(|| { sorted[&false]; }); let unsorted: HashMap<bool, bool> = Default::default(); assert_panicked(|| { unsorted.index(&false); }); assert_panicked(|| { unsorted[&false]; }); let weirdo: VecDeque<()> = Default::default(); assert_panicked(|| { weirdo.index(1); }); assert_panicked(|| { weirdo[1]; }); let refcell: RefCell<()> = Default::default(); let _conflicting = refcell.borrow_mut(); assert_panicked(AssertUnwindSafe(|| { refcell.borrow(); })); assert_panicked(AssertUnwindSafe(|| { refcell.borrow_mut(); })); }
{ std::panic::catch_unwind(f).unwrap_err(); }
identifier_body
std-panic-locations.rs
// run-pass // ignore-wasm32-bare compiled with panic=abort by default // revisions: default mir-opt //[mir-opt] compile-flags: -Zmir-opt-level=4 #![allow(unconditional_panic)] //! Test that panic locations for `#[track_caller]` functions in std have the correct //! location reported. use std::cell::RefCell; use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ops::{Index, IndexMut}; use std::panic::{AssertUnwindSafe, UnwindSafe}; fn main() { // inspect the `PanicInfo` we receive to ensure the right file is the source std::panic::set_hook(Box::new(|info| { let actual = info.location().unwrap(); if actual.file()!= file!() { eprintln!("expected a location in the test file, found {:?}", actual); panic!(); } })); fn
(f: impl FnOnce() + UnwindSafe) { std::panic::catch_unwind(f).unwrap_err(); } let nope: Option<()> = None; assert_panicked(|| nope.unwrap()); assert_panicked(|| nope.expect("")); let oops: Result<(), ()> = Err(()); assert_panicked(|| oops.unwrap()); assert_panicked(|| oops.expect("")); let fine: Result<(), ()> = Ok(()); assert_panicked(|| fine.unwrap_err()); assert_panicked(|| fine.expect_err("")); let mut small = [0]; // the implementation backing str, vec, etc assert_panicked(move || { small.index(1); }); assert_panicked(move || { small[1]; }); assert_panicked(move || { small.index_mut(1); }); assert_panicked(move || { small[1] += 1; }); let sorted: BTreeMap<bool, bool> = Default::default(); assert_panicked(|| { sorted.index(&false); }); assert_panicked(|| { sorted[&false]; }); let unsorted: HashMap<bool, bool> = Default::default(); assert_panicked(|| { unsorted.index(&false); }); assert_panicked(|| { unsorted[&false]; }); let weirdo: VecDeque<()> = Default::default(); assert_panicked(|| { weirdo.index(1); }); assert_panicked(|| { weirdo[1]; }); let refcell: RefCell<()> = Default::default(); let _conflicting = refcell.borrow_mut(); assert_panicked(AssertUnwindSafe(|| { refcell.borrow(); })); assert_panicked(AssertUnwindSafe(|| { refcell.borrow_mut(); })); }
assert_panicked
identifier_name
std-panic-locations.rs
// run-pass // ignore-wasm32-bare compiled with panic=abort by default // revisions: default mir-opt //[mir-opt] compile-flags: -Zmir-opt-level=4 #![allow(unconditional_panic)] //! Test that panic locations for `#[track_caller]` functions in std have the correct //! location reported. use std::cell::RefCell; use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ops::{Index, IndexMut}; use std::panic::{AssertUnwindSafe, UnwindSafe}; fn main() { // inspect the `PanicInfo` we receive to ensure the right file is the source std::panic::set_hook(Box::new(|info| { let actual = info.location().unwrap(); if actual.file()!= file!() { eprintln!("expected a location in the test file, found {:?}", actual); panic!(); } }));
std::panic::catch_unwind(f).unwrap_err(); } let nope: Option<()> = None; assert_panicked(|| nope.unwrap()); assert_panicked(|| nope.expect("")); let oops: Result<(), ()> = Err(()); assert_panicked(|| oops.unwrap()); assert_panicked(|| oops.expect("")); let fine: Result<(), ()> = Ok(()); assert_panicked(|| fine.unwrap_err()); assert_panicked(|| fine.expect_err("")); let mut small = [0]; // the implementation backing str, vec, etc assert_panicked(move || { small.index(1); }); assert_panicked(move || { small[1]; }); assert_panicked(move || { small.index_mut(1); }); assert_panicked(move || { small[1] += 1; }); let sorted: BTreeMap<bool, bool> = Default::default(); assert_panicked(|| { sorted.index(&false); }); assert_panicked(|| { sorted[&false]; }); let unsorted: HashMap<bool, bool> = Default::default(); assert_panicked(|| { unsorted.index(&false); }); assert_panicked(|| { unsorted[&false]; }); let weirdo: VecDeque<()> = Default::default(); assert_panicked(|| { weirdo.index(1); }); assert_panicked(|| { weirdo[1]; }); let refcell: RefCell<()> = Default::default(); let _conflicting = refcell.borrow_mut(); assert_panicked(AssertUnwindSafe(|| { refcell.borrow(); })); assert_panicked(AssertUnwindSafe(|| { refcell.borrow_mut(); })); }
fn assert_panicked(f: impl FnOnce() + UnwindSafe) {
random_line_split
providers.rs
// Copyright 2020 The Kythe Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::error::KytheError; use crate::proxyrequests; use analysis_rust_proto::*; use serde_json::Value; use std::fs::File; use std::io::{self, BufReader, Read, Write}; use std::path::Path; use zip::ZipArchive; /// A trait for retrieving files during indexing. pub trait FileProvider { /// Checks whether a file exists and that the contents are available. /// /// This function takes a file path and digest, and returns whether /// the file exists and that the contents can be requested. /// /// # Errors /// /// If the file is not a valid zip archive, a [KytheError::KzipFileError] /// will be returned. fn exists(&mut self, path: &str, digest: &str) -> Result<bool, KytheError>; /// Retrieves the byte contents of a file. /// /// This function takes a file path and digest, and returns the bytes /// contents of the file in a vector. /// /// # Errors /// /// If the file does not exist, a /// [FileNotFoundError][KytheError::FileNotFoundError] will be returned. /// If the file can't be read, a [FileReadError][KytheError::FileReadError] /// will be returned. fn contents(&mut self, path: &str, digest: &str) -> Result<Vec<u8>, KytheError>; } /// A [FileProvider] that is backed by a.kzip file. pub struct KzipFileProvider { zip_archive: ZipArchive<BufReader<File>>, /// The top level folder name inside of the zip archive root_name: String, } impl KzipFileProvider { /// Create a new instance using a valid [File] object of a kzip /// file. /// /// # Errors /// /// If an error occurs while reading the kzip, a [KzipFileError] will be /// returned. pub fn new(file: File) -> Result<Self, KytheError> { let reader = BufReader::new(file); let mut zip_archive = ZipArchive::new(reader)?; // Get the name of the root folder of the kzip. This should be almost always be // "root" by the kzip spec doesn't guarantee it. let root_name = { let file = zip_archive.by_index(0)?; let mut path = Path::new(file.name()); while let Some(p) = path.parent() { // Last parent will be blank path so break when p is empty. path will contain // root if p == Path::new("") { break; } path = p; } // Safe to unwrap because kzip read would have failed if the internal paths // weren't UTF-8 path.to_str().unwrap().to_owned().replace('/', "") }; Ok(Self { zip_archive, root_name }) } /// Retrieve the Compilation Units from the kzip. /// /// This function will attempt to parse the proto files in the `pbunits` /// folder into Compilation Units, returning a Vector of them. /// /// # Errors /// /// If a file cannot be parsed, a /// [ProtobufParseError][KytheError::ProtobufParseError] will be returned. pub fn get_compilation_units(&mut self) -> Result<Vec<CompilationUnit>, KytheError> { let mut compilation_units = Vec::new(); for i in 0..self.zip_archive.len() { // Protobuf files are in the pbunits folder let file = self.zip_archive.by_index(i)?; if file.is_file() && file.name().contains("/pbunits/") { let mut reader = BufReader::new(file); let indexed_comp = protobuf::parse_from_reader::<IndexedCompilation>(&mut reader)?; compilation_units.push(indexed_comp.get_unit().clone()); } } Ok(compilation_units) } } impl FileProvider for KzipFileProvider { /// Given a file path and digest, returns whether the file exists in the /// kzip. fn exists(&mut self, _path: &str, digest: &str) -> Result<bool, KytheError> { let name = format!("{}/files/{}", self.root_name, digest); Ok(self.zip_archive.by_name(&name).is_ok()) } /// Given a file path and digest, returns the vector of bytes of the file /// from the kzip. /// /// # Errors /// /// An error will be returned if the file does not exist or cannot be read. fn contents(&mut self, _path: &str, digest: &str) -> Result<Vec<u8>, KytheError> { // Ensure the file exists in the kzip let name = format!("{}/files/{}", self.root_name, digest); let file = self.zip_archive.by_name(&name).map_err(|_| KytheError::FileNotFoundError(name))?; let mut reader = BufReader::new(file); let mut file_contents: Vec<u8> = Vec::new(); reader.read_to_end(&mut file_contents)?; Ok(file_contents) } } /// A [FileProvider] that backed by the analysis driver proxy pub struct ProxyFileProvider {} impl ProxyFileProvider { pub fn new() -> Self { Self {} } } impl Default for ProxyFileProvider { fn default() -> Self
} impl FileProvider for ProxyFileProvider { /// Given a file path and digest, returns whether the proxy can find the /// file. fn exists(&mut self, path: &str, digest: &str) -> Result<bool, KytheError> { // Submit the file request to the proxy let request = proxyrequests::file(path.to_string(), digest.to_string())?; println!("{}", request); io::stdout().flush().map_err(|err| { KytheError::IndexerError(format!("Failed to flush stdout: {:?}", err)) })?; // Read the response from the proxy let mut response_string = String::new(); io::stdin().read_line(&mut response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; // Convert to json and extract information let response: Value = serde_json::from_str(&response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; if response["rsp"].as_str().unwrap() == "error" { // The file couldn't be found Ok(false) } else { Ok(true) } } fn contents(&mut self, path: &str, digest: &str) -> Result<Vec<u8>, KytheError> { // Submit the file request to the proxy let request = proxyrequests::file(path.to_string(), digest.to_string())?; println!("{}", request); io::stdout().flush().map_err(|err| { KytheError::IndexerError(format!("Failed to flush stdout: {:?}", err)) })?; // Read the response from the proxy let mut response_string = String::new(); io::stdin().read_line(&mut response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; // Convert to json and extract information let response: Value = serde_json::from_str(&response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; if response["rsp"].as_str().unwrap() == "error" { // The file couldn't be found Err(KytheError::FileNotFoundError(path.to_string())) } else { let args: Value = response["args"].clone(); // Retrieve base64 content and convert to a Vec<u8> let content_option = args["content"].as_str(); if content_option.is_none() { return Ok(vec![]); } let content_base64: &str = content_option.unwrap(); let content: Vec<u8> = base64::decode(&content_base64).map_err(|err| { KytheError::IndexerError(format!( "Failed to convert base64 file contents response to bytes: {:?}", err )) })?; Ok(content) } } }
{ Self::new() }
identifier_body
providers.rs
// Copyright 2020 The Kythe Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::error::KytheError; use crate::proxyrequests; use analysis_rust_proto::*; use serde_json::Value; use std::fs::File; use std::io::{self, BufReader, Read, Write}; use std::path::Path; use zip::ZipArchive; /// A trait for retrieving files during indexing. pub trait FileProvider { /// Checks whether a file exists and that the contents are available. /// /// This function takes a file path and digest, and returns whether /// the file exists and that the contents can be requested. /// /// # Errors /// /// If the file is not a valid zip archive, a [KytheError::KzipFileError] /// will be returned. fn exists(&mut self, path: &str, digest: &str) -> Result<bool, KytheError>; /// Retrieves the byte contents of a file. /// /// This function takes a file path and digest, and returns the bytes /// contents of the file in a vector. /// /// # Errors /// /// If the file does not exist, a /// [FileNotFoundError][KytheError::FileNotFoundError] will be returned. /// If the file can't be read, a [FileReadError][KytheError::FileReadError] /// will be returned. fn contents(&mut self, path: &str, digest: &str) -> Result<Vec<u8>, KytheError>; } /// A [FileProvider] that is backed by a.kzip file. pub struct KzipFileProvider { zip_archive: ZipArchive<BufReader<File>>, /// The top level folder name inside of the zip archive root_name: String, } impl KzipFileProvider { /// Create a new instance using a valid [File] object of a kzip /// file. /// /// # Errors /// /// If an error occurs while reading the kzip, a [KzipFileError] will be /// returned. pub fn new(file: File) -> Result<Self, KytheError> { let reader = BufReader::new(file); let mut zip_archive = ZipArchive::new(reader)?; // Get the name of the root folder of the kzip. This should be almost always be // "root" by the kzip spec doesn't guarantee it. let root_name = { let file = zip_archive.by_index(0)?; let mut path = Path::new(file.name()); while let Some(p) = path.parent() { // Last parent will be blank path so break when p is empty. path will contain // root if p == Path::new("") { break; } path = p; } // Safe to unwrap because kzip read would have failed if the internal paths // weren't UTF-8 path.to_str().unwrap().to_owned().replace('/', "") }; Ok(Self { zip_archive, root_name }) } /// Retrieve the Compilation Units from the kzip. /// /// This function will attempt to parse the proto files in the `pbunits` /// folder into Compilation Units, returning a Vector of them. /// /// # Errors /// /// If a file cannot be parsed, a /// [ProtobufParseError][KytheError::ProtobufParseError] will be returned. pub fn get_compilation_units(&mut self) -> Result<Vec<CompilationUnit>, KytheError> { let mut compilation_units = Vec::new(); for i in 0..self.zip_archive.len() { // Protobuf files are in the pbunits folder let file = self.zip_archive.by_index(i)?; if file.is_file() && file.name().contains("/pbunits/") { let mut reader = BufReader::new(file); let indexed_comp = protobuf::parse_from_reader::<IndexedCompilation>(&mut reader)?; compilation_units.push(indexed_comp.get_unit().clone()); } } Ok(compilation_units) } } impl FileProvider for KzipFileProvider { /// Given a file path and digest, returns whether the file exists in the /// kzip. fn exists(&mut self, _path: &str, digest: &str) -> Result<bool, KytheError> { let name = format!("{}/files/{}", self.root_name, digest); Ok(self.zip_archive.by_name(&name).is_ok()) } /// Given a file path and digest, returns the vector of bytes of the file /// from the kzip. /// /// # Errors /// /// An error will be returned if the file does not exist or cannot be read. fn contents(&mut self, _path: &str, digest: &str) -> Result<Vec<u8>, KytheError> { // Ensure the file exists in the kzip let name = format!("{}/files/{}", self.root_name, digest); let file = self.zip_archive.by_name(&name).map_err(|_| KytheError::FileNotFoundError(name))?; let mut reader = BufReader::new(file); let mut file_contents: Vec<u8> = Vec::new(); reader.read_to_end(&mut file_contents)?; Ok(file_contents) } } /// A [FileProvider] that backed by the analysis driver proxy pub struct ProxyFileProvider {} impl ProxyFileProvider { pub fn new() -> Self { Self {} } } impl Default for ProxyFileProvider { fn default() -> Self { Self::new() } } impl FileProvider for ProxyFileProvider { /// Given a file path and digest, returns whether the proxy can find the /// file. fn
(&mut self, path: &str, digest: &str) -> Result<bool, KytheError> { // Submit the file request to the proxy let request = proxyrequests::file(path.to_string(), digest.to_string())?; println!("{}", request); io::stdout().flush().map_err(|err| { KytheError::IndexerError(format!("Failed to flush stdout: {:?}", err)) })?; // Read the response from the proxy let mut response_string = String::new(); io::stdin().read_line(&mut response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; // Convert to json and extract information let response: Value = serde_json::from_str(&response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; if response["rsp"].as_str().unwrap() == "error" { // The file couldn't be found Ok(false) } else { Ok(true) } } fn contents(&mut self, path: &str, digest: &str) -> Result<Vec<u8>, KytheError> { // Submit the file request to the proxy let request = proxyrequests::file(path.to_string(), digest.to_string())?; println!("{}", request); io::stdout().flush().map_err(|err| { KytheError::IndexerError(format!("Failed to flush stdout: {:?}", err)) })?; // Read the response from the proxy let mut response_string = String::new(); io::stdin().read_line(&mut response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; // Convert to json and extract information let response: Value = serde_json::from_str(&response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; if response["rsp"].as_str().unwrap() == "error" { // The file couldn't be found Err(KytheError::FileNotFoundError(path.to_string())) } else { let args: Value = response["args"].clone(); // Retrieve base64 content and convert to a Vec<u8> let content_option = args["content"].as_str(); if content_option.is_none() { return Ok(vec![]); } let content_base64: &str = content_option.unwrap(); let content: Vec<u8> = base64::decode(&content_base64).map_err(|err| { KytheError::IndexerError(format!( "Failed to convert base64 file contents response to bytes: {:?}", err )) })?; Ok(content) } } }
exists
identifier_name
providers.rs
// Copyright 2020 The Kythe Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::error::KytheError; use crate::proxyrequests; use analysis_rust_proto::*; use serde_json::Value; use std::fs::File; use std::io::{self, BufReader, Read, Write}; use std::path::Path; use zip::ZipArchive; /// A trait for retrieving files during indexing. pub trait FileProvider { /// Checks whether a file exists and that the contents are available. /// /// This function takes a file path and digest, and returns whether /// the file exists and that the contents can be requested. /// /// # Errors /// /// If the file is not a valid zip archive, a [KytheError::KzipFileError] /// will be returned. fn exists(&mut self, path: &str, digest: &str) -> Result<bool, KytheError>; /// Retrieves the byte contents of a file. /// /// This function takes a file path and digest, and returns the bytes /// contents of the file in a vector. /// /// # Errors /// /// If the file does not exist, a /// [FileNotFoundError][KytheError::FileNotFoundError] will be returned. /// If the file can't be read, a [FileReadError][KytheError::FileReadError] /// will be returned. fn contents(&mut self, path: &str, digest: &str) -> Result<Vec<u8>, KytheError>; } /// A [FileProvider] that is backed by a.kzip file. pub struct KzipFileProvider { zip_archive: ZipArchive<BufReader<File>>, /// The top level folder name inside of the zip archive root_name: String, } impl KzipFileProvider { /// Create a new instance using a valid [File] object of a kzip /// file. /// /// # Errors /// /// If an error occurs while reading the kzip, a [KzipFileError] will be /// returned. pub fn new(file: File) -> Result<Self, KytheError> { let reader = BufReader::new(file); let mut zip_archive = ZipArchive::new(reader)?; // Get the name of the root folder of the kzip. This should be almost always be // "root" by the kzip spec doesn't guarantee it. let root_name = { let file = zip_archive.by_index(0)?; let mut path = Path::new(file.name()); while let Some(p) = path.parent() { // Last parent will be blank path so break when p is empty. path will contain // root if p == Path::new("") { break; } path = p; } // Safe to unwrap because kzip read would have failed if the internal paths // weren't UTF-8 path.to_str().unwrap().to_owned().replace('/', "") }; Ok(Self { zip_archive, root_name }) } /// Retrieve the Compilation Units from the kzip. /// /// This function will attempt to parse the proto files in the `pbunits` /// folder into Compilation Units, returning a Vector of them. /// /// # Errors /// /// If a file cannot be parsed, a /// [ProtobufParseError][KytheError::ProtobufParseError] will be returned. pub fn get_compilation_units(&mut self) -> Result<Vec<CompilationUnit>, KytheError> { let mut compilation_units = Vec::new(); for i in 0..self.zip_archive.len() { // Protobuf files are in the pbunits folder let file = self.zip_archive.by_index(i)?; if file.is_file() && file.name().contains("/pbunits/") { let mut reader = BufReader::new(file); let indexed_comp = protobuf::parse_from_reader::<IndexedCompilation>(&mut reader)?; compilation_units.push(indexed_comp.get_unit().clone()); } } Ok(compilation_units) } } impl FileProvider for KzipFileProvider { /// Given a file path and digest, returns whether the file exists in the /// kzip. fn exists(&mut self, _path: &str, digest: &str) -> Result<bool, KytheError> { let name = format!("{}/files/{}", self.root_name, digest); Ok(self.zip_archive.by_name(&name).is_ok()) } /// Given a file path and digest, returns the vector of bytes of the file /// from the kzip. /// /// # Errors /// /// An error will be returned if the file does not exist or cannot be read. fn contents(&mut self, _path: &str, digest: &str) -> Result<Vec<u8>, KytheError> { // Ensure the file exists in the kzip let name = format!("{}/files/{}", self.root_name, digest); let file = self.zip_archive.by_name(&name).map_err(|_| KytheError::FileNotFoundError(name))?; let mut reader = BufReader::new(file); let mut file_contents: Vec<u8> = Vec::new(); reader.read_to_end(&mut file_contents)?; Ok(file_contents) } } /// A [FileProvider] that backed by the analysis driver proxy pub struct ProxyFileProvider {} impl ProxyFileProvider { pub fn new() -> Self { Self {} } } impl Default for ProxyFileProvider { fn default() -> Self { Self::new() } } impl FileProvider for ProxyFileProvider { /// Given a file path and digest, returns whether the proxy can find the /// file. fn exists(&mut self, path: &str, digest: &str) -> Result<bool, KytheError> { // Submit the file request to the proxy let request = proxyrequests::file(path.to_string(), digest.to_string())?; println!("{}", request); io::stdout().flush().map_err(|err| { KytheError::IndexerError(format!("Failed to flush stdout: {:?}", err)) })?; // Read the response from the proxy let mut response_string = String::new(); io::stdin().read_line(&mut response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; // Convert to json and extract information let response: Value = serde_json::from_str(&response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; if response["rsp"].as_str().unwrap() == "error" { // The file couldn't be found Ok(false) } else { Ok(true) } } fn contents(&mut self, path: &str, digest: &str) -> Result<Vec<u8>, KytheError> { // Submit the file request to the proxy let request = proxyrequests::file(path.to_string(), digest.to_string())?; println!("{}", request); io::stdout().flush().map_err(|err| { KytheError::IndexerError(format!("Failed to flush stdout: {:?}", err)) })?; // Read the response from the proxy let mut response_string = String::new(); io::stdin().read_line(&mut response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; // Convert to json and extract information let response: Value = serde_json::from_str(&response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; if response["rsp"].as_str().unwrap() == "error" { // The file couldn't be found Err(KytheError::FileNotFoundError(path.to_string()))
// Retrieve base64 content and convert to a Vec<u8> let content_option = args["content"].as_str(); if content_option.is_none() { return Ok(vec![]); } let content_base64: &str = content_option.unwrap(); let content: Vec<u8> = base64::decode(&content_base64).map_err(|err| { KytheError::IndexerError(format!( "Failed to convert base64 file contents response to bytes: {:?}", err )) })?; Ok(content) } } }
} else { let args: Value = response["args"].clone();
random_line_split
providers.rs
// Copyright 2020 The Kythe Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::error::KytheError; use crate::proxyrequests; use analysis_rust_proto::*; use serde_json::Value; use std::fs::File; use std::io::{self, BufReader, Read, Write}; use std::path::Path; use zip::ZipArchive; /// A trait for retrieving files during indexing. pub trait FileProvider { /// Checks whether a file exists and that the contents are available. /// /// This function takes a file path and digest, and returns whether /// the file exists and that the contents can be requested. /// /// # Errors /// /// If the file is not a valid zip archive, a [KytheError::KzipFileError] /// will be returned. fn exists(&mut self, path: &str, digest: &str) -> Result<bool, KytheError>; /// Retrieves the byte contents of a file. /// /// This function takes a file path and digest, and returns the bytes /// contents of the file in a vector. /// /// # Errors /// /// If the file does not exist, a /// [FileNotFoundError][KytheError::FileNotFoundError] will be returned. /// If the file can't be read, a [FileReadError][KytheError::FileReadError] /// will be returned. fn contents(&mut self, path: &str, digest: &str) -> Result<Vec<u8>, KytheError>; } /// A [FileProvider] that is backed by a.kzip file. pub struct KzipFileProvider { zip_archive: ZipArchive<BufReader<File>>, /// The top level folder name inside of the zip archive root_name: String, } impl KzipFileProvider { /// Create a new instance using a valid [File] object of a kzip /// file. /// /// # Errors /// /// If an error occurs while reading the kzip, a [KzipFileError] will be /// returned. pub fn new(file: File) -> Result<Self, KytheError> { let reader = BufReader::new(file); let mut zip_archive = ZipArchive::new(reader)?; // Get the name of the root folder of the kzip. This should be almost always be // "root" by the kzip spec doesn't guarantee it. let root_name = { let file = zip_archive.by_index(0)?; let mut path = Path::new(file.name()); while let Some(p) = path.parent() { // Last parent will be blank path so break when p is empty. path will contain // root if p == Path::new("") { break; } path = p; } // Safe to unwrap because kzip read would have failed if the internal paths // weren't UTF-8 path.to_str().unwrap().to_owned().replace('/', "") }; Ok(Self { zip_archive, root_name }) } /// Retrieve the Compilation Units from the kzip. /// /// This function will attempt to parse the proto files in the `pbunits` /// folder into Compilation Units, returning a Vector of them. /// /// # Errors /// /// If a file cannot be parsed, a /// [ProtobufParseError][KytheError::ProtobufParseError] will be returned. pub fn get_compilation_units(&mut self) -> Result<Vec<CompilationUnit>, KytheError> { let mut compilation_units = Vec::new(); for i in 0..self.zip_archive.len() { // Protobuf files are in the pbunits folder let file = self.zip_archive.by_index(i)?; if file.is_file() && file.name().contains("/pbunits/") { let mut reader = BufReader::new(file); let indexed_comp = protobuf::parse_from_reader::<IndexedCompilation>(&mut reader)?; compilation_units.push(indexed_comp.get_unit().clone()); } } Ok(compilation_units) } } impl FileProvider for KzipFileProvider { /// Given a file path and digest, returns whether the file exists in the /// kzip. fn exists(&mut self, _path: &str, digest: &str) -> Result<bool, KytheError> { let name = format!("{}/files/{}", self.root_name, digest); Ok(self.zip_archive.by_name(&name).is_ok()) } /// Given a file path and digest, returns the vector of bytes of the file /// from the kzip. /// /// # Errors /// /// An error will be returned if the file does not exist or cannot be read. fn contents(&mut self, _path: &str, digest: &str) -> Result<Vec<u8>, KytheError> { // Ensure the file exists in the kzip let name = format!("{}/files/{}", self.root_name, digest); let file = self.zip_archive.by_name(&name).map_err(|_| KytheError::FileNotFoundError(name))?; let mut reader = BufReader::new(file); let mut file_contents: Vec<u8> = Vec::new(); reader.read_to_end(&mut file_contents)?; Ok(file_contents) } } /// A [FileProvider] that backed by the analysis driver proxy pub struct ProxyFileProvider {} impl ProxyFileProvider { pub fn new() -> Self { Self {} } } impl Default for ProxyFileProvider { fn default() -> Self { Self::new() } } impl FileProvider for ProxyFileProvider { /// Given a file path and digest, returns whether the proxy can find the /// file. fn exists(&mut self, path: &str, digest: &str) -> Result<bool, KytheError> { // Submit the file request to the proxy let request = proxyrequests::file(path.to_string(), digest.to_string())?; println!("{}", request); io::stdout().flush().map_err(|err| { KytheError::IndexerError(format!("Failed to flush stdout: {:?}", err)) })?; // Read the response from the proxy let mut response_string = String::new(); io::stdin().read_line(&mut response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; // Convert to json and extract information let response: Value = serde_json::from_str(&response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; if response["rsp"].as_str().unwrap() == "error" { // The file couldn't be found Ok(false) } else { Ok(true) } } fn contents(&mut self, path: &str, digest: &str) -> Result<Vec<u8>, KytheError> { // Submit the file request to the proxy let request = proxyrequests::file(path.to_string(), digest.to_string())?; println!("{}", request); io::stdout().flush().map_err(|err| { KytheError::IndexerError(format!("Failed to flush stdout: {:?}", err)) })?; // Read the response from the proxy let mut response_string = String::new(); io::stdin().read_line(&mut response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; // Convert to json and extract information let response: Value = serde_json::from_str(&response_string).map_err(|err| { KytheError::IndexerError(format!( "Failed to read proxy file response from stdin: {:?}", err )) })?; if response["rsp"].as_str().unwrap() == "error" { // The file couldn't be found Err(KytheError::FileNotFoundError(path.to_string())) } else
} }
{ let args: Value = response["args"].clone(); // Retrieve base64 content and convert to a Vec<u8> let content_option = args["content"].as_str(); if content_option.is_none() { return Ok(vec![]); } let content_base64: &str = content_option.unwrap(); let content: Vec<u8> = base64::decode(&content_base64).map_err(|err| { KytheError::IndexerError(format!( "Failed to convert base64 file contents response to bytes: {:?}", err )) })?; Ok(content) }
conditional_block
binary.rs
use std::collections::HashMap; use std::hash::BuildHasherDefault; use std::io::{Read, Seek, SeekFrom}; use std::mem; use std::str; use std::time::{Duration, UNIX_EPOCH}; use fnv::FnvHasher; use plist::Plist; use result::{Result, Error}; #[inline] fn be_u16(buf: &[u8]) -> u16 { ((buf[0] as u16) << 8 | (buf[1] as u16)) } #[inline] fn be_u32(buf: &[u8]) -> u32 { ((buf[0] as u32) << 24 | (buf[1] as u32) << 16 | (buf[2] as u32) << 8 | (buf[3] as u32)) } #[inline] fn be_u64(buf: &[u8]) -> u64 { ((buf[0] as u64) << 56 | (buf[1] as u64) << 48 | (buf[2] as u64) << 40 | (buf[3] as u64) << 32 | (buf[4] as u64) << 24 | (buf[5] as u64) << 16 | (buf[6] as u64) << 8 | (buf[7] as u64)) } #[allow(unsafe_code)] #[inline] fn be_f32(buf: &[u8]) -> f32 { unsafe { mem::transmute(be_u32(buf)) } } #[allow(unsafe_code)] #[inline] fn be_f64(buf: &[u8]) -> f64 { unsafe { mem::transmute(be_u64(buf)) } } #[inline] fn validate_size(size: u8) -> Result<u8> { if (size & (!size + 1)) == size && size >> 4 == 0 { Ok(size) } else { return Err(Error::InvalidIntegerSize); } } #[inline] fn sized_int(buf: &[u8], size: u8) -> u64 { match size { 1 => buf[0] as u64, 2 => be_u16(buf) as u64, 4 => be_u32(buf) as u64, 8 => be_u64(buf), _ => panic!("Invalid integer size"), } } #[inline] fn
<R: Read>(input: &mut R, size: u8, count: usize) -> Result<Vec<u64>> { let len = size as usize * count; let mut buf = Vec::with_capacity(len); try!(input.take(len as u64).read_to_end(&mut buf)); Ok(buf.chunks(size as usize) .map(|x| sized_int(x, size)) .collect()) } #[inline] fn read_sized<R: Read>(input: &mut R) -> Result<([u8; 8], u8)> { let mut len = [0; 1]; let mut buf = [0; 8]; try!(input.read_exact(&mut len)); let size = try!(validate_size(1u8 << (len[0] & 0xF))); try!(input.read_exact(&mut buf[0..size as usize])); Ok((buf, size)) } #[inline] fn read_int<R: Read>(input: &mut R) -> Result<u64> { let mut buf = [0; 1]; try!(input.read_exact(&mut buf)); if (buf[0] & 0xF) == 0xF { let (buf, len) = try!(read_sized(input)); Ok(sized_int(&buf[..], len)) } else { Ok(u64::from(buf[0] & 0xF)) } } #[inline] fn trailer<R: Read + Seek>(input: &mut R) -> Result<(usize, u8, Vec<u64>)> { let mut trailer = [0; 26]; try!(input.seek(SeekFrom::End(-26))); try!(input.read_exact(&mut trailer)); let offset_size = try!(validate_size(trailer[0])); let ref_size = try!(validate_size(trailer[1])); let obj_count = be_u64(&trailer[2..]); let root = be_u64(&trailer[10..]) as usize; let table_offset = be_u64(&trailer[18..]); try!(input.seek(SeekFrom::Start(table_offset))); let offsets = try!(sized_ints(input, offset_size, obj_count as usize)); Ok((root, ref_size, offsets)) } #[inline] fn boolean<R: Read>(input: &mut R) -> Result<Plist> { let mut buf = [0; 1]; try!(input.read_exact(&mut buf)); match buf[0] & 0xF { 0x8 => Ok(Plist::Boolean(false)), 0x9 => Ok(Plist::Boolean(true)), _ => Err(Error::InvalidBoolean), } } #[inline] fn integer<R: Read + Seek>(input: &mut R) -> Result<Plist> { try!(input.seek(SeekFrom::Current(1))); Ok(Plist::Integer(try!(read_int(input)) as i64)) } #[inline] fn real<R: Read>(input: &mut R) -> Result<Plist> { let (buf, len) = try!(read_sized(input)); let real = match len { 4 => be_f32(&buf) as f64, 8 => be_f64(&buf), _ => return Err(Error::InvalidIntegerSize), }; Ok(Plist::Real(real)) } #[inline] fn date<R: Read>(input: &mut R) -> Result<Plist> { let mut buf = [0; 9]; try!(input.read_exact(&mut buf)); let secs = be_f64(&buf[1..]); let ref_date = UNIX_EPOCH + Duration::from_secs(978307200); let duration = Duration::new(secs.trunc() as u64, (secs.fract() * 10e9) as u32); Ok(Plist::DateTime(ref_date + duration)) } #[inline] fn data<R: Read>(input: &mut R) -> Result<Plist> { let len = try!(read_int(input)) as usize; let mut buf = Vec::with_capacity(len); try!(input.take(len as u64).read_to_end(&mut buf)); Ok(Plist::Data(buf)) } #[inline] fn string<R: Read>(input: &mut R) -> Result<Plist> { let len = try!(read_int(input)) as usize; let mut buf = Vec::with_capacity(len); try!(input.take(len as u64).read_to_end(&mut buf)); Ok(Plist::String(try!(String::from_utf8(buf)))) } #[inline] fn utf16_string<R: Read>(input: &mut R) -> Result<Plist> { let len = try!(read_int(input)) as usize; let mut buf = Vec::with_capacity(len * 2); try!(input.take((len * 2) as u64).read_to_end(&mut buf)); let points: Vec<u16> = buf.chunks(2).map(|x| be_u16(x)).collect(); Ok(Plist::String(try!(String::from_utf16(&points[..])))) } #[inline] fn array<R: Read + Seek>(input: &mut R, ref_size: u8, offsets: &Vec<u64>) -> Result<Plist> { let len = try!(read_int(input)) as usize; let values = try!(sized_ints(input, ref_size, len)); let mut array = Vec::with_capacity(len); for v in values { let value = try!(object(input, v as usize, ref_size, offsets)); array.push(value); } Ok(Plist::Array(array)) } #[inline] fn dict<R: Read + Seek>(input: &mut R, ref_size: u8, offsets: &Vec<u64>) -> Result<Plist> { let len = try!(read_int(input)) as usize; let keys = try!(sized_ints(input, ref_size, len)); let values = try!(sized_ints(input, ref_size, len)); let fnv = BuildHasherDefault::<FnvHasher>::default(); let mut dict = HashMap::with_capacity_and_hasher(len, fnv); for (k, v) in keys.into_iter().zip(values.into_iter()) { let key = match try!(object(input, k as usize, ref_size, offsets)) { Plist::String(s) => s, _ => return Err(Error::InvalidKeyObject), }; let value = try!(object(input, v as usize, ref_size, offsets)); dict.insert(key, value); } Ok(Plist::Dict(dict)) } fn object<R: Read + Seek>(input: &mut R, obj: usize, ref_size: u8, offsets: &Vec<u64>) -> Result<Plist> { let mut buf = [0; 1]; let offset = SeekFrom::Start(offsets[obj]); try!(input.seek(offset)); try!(input.read_exact(&mut buf)); try!(input.seek(offset)); let obj_type = buf[0] >> 4; match obj_type { 0x0 => boolean(input), 0x1 => integer(input), 0x2 => real(input), 0x3 => date(input), 0x4 => data(input), 0x5 => string(input), 0x6 => utf16_string(input), 0xA => array(input, ref_size, offsets), 0xD => dict(input, ref_size, offsets), _ => Err(Error::ObjectNotSupported(obj_type)), } } pub fn from_binary_reader<R: Read + Seek>(input: &mut R) -> Result<Plist> { try!(input.seek(SeekFrom::Start(0))); let mut magic = [0; 6]; try!(input.read_exact(&mut magic)); if let Ok(s) = str::from_utf8(&magic) { if s!= "bplist" { return Err(Error::InvalidMagicBytes); } } else { return Err(Error::InvalidMagicBytes); } let mut ver = [0; 2]; try!(input.read_exact(&mut ver)); if let Ok(s) = str::from_utf8(&ver) { if s!= "00" { return Err(Error::VersionNotSupported(Some(s.to_string()))); } } else { return Err(Error::VersionNotSupported(None)); } if let Ok((root, ref_size, offsets)) = trailer(input) { object(input, root, ref_size, &offsets) } else { Err(Error::InvalidTrailer) } }
sized_ints
identifier_name
binary.rs
use std::collections::HashMap; use std::hash::BuildHasherDefault; use std::io::{Read, Seek, SeekFrom}; use std::mem; use std::str; use std::time::{Duration, UNIX_EPOCH}; use fnv::FnvHasher; use plist::Plist; use result::{Result, Error}; #[inline] fn be_u16(buf: &[u8]) -> u16 { ((buf[0] as u16) << 8 | (buf[1] as u16)) } #[inline] fn be_u32(buf: &[u8]) -> u32 { ((buf[0] as u32) << 24 | (buf[1] as u32) << 16 | (buf[2] as u32) << 8 | (buf[3] as u32)) } #[inline] fn be_u64(buf: &[u8]) -> u64 { ((buf[0] as u64) << 56 | (buf[1] as u64) << 48 | (buf[2] as u64) << 40 | (buf[3] as u64) << 32 | (buf[4] as u64) << 24 | (buf[5] as u64) << 16 | (buf[6] as u64) << 8 | (buf[7] as u64)) } #[allow(unsafe_code)] #[inline] fn be_f32(buf: &[u8]) -> f32 { unsafe { mem::transmute(be_u32(buf)) } } #[allow(unsafe_code)] #[inline] fn be_f64(buf: &[u8]) -> f64 { unsafe { mem::transmute(be_u64(buf)) } } #[inline] fn validate_size(size: u8) -> Result<u8> { if (size & (!size + 1)) == size && size >> 4 == 0 { Ok(size) } else { return Err(Error::InvalidIntegerSize); } } #[inline] fn sized_int(buf: &[u8], size: u8) -> u64 { match size { 1 => buf[0] as u64, 2 => be_u16(buf) as u64, 4 => be_u32(buf) as u64, 8 => be_u64(buf), _ => panic!("Invalid integer size"), } } #[inline] fn sized_ints<R: Read>(input: &mut R, size: u8, count: usize) -> Result<Vec<u64>> { let len = size as usize * count; let mut buf = Vec::with_capacity(len); try!(input.take(len as u64).read_to_end(&mut buf)); Ok(buf.chunks(size as usize) .map(|x| sized_int(x, size)) .collect()) } #[inline] fn read_sized<R: Read>(input: &mut R) -> Result<([u8; 8], u8)> {
try!(input.read_exact(&mut len)); let size = try!(validate_size(1u8 << (len[0] & 0xF))); try!(input.read_exact(&mut buf[0..size as usize])); Ok((buf, size)) } #[inline] fn read_int<R: Read>(input: &mut R) -> Result<u64> { let mut buf = [0; 1]; try!(input.read_exact(&mut buf)); if (buf[0] & 0xF) == 0xF { let (buf, len) = try!(read_sized(input)); Ok(sized_int(&buf[..], len)) } else { Ok(u64::from(buf[0] & 0xF)) } } #[inline] fn trailer<R: Read + Seek>(input: &mut R) -> Result<(usize, u8, Vec<u64>)> { let mut trailer = [0; 26]; try!(input.seek(SeekFrom::End(-26))); try!(input.read_exact(&mut trailer)); let offset_size = try!(validate_size(trailer[0])); let ref_size = try!(validate_size(trailer[1])); let obj_count = be_u64(&trailer[2..]); let root = be_u64(&trailer[10..]) as usize; let table_offset = be_u64(&trailer[18..]); try!(input.seek(SeekFrom::Start(table_offset))); let offsets = try!(sized_ints(input, offset_size, obj_count as usize)); Ok((root, ref_size, offsets)) } #[inline] fn boolean<R: Read>(input: &mut R) -> Result<Plist> { let mut buf = [0; 1]; try!(input.read_exact(&mut buf)); match buf[0] & 0xF { 0x8 => Ok(Plist::Boolean(false)), 0x9 => Ok(Plist::Boolean(true)), _ => Err(Error::InvalidBoolean), } } #[inline] fn integer<R: Read + Seek>(input: &mut R) -> Result<Plist> { try!(input.seek(SeekFrom::Current(1))); Ok(Plist::Integer(try!(read_int(input)) as i64)) } #[inline] fn real<R: Read>(input: &mut R) -> Result<Plist> { let (buf, len) = try!(read_sized(input)); let real = match len { 4 => be_f32(&buf) as f64, 8 => be_f64(&buf), _ => return Err(Error::InvalidIntegerSize), }; Ok(Plist::Real(real)) } #[inline] fn date<R: Read>(input: &mut R) -> Result<Plist> { let mut buf = [0; 9]; try!(input.read_exact(&mut buf)); let secs = be_f64(&buf[1..]); let ref_date = UNIX_EPOCH + Duration::from_secs(978307200); let duration = Duration::new(secs.trunc() as u64, (secs.fract() * 10e9) as u32); Ok(Plist::DateTime(ref_date + duration)) } #[inline] fn data<R: Read>(input: &mut R) -> Result<Plist> { let len = try!(read_int(input)) as usize; let mut buf = Vec::with_capacity(len); try!(input.take(len as u64).read_to_end(&mut buf)); Ok(Plist::Data(buf)) } #[inline] fn string<R: Read>(input: &mut R) -> Result<Plist> { let len = try!(read_int(input)) as usize; let mut buf = Vec::with_capacity(len); try!(input.take(len as u64).read_to_end(&mut buf)); Ok(Plist::String(try!(String::from_utf8(buf)))) } #[inline] fn utf16_string<R: Read>(input: &mut R) -> Result<Plist> { let len = try!(read_int(input)) as usize; let mut buf = Vec::with_capacity(len * 2); try!(input.take((len * 2) as u64).read_to_end(&mut buf)); let points: Vec<u16> = buf.chunks(2).map(|x| be_u16(x)).collect(); Ok(Plist::String(try!(String::from_utf16(&points[..])))) } #[inline] fn array<R: Read + Seek>(input: &mut R, ref_size: u8, offsets: &Vec<u64>) -> Result<Plist> { let len = try!(read_int(input)) as usize; let values = try!(sized_ints(input, ref_size, len)); let mut array = Vec::with_capacity(len); for v in values { let value = try!(object(input, v as usize, ref_size, offsets)); array.push(value); } Ok(Plist::Array(array)) } #[inline] fn dict<R: Read + Seek>(input: &mut R, ref_size: u8, offsets: &Vec<u64>) -> Result<Plist> { let len = try!(read_int(input)) as usize; let keys = try!(sized_ints(input, ref_size, len)); let values = try!(sized_ints(input, ref_size, len)); let fnv = BuildHasherDefault::<FnvHasher>::default(); let mut dict = HashMap::with_capacity_and_hasher(len, fnv); for (k, v) in keys.into_iter().zip(values.into_iter()) { let key = match try!(object(input, k as usize, ref_size, offsets)) { Plist::String(s) => s, _ => return Err(Error::InvalidKeyObject), }; let value = try!(object(input, v as usize, ref_size, offsets)); dict.insert(key, value); } Ok(Plist::Dict(dict)) } fn object<R: Read + Seek>(input: &mut R, obj: usize, ref_size: u8, offsets: &Vec<u64>) -> Result<Plist> { let mut buf = [0; 1]; let offset = SeekFrom::Start(offsets[obj]); try!(input.seek(offset)); try!(input.read_exact(&mut buf)); try!(input.seek(offset)); let obj_type = buf[0] >> 4; match obj_type { 0x0 => boolean(input), 0x1 => integer(input), 0x2 => real(input), 0x3 => date(input), 0x4 => data(input), 0x5 => string(input), 0x6 => utf16_string(input), 0xA => array(input, ref_size, offsets), 0xD => dict(input, ref_size, offsets), _ => Err(Error::ObjectNotSupported(obj_type)), } } pub fn from_binary_reader<R: Read + Seek>(input: &mut R) -> Result<Plist> { try!(input.seek(SeekFrom::Start(0))); let mut magic = [0; 6]; try!(input.read_exact(&mut magic)); if let Ok(s) = str::from_utf8(&magic) { if s!= "bplist" { return Err(Error::InvalidMagicBytes); } } else { return Err(Error::InvalidMagicBytes); } let mut ver = [0; 2]; try!(input.read_exact(&mut ver)); if let Ok(s) = str::from_utf8(&ver) { if s!= "00" { return Err(Error::VersionNotSupported(Some(s.to_string()))); } } else { return Err(Error::VersionNotSupported(None)); } if let Ok((root, ref_size, offsets)) = trailer(input) { object(input, root, ref_size, &offsets) } else { Err(Error::InvalidTrailer) } }
let mut len = [0; 1]; let mut buf = [0; 8];
random_line_split
binary.rs
use std::collections::HashMap; use std::hash::BuildHasherDefault; use std::io::{Read, Seek, SeekFrom}; use std::mem; use std::str; use std::time::{Duration, UNIX_EPOCH}; use fnv::FnvHasher; use plist::Plist; use result::{Result, Error}; #[inline] fn be_u16(buf: &[u8]) -> u16 { ((buf[0] as u16) << 8 | (buf[1] as u16)) } #[inline] fn be_u32(buf: &[u8]) -> u32
#[inline] fn be_u64(buf: &[u8]) -> u64 { ((buf[0] as u64) << 56 | (buf[1] as u64) << 48 | (buf[2] as u64) << 40 | (buf[3] as u64) << 32 | (buf[4] as u64) << 24 | (buf[5] as u64) << 16 | (buf[6] as u64) << 8 | (buf[7] as u64)) } #[allow(unsafe_code)] #[inline] fn be_f32(buf: &[u8]) -> f32 { unsafe { mem::transmute(be_u32(buf)) } } #[allow(unsafe_code)] #[inline] fn be_f64(buf: &[u8]) -> f64 { unsafe { mem::transmute(be_u64(buf)) } } #[inline] fn validate_size(size: u8) -> Result<u8> { if (size & (!size + 1)) == size && size >> 4 == 0 { Ok(size) } else { return Err(Error::InvalidIntegerSize); } } #[inline] fn sized_int(buf: &[u8], size: u8) -> u64 { match size { 1 => buf[0] as u64, 2 => be_u16(buf) as u64, 4 => be_u32(buf) as u64, 8 => be_u64(buf), _ => panic!("Invalid integer size"), } } #[inline] fn sized_ints<R: Read>(input: &mut R, size: u8, count: usize) -> Result<Vec<u64>> { let len = size as usize * count; let mut buf = Vec::with_capacity(len); try!(input.take(len as u64).read_to_end(&mut buf)); Ok(buf.chunks(size as usize) .map(|x| sized_int(x, size)) .collect()) } #[inline] fn read_sized<R: Read>(input: &mut R) -> Result<([u8; 8], u8)> { let mut len = [0; 1]; let mut buf = [0; 8]; try!(input.read_exact(&mut len)); let size = try!(validate_size(1u8 << (len[0] & 0xF))); try!(input.read_exact(&mut buf[0..size as usize])); Ok((buf, size)) } #[inline] fn read_int<R: Read>(input: &mut R) -> Result<u64> { let mut buf = [0; 1]; try!(input.read_exact(&mut buf)); if (buf[0] & 0xF) == 0xF { let (buf, len) = try!(read_sized(input)); Ok(sized_int(&buf[..], len)) } else { Ok(u64::from(buf[0] & 0xF)) } } #[inline] fn trailer<R: Read + Seek>(input: &mut R) -> Result<(usize, u8, Vec<u64>)> { let mut trailer = [0; 26]; try!(input.seek(SeekFrom::End(-26))); try!(input.read_exact(&mut trailer)); let offset_size = try!(validate_size(trailer[0])); let ref_size = try!(validate_size(trailer[1])); let obj_count = be_u64(&trailer[2..]); let root = be_u64(&trailer[10..]) as usize; let table_offset = be_u64(&trailer[18..]); try!(input.seek(SeekFrom::Start(table_offset))); let offsets = try!(sized_ints(input, offset_size, obj_count as usize)); Ok((root, ref_size, offsets)) } #[inline] fn boolean<R: Read>(input: &mut R) -> Result<Plist> { let mut buf = [0; 1]; try!(input.read_exact(&mut buf)); match buf[0] & 0xF { 0x8 => Ok(Plist::Boolean(false)), 0x9 => Ok(Plist::Boolean(true)), _ => Err(Error::InvalidBoolean), } } #[inline] fn integer<R: Read + Seek>(input: &mut R) -> Result<Plist> { try!(input.seek(SeekFrom::Current(1))); Ok(Plist::Integer(try!(read_int(input)) as i64)) } #[inline] fn real<R: Read>(input: &mut R) -> Result<Plist> { let (buf, len) = try!(read_sized(input)); let real = match len { 4 => be_f32(&buf) as f64, 8 => be_f64(&buf), _ => return Err(Error::InvalidIntegerSize), }; Ok(Plist::Real(real)) } #[inline] fn date<R: Read>(input: &mut R) -> Result<Plist> { let mut buf = [0; 9]; try!(input.read_exact(&mut buf)); let secs = be_f64(&buf[1..]); let ref_date = UNIX_EPOCH + Duration::from_secs(978307200); let duration = Duration::new(secs.trunc() as u64, (secs.fract() * 10e9) as u32); Ok(Plist::DateTime(ref_date + duration)) } #[inline] fn data<R: Read>(input: &mut R) -> Result<Plist> { let len = try!(read_int(input)) as usize; let mut buf = Vec::with_capacity(len); try!(input.take(len as u64).read_to_end(&mut buf)); Ok(Plist::Data(buf)) } #[inline] fn string<R: Read>(input: &mut R) -> Result<Plist> { let len = try!(read_int(input)) as usize; let mut buf = Vec::with_capacity(len); try!(input.take(len as u64).read_to_end(&mut buf)); Ok(Plist::String(try!(String::from_utf8(buf)))) } #[inline] fn utf16_string<R: Read>(input: &mut R) -> Result<Plist> { let len = try!(read_int(input)) as usize; let mut buf = Vec::with_capacity(len * 2); try!(input.take((len * 2) as u64).read_to_end(&mut buf)); let points: Vec<u16> = buf.chunks(2).map(|x| be_u16(x)).collect(); Ok(Plist::String(try!(String::from_utf16(&points[..])))) } #[inline] fn array<R: Read + Seek>(input: &mut R, ref_size: u8, offsets: &Vec<u64>) -> Result<Plist> { let len = try!(read_int(input)) as usize; let values = try!(sized_ints(input, ref_size, len)); let mut array = Vec::with_capacity(len); for v in values { let value = try!(object(input, v as usize, ref_size, offsets)); array.push(value); } Ok(Plist::Array(array)) } #[inline] fn dict<R: Read + Seek>(input: &mut R, ref_size: u8, offsets: &Vec<u64>) -> Result<Plist> { let len = try!(read_int(input)) as usize; let keys = try!(sized_ints(input, ref_size, len)); let values = try!(sized_ints(input, ref_size, len)); let fnv = BuildHasherDefault::<FnvHasher>::default(); let mut dict = HashMap::with_capacity_and_hasher(len, fnv); for (k, v) in keys.into_iter().zip(values.into_iter()) { let key = match try!(object(input, k as usize, ref_size, offsets)) { Plist::String(s) => s, _ => return Err(Error::InvalidKeyObject), }; let value = try!(object(input, v as usize, ref_size, offsets)); dict.insert(key, value); } Ok(Plist::Dict(dict)) } fn object<R: Read + Seek>(input: &mut R, obj: usize, ref_size: u8, offsets: &Vec<u64>) -> Result<Plist> { let mut buf = [0; 1]; let offset = SeekFrom::Start(offsets[obj]); try!(input.seek(offset)); try!(input.read_exact(&mut buf)); try!(input.seek(offset)); let obj_type = buf[0] >> 4; match obj_type { 0x0 => boolean(input), 0x1 => integer(input), 0x2 => real(input), 0x3 => date(input), 0x4 => data(input), 0x5 => string(input), 0x6 => utf16_string(input), 0xA => array(input, ref_size, offsets), 0xD => dict(input, ref_size, offsets), _ => Err(Error::ObjectNotSupported(obj_type)), } } pub fn from_binary_reader<R: Read + Seek>(input: &mut R) -> Result<Plist> { try!(input.seek(SeekFrom::Start(0))); let mut magic = [0; 6]; try!(input.read_exact(&mut magic)); if let Ok(s) = str::from_utf8(&magic) { if s!= "bplist" { return Err(Error::InvalidMagicBytes); } } else { return Err(Error::InvalidMagicBytes); } let mut ver = [0; 2]; try!(input.read_exact(&mut ver)); if let Ok(s) = str::from_utf8(&ver) { if s!= "00" { return Err(Error::VersionNotSupported(Some(s.to_string()))); } } else { return Err(Error::VersionNotSupported(None)); } if let Ok((root, ref_size, offsets)) = trailer(input) { object(input, root, ref_size, &offsets) } else { Err(Error::InvalidTrailer) } }
{ ((buf[0] as u32) << 24 | (buf[1] as u32) << 16 | (buf[2] as u32) << 8 | (buf[3] as u32)) }
identifier_body
pubsub-async-io.rs
use async_lapin::*; use lapin::{ message::DeliveryResult, options::*, publisher_confirm::Confirmation, types::FieldTable, BasicProperties, Connection, ConnectionProperties, Result, }; use tracing::info; fn main() -> Result<()>
"hello", QueueDeclareOptions::default(), FieldTable::default(), ) .await?; info!(?queue, "Declared queue"); let consumer = channel_b .basic_consume( "hello", "my_consumer", BasicConsumeOptions::default(), FieldTable::default(), ) .await?; consumer.set_delegate(move |delivery: DeliveryResult| async move { let delivery = delivery.expect("error caught in in consumer"); if let Some(delivery) = delivery { delivery .ack(BasicAckOptions::default()) .await .expect("failed to ack"); } }); let payload = b"Hello world!"; loop { let confirm = channel_a .basic_publish( "", "hello", BasicPublishOptions::default(), payload.to_vec(), BasicProperties::default(), ) .await? .await?; assert_eq!(confirm, Confirmation::NotRequested); } }) }
{ if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "info"); } tracing_subscriber::fmt::init(); let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into()); async_io::block_on(async { let conn = Connection::connect(&addr, ConnectionProperties::default().with_async_io()).await?; info!("CONNECTED"); let channel_a = conn.create_channel().await?; let channel_b = conn.create_channel().await?; let queue = channel_a .queue_declare(
identifier_body
pubsub-async-io.rs
use async_lapin::*; use lapin::{ message::DeliveryResult, options::*, publisher_confirm::Confirmation, types::FieldTable, BasicProperties, Connection, ConnectionProperties, Result, }; use tracing::info; fn main() -> Result<()> { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "info"); } tracing_subscriber::fmt::init(); let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into()); async_io::block_on(async { let conn = Connection::connect(&addr, ConnectionProperties::default().with_async_io()).await?; info!("CONNECTED"); let channel_a = conn.create_channel().await?; let channel_b = conn.create_channel().await?; let queue = channel_a .queue_declare( "hello", QueueDeclareOptions::default(), FieldTable::default(), ) .await?; info!(?queue, "Declared queue"); let consumer = channel_b .basic_consume( "hello", "my_consumer", BasicConsumeOptions::default(), FieldTable::default(), ) .await?; consumer.set_delegate(move |delivery: DeliveryResult| async move { let delivery = delivery.expect("error caught in in consumer"); if let Some(delivery) = delivery
}); let payload = b"Hello world!"; loop { let confirm = channel_a .basic_publish( "", "hello", BasicPublishOptions::default(), payload.to_vec(), BasicProperties::default(), ) .await? .await?; assert_eq!(confirm, Confirmation::NotRequested); } }) }
{ delivery .ack(BasicAckOptions::default()) .await .expect("failed to ack"); }
conditional_block
pubsub-async-io.rs
use async_lapin::*; use lapin::{ message::DeliveryResult, options::*, publisher_confirm::Confirmation, types::FieldTable, BasicProperties, Connection, ConnectionProperties, Result, }; use tracing::info; fn main() -> Result<()> { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "info"); } tracing_subscriber::fmt::init(); let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into()); async_io::block_on(async { let conn = Connection::connect(&addr, ConnectionProperties::default().with_async_io()).await?; info!("CONNECTED"); let channel_a = conn.create_channel().await?; let channel_b = conn.create_channel().await?; let queue = channel_a .queue_declare( "hello", QueueDeclareOptions::default(), FieldTable::default(), ) .await?; info!(?queue, "Declared queue"); let consumer = channel_b .basic_consume( "hello", "my_consumer", BasicConsumeOptions::default(), FieldTable::default(), ) .await?; consumer.set_delegate(move |delivery: DeliveryResult| async move { let delivery = delivery.expect("error caught in in consumer"); if let Some(delivery) = delivery { delivery .ack(BasicAckOptions::default()) .await .expect("failed to ack"); }
let payload = b"Hello world!"; loop { let confirm = channel_a .basic_publish( "", "hello", BasicPublishOptions::default(), payload.to_vec(), BasicProperties::default(), ) .await? .await?; assert_eq!(confirm, Confirmation::NotRequested); } }) }
});
random_line_split
pubsub-async-io.rs
use async_lapin::*; use lapin::{ message::DeliveryResult, options::*, publisher_confirm::Confirmation, types::FieldTable, BasicProperties, Connection, ConnectionProperties, Result, }; use tracing::info; fn
() -> Result<()> { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "info"); } tracing_subscriber::fmt::init(); let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into()); async_io::block_on(async { let conn = Connection::connect(&addr, ConnectionProperties::default().with_async_io()).await?; info!("CONNECTED"); let channel_a = conn.create_channel().await?; let channel_b = conn.create_channel().await?; let queue = channel_a .queue_declare( "hello", QueueDeclareOptions::default(), FieldTable::default(), ) .await?; info!(?queue, "Declared queue"); let consumer = channel_b .basic_consume( "hello", "my_consumer", BasicConsumeOptions::default(), FieldTable::default(), ) .await?; consumer.set_delegate(move |delivery: DeliveryResult| async move { let delivery = delivery.expect("error caught in in consumer"); if let Some(delivery) = delivery { delivery .ack(BasicAckOptions::default()) .await .expect("failed to ack"); } }); let payload = b"Hello world!"; loop { let confirm = channel_a .basic_publish( "", "hello", BasicPublishOptions::default(), payload.to_vec(), BasicProperties::default(), ) .await? .await?; assert_eq!(confirm, Confirmation::NotRequested); } }) }
main
identifier_name
closure.rs
. The allocation strategy for this // closure depends on the closure type. For a sendfn, the closure // (and the referenced type descriptors) will be allocated in the // exchange heap. For a fn, the closure is allocated in the task heap // and is reference counted. For a block, the closure is allocated on // the stack. // // ## Opaque closures and the embedded type descriptor ## // // One interesting part of closures is that they encapsulate the data // that they close over. So when I have a ptr to a closure, I do not // know how many type descriptors it contains nor what upvars are // captured within. That means I do not know precisely how big it is // nor where its fields are located. This is called an "opaque // closure". // // Typically an opaque closure suffices because we only manipulate it // by ptr. The routine Type::at_box().ptr_to() returns an appropriate // type for such an opaque closure; it allows access to the box fields, // but not the closure_data itself. // // But sometimes, such as when cloning or freeing a closure, we need // to know the full information. That is where the type descriptor // that defines the closure comes in handy. We can use its take and // drop glue functions to allocate/free data as needed. // // ## Subtleties concerning alignment ## // // It is important that we be able to locate the closure data *without // knowing the kind of data that is being bound*. This can be tricky // because the alignment requirements of the bound data affects the // alignment requires of the closure_data struct as a whole. However, // right now this is a non-issue in any case, because the size of the // rust_opaque_box header is always a multiple of 16-bytes, which is // the maximum alignment requirement we ever have to worry about. // // The only reason alignment matters is that, in order to learn what data // is bound, we would normally first load the type descriptors: but their // location is ultimately depend on their content! There is, however, a // workaround. We can load the tydesc from the rust_opaque_box, which // describes the closure_data struct and has self-contained derived type // descriptors, and read the alignment from there. It's just annoying to // do. Hopefully should this ever become an issue we'll have monomorphized // and type descriptors will all be a bad dream. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pub struct EnvValue { action: freevars::CaptureMode, datum: Datum<Lvalue> } impl EnvValue { pub fn
(&self, ccx: &CrateContext) -> String { format!("{}({})", self.action, self.datum.to_string(ccx)) } } // Given a closure ty, emits a corresponding tuple ty pub fn mk_closure_tys(tcx: &ty::ctxt, bound_values: &[EnvValue]) -> ty::t { // determine the types of the values in the env. Note that this // is the actual types that will be stored in the map, not the // logical types as the user sees them, so by-ref upvars must be // converted to ptrs. let bound_tys = bound_values.iter().map(|bv| { match bv.action { freevars::CaptureByValue => bv.datum.ty, freevars::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty) } }).collect(); let cdata_ty = ty::mk_tup(tcx, bound_tys); debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty)); return cdata_ty; } fn tuplify_box_ty(tcx: &ty::ctxt, t: ty::t) -> ty::t { let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8()); ty::mk_tup(tcx, vec!(ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t)) } fn allocate_cbox<'a>(bcx: &'a Block<'a>, store: ty::TraitStore, cdata_ty: ty::t) -> Result<'a> { let _icx = push_ctxt("closure::allocate_cbox"); let tcx = bcx.tcx(); // Allocate and initialize the box: match store { ty::UniqTraitStore => { let ty = type_of(bcx.ccx(), cdata_ty); let size = llsize_of(bcx.ccx(), ty); // we treat proc as @ here, which isn't ideal malloc_raw_dyn_managed(bcx, cdata_ty, ClosureExchangeMallocFnLangItem, size) } ty::RegionTraitStore(..) => { let cbox_ty = tuplify_box_ty(tcx, cdata_ty); let llbox = alloc_ty(bcx, cbox_ty, "__closure"); Result::new(bcx, llbox) } } } pub struct ClosureResult<'a> { llbox: ValueRef, // llvalue of ptr to closure cdata_ty: ty::t, // type of the closure data bcx: &'a Block<'a> // final bcx } // Given a block context and a list of tydescs and values to bind // construct a closure out of them. If copying is true, it is a // heap allocated closure that copies the upvars into environment. // Otherwise, it is stack allocated and copies pointers to the upvars. pub fn store_environment<'a>( bcx: &'a Block<'a>, bound_values: Vec<EnvValue>, store: ty::TraitStore) -> ClosureResult<'a> { let _icx = push_ctxt("closure::store_environment"); let ccx = bcx.ccx(); let tcx = ccx.tcx(); // compute the type of the closure let cdata_ty = mk_closure_tys(tcx, bound_values.as_slice()); // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a // tuple. This could be a ptr in uniq or a box or on stack, // whatever. let cbox_ty = tuplify_box_ty(tcx, cdata_ty); let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable}); let llboxptr_ty = type_of(ccx, cboxptr_ty); // If there are no bound values, no point in allocating anything. if bound_values.is_empty() { return ClosureResult {llbox: C_null(llboxptr_ty), cdata_ty: cdata_ty, bcx: bcx}; } // allocate closure in the heap let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty); let llbox = PointerCast(bcx, llbox, llboxptr_ty); debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty)); // Copy expr values into boxed bindings. let mut bcx = bcx; for (i, bv) in bound_values.move_iter().enumerate() { debug!("Copy {} into closure", bv.to_string(ccx)); if ccx.sess().asm_comments() { add_comment(bcx, format!("Copy {} into closure", bv.to_string(ccx)).as_slice()); } let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]); match bv.action { freevars::CaptureByValue => { bcx = bv.datum.store_to(bcx, bound_data); } freevars::CaptureByRef => { Store(bcx, bv.datum.to_llref(), bound_data); } } } ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx } } // Given a context and a list of upvars, build a closure. This just // collects the upvars and packages them up for store_environment. fn build_closure<'a>(bcx0: &'a Block<'a>, freevar_mode: freevars::CaptureMode, freevars: &Vec<freevars::freevar_entry>, store: ty::TraitStore) -> ClosureResult<'a> { let _icx = push_ctxt("closure::build_closure"); // If we need to, package up the iterator body to call let bcx = bcx0; // Package up the captured upvars let mut env_vals = Vec::new(); for freevar in freevars.iter() { let datum = expr::trans_local_var(bcx, freevar.def); env_vals.push(EnvValue {action: freevar_mode, datum: datum}); } store_environment(bcx, env_vals, store) } // Given an enclosing block context, a new function context, a closure type, // and a list of upvars, generate code to load and populate the environment // with the upvars and type descriptors. fn load_environment<'a>(bcx: &'a Block<'a>, cdata_ty: ty::t, freevars: &Vec<freevars::freevar_entry>, store: ty::TraitStore) -> &'a Block<'a> { let _icx = push_ctxt("closure::load_environment"); // Don't bother to create the block if there's nothing to load if freevars.len() == 0 { return bcx; } // Load a pointer to the closure data, skipping over the box header: let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap()); // Store the pointer to closure data in an alloca for debug info because that's what the // llvm.dbg.declare intrinsic expects let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo { let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr"); Store(bcx, llcdata, alloc); Some(alloc) } else { None }; // Populate the upvars from the environment let mut i = 0u; for freevar in freevars.iter() { let mut upvarptr = GEPi(bcx, llcdata, [0u, i]); match store { ty::RegionTraitStore(..) => { upvarptr = Load(bcx, upvarptr); } ty::UniqTraitStore => {} } let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr); for &env_pointer_alloca in env_pointer_alloca.iter() { debuginfo::create_captured_var_metadata( bcx, def_id.node, cdata_ty, env_pointer_alloca, i, store, freevar.span); } i += 1u; } bcx } fn load_unboxed_closure_environment<'a>( bcx: &'a Block<'a>, freevars: &Vec<freevars::freevar_entry>) -> &'a Block<'a> { let _icx = push_ctxt("closure::load_environment"); if freevars.len() == 0 { return bcx } let llenv = bcx.fcx.llenv.unwrap(); for (i, freevar) in freevars.iter().enumerate() { let upvar_ptr = GEPi(bcx, llenv, [0, i]); let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr); } bcx } fn fill_fn_pair(bcx: &Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) { Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code])); let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx())); Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box])); } pub fn trans_expr_fn<'a>( bcx: &'a Block<'a>, store: ty::TraitStore, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> &'a Block<'a> { /*! * * Translates the body of a closure expression. * * - `store` * - `decl` * - `body` * - `id`: The id of the closure expression. * - `cap_clause`: information about captured variables, if any. * - `dest`: where to write the closure value, which must be a (fn ptr, env) pair */ let _icx = push_ctxt("closure::trans_expr_fn"); let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { return bcx; // closure construction is non-side-effecting } }; let ccx = bcx.ccx(); let tcx = bcx.tcx(); let fty = node_id_type(bcx, id); let s = tcx.map.with_path(id, |path| { mangle_internal_name_by_path_and_seq(path, "closure") }); let llfn = decl_internal_rust_fn(ccx, fty, s.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); let freevar_mode = freevars::get_capture_mode(tcx, id); let freevars: Vec<freevars::freevar_entry> = freevars::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect()); let ClosureResult { llbox, cdata_ty, bcx } = build_closure(bcx, freevar_mode, &freevars, store); trans_closure(ccx, decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(fty), ty::ty_fn_ret(fty), ty::ty_fn_abi(fty), true, NotUnboxedClosure, |bcx| load_environment(bcx, cdata_ty, &freevars, store)); fill_fn_pair(bcx, dest_addr, llfn, llbox); bcx } /// Returns the LLVM function declaration for an unboxed closure, creating it /// if necessary. If the ID does not correspond to a closure ID, returns None. pub fn get_or_create_declaration_if_unboxed_closure(ccx: &CrateContext, closure_id: ast::DefId) -> Option<ValueRef> { if!ccx.tcx.unboxed_closure_types.borrow().contains_key(&closure_id) { // Not an unboxed closure. return None } match ccx.unboxed_closure_vals.borrow().find(&closure_id) { Some(llfn) => { debug!("get_or_create_declaration_if_unboxed_closure(): found \ closure"); return Some(*llfn) } None => {} } let function_type = ty::mk_unboxed_closure(&ccx.tcx, closure_id); let symbol = ccx.tcx.map.with_path(closure_id.node, |path| { mangle_internal_name_by_path_and_seq(path, "unboxed_closure") }); let llfn = decl_internal_rust_fn(ccx, function_type, symbol.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \ closure {} (type {})", closure_id, ccx.tn.type_to_string(val_ty(llfn))); ccx.unboxed_closure_vals.borrow_mut().insert(closure_id, llfn); Some(llfn) } pub fn trans_unboxed_closure<'a>( mut bcx: &'a Block<'a>, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> &'a Block<'a> { let _icx = push_ctxt("closure::trans_unboxed_closure"); debug!("trans_unboxed_closure()"); let closure_id = ast_util::local_def(id); let llfn = get_or_create_declaration_if_unboxed_closure( bcx.ccx(), closure_id).unwrap(); // Untuple the arguments. let unboxed_closure_types = bcx.tcx().unboxed_closure_types.borrow(); let /*mut*/ function_type = (*unboxed_closure_types.get(&closure_id)).clone(); /*function_type.sig.inputs = match ty::get(*function_type.sig.inputs.get(0)).sty { ty::ty_tup(ref tuple_types) => { tuple_types.iter().map(|x| (*x).clone()).collect() } _ => { bcx.tcx().sess.span_bug(body.span, "unboxed closure wasn't a tuple?!") } };*/ let function_type = ty::mk_closure(bcx.tcx(), function_type); let freevars: Vec<freevars::freevar_entry> = freevars::with_freevars(bcx.tcx(), id, |fv| fv.iter().map(|&fv| fv).collect()); let freevars_ptr = &freevars; trans_closure(bcx.ccx(), decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(function_type), ty::ty_fn_ret(function_type), ty::ty_fn_abi(function_type), true, IsUnboxedClosure, |bcx| load_unboxed_closure_environment(bcx, freevars_ptr)); // Don't hoist this to the top of the function. It's perfectly legitimate // to have a zero-size unboxed closure (in which case dest will be // `Ignore`) and we must still generate the closure body. let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { debug!("trans_unboxed_closure() ignoring result"); return bcx } }; let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id)); // Create the closure. for freevar in freevars_ptr.iter() { let datum = expr::trans_local_var(bcx, freevar.def); let upvar_slot_dest = adt::trans_field_ptr(bcx, &*repr, dest_addr, 0, 0); bcx = datum.store_to(bcx, upvar_slot_dest); } adt::trans_set_discr(bcx, &*repr, dest_addr, 0); bcx } pub fn get_wrapper_for_bare_fn(ccx: &CrateContext, closure_ty: ty::t, def: def::Def, fn_ptr: ValueRef, is_local: bool) -> ValueRef { let def_id = match def { def::DefFn(did, _) | def::DefStaticMethod(did, _, _) | def::DefVariant(_, did, _) | def::DefStruct(did) => did, _ => { ccx.sess().bug(format!("get_wrapper_for_bare_fn: \ expected a statically resolved fn, got \
to_string
identifier_name
closure.rs
value> } impl EnvValue { pub fn to_string(&self, ccx: &CrateContext) -> String { format!("{}({})", self.action, self.datum.to_string(ccx)) } } // Given a closure ty, emits a corresponding tuple ty pub fn mk_closure_tys(tcx: &ty::ctxt, bound_values: &[EnvValue]) -> ty::t { // determine the types of the values in the env. Note that this // is the actual types that will be stored in the map, not the // logical types as the user sees them, so by-ref upvars must be // converted to ptrs. let bound_tys = bound_values.iter().map(|bv| { match bv.action { freevars::CaptureByValue => bv.datum.ty, freevars::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty) } }).collect(); let cdata_ty = ty::mk_tup(tcx, bound_tys); debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty)); return cdata_ty; } fn tuplify_box_ty(tcx: &ty::ctxt, t: ty::t) -> ty::t { let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8()); ty::mk_tup(tcx, vec!(ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t)) } fn allocate_cbox<'a>(bcx: &'a Block<'a>, store: ty::TraitStore, cdata_ty: ty::t) -> Result<'a> { let _icx = push_ctxt("closure::allocate_cbox"); let tcx = bcx.tcx(); // Allocate and initialize the box: match store { ty::UniqTraitStore => { let ty = type_of(bcx.ccx(), cdata_ty); let size = llsize_of(bcx.ccx(), ty); // we treat proc as @ here, which isn't ideal malloc_raw_dyn_managed(bcx, cdata_ty, ClosureExchangeMallocFnLangItem, size) } ty::RegionTraitStore(..) => { let cbox_ty = tuplify_box_ty(tcx, cdata_ty); let llbox = alloc_ty(bcx, cbox_ty, "__closure"); Result::new(bcx, llbox) } } } pub struct ClosureResult<'a> { llbox: ValueRef, // llvalue of ptr to closure cdata_ty: ty::t, // type of the closure data bcx: &'a Block<'a> // final bcx } // Given a block context and a list of tydescs and values to bind // construct a closure out of them. If copying is true, it is a // heap allocated closure that copies the upvars into environment. // Otherwise, it is stack allocated and copies pointers to the upvars. pub fn store_environment<'a>( bcx: &'a Block<'a>, bound_values: Vec<EnvValue>, store: ty::TraitStore) -> ClosureResult<'a> { let _icx = push_ctxt("closure::store_environment"); let ccx = bcx.ccx(); let tcx = ccx.tcx(); // compute the type of the closure let cdata_ty = mk_closure_tys(tcx, bound_values.as_slice()); // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a // tuple. This could be a ptr in uniq or a box or on stack, // whatever. let cbox_ty = tuplify_box_ty(tcx, cdata_ty); let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable}); let llboxptr_ty = type_of(ccx, cboxptr_ty); // If there are no bound values, no point in allocating anything. if bound_values.is_empty() { return ClosureResult {llbox: C_null(llboxptr_ty), cdata_ty: cdata_ty, bcx: bcx}; } // allocate closure in the heap let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty); let llbox = PointerCast(bcx, llbox, llboxptr_ty); debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty)); // Copy expr values into boxed bindings. let mut bcx = bcx; for (i, bv) in bound_values.move_iter().enumerate() { debug!("Copy {} into closure", bv.to_string(ccx)); if ccx.sess().asm_comments() { add_comment(bcx, format!("Copy {} into closure", bv.to_string(ccx)).as_slice()); } let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]); match bv.action { freevars::CaptureByValue => { bcx = bv.datum.store_to(bcx, bound_data); } freevars::CaptureByRef => { Store(bcx, bv.datum.to_llref(), bound_data); } } } ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx } } // Given a context and a list of upvars, build a closure. This just // collects the upvars and packages them up for store_environment. fn build_closure<'a>(bcx0: &'a Block<'a>, freevar_mode: freevars::CaptureMode, freevars: &Vec<freevars::freevar_entry>, store: ty::TraitStore) -> ClosureResult<'a> { let _icx = push_ctxt("closure::build_closure"); // If we need to, package up the iterator body to call let bcx = bcx0; // Package up the captured upvars let mut env_vals = Vec::new(); for freevar in freevars.iter() { let datum = expr::trans_local_var(bcx, freevar.def); env_vals.push(EnvValue {action: freevar_mode, datum: datum}); } store_environment(bcx, env_vals, store) } // Given an enclosing block context, a new function context, a closure type, // and a list of upvars, generate code to load and populate the environment // with the upvars and type descriptors. fn load_environment<'a>(bcx: &'a Block<'a>, cdata_ty: ty::t, freevars: &Vec<freevars::freevar_entry>, store: ty::TraitStore) -> &'a Block<'a> { let _icx = push_ctxt("closure::load_environment"); // Don't bother to create the block if there's nothing to load if freevars.len() == 0 { return bcx; } // Load a pointer to the closure data, skipping over the box header: let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap()); // Store the pointer to closure data in an alloca for debug info because that's what the // llvm.dbg.declare intrinsic expects let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo { let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr"); Store(bcx, llcdata, alloc); Some(alloc) } else { None }; // Populate the upvars from the environment let mut i = 0u; for freevar in freevars.iter() { let mut upvarptr = GEPi(bcx, llcdata, [0u, i]); match store { ty::RegionTraitStore(..) => { upvarptr = Load(bcx, upvarptr); } ty::UniqTraitStore => {} } let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr); for &env_pointer_alloca in env_pointer_alloca.iter() { debuginfo::create_captured_var_metadata( bcx, def_id.node, cdata_ty, env_pointer_alloca, i, store, freevar.span); } i += 1u; } bcx } fn load_unboxed_closure_environment<'a>( bcx: &'a Block<'a>, freevars: &Vec<freevars::freevar_entry>) -> &'a Block<'a> { let _icx = push_ctxt("closure::load_environment"); if freevars.len() == 0 { return bcx } let llenv = bcx.fcx.llenv.unwrap(); for (i, freevar) in freevars.iter().enumerate() { let upvar_ptr = GEPi(bcx, llenv, [0, i]); let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr); } bcx } fn fill_fn_pair(bcx: &Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) { Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code])); let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx())); Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box])); } pub fn trans_expr_fn<'a>( bcx: &'a Block<'a>, store: ty::TraitStore, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> &'a Block<'a> { /*! * * Translates the body of a closure expression. * * - `store` * - `decl` * - `body` * - `id`: The id of the closure expression. * - `cap_clause`: information about captured variables, if any. * - `dest`: where to write the closure value, which must be a (fn ptr, env) pair */ let _icx = push_ctxt("closure::trans_expr_fn"); let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { return bcx; // closure construction is non-side-effecting } }; let ccx = bcx.ccx(); let tcx = bcx.tcx(); let fty = node_id_type(bcx, id); let s = tcx.map.with_path(id, |path| { mangle_internal_name_by_path_and_seq(path, "closure") }); let llfn = decl_internal_rust_fn(ccx, fty, s.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); let freevar_mode = freevars::get_capture_mode(tcx, id); let freevars: Vec<freevars::freevar_entry> = freevars::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect()); let ClosureResult { llbox, cdata_ty, bcx } = build_closure(bcx, freevar_mode, &freevars, store); trans_closure(ccx, decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(fty), ty::ty_fn_ret(fty), ty::ty_fn_abi(fty), true, NotUnboxedClosure, |bcx| load_environment(bcx, cdata_ty, &freevars, store)); fill_fn_pair(bcx, dest_addr, llfn, llbox); bcx } /// Returns the LLVM function declaration for an unboxed closure, creating it /// if necessary. If the ID does not correspond to a closure ID, returns None. pub fn get_or_create_declaration_if_unboxed_closure(ccx: &CrateContext, closure_id: ast::DefId) -> Option<ValueRef> { if!ccx.tcx.unboxed_closure_types.borrow().contains_key(&closure_id) { // Not an unboxed closure. return None } match ccx.unboxed_closure_vals.borrow().find(&closure_id) { Some(llfn) => { debug!("get_or_create_declaration_if_unboxed_closure(): found \ closure"); return Some(*llfn) } None => {} } let function_type = ty::mk_unboxed_closure(&ccx.tcx, closure_id); let symbol = ccx.tcx.map.with_path(closure_id.node, |path| { mangle_internal_name_by_path_and_seq(path, "unboxed_closure") }); let llfn = decl_internal_rust_fn(ccx, function_type, symbol.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \ closure {} (type {})", closure_id, ccx.tn.type_to_string(val_ty(llfn))); ccx.unboxed_closure_vals.borrow_mut().insert(closure_id, llfn); Some(llfn) } pub fn trans_unboxed_closure<'a>( mut bcx: &'a Block<'a>, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> &'a Block<'a> { let _icx = push_ctxt("closure::trans_unboxed_closure"); debug!("trans_unboxed_closure()"); let closure_id = ast_util::local_def(id); let llfn = get_or_create_declaration_if_unboxed_closure( bcx.ccx(), closure_id).unwrap(); // Untuple the arguments. let unboxed_closure_types = bcx.tcx().unboxed_closure_types.borrow(); let /*mut*/ function_type = (*unboxed_closure_types.get(&closure_id)).clone(); /*function_type.sig.inputs = match ty::get(*function_type.sig.inputs.get(0)).sty { ty::ty_tup(ref tuple_types) => { tuple_types.iter().map(|x| (*x).clone()).collect() } _ => { bcx.tcx().sess.span_bug(body.span, "unboxed closure wasn't a tuple?!") } };*/ let function_type = ty::mk_closure(bcx.tcx(), function_type); let freevars: Vec<freevars::freevar_entry> = freevars::with_freevars(bcx.tcx(), id, |fv| fv.iter().map(|&fv| fv).collect()); let freevars_ptr = &freevars; trans_closure(bcx.ccx(), decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(function_type), ty::ty_fn_ret(function_type), ty::ty_fn_abi(function_type), true, IsUnboxedClosure, |bcx| load_unboxed_closure_environment(bcx, freevars_ptr)); // Don't hoist this to the top of the function. It's perfectly legitimate // to have a zero-size unboxed closure (in which case dest will be // `Ignore`) and we must still generate the closure body. let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { debug!("trans_unboxed_closure() ignoring result"); return bcx } }; let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id)); // Create the closure. for freevar in freevars_ptr.iter() { let datum = expr::trans_local_var(bcx, freevar.def); let upvar_slot_dest = adt::trans_field_ptr(bcx, &*repr, dest_addr, 0, 0); bcx = datum.store_to(bcx, upvar_slot_dest); } adt::trans_set_discr(bcx, &*repr, dest_addr, 0); bcx } pub fn get_wrapper_for_bare_fn(ccx: &CrateContext, closure_ty: ty::t, def: def::Def, fn_ptr: ValueRef, is_local: bool) -> ValueRef { let def_id = match def { def::DefFn(did, _) | def::DefStaticMethod(did, _, _) | def::DefVariant(_, did, _) | def::DefStruct(did) => did, _ => { ccx.sess().bug(format!("get_wrapper_for_bare_fn: \ expected a statically resolved fn, got \ {:?}", def).as_slice()); } }; match ccx.closure_bare_wrapper_cache.borrow().find(&fn_ptr) { Some(&llval) => return llval, None => {} } let tcx = ccx.tcx(); debug!("get_wrapper_for_bare_fn(closure_ty={})", closure_ty.repr(tcx)); let f = match ty::get(closure_ty).sty { ty::ty_closure(ref f) => f, _ => { ccx.sess().bug(format!("get_wrapper_for_bare_fn: \ expected a closure ty, got {}", closure_ty.repr(tcx)).as_slice()); } }; let name = ty::with_path(tcx, def_id, |path| { mangle_internal_name_by_path_and_seq(path, "as_closure") }); let llfn = if is_local { decl_internal_rust_fn(ccx, closure_ty, name.as_slice()) } else { decl_rust_fn(ccx, closure_ty, name.as_slice()) }; ccx.closure_bare_wrapper_cache.borrow_mut().insert(fn_ptr, llfn); // This is only used by statics inlined from a different crate. if!is_local
{ // Don't regenerate the wrapper, just reuse the original one. return llfn; }
conditional_block
closure.rs
. The allocation strategy for this // closure depends on the closure type. For a sendfn, the closure // (and the referenced type descriptors) will be allocated in the // exchange heap. For a fn, the closure is allocated in the task heap // and is reference counted. For a block, the closure is allocated on // the stack. // // ## Opaque closures and the embedded type descriptor ## // // One interesting part of closures is that they encapsulate the data // that they close over. So when I have a ptr to a closure, I do not // know how many type descriptors it contains nor what upvars are // captured within. That means I do not know precisely how big it is // nor where its fields are located. This is called an "opaque // closure". // // Typically an opaque closure suffices because we only manipulate it // by ptr. The routine Type::at_box().ptr_to() returns an appropriate // type for such an opaque closure; it allows access to the box fields, // but not the closure_data itself. // // But sometimes, such as when cloning or freeing a closure, we need // to know the full information. That is where the type descriptor // that defines the closure comes in handy. We can use its take and // drop glue functions to allocate/free data as needed. // // ## Subtleties concerning alignment ## // // It is important that we be able to locate the closure data *without // knowing the kind of data that is being bound*. This can be tricky // because the alignment requirements of the bound data affects the // alignment requires of the closure_data struct as a whole. However, // right now this is a non-issue in any case, because the size of the // rust_opaque_box header is always a multiple of 16-bytes, which is // the maximum alignment requirement we ever have to worry about. // // The only reason alignment matters is that, in order to learn what data // is bound, we would normally first load the type descriptors: but their // location is ultimately depend on their content! There is, however, a // workaround. We can load the tydesc from the rust_opaque_box, which // describes the closure_data struct and has self-contained derived type // descriptors, and read the alignment from there. It's just annoying to // do. Hopefully should this ever become an issue we'll have monomorphized // and type descriptors will all be a bad dream. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pub struct EnvValue { action: freevars::CaptureMode, datum: Datum<Lvalue> } impl EnvValue { pub fn to_string(&self, ccx: &CrateContext) -> String { format!("{}({})", self.action, self.datum.to_string(ccx)) } } // Given a closure ty, emits a corresponding tuple ty pub fn mk_closure_tys(tcx: &ty::ctxt, bound_values: &[EnvValue]) -> ty::t { // determine the types of the values in the env. Note that this // is the actual types that will be stored in the map, not the // logical types as the user sees them, so by-ref upvars must be // converted to ptrs. let bound_tys = bound_values.iter().map(|bv| { match bv.action { freevars::CaptureByValue => bv.datum.ty, freevars::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty) } }).collect(); let cdata_ty = ty::mk_tup(tcx, bound_tys); debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty)); return cdata_ty; } fn tuplify_box_ty(tcx: &ty::ctxt, t: ty::t) -> ty::t { let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8()); ty::mk_tup(tcx, vec!(ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t)) } fn allocate_cbox<'a>(bcx: &'a Block<'a>, store: ty::TraitStore, cdata_ty: ty::t) -> Result<'a> { let _icx = push_ctxt("closure::allocate_cbox"); let tcx = bcx.tcx(); // Allocate and initialize the box: match store { ty::UniqTraitStore => { let ty = type_of(bcx.ccx(), cdata_ty); let size = llsize_of(bcx.ccx(), ty); // we treat proc as @ here, which isn't ideal malloc_raw_dyn_managed(bcx, cdata_ty, ClosureExchangeMallocFnLangItem, size) } ty::RegionTraitStore(..) => { let cbox_ty = tuplify_box_ty(tcx, cdata_ty); let llbox = alloc_ty(bcx, cbox_ty, "__closure"); Result::new(bcx, llbox) } } } pub struct ClosureResult<'a> { llbox: ValueRef, // llvalue of ptr to closure cdata_ty: ty::t, // type of the closure data bcx: &'a Block<'a> // final bcx } // Given a block context and a list of tydescs and values to bind // construct a closure out of them. If copying is true, it is a // heap allocated closure that copies the upvars into environment. // Otherwise, it is stack allocated and copies pointers to the upvars. pub fn store_environment<'a>( bcx: &'a Block<'a>, bound_values: Vec<EnvValue>, store: ty::TraitStore) -> ClosureResult<'a> { let _icx = push_ctxt("closure::store_environment"); let ccx = bcx.ccx(); let tcx = ccx.tcx(); // compute the type of the closure let cdata_ty = mk_closure_tys(tcx, bound_values.as_slice()); // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a // tuple. This could be a ptr in uniq or a box or on stack, // whatever. let cbox_ty = tuplify_box_ty(tcx, cdata_ty); let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable}); let llboxptr_ty = type_of(ccx, cboxptr_ty); // If there are no bound values, no point in allocating anything. if bound_values.is_empty() { return ClosureResult {llbox: C_null(llboxptr_ty), cdata_ty: cdata_ty, bcx: bcx}; } // allocate closure in the heap let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty); let llbox = PointerCast(bcx, llbox, llboxptr_ty); debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty)); // Copy expr values into boxed bindings. let mut bcx = bcx; for (i, bv) in bound_values.move_iter().enumerate() { debug!("Copy {} into closure", bv.to_string(ccx)); if ccx.sess().asm_comments() { add_comment(bcx, format!("Copy {} into closure", bv.to_string(ccx)).as_slice()); } let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]); match bv.action { freevars::CaptureByValue => { bcx = bv.datum.store_to(bcx, bound_data); } freevars::CaptureByRef => { Store(bcx, bv.datum.to_llref(), bound_data); } } } ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx } } // Given a context and a list of upvars, build a closure. This just // collects the upvars and packages them up for store_environment. fn build_closure<'a>(bcx0: &'a Block<'a>, freevar_mode: freevars::CaptureMode, freevars: &Vec<freevars::freevar_entry>, store: ty::TraitStore) -> ClosureResult<'a> { let _icx = push_ctxt("closure::build_closure"); // If we need to, package up the iterator body to call let bcx = bcx0; // Package up the captured upvars let mut env_vals = Vec::new(); for freevar in freevars.iter() { let datum = expr::trans_local_var(bcx, freevar.def); env_vals.push(EnvValue {action: freevar_mode, datum: datum}); } store_environment(bcx, env_vals, store) } // Given an enclosing block context, a new function context, a closure type, // and a list of upvars, generate code to load and populate the environment // with the upvars and type descriptors. fn load_environment<'a>(bcx: &'a Block<'a>, cdata_ty: ty::t, freevars: &Vec<freevars::freevar_entry>, store: ty::TraitStore) -> &'a Block<'a> { let _icx = push_ctxt("closure::load_environment"); // Don't bother to create the block if there's nothing to load if freevars.len() == 0 { return bcx; } // Load a pointer to the closure data, skipping over the box header: let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap()); // Store the pointer to closure data in an alloca for debug info because that's what the // llvm.dbg.declare intrinsic expects let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo { let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr"); Store(bcx, llcdata, alloc); Some(alloc) } else { None }; // Populate the upvars from the environment let mut i = 0u; for freevar in freevars.iter() { let mut upvarptr = GEPi(bcx, llcdata, [0u, i]); match store { ty::RegionTraitStore(..) => { upvarptr = Load(bcx, upvarptr); } ty::UniqTraitStore => {} } let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr); for &env_pointer_alloca in env_pointer_alloca.iter() { debuginfo::create_captured_var_metadata( bcx, def_id.node, cdata_ty, env_pointer_alloca, i, store, freevar.span); } i += 1u; } bcx } fn load_unboxed_closure_environment<'a>( bcx: &'a Block<'a>, freevars: &Vec<freevars::freevar_entry>) -> &'a Block<'a>
fn fill_fn_pair(bcx: &Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) { Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code])); let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx())); Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box])); } pub fn trans_expr_fn<'a>( bcx: &'a Block<'a>, store: ty::TraitStore, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> &'a Block<'a> { /*! * * Translates the body of a closure expression. * * - `store` * - `decl` * - `body` * - `id`: The id of the closure expression. * - `cap_clause`: information about captured variables, if any. * - `dest`: where to write the closure value, which must be a (fn ptr, env) pair */ let _icx = push_ctxt("closure::trans_expr_fn"); let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { return bcx; // closure construction is non-side-effecting } }; let ccx = bcx.ccx(); let tcx = bcx.tcx(); let fty = node_id_type(bcx, id); let s = tcx.map.with_path(id, |path| { mangle_internal_name_by_path_and_seq(path, "closure") }); let llfn = decl_internal_rust_fn(ccx, fty, s.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); let freevar_mode = freevars::get_capture_mode(tcx, id); let freevars: Vec<freevars::freevar_entry> = freevars::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect()); let ClosureResult { llbox, cdata_ty, bcx } = build_closure(bcx, freevar_mode, &freevars, store); trans_closure(ccx, decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(fty), ty::ty_fn_ret(fty), ty::ty_fn_abi(fty), true, NotUnboxedClosure, |bcx| load_environment(bcx, cdata_ty, &freevars, store)); fill_fn_pair(bcx, dest_addr, llfn, llbox); bcx } /// Returns the LLVM function declaration for an unboxed closure, creating it /// if necessary. If the ID does not correspond to a closure ID, returns None. pub fn get_or_create_declaration_if_unboxed_closure(ccx: &CrateContext, closure_id: ast::DefId) -> Option<ValueRef> { if!ccx.tcx.unboxed_closure_types.borrow().contains_key(&closure_id) { // Not an unboxed closure. return None } match ccx.unboxed_closure_vals.borrow().find(&closure_id) { Some(llfn) => { debug!("get_or_create_declaration_if_unboxed_closure(): found \ closure"); return Some(*llfn) } None => {} } let function_type = ty::mk_unboxed_closure(&ccx.tcx, closure_id); let symbol = ccx.tcx.map.with_path(closure_id.node, |path| { mangle_internal_name_by_path_and_seq(path, "unboxed_closure") }); let llfn = decl_internal_rust_fn(ccx, function_type, symbol.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \ closure {} (type {})", closure_id, ccx.tn.type_to_string(val_ty(llfn))); ccx.unboxed_closure_vals.borrow_mut().insert(closure_id, llfn); Some(llfn) } pub fn trans_unboxed_closure<'a>( mut bcx: &'a Block<'a>, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> &'a Block<'a> { let _icx = push_ctxt("closure::trans_unboxed_closure"); debug!("trans_unboxed_closure()"); let closure_id = ast_util::local_def(id); let llfn = get_or_create_declaration_if_unboxed_closure( bcx.ccx(), closure_id).unwrap(); // Untuple the arguments. let unboxed_closure_types = bcx.tcx().unboxed_closure_types.borrow(); let /*mut*/ function_type = (*unboxed_closure_types.get(&closure_id)).clone(); /*function_type.sig.inputs = match ty::get(*function_type.sig.inputs.get(0)).sty { ty::ty_tup(ref tuple_types) => { tuple_types.iter().map(|x| (*x).clone()).collect() } _ => { bcx.tcx().sess.span_bug(body.span, "unboxed closure wasn't a tuple?!") } };*/ let function_type = ty::mk_closure(bcx.tcx(), function_type); let freevars: Vec<freevars::freevar_entry> = freevars::with_freevars(bcx.tcx(), id, |fv| fv.iter().map(|&fv| fv).collect()); let freevars_ptr = &freevars; trans_closure(bcx.ccx(), decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(function_type), ty::ty_fn_ret(function_type), ty::ty_fn_abi(function_type), true, IsUnboxedClosure, |bcx| load_unboxed_closure_environment(bcx, freevars_ptr)); // Don't hoist this to the top of the function. It's perfectly legitimate // to have a zero-size unboxed closure (in which case dest will be // `Ignore`) and we must still generate the closure body. let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { debug!("trans_unboxed_closure() ignoring result"); return bcx } }; let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id)); // Create the closure. for freevar in freevars_ptr.iter() { let datum = expr::trans_local_var(bcx, freevar.def); let upvar_slot_dest = adt::trans_field_ptr(bcx, &*repr, dest_addr, 0, 0); bcx = datum.store_to(bcx, upvar_slot_dest); } adt::trans_set_discr(bcx, &*repr, dest_addr, 0); bcx } pub fn get_wrapper_for_bare_fn(ccx: &CrateContext, closure_ty: ty::t, def: def::Def, fn_ptr: ValueRef, is_local: bool) -> ValueRef { let def_id = match def { def::DefFn(did, _) | def::DefStaticMethod(did, _, _) | def::DefVariant(_, did, _) | def::DefStruct(did) => did, _ => { ccx.sess().bug(format!("get_wrapper_for_bare_fn: \ expected a statically resolved fn, got \
{ let _icx = push_ctxt("closure::load_environment"); if freevars.len() == 0 { return bcx } let llenv = bcx.fcx.llenv.unwrap(); for (i, freevar) in freevars.iter().enumerate() { let upvar_ptr = GEPi(bcx, llenv, [0, i]); let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr); } bcx }
identifier_body
closure.rs
use middle::trans::machine::llsize_of; use middle::trans::type_of::*; use middle::trans::type_::Type; use middle::ty; use util::ppaux::Repr; use util::ppaux::ty_to_string; use arena::TypedArena; use syntax::ast; use syntax::ast_util; // ___Good to know (tm)__________________________________________________ // // The layout of a closure environment in memory is // roughly as follows: // // struct rust_opaque_box { // see rust_internal.h // unsigned ref_count; // obsolete (part of @T's header) // fn(void*) *drop_glue; // destructor (for proc) // rust_opaque_box *prev; // obsolete (part of @T's header) // rust_opaque_box *next; // obsolete (part of @T's header) // struct closure_data { // upvar1_t upvar1; // ... // upvarN_t upvarN; // } // }; // // Note that the closure is itself a rust_opaque_box. This is true // even for ~fn and ||, because we wish to keep binary compatibility // between all kinds of closures. The allocation strategy for this // closure depends on the closure type. For a sendfn, the closure // (and the referenced type descriptors) will be allocated in the // exchange heap. For a fn, the closure is allocated in the task heap // and is reference counted. For a block, the closure is allocated on // the stack. // // ## Opaque closures and the embedded type descriptor ## // // One interesting part of closures is that they encapsulate the data // that they close over. So when I have a ptr to a closure, I do not // know how many type descriptors it contains nor what upvars are // captured within. That means I do not know precisely how big it is // nor where its fields are located. This is called an "opaque // closure". // // Typically an opaque closure suffices because we only manipulate it // by ptr. The routine Type::at_box().ptr_to() returns an appropriate // type for such an opaque closure; it allows access to the box fields, // but not the closure_data itself. // // But sometimes, such as when cloning or freeing a closure, we need // to know the full information. That is where the type descriptor // that defines the closure comes in handy. We can use its take and // drop glue functions to allocate/free data as needed. // // ## Subtleties concerning alignment ## // // It is important that we be able to locate the closure data *without // knowing the kind of data that is being bound*. This can be tricky // because the alignment requirements of the bound data affects the // alignment requires of the closure_data struct as a whole. However, // right now this is a non-issue in any case, because the size of the // rust_opaque_box header is always a multiple of 16-bytes, which is // the maximum alignment requirement we ever have to worry about. // // The only reason alignment matters is that, in order to learn what data // is bound, we would normally first load the type descriptors: but their // location is ultimately depend on their content! There is, however, a // workaround. We can load the tydesc from the rust_opaque_box, which // describes the closure_data struct and has self-contained derived type // descriptors, and read the alignment from there. It's just annoying to // do. Hopefully should this ever become an issue we'll have monomorphized // and type descriptors will all be a bad dream. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pub struct EnvValue { action: freevars::CaptureMode, datum: Datum<Lvalue> } impl EnvValue { pub fn to_string(&self, ccx: &CrateContext) -> String { format!("{}({})", self.action, self.datum.to_string(ccx)) } } // Given a closure ty, emits a corresponding tuple ty pub fn mk_closure_tys(tcx: &ty::ctxt, bound_values: &[EnvValue]) -> ty::t { // determine the types of the values in the env. Note that this // is the actual types that will be stored in the map, not the // logical types as the user sees them, so by-ref upvars must be // converted to ptrs. let bound_tys = bound_values.iter().map(|bv| { match bv.action { freevars::CaptureByValue => bv.datum.ty, freevars::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty) } }).collect(); let cdata_ty = ty::mk_tup(tcx, bound_tys); debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty)); return cdata_ty; } fn tuplify_box_ty(tcx: &ty::ctxt, t: ty::t) -> ty::t { let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8()); ty::mk_tup(tcx, vec!(ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t)) } fn allocate_cbox<'a>(bcx: &'a Block<'a>, store: ty::TraitStore, cdata_ty: ty::t) -> Result<'a> { let _icx = push_ctxt("closure::allocate_cbox"); let tcx = bcx.tcx(); // Allocate and initialize the box: match store { ty::UniqTraitStore => { let ty = type_of(bcx.ccx(), cdata_ty); let size = llsize_of(bcx.ccx(), ty); // we treat proc as @ here, which isn't ideal malloc_raw_dyn_managed(bcx, cdata_ty, ClosureExchangeMallocFnLangItem, size) } ty::RegionTraitStore(..) => { let cbox_ty = tuplify_box_ty(tcx, cdata_ty); let llbox = alloc_ty(bcx, cbox_ty, "__closure"); Result::new(bcx, llbox) } } } pub struct ClosureResult<'a> { llbox: ValueRef, // llvalue of ptr to closure cdata_ty: ty::t, // type of the closure data bcx: &'a Block<'a> // final bcx } // Given a block context and a list of tydescs and values to bind // construct a closure out of them. If copying is true, it is a // heap allocated closure that copies the upvars into environment. // Otherwise, it is stack allocated and copies pointers to the upvars. pub fn store_environment<'a>( bcx: &'a Block<'a>, bound_values: Vec<EnvValue>, store: ty::TraitStore) -> ClosureResult<'a> { let _icx = push_ctxt("closure::store_environment"); let ccx = bcx.ccx(); let tcx = ccx.tcx(); // compute the type of the closure let cdata_ty = mk_closure_tys(tcx, bound_values.as_slice()); // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a // tuple. This could be a ptr in uniq or a box or on stack, // whatever. let cbox_ty = tuplify_box_ty(tcx, cdata_ty); let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable}); let llboxptr_ty = type_of(ccx, cboxptr_ty); // If there are no bound values, no point in allocating anything. if bound_values.is_empty() { return ClosureResult {llbox: C_null(llboxptr_ty), cdata_ty: cdata_ty, bcx: bcx}; } // allocate closure in the heap let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty); let llbox = PointerCast(bcx, llbox, llboxptr_ty); debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty)); // Copy expr values into boxed bindings. let mut bcx = bcx; for (i, bv) in bound_values.move_iter().enumerate() { debug!("Copy {} into closure", bv.to_string(ccx)); if ccx.sess().asm_comments() { add_comment(bcx, format!("Copy {} into closure", bv.to_string(ccx)).as_slice()); } let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]); match bv.action { freevars::CaptureByValue => { bcx = bv.datum.store_to(bcx, bound_data); } freevars::CaptureByRef => { Store(bcx, bv.datum.to_llref(), bound_data); } } } ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx } } // Given a context and a list of upvars, build a closure. This just // collects the upvars and packages them up for store_environment. fn build_closure<'a>(bcx0: &'a Block<'a>, freevar_mode: freevars::CaptureMode, freevars: &Vec<freevars::freevar_entry>, store: ty::TraitStore) -> ClosureResult<'a> { let _icx = push_ctxt("closure::build_closure"); // If we need to, package up the iterator body to call let bcx = bcx0; // Package up the captured upvars let mut env_vals = Vec::new(); for freevar in freevars.iter() { let datum = expr::trans_local_var(bcx, freevar.def); env_vals.push(EnvValue {action: freevar_mode, datum: datum}); } store_environment(bcx, env_vals, store) } // Given an enclosing block context, a new function context, a closure type, // and a list of upvars, generate code to load and populate the environment // with the upvars and type descriptors. fn load_environment<'a>(bcx: &'a Block<'a>, cdata_ty: ty::t, freevars: &Vec<freevars::freevar_entry>, store: ty::TraitStore) -> &'a Block<'a> { let _icx = push_ctxt("closure::load_environment"); // Don't bother to create the block if there's nothing to load if freevars.len() == 0 { return bcx; } // Load a pointer to the closure data, skipping over the box header: let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap()); // Store the pointer to closure data in an alloca for debug info because that's what the // llvm.dbg.declare intrinsic expects let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo { let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr"); Store(bcx, llcdata, alloc); Some(alloc) } else { None }; // Populate the upvars from the environment let mut i = 0u; for freevar in freevars.iter() { let mut upvarptr = GEPi(bcx, llcdata, [0u, i]); match store { ty::RegionTraitStore(..) => { upvarptr = Load(bcx, upvarptr); } ty::UniqTraitStore => {} } let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr); for &env_pointer_alloca in env_pointer_alloca.iter() { debuginfo::create_captured_var_metadata( bcx, def_id.node, cdata_ty, env_pointer_alloca, i, store, freevar.span); } i += 1u; } bcx } fn load_unboxed_closure_environment<'a>( bcx: &'a Block<'a>, freevars: &Vec<freevars::freevar_entry>) -> &'a Block<'a> { let _icx = push_ctxt("closure::load_environment"); if freevars.len() == 0 { return bcx } let llenv = bcx.fcx.llenv.unwrap(); for (i, freevar) in freevars.iter().enumerate() { let upvar_ptr = GEPi(bcx, llenv, [0, i]); let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr); } bcx } fn fill_fn_pair(bcx: &Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) { Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code])); let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx())); Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box])); } pub fn trans_expr_fn<'a>( bcx: &'a Block<'a>, store: ty::TraitStore, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> &'a Block<'a> { /*! * * Translates the body of a closure expression. * * - `store` * - `decl` * - `body` * - `id`: The id of the closure expression. * - `cap_clause`: information about captured variables, if any. * - `dest`: where to write the closure value, which must be a (fn ptr, env) pair */ let _icx = push_ctxt("closure::trans_expr_fn"); let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { return bcx; // closure construction is non-side-effecting } }; let ccx = bcx.ccx(); let tcx = bcx.tcx(); let fty = node_id_type(bcx, id); let s = tcx.map.with_path(id, |path| { mangle_internal_name_by_path_and_seq(path, "closure") }); let llfn = decl_internal_rust_fn(ccx, fty, s.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); let freevar_mode = freevars::get_capture_mode(tcx, id); let freevars: Vec<freevars::freevar_entry> = freevars::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect()); let ClosureResult { llbox, cdata_ty, bcx } = build_closure(bcx, freevar_mode, &freevars, store); trans_closure(ccx, decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(fty), ty::ty_fn_ret(fty), ty::ty_fn_abi(fty), true, NotUnboxedClosure, |bcx| load_environment(bcx, cdata_ty, &freevars, store)); fill_fn_pair(bcx, dest_addr, llfn, llbox); bcx } /// Returns the LLVM function declaration for an unboxed closure, creating it /// if necessary. If the ID does not correspond to a closure ID, returns None. pub fn get_or_create_declaration_if_unboxed_closure(ccx: &CrateContext, closure_id: ast::DefId) -> Option<ValueRef> { if!ccx.tcx.unboxed_closure_types.borrow().contains_key(&closure_id) { // Not an unboxed closure. return None } match ccx.unboxed_closure_vals.borrow().find(&closure_id) { Some(llfn) => { debug!("get_or_create_declaration_if_unboxed_closure(): found \ closure"); return Some(*llfn) } None => {} } let function_type = ty::mk_unboxed_closure(&ccx.tcx, closure_id); let symbol = ccx.tcx.map.with_path(closure_id.node, |path| { mangle_internal_name_by_path_and_seq(path, "unboxed_closure") }); let llfn = decl_internal_rust_fn(ccx, function_type, symbol.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \ closure {} (type {})", closure_id, ccx.tn.type_to_string(val_ty(llfn))); ccx.unboxed_closure_vals.borrow_mut().insert(closure_id, llfn); Some(llfn) } pub fn trans_unboxed_closure<'a>( mut bcx: &'a Block<'a>, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> &'a Block<'a> { let _icx = push_ctxt("closure::trans_unboxed_closure"); debug!("trans_unboxed_closure()"); let closure_id = ast_util::local_def(id); let llfn = get_or_create_declaration_if_unboxed_closure( bcx.ccx(), closure_id).unwrap(); // Untuple the arguments. let unboxed_closure_types = bcx.tcx().unboxed_closure_types.borrow(); let /*mut*/ function_type = (*unboxed_closure_types.get(&closure_id)).clone(); /*function_type.sig.inputs = match ty::get(*function_type.sig.inputs.get(0)).sty { ty::ty_tup(ref tuple_types) => { tuple_types.iter().map(|x| (*x).clone()).collect() } _ => { bcx.tcx().sess.span_bug(body.span, "unboxed closure wasn't a tuple?!") } };*/ let function_type = ty::mk_closure(bcx.tcx(), function_type); let freevars: Vec<freevars::freevar_entry> = freevars::with_freevars(bcx.tcx(), id, |fv| fv.iter().map(|&fv| fv).collect()); let freevars_ptr = &freevars; trans_closure(bcx.ccx(), decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(function_type), ty::ty_fn_ret(function_type), ty::ty_fn_abi(function_type), true, IsUnboxedClosure, |bcx| load_unboxed_closure_environment(bcx, freevars_ptr)); // Don't hoist this to the top of the function. It's perfectly legitimate // to have a zero-size unboxed closure (in which case dest will be // `Ignore`) and we must still generate the closure body. let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { debug!("trans_unboxed_closure() ignoring result"); return bcx } }; let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id)); // Create the closure. for freevar in freevars_ptr.iter() { let datum = expr::trans_local_var(bcx, freevar.def); let upvar_slot_dest = adt::trans_field_ptr(bcx, &*repr, dest_addr, 0, 0); bcx = datum.store_to(bcx, upvar_slot_dest); } adt::trans_set_discr(bcx, &*repr, dest_
random_line_split
writer.rs
use std::io::{Write, Result}; use std::path::Path; use std::fs::File; use std::iter; use std::collections::HashMap; use inflections::Inflect; use types::{Section, Documentation, Type}; macro_rules! w { ($w:ident) => { writeln!($w) }; ($w:ident, $indent:expr, $s:expr) => { writeln!($w, "{}{}", indent($indent), $s) }; ($w:ident, $indent:expr, $fmt:expr, $($arg:expr),+) => { writeln!($w, "{}{}", indent($indent), format!($fmt, $($arg),+)) }; } pub fn write<P: AsRef<Path>>(path: P, sections: Vec<Section>, mut types: HashMap<String, Type>) -> Result<()> { let mut file = File::create(path).expect("Unknown path"); write_internal(&mut file, sections, &mut types, 0) } fn write_internal<W: Write>(w: &mut W, sections: Vec<Section>, types: &mut HashMap<String, Type>, i: usize) -> Result<()> { let mut todos = Vec::new(); for Section { name, doc, typ } in sections { let Documentation { name: doc_name, documentation: doc, example: ex, parameters: params, since: since, notes: notes, returns: returns, } = doc; assert_eq!(name, doc_name, "Name and Doc-Name must equal"); // TODO: proper example let ex = ex.replace("\n##", "").replace("\n#", "\n")[1..].trim().to_string(); let ex = ex.replace("\n", &format!("\n{}///", indent(i))); w!(w, i, "/// {}", doc)?; w!(w, i, "///")?; w!(w, i, "/// Since qemu version {}", since)?; w!(w, i, "///")?; for note in notes { w!(w, i, "/// Note: {}", note)?; w!(w, i, "///")?; } let write_params = params.len() > 0; if write_params { w!(w, i, "/// # Parameters")?; w!(w, i, "///")?; } for (name, doc) in params { w!(w, i, "/// * {}: {}", name.to_snake_case(), doc)?; } if write_params { w!(w, i, "///")?; } if let Some(returns) = returns { w!(w, i, "/// # Returns {}", returns)?; w!(w, i, "///")?; } w!(w, i, "/// # Example")?; w!(w, i, "///")?; w!(w, i, "/// ```")?; w!(w, i, "/// {}", ex)?; w!(w, i, "/// ```")?; todos.extend(write_complex_type(w, name, typ, i)?); w!(w)?; } // write all missing while { let todos_new = match todos.pop().unwrap() { Todo::Existing(s) => { match types.remove(&s) { Some(typ) => write_complex_type(w, s.clone(), typ, 0)?, None => { println!("Let's just assume we already wrote {}", s); vec![] } } }, Todo::New(s, t) => write_complex_type(w, s, t, 0)?, }; todos.extend(todos_new); todos.len()!= 0 } {} Ok(()) }
New(String, Type), } fn write_complex_type<W: Write>(w: &mut W, type_name: String, typ: Type, indent: usize) -> Result<Vec<Todo>> { let mut todos = Vec::new(); match typ { Type::Enum(variants) => { w!(w, indent, "#[derive(Deserialize, Debug, PartialEq, Clone)]")?; w!(w, indent, "#[serde(rename = \"{}\")]", type_name)?; w!(w, indent, "pub enum {} {{", type_name.to_pascal_case())?; for variant in variants { w!(w, indent+4, "#[serde(rename = \"{}\")]", variant)?; w!(w, indent+4, "{},", variant.to_pascal_case())?; } w!(w, indent, "}")?; }, Type::Union(_, variants) => { w!(w, indent, "#[derive(Deserialize, Debug, PartialEq, Clone)]")?; w!(w, indent, "#[serde(rename = \"{}\")]", type_name)?; w!(w, indent, "pub enum {} {{", type_name.to_pascal_case())?; for (name, typ) in variants { w!(w, indent+4, "#[serde(rename = \"{}\")]", name)?; w!(w, indent+4, "{}({}),", name.to_pascal_case(), simple_type(typ, &mut todos).unwrap())?; } w!(w, indent, "}")?; }, Type::Map(map) => { w!(w, indent, "#[derive(Deserialize, Debug, PartialEq, Clone)]")?; w!(w, indent, "#[serde(rename = \"{}\")]", type_name)?; w!(w, indent, "pub struct {} {{", type_name.to_pascal_case())?; for (name, typ) in map { w!(w, indent+4, "#[serde(rename = \"{}\")]", name)?; if let Some(typ) = simple_type(typ.clone(), &mut todos) { w!(w, indent+4, "{}: {},", name.to_snake_case(), typ)?; } else { let new_name = type_name.to_pascal_case() + &name.to_pascal_case(); w!(w, indent+4, "{}: {},", name.to_snake_case(), new_name)?; todos.push(Todo::New(new_name, typ)); } } w!(w, indent, "}")?; }, _ => unreachable!() } Ok(todos) } fn simple_type(typ: Type, todos: &mut Vec<Todo>) -> Option<String> { match typ { Type::Bool => Some("bool".to_string()), Type::F64 => Some("f64".to_string()), Type::I8 => Some("i8".to_string()), Type::I16 => Some("i16".to_string()), Type::I32 => Some("i32".to_string()), Type::I64 => Some("i64".to_string()), Type::U8 => Some("u8".to_string()), Type::U16 => Some("u16".to_string()), Type::U32 => Some("u32".to_string()), Type::U64 => Some("u64".to_string()), Type::String => Some("String".to_string()), Type::Existing(name) => { todos.push(Todo::Existing(name.clone())); Some(name.to_pascal_case()) }, Type::Option(typ) => Some(format!("Option<{}>", simple_type(*typ, todos).unwrap())), Type::List(typ) => Some(format!("Vec<{}>", simple_type(*typ, todos).unwrap())), _ => None } } fn indent(indent: usize) -> String { iter::repeat(" ").take(indent).collect() }
enum Todo { Existing(String),
random_line_split
writer.rs
use std::io::{Write, Result}; use std::path::Path; use std::fs::File; use std::iter; use std::collections::HashMap; use inflections::Inflect; use types::{Section, Documentation, Type}; macro_rules! w { ($w:ident) => { writeln!($w) }; ($w:ident, $indent:expr, $s:expr) => { writeln!($w, "{}{}", indent($indent), $s) }; ($w:ident, $indent:expr, $fmt:expr, $($arg:expr),+) => { writeln!($w, "{}{}", indent($indent), format!($fmt, $($arg),+)) }; } pub fn
<P: AsRef<Path>>(path: P, sections: Vec<Section>, mut types: HashMap<String, Type>) -> Result<()> { let mut file = File::create(path).expect("Unknown path"); write_internal(&mut file, sections, &mut types, 0) } fn write_internal<W: Write>(w: &mut W, sections: Vec<Section>, types: &mut HashMap<String, Type>, i: usize) -> Result<()> { let mut todos = Vec::new(); for Section { name, doc, typ } in sections { let Documentation { name: doc_name, documentation: doc, example: ex, parameters: params, since: since, notes: notes, returns: returns, } = doc; assert_eq!(name, doc_name, "Name and Doc-Name must equal"); // TODO: proper example let ex = ex.replace("\n##", "").replace("\n#", "\n")[1..].trim().to_string(); let ex = ex.replace("\n", &format!("\n{}///", indent(i))); w!(w, i, "/// {}", doc)?; w!(w, i, "///")?; w!(w, i, "/// Since qemu version {}", since)?; w!(w, i, "///")?; for note in notes { w!(w, i, "/// Note: {}", note)?; w!(w, i, "///")?; } let write_params = params.len() > 0; if write_params { w!(w, i, "/// # Parameters")?; w!(w, i, "///")?; } for (name, doc) in params { w!(w, i, "/// * {}: {}", name.to_snake_case(), doc)?; } if write_params { w!(w, i, "///")?; } if let Some(returns) = returns { w!(w, i, "/// # Returns {}", returns)?; w!(w, i, "///")?; } w!(w, i, "/// # Example")?; w!(w, i, "///")?; w!(w, i, "/// ```")?; w!(w, i, "/// {}", ex)?; w!(w, i, "/// ```")?; todos.extend(write_complex_type(w, name, typ, i)?); w!(w)?; } // write all missing while { let todos_new = match todos.pop().unwrap() { Todo::Existing(s) => { match types.remove(&s) { Some(typ) => write_complex_type(w, s.clone(), typ, 0)?, None => { println!("Let's just assume we already wrote {}", s); vec![] } } }, Todo::New(s, t) => write_complex_type(w, s, t, 0)?, }; todos.extend(todos_new); todos.len()!= 0 } {} Ok(()) } enum Todo { Existing(String), New(String, Type), } fn write_complex_type<W: Write>(w: &mut W, type_name: String, typ: Type, indent: usize) -> Result<Vec<Todo>> { let mut todos = Vec::new(); match typ { Type::Enum(variants) => { w!(w, indent, "#[derive(Deserialize, Debug, PartialEq, Clone)]")?; w!(w, indent, "#[serde(rename = \"{}\")]", type_name)?; w!(w, indent, "pub enum {} {{", type_name.to_pascal_case())?; for variant in variants { w!(w, indent+4, "#[serde(rename = \"{}\")]", variant)?; w!(w, indent+4, "{},", variant.to_pascal_case())?; } w!(w, indent, "}")?; }, Type::Union(_, variants) => { w!(w, indent, "#[derive(Deserialize, Debug, PartialEq, Clone)]")?; w!(w, indent, "#[serde(rename = \"{}\")]", type_name)?; w!(w, indent, "pub enum {} {{", type_name.to_pascal_case())?; for (name, typ) in variants { w!(w, indent+4, "#[serde(rename = \"{}\")]", name)?; w!(w, indent+4, "{}({}),", name.to_pascal_case(), simple_type(typ, &mut todos).unwrap())?; } w!(w, indent, "}")?; }, Type::Map(map) => { w!(w, indent, "#[derive(Deserialize, Debug, PartialEq, Clone)]")?; w!(w, indent, "#[serde(rename = \"{}\")]", type_name)?; w!(w, indent, "pub struct {} {{", type_name.to_pascal_case())?; for (name, typ) in map { w!(w, indent+4, "#[serde(rename = \"{}\")]", name)?; if let Some(typ) = simple_type(typ.clone(), &mut todos) { w!(w, indent+4, "{}: {},", name.to_snake_case(), typ)?; } else { let new_name = type_name.to_pascal_case() + &name.to_pascal_case(); w!(w, indent+4, "{}: {},", name.to_snake_case(), new_name)?; todos.push(Todo::New(new_name, typ)); } } w!(w, indent, "}")?; }, _ => unreachable!() } Ok(todos) } fn simple_type(typ: Type, todos: &mut Vec<Todo>) -> Option<String> { match typ { Type::Bool => Some("bool".to_string()), Type::F64 => Some("f64".to_string()), Type::I8 => Some("i8".to_string()), Type::I16 => Some("i16".to_string()), Type::I32 => Some("i32".to_string()), Type::I64 => Some("i64".to_string()), Type::U8 => Some("u8".to_string()), Type::U16 => Some("u16".to_string()), Type::U32 => Some("u32".to_string()), Type::U64 => Some("u64".to_string()), Type::String => Some("String".to_string()), Type::Existing(name) => { todos.push(Todo::Existing(name.clone())); Some(name.to_pascal_case()) }, Type::Option(typ) => Some(format!("Option<{}>", simple_type(*typ, todos).unwrap())), Type::List(typ) => Some(format!("Vec<{}>", simple_type(*typ, todos).unwrap())), _ => None } } fn indent(indent: usize) -> String { iter::repeat(" ").take(indent).collect() }
write
identifier_name
writer.rs
use std::io::{Write, Result}; use std::path::Path; use std::fs::File; use std::iter; use std::collections::HashMap; use inflections::Inflect; use types::{Section, Documentation, Type}; macro_rules! w { ($w:ident) => { writeln!($w) }; ($w:ident, $indent:expr, $s:expr) => { writeln!($w, "{}{}", indent($indent), $s) }; ($w:ident, $indent:expr, $fmt:expr, $($arg:expr),+) => { writeln!($w, "{}{}", indent($indent), format!($fmt, $($arg),+)) }; } pub fn write<P: AsRef<Path>>(path: P, sections: Vec<Section>, mut types: HashMap<String, Type>) -> Result<()> { let mut file = File::create(path).expect("Unknown path"); write_internal(&mut file, sections, &mut types, 0) } fn write_internal<W: Write>(w: &mut W, sections: Vec<Section>, types: &mut HashMap<String, Type>, i: usize) -> Result<()> { let mut todos = Vec::new(); for Section { name, doc, typ } in sections { let Documentation { name: doc_name, documentation: doc, example: ex, parameters: params, since: since, notes: notes, returns: returns, } = doc; assert_eq!(name, doc_name, "Name and Doc-Name must equal"); // TODO: proper example let ex = ex.replace("\n##", "").replace("\n#", "\n")[1..].trim().to_string(); let ex = ex.replace("\n", &format!("\n{}///", indent(i))); w!(w, i, "/// {}", doc)?; w!(w, i, "///")?; w!(w, i, "/// Since qemu version {}", since)?; w!(w, i, "///")?; for note in notes { w!(w, i, "/// Note: {}", note)?; w!(w, i, "///")?; } let write_params = params.len() > 0; if write_params { w!(w, i, "/// # Parameters")?; w!(w, i, "///")?; } for (name, doc) in params { w!(w, i, "/// * {}: {}", name.to_snake_case(), doc)?; } if write_params { w!(w, i, "///")?; } if let Some(returns) = returns { w!(w, i, "/// # Returns {}", returns)?; w!(w, i, "///")?; } w!(w, i, "/// # Example")?; w!(w, i, "///")?; w!(w, i, "/// ```")?; w!(w, i, "/// {}", ex)?; w!(w, i, "/// ```")?; todos.extend(write_complex_type(w, name, typ, i)?); w!(w)?; } // write all missing while { let todos_new = match todos.pop().unwrap() { Todo::Existing(s) => { match types.remove(&s) { Some(typ) => write_complex_type(w, s.clone(), typ, 0)?, None => { println!("Let's just assume we already wrote {}", s); vec![] } } }, Todo::New(s, t) => write_complex_type(w, s, t, 0)?, }; todos.extend(todos_new); todos.len()!= 0 } {} Ok(()) } enum Todo { Existing(String), New(String, Type), } fn write_complex_type<W: Write>(w: &mut W, type_name: String, typ: Type, indent: usize) -> Result<Vec<Todo>> { let mut todos = Vec::new(); match typ { Type::Enum(variants) => { w!(w, indent, "#[derive(Deserialize, Debug, PartialEq, Clone)]")?; w!(w, indent, "#[serde(rename = \"{}\")]", type_name)?; w!(w, indent, "pub enum {} {{", type_name.to_pascal_case())?; for variant in variants { w!(w, indent+4, "#[serde(rename = \"{}\")]", variant)?; w!(w, indent+4, "{},", variant.to_pascal_case())?; } w!(w, indent, "}")?; }, Type::Union(_, variants) => { w!(w, indent, "#[derive(Deserialize, Debug, PartialEq, Clone)]")?; w!(w, indent, "#[serde(rename = \"{}\")]", type_name)?; w!(w, indent, "pub enum {} {{", type_name.to_pascal_case())?; for (name, typ) in variants { w!(w, indent+4, "#[serde(rename = \"{}\")]", name)?; w!(w, indent+4, "{}({}),", name.to_pascal_case(), simple_type(typ, &mut todos).unwrap())?; } w!(w, indent, "}")?; }, Type::Map(map) => { w!(w, indent, "#[derive(Deserialize, Debug, PartialEq, Clone)]")?; w!(w, indent, "#[serde(rename = \"{}\")]", type_name)?; w!(w, indent, "pub struct {} {{", type_name.to_pascal_case())?; for (name, typ) in map { w!(w, indent+4, "#[serde(rename = \"{}\")]", name)?; if let Some(typ) = simple_type(typ.clone(), &mut todos) { w!(w, indent+4, "{}: {},", name.to_snake_case(), typ)?; } else { let new_name = type_name.to_pascal_case() + &name.to_pascal_case(); w!(w, indent+4, "{}: {},", name.to_snake_case(), new_name)?; todos.push(Todo::New(new_name, typ)); } } w!(w, indent, "}")?; }, _ => unreachable!() } Ok(todos) } fn simple_type(typ: Type, todos: &mut Vec<Todo>) -> Option<String>
} } fn indent(indent: usize) -> String { iter::repeat(" ").take(indent).collect() }
{ match typ { Type::Bool => Some("bool".to_string()), Type::F64 => Some("f64".to_string()), Type::I8 => Some("i8".to_string()), Type::I16 => Some("i16".to_string()), Type::I32 => Some("i32".to_string()), Type::I64 => Some("i64".to_string()), Type::U8 => Some("u8".to_string()), Type::U16 => Some("u16".to_string()), Type::U32 => Some("u32".to_string()), Type::U64 => Some("u64".to_string()), Type::String => Some("String".to_string()), Type::Existing(name) => { todos.push(Todo::Existing(name.clone())); Some(name.to_pascal_case()) }, Type::Option(typ) => Some(format!("Option<{}>", simple_type(*typ, todos).unwrap())), Type::List(typ) => Some(format!("Vec<{}>", simple_type(*typ, todos).unwrap())), _ => None
identifier_body
encoding_support.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/. */ //! Parsing stylesheets from bytes (not `&str`). extern crate encoding; use context::QuirksMode; use cssparser::{stylesheet_encoding, EncodingSupport}; use error_reporting::ParseErrorReporter; use media_queries::MediaList; use self::encoding::{EncodingRef, DecoderTrap}; use shared_lock::SharedRwLock; use std::str; use stylearc::Arc; use stylesheets::{Stylesheet, StylesheetLoader, Origin, UrlExtraData}; struct RustEncoding; impl EncodingSupport for RustEncoding { type Encoding = EncodingRef; fn utf8() -> Self::Encoding { encoding::all::UTF_8 } fn is_utf16_be_or_le(encoding: &Self::Encoding) -> bool { matches!(encoding.name(), "utf-16be" | "utf-16le") } fn from_label(ascii_label: &[u8]) -> Option<Self::Encoding> { str::from_utf8(ascii_label).ok().and_then(encoding::label::encoding_from_whatwg_label) } } fn decode_stylesheet_bytes(css: &[u8], protocol_encoding_label: Option<&str>, environment_encoding: Option<EncodingRef>) -> (String, EncodingRef) { let fallback_encoding = stylesheet_encoding::<RustEncoding>( css, protocol_encoding_label.map(str::as_bytes), environment_encoding); let (result, used_encoding) = encoding::decode(css, DecoderTrap::Replace, fallback_encoding); (result.unwrap(), used_encoding) } impl Stylesheet { /// Parse a stylesheet from a set of bytes, potentially received over the /// network. /// /// Takes care of decoding the network bytes and forwards the resulting /// string to `Stylesheet::from_str`. pub fn from_bytes(bytes: &[u8], url_data: UrlExtraData, protocol_encoding_label: Option<&str>, environment_encoding: Option<EncodingRef>, origin: Origin, media: MediaList, shared_lock: SharedRwLock, stylesheet_loader: Option<&StylesheetLoader>, error_reporter: &ParseErrorReporter, quirks_mode: QuirksMode) -> Stylesheet { let (string, _) = decode_stylesheet_bytes( bytes, protocol_encoding_label, environment_encoding); Stylesheet::from_str(&string, url_data, origin, Arc::new(shared_lock.wrap(media)), shared_lock, stylesheet_loader, error_reporter, quirks_mode, 0u64) } /// Updates an empty stylesheet with a set of bytes that reached over the /// network. pub fn update_from_bytes(existing: &Stylesheet, bytes: &[u8], protocol_encoding_label: Option<&str>, environment_encoding: Option<EncodingRef>,
let (string, _) = decode_stylesheet_bytes( bytes, protocol_encoding_label, environment_encoding); Self::update_from_str(existing, &string, url_data, stylesheet_loader, error_reporter, 0) } }
url_data: UrlExtraData, stylesheet_loader: Option<&StylesheetLoader>, error_reporter: &ParseErrorReporter) {
random_line_split
encoding_support.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/. */ //! Parsing stylesheets from bytes (not `&str`). extern crate encoding; use context::QuirksMode; use cssparser::{stylesheet_encoding, EncodingSupport}; use error_reporting::ParseErrorReporter; use media_queries::MediaList; use self::encoding::{EncodingRef, DecoderTrap}; use shared_lock::SharedRwLock; use std::str; use stylearc::Arc; use stylesheets::{Stylesheet, StylesheetLoader, Origin, UrlExtraData}; struct RustEncoding; impl EncodingSupport for RustEncoding { type Encoding = EncodingRef; fn utf8() -> Self::Encoding { encoding::all::UTF_8 } fn
(encoding: &Self::Encoding) -> bool { matches!(encoding.name(), "utf-16be" | "utf-16le") } fn from_label(ascii_label: &[u8]) -> Option<Self::Encoding> { str::from_utf8(ascii_label).ok().and_then(encoding::label::encoding_from_whatwg_label) } } fn decode_stylesheet_bytes(css: &[u8], protocol_encoding_label: Option<&str>, environment_encoding: Option<EncodingRef>) -> (String, EncodingRef) { let fallback_encoding = stylesheet_encoding::<RustEncoding>( css, protocol_encoding_label.map(str::as_bytes), environment_encoding); let (result, used_encoding) = encoding::decode(css, DecoderTrap::Replace, fallback_encoding); (result.unwrap(), used_encoding) } impl Stylesheet { /// Parse a stylesheet from a set of bytes, potentially received over the /// network. /// /// Takes care of decoding the network bytes and forwards the resulting /// string to `Stylesheet::from_str`. pub fn from_bytes(bytes: &[u8], url_data: UrlExtraData, protocol_encoding_label: Option<&str>, environment_encoding: Option<EncodingRef>, origin: Origin, media: MediaList, shared_lock: SharedRwLock, stylesheet_loader: Option<&StylesheetLoader>, error_reporter: &ParseErrorReporter, quirks_mode: QuirksMode) -> Stylesheet { let (string, _) = decode_stylesheet_bytes( bytes, protocol_encoding_label, environment_encoding); Stylesheet::from_str(&string, url_data, origin, Arc::new(shared_lock.wrap(media)), shared_lock, stylesheet_loader, error_reporter, quirks_mode, 0u64) } /// Updates an empty stylesheet with a set of bytes that reached over the /// network. pub fn update_from_bytes(existing: &Stylesheet, bytes: &[u8], protocol_encoding_label: Option<&str>, environment_encoding: Option<EncodingRef>, url_data: UrlExtraData, stylesheet_loader: Option<&StylesheetLoader>, error_reporter: &ParseErrorReporter) { let (string, _) = decode_stylesheet_bytes( bytes, protocol_encoding_label, environment_encoding); Self::update_from_str(existing, &string, url_data, stylesheet_loader, error_reporter, 0) } }
is_utf16_be_or_le
identifier_name
noise_traits.rs
//! Noise sampling. use crate::{P2, P3}; use noise::NoiseFn; /// A trait for types which are sources of noise, samplable by type `P`. pub trait NoiseSrc<P> { /// Samples noise. fn noise(&self, p: P) -> f32; } impl<N> NoiseSrc<P2> for N where N: NoiseFn<[f64; 2]>, { fn noise(&self, p: P2) -> f32 { self.get([p.x as f64, p.y as f64]) as f32 } } impl<N> NoiseSrc<P3> for N where N: NoiseFn<[f64; 3]>, { fn
(&self, p: P3) -> f32 { self.get([p.x as f64, p.y as f64, p.z as f64]) as f32 } }
noise
identifier_name
noise_traits.rs
//! Noise sampling. use crate::{P2, P3}; use noise::NoiseFn; /// A trait for types which are sources of noise, samplable by type `P`.
fn noise(&self, p: P) -> f32; } impl<N> NoiseSrc<P2> for N where N: NoiseFn<[f64; 2]>, { fn noise(&self, p: P2) -> f32 { self.get([p.x as f64, p.y as f64]) as f32 } } impl<N> NoiseSrc<P3> for N where N: NoiseFn<[f64; 3]>, { fn noise(&self, p: P3) -> f32 { self.get([p.x as f64, p.y as f64, p.z as f64]) as f32 } }
pub trait NoiseSrc<P> { /// Samples noise.
random_line_split
noise_traits.rs
//! Noise sampling. use crate::{P2, P3}; use noise::NoiseFn; /// A trait for types which are sources of noise, samplable by type `P`. pub trait NoiseSrc<P> { /// Samples noise. fn noise(&self, p: P) -> f32; } impl<N> NoiseSrc<P2> for N where N: NoiseFn<[f64; 2]>, { fn noise(&self, p: P2) -> f32
} impl<N> NoiseSrc<P3> for N where N: NoiseFn<[f64; 3]>, { fn noise(&self, p: P3) -> f32 { self.get([p.x as f64, p.y as f64, p.z as f64]) as f32 } }
{ self.get([p.x as f64, p.y as f64]) as f32 }
identifier_body
domrect.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::DOMRectBinding; use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::num::Finite; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::window::Window; use util::geometry::Au; use std::num::Float; #[dom_struct] pub struct DOMRect { reflector_: Reflector, top: f32, bottom: f32, left: f32,
left: Au, right: Au) -> DOMRect { DOMRect { top: top.to_nearest_px() as f32, bottom: bottom.to_nearest_px() as f32, left: left.to_nearest_px() as f32, right: right.to_nearest_px() as f32, reflector_: Reflector::new(), } } pub fn new(window: JSRef<Window>, top: Au, bottom: Au, left: Au, right: Au) -> Temporary<DOMRect> { reflect_dom_object(box DOMRect::new_inherited(top, bottom, left, right), GlobalRef::Window(window), DOMRectBinding::Wrap) } } impl<'a> DOMRectMethods for JSRef<'a, DOMRect> { fn Top(self) -> Finite<f32> { Finite::wrap(self.top) } fn Bottom(self) -> Finite<f32> { Finite::wrap(self.bottom) } fn Left(self) -> Finite<f32> { Finite::wrap(self.left) } fn Right(self) -> Finite<f32> { Finite::wrap(self.right) } fn Width(self) -> Finite<f32> { let result = (self.right - self.left).abs(); Finite::wrap(result) } fn Height(self) -> Finite<f32> { let result = (self.bottom - self.top).abs(); Finite::wrap(result) } }
right: f32, } impl DOMRect { fn new_inherited(top: Au, bottom: Au,
random_line_split
domrect.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::DOMRectBinding; use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::num::Finite; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::window::Window; use util::geometry::Au; use std::num::Float; #[dom_struct] pub struct DOMRect { reflector_: Reflector, top: f32, bottom: f32, left: f32, right: f32, } impl DOMRect { fn new_inherited(top: Au, bottom: Au, left: Au, right: Au) -> DOMRect { DOMRect { top: top.to_nearest_px() as f32, bottom: bottom.to_nearest_px() as f32, left: left.to_nearest_px() as f32, right: right.to_nearest_px() as f32, reflector_: Reflector::new(), } } pub fn new(window: JSRef<Window>, top: Au, bottom: Au, left: Au, right: Au) -> Temporary<DOMRect> { reflect_dom_object(box DOMRect::new_inherited(top, bottom, left, right), GlobalRef::Window(window), DOMRectBinding::Wrap) } } impl<'a> DOMRectMethods for JSRef<'a, DOMRect> { fn Top(self) -> Finite<f32> { Finite::wrap(self.top) } fn Bottom(self) -> Finite<f32> { Finite::wrap(self.bottom) } fn Left(self) -> Finite<f32> { Finite::wrap(self.left) } fn Right(self) -> Finite<f32> { Finite::wrap(self.right) } fn
(self) -> Finite<f32> { let result = (self.right - self.left).abs(); Finite::wrap(result) } fn Height(self) -> Finite<f32> { let result = (self.bottom - self.top).abs(); Finite::wrap(result) } }
Width
identifier_name
domrect.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::DOMRectBinding; use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::num::Finite; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::window::Window; use util::geometry::Au; use std::num::Float; #[dom_struct] pub struct DOMRect { reflector_: Reflector, top: f32, bottom: f32, left: f32, right: f32, } impl DOMRect { fn new_inherited(top: Au, bottom: Au, left: Au, right: Au) -> DOMRect { DOMRect { top: top.to_nearest_px() as f32, bottom: bottom.to_nearest_px() as f32, left: left.to_nearest_px() as f32, right: right.to_nearest_px() as f32, reflector_: Reflector::new(), } } pub fn new(window: JSRef<Window>, top: Au, bottom: Au, left: Au, right: Au) -> Temporary<DOMRect> { reflect_dom_object(box DOMRect::new_inherited(top, bottom, left, right), GlobalRef::Window(window), DOMRectBinding::Wrap) } } impl<'a> DOMRectMethods for JSRef<'a, DOMRect> { fn Top(self) -> Finite<f32> { Finite::wrap(self.top) } fn Bottom(self) -> Finite<f32>
fn Left(self) -> Finite<f32> { Finite::wrap(self.left) } fn Right(self) -> Finite<f32> { Finite::wrap(self.right) } fn Width(self) -> Finite<f32> { let result = (self.right - self.left).abs(); Finite::wrap(result) } fn Height(self) -> Finite<f32> { let result = (self.bottom - self.top).abs(); Finite::wrap(result) } }
{ Finite::wrap(self.bottom) }
identifier_body
euler.rs
// Copyright 2016 The CGMath Developers. For a full listing of the authors, // refer to the Cargo.toml file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use num_traits::cast; #[cfg(feature = "rand")] use rand::{ distributions::{Distribution, Standard}, Rng, }; use structure::*; use angle::Rad; use approx; #[cfg(feature = "mint")] use mint; use num::BaseFloat; use quaternion::Quaternion; /// A set of [Euler angles] representing a rotation in three-dimensional space. /// /// This type is marked as `#[repr(C)]`. /// /// The axis rotation sequence is XYZ. That is, the rotation is first around /// the X axis, then the Y axis, and lastly the Z axis (using intrinsic /// rotations). Since all three rotation axes are used, the angles are /// Tait–Bryan angles rather than proper Euler angles. /// /// # Ranges /// /// - x: [-pi, pi] /// - y: [-pi/2, pi/2] /// - z: [-pi, pi] /// /// # Defining rotations using Euler angles /// /// Note that while [Euler angles] are intuitive to define, they are prone to /// [gimbal lock] and are challenging to interpolate between. Instead we /// recommend that you convert them to a more robust representation, such as a /// quaternion or a rotation matrix. To this end, `From<Euler<A>>` conversions /// are provided for the following types: /// /// - [`Basis3`](struct.Basis3.html) /// - [`Matrix3`](struct.Matrix3.html) /// - [`Matrix4`](struct.Matrix4.html) /// - [`Quaternion`](struct.Quaternion.html) /// /// For example, to define a quaternion that applies the following: /// /// 1. a 90° rotation around the _x_ axis /// 2. a 45° rotation around the _y_ axis /// 3. a 15° rotation around the _z_ axis /// /// you can use the following code: /// /// ``` /// use cgmath::{Deg, Euler, Quaternion}; /// /// let rotation = Quaternion::from(Euler { /// x: Deg(90.0), /// y: Deg(45.0), /// z: Deg(15.0), /// }); /// ``` /// /// [Euler angles]: https://en.wikipedia.org/wiki/Euler_angles /// [gimbal lock]: https://en.wikipedia.org/wiki/Gimbal_lock#Gimbal_lock_in_applied_mathematics /// [convert]: #defining-rotations-using-euler-angles #[repr(C)] #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Euler<A> { /// The angle to apply around the _x_ axis. Also known at the _pitch_. pub x: A, /// The angle to apply around the _y_ axis. Also known at the _yaw_. pub y: A, /// The angle to apply around the _z_ axis. Also known at the _roll_. pub z: A, } impl<A> Euler<A> { /// Construct a set of euler angles. /// /// # Arguments /// /// * `x` - The angle to apply around the _x_ axis. Also known at the _pitch_. /// * `y` - The angle to apply around the _y_ axis. Also known at the _yaw_. /// * `z` - The angle to apply around the _z_ axis. Also known at the _roll_. pub const fn new(x: A, y: A, z: A) -> Euler<A> { Euler { x, y, z } } } impl<S: BaseFloat> From<Quaternion<S>> for Euler<Rad<S>> { fn from(src: Quaternion<S>) -> Euler<Rad<S>> { let sig: S = cast(0.499).unwrap(); let two: S = cast(2).unwrap(); let one: S = cast(1).unwrap(); let (qw, qx, qy, qz) = (src.s, src.v.x, src.v.y, src.v.z); let (sqw, sqx, sqy, sqz) = (qw * qw, qx * qx, qy * qy, qz * qz); let unit = sqx + sqz + sqy + sqw; let test = qx * qz + qy * qw; // We set x to zero and z to the value, but the other way would work too. if test > sig * unit { // x + z = 2 * atan(x / w) Euler { x: Rad::zero(), y: Rad::turn_div_4(), z: Rad::atan2(qx, qw) * two, } } else if test < -sig * unit { // x - z = 2 * atan(x / w) Euler { x: Rad::zero(), y: -Rad::turn_div_4(), z: -Rad::atan2(qx, qw) * two, } } else { // Using the quat-to-matrix equation from either // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/index.htm // or equation 15 on page 7 of // http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770024290.pdf // to fill in the equations on page A-2 of the NASA document gives the below. Euler { x: Rad::atan2(two * (-qy * qz + qx * qw), one - two * (sqx + sqy)), y: Rad::asin(two * (qx * qz + qy * qw)), z: Rad::atan2(two * (-qx * qy + qz * qw), one - two * (sqy + sqz)), } } } } impl<A: Angle> approx::AbsDiffEq for Euler<A> { type Epsilon = A::Epsilon; #[inline] fn defau
A::Epsilon { A::default_epsilon() } #[inline] fn abs_diff_eq(&self, other: &Self, epsilon: A::Epsilon) -> bool { A::abs_diff_eq(&self.x, &other.x, epsilon) && A::abs_diff_eq(&self.y, &other.y, epsilon) && A::abs_diff_eq(&self.z, &other.z, epsilon) } } impl<A: Angle> approx::RelativeEq for Euler<A> { #[inline] fn default_max_relative() -> A::Epsilon { A::default_max_relative() } #[inline] fn relative_eq(&self, other: &Self, epsilon: A::Epsilon, max_relative: A::Epsilon) -> bool { A::relative_eq(&self.x, &other.x, epsilon, max_relative) && A::relative_eq(&self.y, &other.y, epsilon, max_relative) && A::relative_eq(&self.z, &other.z, epsilon, max_relative) } } impl<A: Angle> approx::UlpsEq for Euler<A> { #[inline] fn default_max_ulps() -> u32 { A::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &Self, epsilon: A::Epsilon, max_ulps: u32) -> bool { A::ulps_eq(&self.x, &other.x, epsilon, max_ulps) && A::ulps_eq(&self.y, &other.y, epsilon, max_ulps) && A::ulps_eq(&self.z, &other.z, epsilon, max_ulps) } } #[cfg(feature = "rand")] impl<A> Distribution<Euler<A>> for Standard where Standard: Distribution<A>, A: Angle, { fn sample<R: Rng +?Sized>(&self, rng: &mut R) -> Euler<A> { Euler { x: rng.gen(), y: rng.gen(), z: rng.gen(), } } } #[cfg(feature = "mint")] type MintEuler<S> = mint::EulerAngles<S, mint::IntraXYZ>; #[cfg(feature = "mint")] impl<S, A: Angle + From<S>> From<MintEuler<S>> for Euler<A> { fn from(mint: MintEuler<S>) -> Self { Euler { x: mint.a.into(), y: mint.b.into(), z: mint.c.into(), } } } #[cfg(feature = "mint")] impl<S: Clone, A: Angle + Into<S>> From<Euler<A>> for MintEuler<S> { fn from(v: Euler<A>) -> Self { MintEuler::from([v.x.into(), v.y.into(), v.z.into()]) } }
lt_epsilon() ->
identifier_name
euler.rs
// Copyright 2016 The CGMath Developers. For a full listing of the authors, // refer to the Cargo.toml file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use num_traits::cast; #[cfg(feature = "rand")] use rand::{ distributions::{Distribution, Standard}, Rng, }; use structure::*; use angle::Rad; use approx; #[cfg(feature = "mint")] use mint; use num::BaseFloat; use quaternion::Quaternion; /// A set of [Euler angles] representing a rotation in three-dimensional space. /// /// This type is marked as `#[repr(C)]`. /// /// The axis rotation sequence is XYZ. That is, the rotation is first around /// the X axis, then the Y axis, and lastly the Z axis (using intrinsic /// rotations). Since all three rotation axes are used, the angles are /// Tait–Bryan angles rather than proper Euler angles. /// /// # Ranges /// /// - x: [-pi, pi] /// - y: [-pi/2, pi/2] /// - z: [-pi, pi] /// /// # Defining rotations using Euler angles /// /// Note that while [Euler angles] are intuitive to define, they are prone to /// [gimbal lock] and are challenging to interpolate between. Instead we /// recommend that you convert them to a more robust representation, such as a /// quaternion or a rotation matrix. To this end, `From<Euler<A>>` conversions /// are provided for the following types: /// /// - [`Basis3`](struct.Basis3.html) /// - [`Matrix3`](struct.Matrix3.html) /// - [`Matrix4`](struct.Matrix4.html) /// - [`Quaternion`](struct.Quaternion.html) /// /// For example, to define a quaternion that applies the following: /// /// 1. a 90° rotation around the _x_ axis /// 2. a 45° rotation around the _y_ axis /// 3. a 15° rotation around the _z_ axis /// /// you can use the following code: /// /// ``` /// use cgmath::{Deg, Euler, Quaternion}; /// /// let rotation = Quaternion::from(Euler { /// x: Deg(90.0), /// y: Deg(45.0), /// z: Deg(15.0), /// }); /// ``` /// /// [Euler angles]: https://en.wikipedia.org/wiki/Euler_angles /// [gimbal lock]: https://en.wikipedia.org/wiki/Gimbal_lock#Gimbal_lock_in_applied_mathematics /// [convert]: #defining-rotations-using-euler-angles #[repr(C)] #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Euler<A> { /// The angle to apply around the _x_ axis. Also known at the _pitch_. pub x: A, /// The angle to apply around the _y_ axis. Also known at the _yaw_. pub y: A, /// The angle to apply around the _z_ axis. Also known at the _roll_. pub z: A, } impl<A> Euler<A> { /// Construct a set of euler angles. /// /// # Arguments /// /// * `x` - The angle to apply around the _x_ axis. Also known at the _pitch_. /// * `y` - The angle to apply around the _y_ axis. Also known at the _yaw_. /// * `z` - The angle to apply around the _z_ axis. Also known at the _roll_. pub const fn new(x: A, y: A, z: A) -> Euler<A> { Euler { x, y, z } } } impl<S: BaseFloat> From<Quaternion<S>> for Euler<Rad<S>> { fn from(src: Quaternion<S>) -> Euler<Rad<S>> { let sig: S = cast(0.499).unwrap(); let two: S = cast(2).unwrap(); let one: S = cast(1).unwrap(); let (qw, qx, qy, qz) = (src.s, src.v.x, src.v.y, src.v.z); let (sqw, sqx, sqy, sqz) = (qw * qw, qx * qx, qy * qy, qz * qz); let unit = sqx + sqz + sqy + sqw; let test = qx * qz + qy * qw; // We set x to zero and z to the value, but the other way would work too. if test > sig * unit { // x + z = 2 * atan(x / w) Euler { x: Rad::zero(), y: Rad::turn_div_4(), z: Rad::atan2(qx, qw) * two, } } else if test < -sig * unit { // x - z = 2 * atan(x / w) Euler { x: Rad::zero(), y: -Rad::turn_div_4(), z: -Rad::atan2(qx, qw) * two, } } else { // Using the quat-to-matrix equation from either // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/index.htm // or equation 15 on page 7 of // http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770024290.pdf // to fill in the equations on page A-2 of the NASA document gives the below. Euler { x: Rad::atan2(two * (-qy * qz + qx * qw), one - two * (sqx + sqy)), y: Rad::asin(two * (qx * qz + qy * qw)), z: Rad::atan2(two * (-qx * qy + qz * qw), one - two * (sqy + sqz)), } } } } impl<A: Angle> approx::AbsDiffEq for Euler<A> { type Epsilon = A::Epsilon; #[inline] fn default_epsilon() -> A::Epsilon { A::default_epsilon() } #[inline] fn abs_diff_eq(&self, other: &Self, epsilon: A::Epsilon) -> bool { A::abs_diff_eq(&self.x, &other.x, epsilon) && A::abs_diff_eq(&self.y, &other.y, epsilon) && A::abs_diff_eq(&self.z, &other.z, epsilon) } } impl<A: Angle> approx::RelativeEq for Euler<A> { #[inline] fn default_max_relative() -> A::Epsilon { A::default_max_relative() } #[inline] fn relative_eq(&self, other: &Self, epsilon: A::Epsilon, max_relative: A::Epsilon) -> bool { A::relative_eq(&self.x, &other.x, epsilon, max_relative) && A::relative_eq(&self.y, &other.y, epsilon, max_relative) && A::relative_eq(&self.z, &other.z, epsilon, max_relative) } } impl<A: Angle> approx::UlpsEq for Euler<A> { #[inline] fn default_max_ulps() -> u32 { A::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &Self, epsilon: A::Epsilon, max_ulps: u32) -> bool { A::ulps_eq(&self.x, &other.x, epsilon, max_ulps)
} #[cfg(feature = "rand")] impl<A> Distribution<Euler<A>> for Standard where Standard: Distribution<A>, A: Angle, { fn sample<R: Rng +?Sized>(&self, rng: &mut R) -> Euler<A> { Euler { x: rng.gen(), y: rng.gen(), z: rng.gen(), } } } #[cfg(feature = "mint")] type MintEuler<S> = mint::EulerAngles<S, mint::IntraXYZ>; #[cfg(feature = "mint")] impl<S, A: Angle + From<S>> From<MintEuler<S>> for Euler<A> { fn from(mint: MintEuler<S>) -> Self { Euler { x: mint.a.into(), y: mint.b.into(), z: mint.c.into(), } } } #[cfg(feature = "mint")] impl<S: Clone, A: Angle + Into<S>> From<Euler<A>> for MintEuler<S> { fn from(v: Euler<A>) -> Self { MintEuler::from([v.x.into(), v.y.into(), v.z.into()]) } }
&& A::ulps_eq(&self.y, &other.y, epsilon, max_ulps) && A::ulps_eq(&self.z, &other.z, epsilon, max_ulps) }
random_line_split
authority.rs
// Copyright 2015-2019 Benjamin Fry <[email protected]> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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 std::io; use std::pin::Pin; use std::task::{Context, Poll}; use futures::{future, Future, FutureExt}; use tokio::runtime::Handle; use trust_dns_client::op::LowerQuery; use trust_dns_client::op::ResponseCode; use trust_dns_client::rr::dnssec::SupportedAlgorithms; use trust_dns_client::rr::{LowerName, Name, Record, RecordType}; use trust_dns_resolver::config::ResolverConfig; use trust_dns_resolver::error::ResolveError; use trust_dns_resolver::lookup::Lookup as ResolverLookup; use trust_dns_resolver::TokioAsyncResolver; use crate::authority::{ Authority, LookupError, LookupObject, MessageRequest, UpdateResult, ZoneType, }; use crate::store::forwarder::ForwardConfig; /// An authority that will forward resolutions to upstream resolvers. /// /// This uses the trust-dns-resolver for resolving requests. pub struct ForwardAuthority { origin: LowerName, resolver: TokioAsyncResolver, } impl ForwardAuthority { /// TODO: change this name to create or something #[allow(clippy::new_without_default)] #[doc(hidden)]
Ok(ForwardAuthority { origin: Name::root().into(), resolver, }) } /// Read the Authority for the origin from the specified configuration pub async fn try_from_config( origin: Name, _zone_type: ZoneType, config: &ForwardConfig, runtime: Handle, ) -> Result<Self, String> { info!("loading forwarder config: {}", origin); let name_servers = config.name_servers.clone(); let options = config.options.unwrap_or_default(); let config = ResolverConfig::from_parts(None, vec![], name_servers); let resolver = TokioAsyncResolver::new(config, options, runtime) .map_err(|e| format!("error constructing new Resolver: {}", e))?; info!("forward resolver configured: {}: ", origin); // TODO: this might be infallible? Ok(ForwardAuthority { origin: origin.into(), resolver, }) } } impl Authority for ForwardAuthority { type Lookup = ForwardLookup; type LookupFuture = Pin<Box<dyn Future<Output = Result<Self::Lookup, LookupError>> + Send>>; /// Always Forward fn zone_type(&self) -> ZoneType { ZoneType::Forward } /// Always false for Forward zones fn is_axfr_allowed(&self) -> bool { false } fn update(&mut self, _update: &MessageRequest) -> UpdateResult<bool> { Err(ResponseCode::NotImp) } /// Get the origin of this zone, i.e. example.com is the origin for www.example.com /// /// In the context of a forwarder, this is either a zone which this forwarder is associated, /// or `.`, the root zone for all zones. If this is not the root zone, then it will only forward /// for lookups which match the given zone name. fn origin(&self) -> &LowerName { &self.origin } /// Forwards a lookup given the resolver configuration for this Forwarded zone fn lookup( &self, name: &LowerName, rtype: RecordType, _is_secure: bool, _supported_algorithms: SupportedAlgorithms, ) -> Pin<Box<dyn Future<Output = Result<Self::Lookup, LookupError>> + Send>> { // TODO: make this an error? assert!(self.origin.zone_of(name)); info!("forwarding lookup: {} {}", name, rtype); let name: LowerName = name.clone(); Box::pin(ForwardLookupFuture(self.resolver.lookup( name, rtype, Default::default(), ))) } fn search( &self, query: &LowerQuery, is_secure: bool, supported_algorithms: SupportedAlgorithms, ) -> Pin<Box<dyn Future<Output = Result<Self::Lookup, LookupError>> + Send>> { Box::pin(self.lookup( query.name(), query.query_type(), is_secure, supported_algorithms, )) } fn get_nsec_records( &self, _name: &LowerName, _is_secure: bool, _supported_algorithms: SupportedAlgorithms, ) -> Pin<Box<dyn Future<Output = Result<Self::Lookup, LookupError>> + Send>> { Box::pin(future::err(LookupError::from(io::Error::new( io::ErrorKind::Other, "Getting NSEC records is unimplemented for the forwarder", )))) } } pub struct ForwardLookup(ResolverLookup); impl LookupObject for ForwardLookup { fn is_empty(&self) -> bool { self.0.is_empty() } fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = &'a Record> + Send + 'a> { Box::new(self.0.record_iter()) } fn take_additionals(&mut self) -> Option<Box<dyn LookupObject>> { None } } pub struct ForwardLookupFuture< F: Future<Output = Result<ResolverLookup, ResolveError>> + Send + Unpin +'static, >(F); impl<F: Future<Output = Result<ResolverLookup, ResolveError>> + Send + Unpin> Future for ForwardLookupFuture<F> { type Output = Result<ForwardLookup, LookupError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { match self.0.poll_unpin(cx) { Poll::Ready(Ok(f)) => Poll::Ready(Ok(ForwardLookup(f))), Poll::Pending => Poll::Pending, Poll::Ready(Err(e)) => Poll::Ready(Err(e.into())), } } }
pub async fn new(runtime: Handle) -> Result<Self, String> { let resolver = TokioAsyncResolver::from_system_conf(runtime) .map_err(|e| format!("error constructing new Resolver: {}", e))?;
random_line_split
authority.rs
// Copyright 2015-2019 Benjamin Fry <[email protected]> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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 std::io; use std::pin::Pin; use std::task::{Context, Poll}; use futures::{future, Future, FutureExt}; use tokio::runtime::Handle; use trust_dns_client::op::LowerQuery; use trust_dns_client::op::ResponseCode; use trust_dns_client::rr::dnssec::SupportedAlgorithms; use trust_dns_client::rr::{LowerName, Name, Record, RecordType}; use trust_dns_resolver::config::ResolverConfig; use trust_dns_resolver::error::ResolveError; use trust_dns_resolver::lookup::Lookup as ResolverLookup; use trust_dns_resolver::TokioAsyncResolver; use crate::authority::{ Authority, LookupError, LookupObject, MessageRequest, UpdateResult, ZoneType, }; use crate::store::forwarder::ForwardConfig; /// An authority that will forward resolutions to upstream resolvers. /// /// This uses the trust-dns-resolver for resolving requests. pub struct
{ origin: LowerName, resolver: TokioAsyncResolver, } impl ForwardAuthority { /// TODO: change this name to create or something #[allow(clippy::new_without_default)] #[doc(hidden)] pub async fn new(runtime: Handle) -> Result<Self, String> { let resolver = TokioAsyncResolver::from_system_conf(runtime) .map_err(|e| format!("error constructing new Resolver: {}", e))?; Ok(ForwardAuthority { origin: Name::root().into(), resolver, }) } /// Read the Authority for the origin from the specified configuration pub async fn try_from_config( origin: Name, _zone_type: ZoneType, config: &ForwardConfig, runtime: Handle, ) -> Result<Self, String> { info!("loading forwarder config: {}", origin); let name_servers = config.name_servers.clone(); let options = config.options.unwrap_or_default(); let config = ResolverConfig::from_parts(None, vec![], name_servers); let resolver = TokioAsyncResolver::new(config, options, runtime) .map_err(|e| format!("error constructing new Resolver: {}", e))?; info!("forward resolver configured: {}: ", origin); // TODO: this might be infallible? Ok(ForwardAuthority { origin: origin.into(), resolver, }) } } impl Authority for ForwardAuthority { type Lookup = ForwardLookup; type LookupFuture = Pin<Box<dyn Future<Output = Result<Self::Lookup, LookupError>> + Send>>; /// Always Forward fn zone_type(&self) -> ZoneType { ZoneType::Forward } /// Always false for Forward zones fn is_axfr_allowed(&self) -> bool { false } fn update(&mut self, _update: &MessageRequest) -> UpdateResult<bool> { Err(ResponseCode::NotImp) } /// Get the origin of this zone, i.e. example.com is the origin for www.example.com /// /// In the context of a forwarder, this is either a zone which this forwarder is associated, /// or `.`, the root zone for all zones. If this is not the root zone, then it will only forward /// for lookups which match the given zone name. fn origin(&self) -> &LowerName { &self.origin } /// Forwards a lookup given the resolver configuration for this Forwarded zone fn lookup( &self, name: &LowerName, rtype: RecordType, _is_secure: bool, _supported_algorithms: SupportedAlgorithms, ) -> Pin<Box<dyn Future<Output = Result<Self::Lookup, LookupError>> + Send>> { // TODO: make this an error? assert!(self.origin.zone_of(name)); info!("forwarding lookup: {} {}", name, rtype); let name: LowerName = name.clone(); Box::pin(ForwardLookupFuture(self.resolver.lookup( name, rtype, Default::default(), ))) } fn search( &self, query: &LowerQuery, is_secure: bool, supported_algorithms: SupportedAlgorithms, ) -> Pin<Box<dyn Future<Output = Result<Self::Lookup, LookupError>> + Send>> { Box::pin(self.lookup( query.name(), query.query_type(), is_secure, supported_algorithms, )) } fn get_nsec_records( &self, _name: &LowerName, _is_secure: bool, _supported_algorithms: SupportedAlgorithms, ) -> Pin<Box<dyn Future<Output = Result<Self::Lookup, LookupError>> + Send>> { Box::pin(future::err(LookupError::from(io::Error::new( io::ErrorKind::Other, "Getting NSEC records is unimplemented for the forwarder", )))) } } pub struct ForwardLookup(ResolverLookup); impl LookupObject for ForwardLookup { fn is_empty(&self) -> bool { self.0.is_empty() } fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = &'a Record> + Send + 'a> { Box::new(self.0.record_iter()) } fn take_additionals(&mut self) -> Option<Box<dyn LookupObject>> { None } } pub struct ForwardLookupFuture< F: Future<Output = Result<ResolverLookup, ResolveError>> + Send + Unpin +'static, >(F); impl<F: Future<Output = Result<ResolverLookup, ResolveError>> + Send + Unpin> Future for ForwardLookupFuture<F> { type Output = Result<ForwardLookup, LookupError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { match self.0.poll_unpin(cx) { Poll::Ready(Ok(f)) => Poll::Ready(Ok(ForwardLookup(f))), Poll::Pending => Poll::Pending, Poll::Ready(Err(e)) => Poll::Ready(Err(e.into())), } } }
ForwardAuthority
identifier_name
lib.rs
#![feature(quote, plugin_registrar, rustc_private)] #![feature(tempdir, path, io, fs, process)] extern crate syntax; extern crate rustc; use std::path::{PathBuf, Path}; use std::fs::{self, TempDir, File}; use std::io; use std::io::prelude::*; use std::process::Command; use syntax::ast; use syntax::codemap; use syntax::ext::base::{self, ExtCtxt, MacResult}; use syntax::parse::{self, token}; use rustc::plugin::Registry; mod parser_any_macro; mod set_once; #[plugin_registrar] #[doc(hidden)] pub fn plugin_registrar(registrar: &mut Registry) { let dir = match TempDir::new("rustc_python_mixin") { Ok(d) => d, Err(e) => { registrar.sess.span_err(registrar.krate_span, &format!("could not create temporary directory: {}", e)); return; } }; registrar.register_syntax_extension(token::intern("python_mixin"), base::NormalTT(Box::new(Expander { dir: dir }), None)); } struct Expander { dir: TempDir } impl base::TTMacroExpander for Expander { fn expand<'cx>(&self, cx: &'cx mut ExtCtxt, sp: codemap::Span, raw_tts: &[ast::TokenTree]) -> Box<MacResult+'cx> { macro_rules! mac_try { ($run: expr, $p: pat => $($fmt: tt)+) => { match $run { Ok(x) => x, Err($p) => { cx.span_err(sp, &format!($($fmt)+)); return base::DummyResult::any(sp) } } } } let (tts, option_tts): (_, &[_]) = match raw_tts.get(0) { Some(&ast::TtDelimited(_, ref delim)) if delim.delim == token::Brace => { (&raw_tts[1..], &delim.tts[..]) } _ => (raw_tts, &[]) }; let opts = Options::parse(cx, option_tts); let code = match base::get_single_str_from_tts(cx, sp, tts, "`python_mixin!`") { Some(c) => c, None => return base::DummyResult::any(sp) }; let lo = tts[0].get_span().lo; let first_line = cx.codemap().lookup_char_pos(lo).line as u64; let filename = cx.codemap().span_to_filename(sp); let path = PathBuf::new(&filename); let name = if path.is_absolute() { Path::new(path.file_name().unwrap()) } else { &*path }; let python_file = self.dir.path().join(name); mac_try! { fs::create_dir_all(python_file.parent().unwrap()), e => "`python_mixin!` could not create temporary directory: {}", e } let file = mac_try!(File::create(&python_file), e => "`python_mixin!` could not create temporary file: {}", e); let mut file = io::BufWriter::new(file); mac_try!(io::copy(&mut io::repeat(b'\n').take(first_line - 1), &mut file), e => "`python_mixin!` could not write output: {}", e); mac_try!(file.write(code.as_bytes()), e => "`python_mixin!` could not write output: {}", e); mac_try!(file.flush(), e => "`python_mixin!` could not flush output: {}", e); let command_name = format!("python{}", opts.version); let output = Command::new(&command_name) .current_dir(self.dir.path()) .arg(name) .output(); let output = mac_try!(output, e => "`python_mixin!` could not execute `{}`: {}", command_name, e); if!output.status.success() { cx.span_err(sp, &format!("`python_mixin!` did not execute successfully: {}", output.status)); let msg = if output.stderr.is_empty() { "there was no output on stderr".to_string() } else { format!("the process emitted the following on stderr:\n{}", String::from_utf8_lossy(&output.stderr)) }; cx.parse_sess().span_diagnostic.fileline_note(sp, &msg); return base::DummyResult::any(sp); } else if!output.stderr.is_empty() { cx.span_warn(sp, "`python_mixin!` ran successfully, but had output on stderr"); let msg = format!("output:\n{}", String::from_utf8_lossy(&output.stderr)); cx.parse_sess().span_diagnostic.fileline_note(sp, &msg); } let emitted_code = mac_try!(String::from_utf8(output.stdout), e => "`python_mixin!` emitted invalid UTF-8: {}", e); let name = format!("<{}:{} python_mixin!>", filename, first_line); let parser = parse::new_parser_from_source_str(cx.parse_sess(), cx.cfg(), name, emitted_code); Box::new(parser_any_macro::ParserAnyMacro::new(parser)) } } const DEFAULT_VERSION: &'static str = ""; struct Options { version: String, }
let mut version = set_once::SetOnce::new(); let mut p = cx.new_parser_from_tts(tts); while p.token!= token::Eof { // <name> = "..." let ident = p.parse_ident(); let ident_span = p.last_span; match ident.as_str() { "version" => { p.expect(&token::Eq); let (s, _) = p.parse_str(); let span = codemap::mk_sp(ident_span.lo, p.last_span.hi); if let Err(&(_, older_span)) = version.set((s.to_string(), span)) { cx.span_err(span, &format!("`python_mixin!`: option `version` already set")); cx.span_note(older_span, "set here"); } } s => { cx.span_err(p.last_span, &format!("`python_mixing!`: unknown option `{}`", s)); // heuristically skip forward, so we can check // more things later. while p.token!= token::Comma { p.bump(); } } } if p.token == token::Eof { break } p.expect(&token::Comma); } Options { version: version.get().map_or_else(|| DEFAULT_VERSION.to_string(), |t| t.0), } } }
impl Options { fn parse(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> Options {
random_line_split
lib.rs
#![feature(quote, plugin_registrar, rustc_private)] #![feature(tempdir, path, io, fs, process)] extern crate syntax; extern crate rustc; use std::path::{PathBuf, Path}; use std::fs::{self, TempDir, File}; use std::io; use std::io::prelude::*; use std::process::Command; use syntax::ast; use syntax::codemap; use syntax::ext::base::{self, ExtCtxt, MacResult}; use syntax::parse::{self, token}; use rustc::plugin::Registry; mod parser_any_macro; mod set_once; #[plugin_registrar] #[doc(hidden)] pub fn plugin_registrar(registrar: &mut Registry)
struct Expander { dir: TempDir } impl base::TTMacroExpander for Expander { fn expand<'cx>(&self, cx: &'cx mut ExtCtxt, sp: codemap::Span, raw_tts: &[ast::TokenTree]) -> Box<MacResult+'cx> { macro_rules! mac_try { ($run: expr, $p: pat => $($fmt: tt)+) => { match $run { Ok(x) => x, Err($p) => { cx.span_err(sp, &format!($($fmt)+)); return base::DummyResult::any(sp) } } } } let (tts, option_tts): (_, &[_]) = match raw_tts.get(0) { Some(&ast::TtDelimited(_, ref delim)) if delim.delim == token::Brace => { (&raw_tts[1..], &delim.tts[..]) } _ => (raw_tts, &[]) }; let opts = Options::parse(cx, option_tts); let code = match base::get_single_str_from_tts(cx, sp, tts, "`python_mixin!`") { Some(c) => c, None => return base::DummyResult::any(sp) }; let lo = tts[0].get_span().lo; let first_line = cx.codemap().lookup_char_pos(lo).line as u64; let filename = cx.codemap().span_to_filename(sp); let path = PathBuf::new(&filename); let name = if path.is_absolute() { Path::new(path.file_name().unwrap()) } else { &*path }; let python_file = self.dir.path().join(name); mac_try! { fs::create_dir_all(python_file.parent().unwrap()), e => "`python_mixin!` could not create temporary directory: {}", e } let file = mac_try!(File::create(&python_file), e => "`python_mixin!` could not create temporary file: {}", e); let mut file = io::BufWriter::new(file); mac_try!(io::copy(&mut io::repeat(b'\n').take(first_line - 1), &mut file), e => "`python_mixin!` could not write output: {}", e); mac_try!(file.write(code.as_bytes()), e => "`python_mixin!` could not write output: {}", e); mac_try!(file.flush(), e => "`python_mixin!` could not flush output: {}", e); let command_name = format!("python{}", opts.version); let output = Command::new(&command_name) .current_dir(self.dir.path()) .arg(name) .output(); let output = mac_try!(output, e => "`python_mixin!` could not execute `{}`: {}", command_name, e); if!output.status.success() { cx.span_err(sp, &format!("`python_mixin!` did not execute successfully: {}", output.status)); let msg = if output.stderr.is_empty() { "there was no output on stderr".to_string() } else { format!("the process emitted the following on stderr:\n{}", String::from_utf8_lossy(&output.stderr)) }; cx.parse_sess().span_diagnostic.fileline_note(sp, &msg); return base::DummyResult::any(sp); } else if!output.stderr.is_empty() { cx.span_warn(sp, "`python_mixin!` ran successfully, but had output on stderr"); let msg = format!("output:\n{}", String::from_utf8_lossy(&output.stderr)); cx.parse_sess().span_diagnostic.fileline_note(sp, &msg); } let emitted_code = mac_try!(String::from_utf8(output.stdout), e => "`python_mixin!` emitted invalid UTF-8: {}", e); let name = format!("<{}:{} python_mixin!>", filename, first_line); let parser = parse::new_parser_from_source_str(cx.parse_sess(), cx.cfg(), name, emitted_code); Box::new(parser_any_macro::ParserAnyMacro::new(parser)) } } const DEFAULT_VERSION: &'static str = ""; struct Options { version: String, } impl Options { fn parse(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> Options { let mut version = set_once::SetOnce::new(); let mut p = cx.new_parser_from_tts(tts); while p.token!= token::Eof { // <name> = "..." let ident = p.parse_ident(); let ident_span = p.last_span; match ident.as_str() { "version" => { p.expect(&token::Eq); let (s, _) = p.parse_str(); let span = codemap::mk_sp(ident_span.lo, p.last_span.hi); if let Err(&(_, older_span)) = version.set((s.to_string(), span)) { cx.span_err(span, &format!("`python_mixin!`: option `version` already set")); cx.span_note(older_span, "set here"); } } s => { cx.span_err(p.last_span, &format!("`python_mixing!`: unknown option `{}`", s)); // heuristically skip forward, so we can check // more things later. while p.token!= token::Comma { p.bump(); } } } if p.token == token::Eof { break } p.expect(&token::Comma); } Options { version: version.get().map_or_else(|| DEFAULT_VERSION.to_string(), |t| t.0), } } }
{ let dir = match TempDir::new("rustc_python_mixin") { Ok(d) => d, Err(e) => { registrar.sess.span_err(registrar.krate_span, &format!("could not create temporary directory: {}", e)); return; } }; registrar.register_syntax_extension(token::intern("python_mixin"), base::NormalTT(Box::new(Expander { dir: dir }), None)); }
identifier_body
lib.rs
#![feature(quote, plugin_registrar, rustc_private)] #![feature(tempdir, path, io, fs, process)] extern crate syntax; extern crate rustc; use std::path::{PathBuf, Path}; use std::fs::{self, TempDir, File}; use std::io; use std::io::prelude::*; use std::process::Command; use syntax::ast; use syntax::codemap; use syntax::ext::base::{self, ExtCtxt, MacResult}; use syntax::parse::{self, token}; use rustc::plugin::Registry; mod parser_any_macro; mod set_once; #[plugin_registrar] #[doc(hidden)] pub fn plugin_registrar(registrar: &mut Registry) { let dir = match TempDir::new("rustc_python_mixin") { Ok(d) => d, Err(e) => { registrar.sess.span_err(registrar.krate_span, &format!("could not create temporary directory: {}", e)); return; } }; registrar.register_syntax_extension(token::intern("python_mixin"), base::NormalTT(Box::new(Expander { dir: dir }), None)); } struct Expander { dir: TempDir } impl base::TTMacroExpander for Expander { fn expand<'cx>(&self, cx: &'cx mut ExtCtxt, sp: codemap::Span, raw_tts: &[ast::TokenTree]) -> Box<MacResult+'cx> { macro_rules! mac_try { ($run: expr, $p: pat => $($fmt: tt)+) => { match $run { Ok(x) => x, Err($p) => { cx.span_err(sp, &format!($($fmt)+)); return base::DummyResult::any(sp) } } } } let (tts, option_tts): (_, &[_]) = match raw_tts.get(0) { Some(&ast::TtDelimited(_, ref delim)) if delim.delim == token::Brace => { (&raw_tts[1..], &delim.tts[..]) } _ => (raw_tts, &[]) }; let opts = Options::parse(cx, option_tts); let code = match base::get_single_str_from_tts(cx, sp, tts, "`python_mixin!`") { Some(c) => c, None => return base::DummyResult::any(sp) }; let lo = tts[0].get_span().lo; let first_line = cx.codemap().lookup_char_pos(lo).line as u64; let filename = cx.codemap().span_to_filename(sp); let path = PathBuf::new(&filename); let name = if path.is_absolute() { Path::new(path.file_name().unwrap()) } else { &*path }; let python_file = self.dir.path().join(name); mac_try! { fs::create_dir_all(python_file.parent().unwrap()), e => "`python_mixin!` could not create temporary directory: {}", e } let file = mac_try!(File::create(&python_file), e => "`python_mixin!` could not create temporary file: {}", e); let mut file = io::BufWriter::new(file); mac_try!(io::copy(&mut io::repeat(b'\n').take(first_line - 1), &mut file), e => "`python_mixin!` could not write output: {}", e); mac_try!(file.write(code.as_bytes()), e => "`python_mixin!` could not write output: {}", e); mac_try!(file.flush(), e => "`python_mixin!` could not flush output: {}", e); let command_name = format!("python{}", opts.version); let output = Command::new(&command_name) .current_dir(self.dir.path()) .arg(name) .output(); let output = mac_try!(output, e => "`python_mixin!` could not execute `{}`: {}", command_name, e); if!output.status.success() { cx.span_err(sp, &format!("`python_mixin!` did not execute successfully: {}", output.status)); let msg = if output.stderr.is_empty() { "there was no output on stderr".to_string() } else { format!("the process emitted the following on stderr:\n{}", String::from_utf8_lossy(&output.stderr)) }; cx.parse_sess().span_diagnostic.fileline_note(sp, &msg); return base::DummyResult::any(sp); } else if!output.stderr.is_empty() { cx.span_warn(sp, "`python_mixin!` ran successfully, but had output on stderr"); let msg = format!("output:\n{}", String::from_utf8_lossy(&output.stderr)); cx.parse_sess().span_diagnostic.fileline_note(sp, &msg); } let emitted_code = mac_try!(String::from_utf8(output.stdout), e => "`python_mixin!` emitted invalid UTF-8: {}", e); let name = format!("<{}:{} python_mixin!>", filename, first_line); let parser = parse::new_parser_from_source_str(cx.parse_sess(), cx.cfg(), name, emitted_code); Box::new(parser_any_macro::ParserAnyMacro::new(parser)) } } const DEFAULT_VERSION: &'static str = ""; struct
{ version: String, } impl Options { fn parse(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> Options { let mut version = set_once::SetOnce::new(); let mut p = cx.new_parser_from_tts(tts); while p.token!= token::Eof { // <name> = "..." let ident = p.parse_ident(); let ident_span = p.last_span; match ident.as_str() { "version" => { p.expect(&token::Eq); let (s, _) = p.parse_str(); let span = codemap::mk_sp(ident_span.lo, p.last_span.hi); if let Err(&(_, older_span)) = version.set((s.to_string(), span)) { cx.span_err(span, &format!("`python_mixin!`: option `version` already set")); cx.span_note(older_span, "set here"); } } s => { cx.span_err(p.last_span, &format!("`python_mixing!`: unknown option `{}`", s)); // heuristically skip forward, so we can check // more things later. while p.token!= token::Comma { p.bump(); } } } if p.token == token::Eof { break } p.expect(&token::Comma); } Options { version: version.get().map_or_else(|| DEFAULT_VERSION.to_string(), |t| t.0), } } }
Options
identifier_name
const-bound.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. // Make sure const bounds work on things, and test that a few types // are const. #![allow(unknown_features)] #![feature(box_syntax)] fn foo<T: Sync>(x: T) -> T { x } struct F { field: int } pub fn main()
{ /*foo(1); foo("hi".to_string()); foo(~[1, 2, 3]); foo(F{field: 42}); foo((1, 2_usize)); foo(@1);*/ foo(box 1); }
identifier_body
const-bound.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. // Make sure const bounds work on things, and test that a few types // are const. #![allow(unknown_features)] #![feature(box_syntax)] fn
<T: Sync>(x: T) -> T { x } struct F { field: int } pub fn main() { /*foo(1); foo("hi".to_string()); foo(~[1, 2, 3]); foo(F{field: 42}); foo((1, 2_usize)); foo(@1);*/ foo(box 1); }
foo
identifier_name
const-bound.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. // Make sure const bounds work on things, and test that a few types // are const. #![allow(unknown_features)] #![feature(box_syntax)] fn foo<T: Sync>(x: T) -> T { x } struct F { field: int } pub fn main() { /*foo(1); foo("hi".to_string()); foo(~[1, 2, 3]); foo(F{field: 42}); foo((1, 2_usize));
foo(box 1); }
foo(@1);*/
random_line_split
step6_file.rs
#![feature(exit_status)] extern crate mal; use std::collections::HashMap; use std::env as stdenv; use mal::types::{MalVal, MalRet, MalError, err_str}; use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc}; use mal::types::MalError::{ErrString, ErrMalVal}; use mal::types::MalType::{Nil, False, Sym, List, Vector, Hash_Map, Func, MalFunc}; use mal::{readline, reader, core}; use mal::env::{env_set, env_get, env_new, env_bind, env_root, Env}; // read fn read(str: String) -> MalRet { reader::read_str(str) } // eval fn eval_ast(ast: MalVal, env: Env) -> MalRet { match *ast { Sym(_) => env_get(&env, &ast), List(ref a,_) | Vector(ref a,_) => { let mut ast_vec : Vec<MalVal> = vec![]; for mv in a.iter() { let mv2 = mv.clone(); ast_vec.push(try!(eval(mv2, env.clone()))); } Ok(match *ast { List(_,_) => list(ast_vec), _ => vector(ast_vec) }) } Hash_Map(ref hm,_) => { let mut new_hm: HashMap<String,MalVal> = HashMap::new(); for (key, value) in hm.iter() { new_hm.insert(key.to_string(), try!(eval(value.clone(), env.clone()))); } Ok(hash_map(new_hm)) } _ => Ok(ast.clone()), } } fn eval(mut ast: MalVal, mut env: Env) -> MalRet { 'tco: loop { //println!("eval: {}, {}", ast, env.borrow()); //println!("eval: {}", ast); match *ast { List(_,_) => (), // continue _ => return eval_ast(ast, env), } // apply list match *ast { List(_,_) => (), // continue _ => return Ok(ast), } let tmp = ast; let (args, a0sym) = match *tmp { List(ref args,_) => { if args.len() == 0 { return Ok(tmp.clone()); } let ref a0 = *args[0]; match *a0 { Sym(ref a0sym) => (args, &a0sym[..]), _ => (args, "__<fn*>__"), } }, _ => return err_str("Expected list"), }; match a0sym { "def!" => { let a1 = (*args)[1].clone(); let a2 = (*args)[2].clone(); let r = try!(eval(a2, env.clone())); match *a1 { Sym(_) => { env_set(&env.clone(), a1, r.clone()); return Ok(r); }, _ => return err_str("def! of non-symbol"), } }, "let*" => { let let_env = env_new(Some(env.clone())); let a1 = (*args)[1].clone(); let a2 = (*args)[2].clone(); match *a1 { List(ref binds,_) | Vector(ref binds,_) => { let mut it = binds.iter(); while it.len() >= 2 { let b = it.next().unwrap(); let exp = it.next().unwrap(); match **b { Sym(_) => { let r = try!(eval(exp.clone(), let_env.clone())); env_set(&let_env, b.clone(), r); }, _ => return err_str("let* with non-symbol binding"), } } }, _ => return err_str("let* with non-list bindings"), } ast = a2; env = let_env.clone(); continue 'tco; }, "do" => { let el = list(args[1..args.len()-1].to_vec()); try!(eval_ast(el, env.clone())); ast = args[args.len() - 1].clone(); continue 'tco; }, "if" => { let a1 = (*args)[1].clone(); let c = try!(eval(a1, env.clone())); match *c { False | Nil => { if args.len() >= 4 { ast = args[3].clone(); continue 'tco; } else { return Ok(_nil()); } }, _ => { ast = args[2].clone(); continue 'tco; }, } }, "fn*" => { let a1 = args[1].clone(); let a2 = args[2].clone(); return Ok(malfunc(eval, a2, env, a1, _nil())); }, "eval" =>
, _ => { // function call let el = try!(eval_ast(tmp.clone(), env.clone())); let args = match *el { List(ref args,_) => args, _ => return err_str("Invalid apply"), }; return match *args.clone()[0] { Func(f,_) => f(args[1..].to_vec()), MalFunc(ref mf,_) => { let mfc = mf.clone(); let alst = list(args[1..].to_vec()); let new_env = env_new(Some(mfc.env.clone())); match env_bind(&new_env, mfc.params, alst) { Ok(_) => { ast = mfc.exp; env = new_env; continue 'tco; }, Err(e) => err_str(&e), } }, _ => err_str("attempt to call non-function"), } }, } } } // print fn print(exp: MalVal) -> String { exp.pr_str(true) } fn rep(str: &str, env: Env) -> Result<String,MalError> { let ast = try!(read(str.to_string())); //println!("read: {}", ast); let exp = try!(eval(ast, env)); Ok(print(exp)) } fn main() { // core.rs: defined using rust let repl_env = env_new(None); for (k, v) in core::ns().into_iter() { env_set(&repl_env, symbol(&k), v); } // see eval() for definition of "eval" env_set(&repl_env, symbol("*ARGV*"), list(vec![])); // core.mal: defined using the language itself let _ = rep("(def! not (fn* (a) (if a false true)))", repl_env.clone()); let _ = rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env.clone()); // Invoked with command line arguments let args = stdenv::args(); if args.len() > 1 { let mv_args = args.skip(2) .map(|a| string(a)) .collect::<Vec<MalVal>>(); env_set(&repl_env, symbol("*ARGV*"), list(mv_args)); let lf = format!("(load-file \"{}\")", stdenv::args().skip(1).next().unwrap()); return match rep(&lf, repl_env.clone()) { Ok(_) => stdenv::set_exit_status(0), Err(str) => { println!("Error: {:?}", str); stdenv::set_exit_status(1); } }; } // repl loop loop { let line = readline::mal_readline("user> "); match line { None => break, _ => () } match rep(&line.unwrap(), repl_env.clone()) { Ok(str) => println!("{}", str), Err(ErrMalVal(_)) => (), // Blank line Err(ErrString(s)) => println!("Error: {}", s), } } }
{ let a1 = (*args)[1].clone(); ast = try!(eval(a1, env.clone())); env = env_root(&env); continue 'tco; }
conditional_block
step6_file.rs
#![feature(exit_status)] extern crate mal; use std::collections::HashMap; use std::env as stdenv; use mal::types::{MalVal, MalRet, MalError, err_str}; use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc}; use mal::types::MalError::{ErrString, ErrMalVal}; use mal::types::MalType::{Nil, False, Sym, List, Vector, Hash_Map, Func, MalFunc}; use mal::{readline, reader, core}; use mal::env::{env_set, env_get, env_new, env_bind, env_root, Env}; // read fn read(str: String) -> MalRet { reader::read_str(str) } // eval fn eval_ast(ast: MalVal, env: Env) -> MalRet
_ => Ok(ast.clone()), } } fn eval(mut ast: MalVal, mut env: Env) -> MalRet { 'tco: loop { //println!("eval: {}, {}", ast, env.borrow()); //println!("eval: {}", ast); match *ast { List(_,_) => (), // continue _ => return eval_ast(ast, env), } // apply list match *ast { List(_,_) => (), // continue _ => return Ok(ast), } let tmp = ast; let (args, a0sym) = match *tmp { List(ref args,_) => { if args.len() == 0 { return Ok(tmp.clone()); } let ref a0 = *args[0]; match *a0 { Sym(ref a0sym) => (args, &a0sym[..]), _ => (args, "__<fn*>__"), } }, _ => return err_str("Expected list"), }; match a0sym { "def!" => { let a1 = (*args)[1].clone(); let a2 = (*args)[2].clone(); let r = try!(eval(a2, env.clone())); match *a1 { Sym(_) => { env_set(&env.clone(), a1, r.clone()); return Ok(r); }, _ => return err_str("def! of non-symbol"), } }, "let*" => { let let_env = env_new(Some(env.clone())); let a1 = (*args)[1].clone(); let a2 = (*args)[2].clone(); match *a1 { List(ref binds,_) | Vector(ref binds,_) => { let mut it = binds.iter(); while it.len() >= 2 { let b = it.next().unwrap(); let exp = it.next().unwrap(); match **b { Sym(_) => { let r = try!(eval(exp.clone(), let_env.clone())); env_set(&let_env, b.clone(), r); }, _ => return err_str("let* with non-symbol binding"), } } }, _ => return err_str("let* with non-list bindings"), } ast = a2; env = let_env.clone(); continue 'tco; }, "do" => { let el = list(args[1..args.len()-1].to_vec()); try!(eval_ast(el, env.clone())); ast = args[args.len() - 1].clone(); continue 'tco; }, "if" => { let a1 = (*args)[1].clone(); let c = try!(eval(a1, env.clone())); match *c { False | Nil => { if args.len() >= 4 { ast = args[3].clone(); continue 'tco; } else { return Ok(_nil()); } }, _ => { ast = args[2].clone(); continue 'tco; }, } }, "fn*" => { let a1 = args[1].clone(); let a2 = args[2].clone(); return Ok(malfunc(eval, a2, env, a1, _nil())); }, "eval" => { let a1 = (*args)[1].clone(); ast = try!(eval(a1, env.clone())); env = env_root(&env); continue 'tco; }, _ => { // function call let el = try!(eval_ast(tmp.clone(), env.clone())); let args = match *el { List(ref args,_) => args, _ => return err_str("Invalid apply"), }; return match *args.clone()[0] { Func(f,_) => f(args[1..].to_vec()), MalFunc(ref mf,_) => { let mfc = mf.clone(); let alst = list(args[1..].to_vec()); let new_env = env_new(Some(mfc.env.clone())); match env_bind(&new_env, mfc.params, alst) { Ok(_) => { ast = mfc.exp; env = new_env; continue 'tco; }, Err(e) => err_str(&e), } }, _ => err_str("attempt to call non-function"), } }, } } } // print fn print(exp: MalVal) -> String { exp.pr_str(true) } fn rep(str: &str, env: Env) -> Result<String,MalError> { let ast = try!(read(str.to_string())); //println!("read: {}", ast); let exp = try!(eval(ast, env)); Ok(print(exp)) } fn main() { // core.rs: defined using rust let repl_env = env_new(None); for (k, v) in core::ns().into_iter() { env_set(&repl_env, symbol(&k), v); } // see eval() for definition of "eval" env_set(&repl_env, symbol("*ARGV*"), list(vec![])); // core.mal: defined using the language itself let _ = rep("(def! not (fn* (a) (if a false true)))", repl_env.clone()); let _ = rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env.clone()); // Invoked with command line arguments let args = stdenv::args(); if args.len() > 1 { let mv_args = args.skip(2) .map(|a| string(a)) .collect::<Vec<MalVal>>(); env_set(&repl_env, symbol("*ARGV*"), list(mv_args)); let lf = format!("(load-file \"{}\")", stdenv::args().skip(1).next().unwrap()); return match rep(&lf, repl_env.clone()) { Ok(_) => stdenv::set_exit_status(0), Err(str) => { println!("Error: {:?}", str); stdenv::set_exit_status(1); } }; } // repl loop loop { let line = readline::mal_readline("user> "); match line { None => break, _ => () } match rep(&line.unwrap(), repl_env.clone()) { Ok(str) => println!("{}", str), Err(ErrMalVal(_)) => (), // Blank line Err(ErrString(s)) => println!("Error: {}", s), } } }
{ match *ast { Sym(_) => env_get(&env, &ast), List(ref a,_) | Vector(ref a,_) => { let mut ast_vec : Vec<MalVal> = vec![]; for mv in a.iter() { let mv2 = mv.clone(); ast_vec.push(try!(eval(mv2, env.clone()))); } Ok(match *ast { List(_,_) => list(ast_vec), _ => vector(ast_vec) }) } Hash_Map(ref hm,_) => { let mut new_hm: HashMap<String,MalVal> = HashMap::new(); for (key, value) in hm.iter() { new_hm.insert(key.to_string(), try!(eval(value.clone(), env.clone()))); } Ok(hash_map(new_hm)) }
identifier_body
step6_file.rs
#![feature(exit_status)] extern crate mal; use std::collections::HashMap; use std::env as stdenv; use mal::types::{MalVal, MalRet, MalError, err_str}; use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc}; use mal::types::MalError::{ErrString, ErrMalVal}; use mal::types::MalType::{Nil, False, Sym, List, Vector, Hash_Map, Func, MalFunc}; use mal::{readline, reader, core}; use mal::env::{env_set, env_get, env_new, env_bind, env_root, Env}; // read fn read(str: String) -> MalRet { reader::read_str(str) } // eval fn eval_ast(ast: MalVal, env: Env) -> MalRet { match *ast { Sym(_) => env_get(&env, &ast), List(ref a,_) | Vector(ref a,_) => { let mut ast_vec : Vec<MalVal> = vec![]; for mv in a.iter() { let mv2 = mv.clone(); ast_vec.push(try!(eval(mv2, env.clone()))); } Ok(match *ast { List(_,_) => list(ast_vec), _ => vector(ast_vec) }) } Hash_Map(ref hm,_) => { let mut new_hm: HashMap<String,MalVal> = HashMap::new(); for (key, value) in hm.iter() { new_hm.insert(key.to_string(), try!(eval(value.clone(), env.clone()))); } Ok(hash_map(new_hm)) } _ => Ok(ast.clone()), } } fn eval(mut ast: MalVal, mut env: Env) -> MalRet { 'tco: loop { //println!("eval: {}, {}", ast, env.borrow()); //println!("eval: {}", ast); match *ast { List(_,_) => (), // continue _ => return eval_ast(ast, env), } // apply list match *ast { List(_,_) => (), // continue _ => return Ok(ast), } let tmp = ast; let (args, a0sym) = match *tmp { List(ref args,_) => { if args.len() == 0 { return Ok(tmp.clone()); } let ref a0 = *args[0]; match *a0 { Sym(ref a0sym) => (args, &a0sym[..]), _ => (args, "__<fn*>__"), } }, _ => return err_str("Expected list"), }; match a0sym { "def!" => { let a1 = (*args)[1].clone(); let a2 = (*args)[2].clone(); let r = try!(eval(a2, env.clone())); match *a1 { Sym(_) => { env_set(&env.clone(), a1, r.clone()); return Ok(r); }, _ => return err_str("def! of non-symbol"), } }, "let*" => { let let_env = env_new(Some(env.clone())); let a1 = (*args)[1].clone(); let a2 = (*args)[2].clone(); match *a1 { List(ref binds,_) | Vector(ref binds,_) => { let mut it = binds.iter(); while it.len() >= 2 { let b = it.next().unwrap(); let exp = it.next().unwrap(); match **b { Sym(_) => { let r = try!(eval(exp.clone(), let_env.clone())); env_set(&let_env, b.clone(), r); }, _ => return err_str("let* with non-symbol binding"), } } }, _ => return err_str("let* with non-list bindings"), } ast = a2; env = let_env.clone(); continue 'tco; }, "do" => { let el = list(args[1..args.len()-1].to_vec()); try!(eval_ast(el, env.clone())); ast = args[args.len() - 1].clone(); continue 'tco; }, "if" => {
let c = try!(eval(a1, env.clone())); match *c { False | Nil => { if args.len() >= 4 { ast = args[3].clone(); continue 'tco; } else { return Ok(_nil()); } }, _ => { ast = args[2].clone(); continue 'tco; }, } }, "fn*" => { let a1 = args[1].clone(); let a2 = args[2].clone(); return Ok(malfunc(eval, a2, env, a1, _nil())); }, "eval" => { let a1 = (*args)[1].clone(); ast = try!(eval(a1, env.clone())); env = env_root(&env); continue 'tco; }, _ => { // function call let el = try!(eval_ast(tmp.clone(), env.clone())); let args = match *el { List(ref args,_) => args, _ => return err_str("Invalid apply"), }; return match *args.clone()[0] { Func(f,_) => f(args[1..].to_vec()), MalFunc(ref mf,_) => { let mfc = mf.clone(); let alst = list(args[1..].to_vec()); let new_env = env_new(Some(mfc.env.clone())); match env_bind(&new_env, mfc.params, alst) { Ok(_) => { ast = mfc.exp; env = new_env; continue 'tco; }, Err(e) => err_str(&e), } }, _ => err_str("attempt to call non-function"), } }, } } } // print fn print(exp: MalVal) -> String { exp.pr_str(true) } fn rep(str: &str, env: Env) -> Result<String,MalError> { let ast = try!(read(str.to_string())); //println!("read: {}", ast); let exp = try!(eval(ast, env)); Ok(print(exp)) } fn main() { // core.rs: defined using rust let repl_env = env_new(None); for (k, v) in core::ns().into_iter() { env_set(&repl_env, symbol(&k), v); } // see eval() for definition of "eval" env_set(&repl_env, symbol("*ARGV*"), list(vec![])); // core.mal: defined using the language itself let _ = rep("(def! not (fn* (a) (if a false true)))", repl_env.clone()); let _ = rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env.clone()); // Invoked with command line arguments let args = stdenv::args(); if args.len() > 1 { let mv_args = args.skip(2) .map(|a| string(a)) .collect::<Vec<MalVal>>(); env_set(&repl_env, symbol("*ARGV*"), list(mv_args)); let lf = format!("(load-file \"{}\")", stdenv::args().skip(1).next().unwrap()); return match rep(&lf, repl_env.clone()) { Ok(_) => stdenv::set_exit_status(0), Err(str) => { println!("Error: {:?}", str); stdenv::set_exit_status(1); } }; } // repl loop loop { let line = readline::mal_readline("user> "); match line { None => break, _ => () } match rep(&line.unwrap(), repl_env.clone()) { Ok(str) => println!("{}", str), Err(ErrMalVal(_)) => (), // Blank line Err(ErrString(s)) => println!("Error: {}", s), } } }
let a1 = (*args)[1].clone();
random_line_split
step6_file.rs
#![feature(exit_status)] extern crate mal; use std::collections::HashMap; use std::env as stdenv; use mal::types::{MalVal, MalRet, MalError, err_str}; use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc}; use mal::types::MalError::{ErrString, ErrMalVal}; use mal::types::MalType::{Nil, False, Sym, List, Vector, Hash_Map, Func, MalFunc}; use mal::{readline, reader, core}; use mal::env::{env_set, env_get, env_new, env_bind, env_root, Env}; // read fn
(str: String) -> MalRet { reader::read_str(str) } // eval fn eval_ast(ast: MalVal, env: Env) -> MalRet { match *ast { Sym(_) => env_get(&env, &ast), List(ref a,_) | Vector(ref a,_) => { let mut ast_vec : Vec<MalVal> = vec![]; for mv in a.iter() { let mv2 = mv.clone(); ast_vec.push(try!(eval(mv2, env.clone()))); } Ok(match *ast { List(_,_) => list(ast_vec), _ => vector(ast_vec) }) } Hash_Map(ref hm,_) => { let mut new_hm: HashMap<String,MalVal> = HashMap::new(); for (key, value) in hm.iter() { new_hm.insert(key.to_string(), try!(eval(value.clone(), env.clone()))); } Ok(hash_map(new_hm)) } _ => Ok(ast.clone()), } } fn eval(mut ast: MalVal, mut env: Env) -> MalRet { 'tco: loop { //println!("eval: {}, {}", ast, env.borrow()); //println!("eval: {}", ast); match *ast { List(_,_) => (), // continue _ => return eval_ast(ast, env), } // apply list match *ast { List(_,_) => (), // continue _ => return Ok(ast), } let tmp = ast; let (args, a0sym) = match *tmp { List(ref args,_) => { if args.len() == 0 { return Ok(tmp.clone()); } let ref a0 = *args[0]; match *a0 { Sym(ref a0sym) => (args, &a0sym[..]), _ => (args, "__<fn*>__"), } }, _ => return err_str("Expected list"), }; match a0sym { "def!" => { let a1 = (*args)[1].clone(); let a2 = (*args)[2].clone(); let r = try!(eval(a2, env.clone())); match *a1 { Sym(_) => { env_set(&env.clone(), a1, r.clone()); return Ok(r); }, _ => return err_str("def! of non-symbol"), } }, "let*" => { let let_env = env_new(Some(env.clone())); let a1 = (*args)[1].clone(); let a2 = (*args)[2].clone(); match *a1 { List(ref binds,_) | Vector(ref binds,_) => { let mut it = binds.iter(); while it.len() >= 2 { let b = it.next().unwrap(); let exp = it.next().unwrap(); match **b { Sym(_) => { let r = try!(eval(exp.clone(), let_env.clone())); env_set(&let_env, b.clone(), r); }, _ => return err_str("let* with non-symbol binding"), } } }, _ => return err_str("let* with non-list bindings"), } ast = a2; env = let_env.clone(); continue 'tco; }, "do" => { let el = list(args[1..args.len()-1].to_vec()); try!(eval_ast(el, env.clone())); ast = args[args.len() - 1].clone(); continue 'tco; }, "if" => { let a1 = (*args)[1].clone(); let c = try!(eval(a1, env.clone())); match *c { False | Nil => { if args.len() >= 4 { ast = args[3].clone(); continue 'tco; } else { return Ok(_nil()); } }, _ => { ast = args[2].clone(); continue 'tco; }, } }, "fn*" => { let a1 = args[1].clone(); let a2 = args[2].clone(); return Ok(malfunc(eval, a2, env, a1, _nil())); }, "eval" => { let a1 = (*args)[1].clone(); ast = try!(eval(a1, env.clone())); env = env_root(&env); continue 'tco; }, _ => { // function call let el = try!(eval_ast(tmp.clone(), env.clone())); let args = match *el { List(ref args,_) => args, _ => return err_str("Invalid apply"), }; return match *args.clone()[0] { Func(f,_) => f(args[1..].to_vec()), MalFunc(ref mf,_) => { let mfc = mf.clone(); let alst = list(args[1..].to_vec()); let new_env = env_new(Some(mfc.env.clone())); match env_bind(&new_env, mfc.params, alst) { Ok(_) => { ast = mfc.exp; env = new_env; continue 'tco; }, Err(e) => err_str(&e), } }, _ => err_str("attempt to call non-function"), } }, } } } // print fn print(exp: MalVal) -> String { exp.pr_str(true) } fn rep(str: &str, env: Env) -> Result<String,MalError> { let ast = try!(read(str.to_string())); //println!("read: {}", ast); let exp = try!(eval(ast, env)); Ok(print(exp)) } fn main() { // core.rs: defined using rust let repl_env = env_new(None); for (k, v) in core::ns().into_iter() { env_set(&repl_env, symbol(&k), v); } // see eval() for definition of "eval" env_set(&repl_env, symbol("*ARGV*"), list(vec![])); // core.mal: defined using the language itself let _ = rep("(def! not (fn* (a) (if a false true)))", repl_env.clone()); let _ = rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env.clone()); // Invoked with command line arguments let args = stdenv::args(); if args.len() > 1 { let mv_args = args.skip(2) .map(|a| string(a)) .collect::<Vec<MalVal>>(); env_set(&repl_env, symbol("*ARGV*"), list(mv_args)); let lf = format!("(load-file \"{}\")", stdenv::args().skip(1).next().unwrap()); return match rep(&lf, repl_env.clone()) { Ok(_) => stdenv::set_exit_status(0), Err(str) => { println!("Error: {:?}", str); stdenv::set_exit_status(1); } }; } // repl loop loop { let line = readline::mal_readline("user> "); match line { None => break, _ => () } match rep(&line.unwrap(), repl_env.clone()) { Ok(str) => println!("{}", str), Err(ErrMalVal(_)) => (), // Blank line Err(ErrString(s)) => println!("Error: {}", s), } } }
read
identifier_name
list_blobs_00.rs
use futures::stream::StreamExt; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { // First we retrieve the account name and master key from environment variables. let account = std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!"); let master_key = std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!"); let container_name = std::env::args() .nth(1) .expect("please specify container name as command line parameter"); let client = client::with_access_key(&account, &master_key); let iv = client.list_containers().finalize().await?; if iv .incomplete_vector .iter() .find(|item| item.name == container_name) .is_some() { panic!("The specified container must not exists!"); } // create the container client .create_container() .with_container_name(&container_name) .with_public_access(PublicAccess::None) .with_timeout(100) .finalize() .await?; println!("Container {} created", container_name); // create 10 blobs for i in 0..10u8 { client .put_block_blob() .with_container_name(&container_name) .with_blob_name(&format!("blob{}.txt", i)) .with_content_type("text/plain") .with_body("somedata".as_bytes()) .finalize() .await?; println!("\tAdded blob {}", i); } let iv = client .list_blobs() .with_container_name(&container_name) .with_max_results(3) .finalize() .await?; println!("List blob returned {} blobs.", iv.incomplete_vector.len()); for cont in iv.incomplete_vector.iter() { println!("\t{}\t{} bytes", cont.name, cont.content_length); } let mut stream = Box::pin( client .list_blobs() .with_max_results(3) .with_container_name(&container_name) .stream(), ); let mut cnt = 0; while let Some(value) = stream.next().await { let len = value?.incomplete_vector.len(); println!("received {} blobs", len); match cnt { 0 | 1 | 2 => assert_eq!(len, 3), 3 => assert_eq!(len, 1), _ => panic!("more than 10 entries??"), } cnt += 1; } client .delete_container() .with_container_name(&container_name) .finalize() .await?; println!("Container {} deleted", container_name); Ok(()) }
use azure_sdk_core::prelude::*; use azure_sdk_storage_blob::prelude::*; use azure_sdk_storage_core::prelude::*;
random_line_split
list_blobs_00.rs
use azure_sdk_core::prelude::*; use azure_sdk_storage_blob::prelude::*; use azure_sdk_storage_core::prelude::*; use futures::stream::StreamExt; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>>
{ panic!("The specified container must not exists!"); } // create the container client .create_container() .with_container_name(&container_name) .with_public_access(PublicAccess::None) .with_timeout(100) .finalize() .await?; println!("Container {} created", container_name); // create 10 blobs for i in 0..10u8 { client .put_block_blob() .with_container_name(&container_name) .with_blob_name(&format!("blob{}.txt", i)) .with_content_type("text/plain") .with_body("somedata".as_bytes()) .finalize() .await?; println!("\tAdded blob {}", i); } let iv = client .list_blobs() .with_container_name(&container_name) .with_max_results(3) .finalize() .await?; println!("List blob returned {} blobs.", iv.incomplete_vector.len()); for cont in iv.incomplete_vector.iter() { println!("\t{}\t{} bytes", cont.name, cont.content_length); } let mut stream = Box::pin( client .list_blobs() .with_max_results(3) .with_container_name(&container_name) .stream(), ); let mut cnt = 0; while let Some(value) = stream.next().await { let len = value?.incomplete_vector.len(); println!("received {} blobs", len); match cnt { 0 | 1 | 2 => assert_eq!(len, 3), 3 => assert_eq!(len, 1), _ => panic!("more than 10 entries??"), } cnt += 1; } client .delete_container() .with_container_name(&container_name) .finalize() .await?; println!("Container {} deleted", container_name); Ok(()) }
{ // First we retrieve the account name and master key from environment variables. let account = std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!"); let master_key = std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!"); let container_name = std::env::args() .nth(1) .expect("please specify container name as command line parameter"); let client = client::with_access_key(&account, &master_key); let iv = client.list_containers().finalize().await?; if iv .incomplete_vector .iter() .find(|item| item.name == container_name) .is_some()
identifier_body
list_blobs_00.rs
use azure_sdk_core::prelude::*; use azure_sdk_storage_blob::prelude::*; use azure_sdk_storage_core::prelude::*; use futures::stream::StreamExt; use std::error::Error; #[tokio::main] async fn
() -> Result<(), Box<dyn Error>> { // First we retrieve the account name and master key from environment variables. let account = std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!"); let master_key = std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!"); let container_name = std::env::args() .nth(1) .expect("please specify container name as command line parameter"); let client = client::with_access_key(&account, &master_key); let iv = client.list_containers().finalize().await?; if iv .incomplete_vector .iter() .find(|item| item.name == container_name) .is_some() { panic!("The specified container must not exists!"); } // create the container client .create_container() .with_container_name(&container_name) .with_public_access(PublicAccess::None) .with_timeout(100) .finalize() .await?; println!("Container {} created", container_name); // create 10 blobs for i in 0..10u8 { client .put_block_blob() .with_container_name(&container_name) .with_blob_name(&format!("blob{}.txt", i)) .with_content_type("text/plain") .with_body("somedata".as_bytes()) .finalize() .await?; println!("\tAdded blob {}", i); } let iv = client .list_blobs() .with_container_name(&container_name) .with_max_results(3) .finalize() .await?; println!("List blob returned {} blobs.", iv.incomplete_vector.len()); for cont in iv.incomplete_vector.iter() { println!("\t{}\t{} bytes", cont.name, cont.content_length); } let mut stream = Box::pin( client .list_blobs() .with_max_results(3) .with_container_name(&container_name) .stream(), ); let mut cnt = 0; while let Some(value) = stream.next().await { let len = value?.incomplete_vector.len(); println!("received {} blobs", len); match cnt { 0 | 1 | 2 => assert_eq!(len, 3), 3 => assert_eq!(len, 1), _ => panic!("more than 10 entries??"), } cnt += 1; } client .delete_container() .with_container_name(&container_name) .finalize() .await?; println!("Container {} deleted", container_name); Ok(()) }
main
identifier_name
build.rs
/* Copyright ⓒ 2017 cargo-script contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ extern crate rustc_version; use rustc_version::{version_matches}; fn main() { println!("cargo:rerun-if-changed=build.rs"); /* Environment might suffer from <https://github.com/DanielKeep/cargo-script/issues/50>. */ if cfg!(windows) { println!("cargo:rustc-cfg=issue_50"); } /* With 1.15, linking on Windows was changed in regards to when it emits `dllimport`. This means that the *old* code for linking to `FOLDERID_LocalAppData` no longer works. Unfortunately, it *also* means that the *new* code doesn't work prior to 1.15. This controls which linking behaviour we need to work with. */ if version_matches("<1.15.0") {
/* Before 1.13, there was no `?` operator. One of the tests needs this information. */ if version_matches(">=1.13.0") { println!("cargo:rustc-cfg=has_qmark"); } }
println!("cargo:rustc-cfg=old_rustc_windows_linking_behaviour"); }
conditional_block
build.rs
/* Copyright ⓒ 2017 cargo-script contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ extern crate rustc_version; use rustc_version::{version_matches}; fn ma
{ println!("cargo:rerun-if-changed=build.rs"); /* Environment might suffer from <https://github.com/DanielKeep/cargo-script/issues/50>. */ if cfg!(windows) { println!("cargo:rustc-cfg=issue_50"); } /* With 1.15, linking on Windows was changed in regards to when it emits `dllimport`. This means that the *old* code for linking to `FOLDERID_LocalAppData` no longer works. Unfortunately, it *also* means that the *new* code doesn't work prior to 1.15. This controls which linking behaviour we need to work with. */ if version_matches("<1.15.0") { println!("cargo:rustc-cfg=old_rustc_windows_linking_behaviour"); } /* Before 1.13, there was no `?` operator. One of the tests needs this information. */ if version_matches(">=1.13.0") { println!("cargo:rustc-cfg=has_qmark"); } }
in()
identifier_name
build.rs
/* Copyright ⓒ 2017 cargo-script contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ extern crate rustc_version; use rustc_version::{version_matches}; fn main() {
*/ if version_matches(">=1.13.0") { println!("cargo:rustc-cfg=has_qmark"); } }
println!("cargo:rerun-if-changed=build.rs"); /* Environment might suffer from <https://github.com/DanielKeep/cargo-script/issues/50>. */ if cfg!(windows) { println!("cargo:rustc-cfg=issue_50"); } /* With 1.15, linking on Windows was changed in regards to when it emits `dllimport`. This means that the *old* code for linking to `FOLDERID_LocalAppData` no longer works. Unfortunately, it *also* means that the *new* code doesn't work prior to 1.15. This controls which linking behaviour we need to work with. */ if version_matches("<1.15.0") { println!("cargo:rustc-cfg=old_rustc_windows_linking_behaviour"); } /* Before 1.13, there was no `?` operator. One of the tests needs this information.
identifier_body
build.rs
/* Copyright ⓒ 2017 cargo-script contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified,
extern crate rustc_version; use rustc_version::{version_matches}; fn main() { println!("cargo:rerun-if-changed=build.rs"); /* Environment might suffer from <https://github.com/DanielKeep/cargo-script/issues/50>. */ if cfg!(windows) { println!("cargo:rustc-cfg=issue_50"); } /* With 1.15, linking on Windows was changed in regards to when it emits `dllimport`. This means that the *old* code for linking to `FOLDERID_LocalAppData` no longer works. Unfortunately, it *also* means that the *new* code doesn't work prior to 1.15. This controls which linking behaviour we need to work with. */ if version_matches("<1.15.0") { println!("cargo:rustc-cfg=old_rustc_windows_linking_behaviour"); } /* Before 1.13, there was no `?` operator. One of the tests needs this information. */ if version_matches(">=1.13.0") { println!("cargo:rustc-cfg=has_qmark"); } }
or distributed except according to those terms. */
random_line_split
monitor.rs
use winapi; use std::collections::RingBuf; /// Win32 implementation of the main `MonitorID` object. pub struct MonitorID { /// The system name of the monitor. name: [winapi::WCHAR; 32], /// Name to give to the user. readable_name: String, /// See the `StateFlags` element here: /// http://msdn.microsoft.com/en-us/library/dd183569(v=vs.85).aspx flags: winapi::DWORD, /// The position of the monitor in pixels on the desktop. /// /// A window that is positionned at these coordinates will overlap the monitor. position: (uint, uint), /// The current resolution in pixels on the monitor. dimensions: (uint, uint), } /// Win32 implementation of the main `get_available_monitors` function. pub fn get_available_monitors() -> RingBuf<MonitorID> { use std::{iter, mem, ptr}; // return value let mut result = RingBuf::new(); // enumerating the devices is done by querying device 0, then device 1, then device 2, etc. // until the query function returns null for id in iter::count(0u, 1) { // getting the DISPLAY_DEVICEW object of the current device let output = { let mut output: winapi::DISPLAY_DEVICEW = unsafe { mem::zeroed() }; output.cb = mem::size_of::<winapi::DISPLAY_DEVICEW>() as winapi::DWORD; if unsafe { winapi::EnumDisplayDevicesW(ptr::null(), id as winapi::DWORD, &mut output, 0) } == 0 { // the device doesn't exist, which means we have finished enumerating break; } if (output.StateFlags & winapi::DISPLAY_DEVICE_ACTIVE) == 0 || (output.StateFlags & winapi::DISPLAY_DEVICE_MIRRORING_DRIVER)!= 0 { // the device is not active // the Win32 api usually returns a lot of inactive devices continue; } output }; // computing the human-friendly name let readable_name = String::from_utf16_lossy(output.DeviceString.as_slice()); let readable_name = readable_name.as_slice().trim_right_matches(0 as char).to_string(); // getting the position let (position, dimensions) = unsafe { let mut dev: winapi::DEVMODEW = mem::zeroed(); dev.dmSize = mem::size_of::<winapi::DEVMODEW>() as winapi::WORD; if winapi::EnumDisplaySettingsExW(output.DeviceName.as_ptr(), winapi::ENUM_CURRENT_SETTINGS, &mut dev, 0) == 0 { continue; } let point: &winapi::POINTL = mem::transmute(&dev.union1); let position = (point.x as uint, point.y as uint); let dimensions = (dev.dmPelsWidth as uint, dev.dmPelsHeight as uint); (position, dimensions) }; // adding to the resulting list result.push_back(MonitorID { name: output.DeviceName, readable_name: readable_name, flags: output.StateFlags, position: position, dimensions: dimensions, }); } result } /// Win32 implementation of the main `get_primary_monitor` function. pub fn get_primary_monitor() -> MonitorID { // we simply get all available monitors and return the one with the `PRIMARY_DEVICE` flag // TODO: it is possible to query the win32 API for the primary monitor, this should be done // instead for monitor in get_available_monitors().into_iter() { if (monitor.flags & winapi::DISPLAY_DEVICE_PRIMARY_DEVICE)!= 0 { return monitor } } panic!("Failed to find the primary monitor") } impl MonitorID { /// See the docs if the crate root file. pub fn get_name(&self) -> Option<String>
/// See the docs if the crate root file. pub fn get_dimensions(&self) -> (uint, uint) { // TODO: retreive the dimensions every time this is called self.dimensions } /// This is a Win32-only function for `MonitorID` that returns the system name of the device. pub fn get_system_name(&self) -> &[winapi::WCHAR] { // TODO: retreive the position every time this is called self.name.as_slice() } /// This is a Win32-only function for `MonitorID` that returns the position of the /// monitor on the desktop. /// A window that is positionned at these coordinates will overlap the monitor. pub fn get_position(&self) -> (uint, uint) { self.position } }
{ Some(self.readable_name.clone()) }
identifier_body
monitor.rs
use winapi; use std::collections::RingBuf; /// Win32 implementation of the main `MonitorID` object. pub struct MonitorID { /// The system name of the monitor. name: [winapi::WCHAR; 32], /// Name to give to the user. readable_name: String, /// See the `StateFlags` element here: /// http://msdn.microsoft.com/en-us/library/dd183569(v=vs.85).aspx flags: winapi::DWORD, /// The position of the monitor in pixels on the desktop. /// /// A window that is positionned at these coordinates will overlap the monitor. position: (uint, uint), /// The current resolution in pixels on the monitor. dimensions: (uint, uint), } /// Win32 implementation of the main `get_available_monitors` function. pub fn get_available_monitors() -> RingBuf<MonitorID> { use std::{iter, mem, ptr}; // return value let mut result = RingBuf::new(); // enumerating the devices is done by querying device 0, then device 1, then device 2, etc. // until the query function returns null for id in iter::count(0u, 1) { // getting the DISPLAY_DEVICEW object of the current device let output = { let mut output: winapi::DISPLAY_DEVICEW = unsafe { mem::zeroed() }; output.cb = mem::size_of::<winapi::DISPLAY_DEVICEW>() as winapi::DWORD; if unsafe { winapi::EnumDisplayDevicesW(ptr::null(), id as winapi::DWORD, &mut output, 0) } == 0
if (output.StateFlags & winapi::DISPLAY_DEVICE_ACTIVE) == 0 || (output.StateFlags & winapi::DISPLAY_DEVICE_MIRRORING_DRIVER)!= 0 { // the device is not active // the Win32 api usually returns a lot of inactive devices continue; } output }; // computing the human-friendly name let readable_name = String::from_utf16_lossy(output.DeviceString.as_slice()); let readable_name = readable_name.as_slice().trim_right_matches(0 as char).to_string(); // getting the position let (position, dimensions) = unsafe { let mut dev: winapi::DEVMODEW = mem::zeroed(); dev.dmSize = mem::size_of::<winapi::DEVMODEW>() as winapi::WORD; if winapi::EnumDisplaySettingsExW(output.DeviceName.as_ptr(), winapi::ENUM_CURRENT_SETTINGS, &mut dev, 0) == 0 { continue; } let point: &winapi::POINTL = mem::transmute(&dev.union1); let position = (point.x as uint, point.y as uint); let dimensions = (dev.dmPelsWidth as uint, dev.dmPelsHeight as uint); (position, dimensions) }; // adding to the resulting list result.push_back(MonitorID { name: output.DeviceName, readable_name: readable_name, flags: output.StateFlags, position: position, dimensions: dimensions, }); } result } /// Win32 implementation of the main `get_primary_monitor` function. pub fn get_primary_monitor() -> MonitorID { // we simply get all available monitors and return the one with the `PRIMARY_DEVICE` flag // TODO: it is possible to query the win32 API for the primary monitor, this should be done // instead for monitor in get_available_monitors().into_iter() { if (monitor.flags & winapi::DISPLAY_DEVICE_PRIMARY_DEVICE)!= 0 { return monitor } } panic!("Failed to find the primary monitor") } impl MonitorID { /// See the docs if the crate root file. pub fn get_name(&self) -> Option<String> { Some(self.readable_name.clone()) } /// See the docs if the crate root file. pub fn get_dimensions(&self) -> (uint, uint) { // TODO: retreive the dimensions every time this is called self.dimensions } /// This is a Win32-only function for `MonitorID` that returns the system name of the device. pub fn get_system_name(&self) -> &[winapi::WCHAR] { // TODO: retreive the position every time this is called self.name.as_slice() } /// This is a Win32-only function for `MonitorID` that returns the position of the /// monitor on the desktop. /// A window that is positionned at these coordinates will overlap the monitor. pub fn get_position(&self) -> (uint, uint) { self.position } }
{ // the device doesn't exist, which means we have finished enumerating break; }
conditional_block
monitor.rs
use winapi; use std::collections::RingBuf; /// Win32 implementation of the main `MonitorID` object. pub struct MonitorID { /// The system name of the monitor. name: [winapi::WCHAR; 32], /// Name to give to the user. readable_name: String, /// See the `StateFlags` element here: /// http://msdn.microsoft.com/en-us/library/dd183569(v=vs.85).aspx flags: winapi::DWORD, /// The position of the monitor in pixels on the desktop. /// /// A window that is positionned at these coordinates will overlap the monitor. position: (uint, uint), /// The current resolution in pixels on the monitor. dimensions: (uint, uint), } /// Win32 implementation of the main `get_available_monitors` function. pub fn get_available_monitors() -> RingBuf<MonitorID> { use std::{iter, mem, ptr}; // return value let mut result = RingBuf::new(); // enumerating the devices is done by querying device 0, then device 1, then device 2, etc. // until the query function returns null for id in iter::count(0u, 1) { // getting the DISPLAY_DEVICEW object of the current device let output = { let mut output: winapi::DISPLAY_DEVICEW = unsafe { mem::zeroed() }; output.cb = mem::size_of::<winapi::DISPLAY_DEVICEW>() as winapi::DWORD; if unsafe { winapi::EnumDisplayDevicesW(ptr::null(), id as winapi::DWORD, &mut output, 0) } == 0 { // the device doesn't exist, which means we have finished enumerating break; } if (output.StateFlags & winapi::DISPLAY_DEVICE_ACTIVE) == 0 || (output.StateFlags & winapi::DISPLAY_DEVICE_MIRRORING_DRIVER)!= 0 { // the device is not active // the Win32 api usually returns a lot of inactive devices continue; } output }; // computing the human-friendly name let readable_name = String::from_utf16_lossy(output.DeviceString.as_slice()); let readable_name = readable_name.as_slice().trim_right_matches(0 as char).to_string(); // getting the position let (position, dimensions) = unsafe { let mut dev: winapi::DEVMODEW = mem::zeroed(); dev.dmSize = mem::size_of::<winapi::DEVMODEW>() as winapi::WORD; if winapi::EnumDisplaySettingsExW(output.DeviceName.as_ptr(), winapi::ENUM_CURRENT_SETTINGS, &mut dev, 0) == 0 { continue; } let point: &winapi::POINTL = mem::transmute(&dev.union1); let position = (point.x as uint, point.y as uint); let dimensions = (dev.dmPelsWidth as uint, dev.dmPelsHeight as uint); (position, dimensions) }; // adding to the resulting list result.push_back(MonitorID { name: output.DeviceName, readable_name: readable_name, flags: output.StateFlags, position: position, dimensions: dimensions, }); } result } /// Win32 implementation of the main `get_primary_monitor` function. pub fn
() -> MonitorID { // we simply get all available monitors and return the one with the `PRIMARY_DEVICE` flag // TODO: it is possible to query the win32 API for the primary monitor, this should be done // instead for monitor in get_available_monitors().into_iter() { if (monitor.flags & winapi::DISPLAY_DEVICE_PRIMARY_DEVICE)!= 0 { return monitor } } panic!("Failed to find the primary monitor") } impl MonitorID { /// See the docs if the crate root file. pub fn get_name(&self) -> Option<String> { Some(self.readable_name.clone()) } /// See the docs if the crate root file. pub fn get_dimensions(&self) -> (uint, uint) { // TODO: retreive the dimensions every time this is called self.dimensions } /// This is a Win32-only function for `MonitorID` that returns the system name of the device. pub fn get_system_name(&self) -> &[winapi::WCHAR] { // TODO: retreive the position every time this is called self.name.as_slice() } /// This is a Win32-only function for `MonitorID` that returns the position of the /// monitor on the desktop. /// A window that is positionned at these coordinates will overlap the monitor. pub fn get_position(&self) -> (uint, uint) { self.position } }
get_primary_monitor
identifier_name
monitor.rs
use winapi; use std::collections::RingBuf; /// Win32 implementation of the main `MonitorID` object. pub struct MonitorID { /// The system name of the monitor. name: [winapi::WCHAR; 32], /// Name to give to the user. readable_name: String, /// See the `StateFlags` element here: /// http://msdn.microsoft.com/en-us/library/dd183569(v=vs.85).aspx flags: winapi::DWORD, /// The position of the monitor in pixels on the desktop. /// /// A window that is positionned at these coordinates will overlap the monitor. position: (uint, uint), /// The current resolution in pixels on the monitor. dimensions: (uint, uint), } /// Win32 implementation of the main `get_available_monitors` function. pub fn get_available_monitors() -> RingBuf<MonitorID> { use std::{iter, mem, ptr}; // return value let mut result = RingBuf::new(); // enumerating the devices is done by querying device 0, then device 1, then device 2, etc. // until the query function returns null for id in iter::count(0u, 1) { // getting the DISPLAY_DEVICEW object of the current device let output = { let mut output: winapi::DISPLAY_DEVICEW = unsafe { mem::zeroed() }; output.cb = mem::size_of::<winapi::DISPLAY_DEVICEW>() as winapi::DWORD; if unsafe { winapi::EnumDisplayDevicesW(ptr::null(), id as winapi::DWORD, &mut output, 0) } == 0 { // the device doesn't exist, which means we have finished enumerating break; } if (output.StateFlags & winapi::DISPLAY_DEVICE_ACTIVE) == 0 || (output.StateFlags & winapi::DISPLAY_DEVICE_MIRRORING_DRIVER)!= 0 { // the device is not active // the Win32 api usually returns a lot of inactive devices continue; } output }; // computing the human-friendly name let readable_name = String::from_utf16_lossy(output.DeviceString.as_slice()); let readable_name = readable_name.as_slice().trim_right_matches(0 as char).to_string(); // getting the position let (position, dimensions) = unsafe { let mut dev: winapi::DEVMODEW = mem::zeroed(); dev.dmSize = mem::size_of::<winapi::DEVMODEW>() as winapi::WORD; if winapi::EnumDisplaySettingsExW(output.DeviceName.as_ptr(), winapi::ENUM_CURRENT_SETTINGS, &mut dev, 0) == 0 { continue; } let point: &winapi::POINTL = mem::transmute(&dev.union1); let position = (point.x as uint, point.y as uint); let dimensions = (dev.dmPelsWidth as uint, dev.dmPelsHeight as uint); (position, dimensions) }; // adding to the resulting list result.push_back(MonitorID { name: output.DeviceName, readable_name: readable_name, flags: output.StateFlags, position: position, dimensions: dimensions, }); } result } /// Win32 implementation of the main `get_primary_monitor` function. pub fn get_primary_monitor() -> MonitorID {
// TODO: it is possible to query the win32 API for the primary monitor, this should be done // instead for monitor in get_available_monitors().into_iter() { if (monitor.flags & winapi::DISPLAY_DEVICE_PRIMARY_DEVICE)!= 0 { return monitor } } panic!("Failed to find the primary monitor") } impl MonitorID { /// See the docs if the crate root file. pub fn get_name(&self) -> Option<String> { Some(self.readable_name.clone()) } /// See the docs if the crate root file. pub fn get_dimensions(&self) -> (uint, uint) { // TODO: retreive the dimensions every time this is called self.dimensions } /// This is a Win32-only function for `MonitorID` that returns the system name of the device. pub fn get_system_name(&self) -> &[winapi::WCHAR] { // TODO: retreive the position every time this is called self.name.as_slice() } /// This is a Win32-only function for `MonitorID` that returns the position of the /// monitor on the desktop. /// A window that is positionned at these coordinates will overlap the monitor. pub fn get_position(&self) -> (uint, uint) { self.position } }
// we simply get all available monitors and return the one with the `PRIMARY_DEVICE` flag
random_line_split
mod.rs
/// Terminal functionality built upon core VGA driver pub mod terminal; pub const VIDEO_WIDTH: usize = 80; pub const VIDEO_HEIGHT: usize = 25; #[allow(dead_code)] #[repr(u8)] pub enum Color { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12,
Yellow = 14, White = 15, } pub const WHITE: u8 = Color::new(Color::White, Color::Black); pub const GREEN: u8 = Color::new(Color::Green, Color::Black); pub const RED: u8 = Color::new(Color::Red, Color::Black); pub const LCYAN: u8 = Color::new(Color::LightCyan, Color::Black); impl Color { pub const fn new(fg: Color, bg: Color) -> u8 { (bg as u8) << 4 | (fg as u8) } } pub struct Entry(u16); impl Entry { pub fn new(c: u8, color: u8) -> Entry { Entry((color as u16) << 8 | (c as u16)) } pub fn from_u16(data: u16) -> Entry { Entry(data) } } pub struct Writer { ptr: usize, } impl Writer { pub fn new(ptr: usize) -> Writer { Writer { ptr: ptr } } unsafe fn get_buffer(&self) -> *mut u16 { self.ptr as *mut u16 } pub fn at(&self, index: usize) -> Entry { Entry::from_u16(unsafe { *self.get_buffer().offset(index as isize) }) } pub fn write_index(&self, entry: Entry, index: usize) { unsafe { *self.get_buffer().offset(index as isize) = entry.0 as u16; } } pub fn write_pos(&self, entry: Entry, x: usize, y: usize) { let index = y * VIDEO_WIDTH + x; unsafe { *self.get_buffer().offset(index as isize) = entry.0 as u16; } } }
Pink = 13,
random_line_split
mod.rs
/// Terminal functionality built upon core VGA driver pub mod terminal; pub const VIDEO_WIDTH: usize = 80; pub const VIDEO_HEIGHT: usize = 25; #[allow(dead_code)] #[repr(u8)] pub enum Color { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, Pink = 13, Yellow = 14, White = 15, } pub const WHITE: u8 = Color::new(Color::White, Color::Black); pub const GREEN: u8 = Color::new(Color::Green, Color::Black); pub const RED: u8 = Color::new(Color::Red, Color::Black); pub const LCYAN: u8 = Color::new(Color::LightCyan, Color::Black); impl Color { pub const fn new(fg: Color, bg: Color) -> u8 { (bg as u8) << 4 | (fg as u8) } } pub struct
(u16); impl Entry { pub fn new(c: u8, color: u8) -> Entry { Entry((color as u16) << 8 | (c as u16)) } pub fn from_u16(data: u16) -> Entry { Entry(data) } } pub struct Writer { ptr: usize, } impl Writer { pub fn new(ptr: usize) -> Writer { Writer { ptr: ptr } } unsafe fn get_buffer(&self) -> *mut u16 { self.ptr as *mut u16 } pub fn at(&self, index: usize) -> Entry { Entry::from_u16(unsafe { *self.get_buffer().offset(index as isize) }) } pub fn write_index(&self, entry: Entry, index: usize) { unsafe { *self.get_buffer().offset(index as isize) = entry.0 as u16; } } pub fn write_pos(&self, entry: Entry, x: usize, y: usize) { let index = y * VIDEO_WIDTH + x; unsafe { *self.get_buffer().offset(index as isize) = entry.0 as u16; } } }
Entry
identifier_name
util.rs
#[cfg(test)] use std::process::Command; #[cfg(test)] use rand::{self, Rng}; #[cfg(test)] use std::env::temp_dir; #[cfg(test)] use std::ffi::{OsString}; #[cfg(test)] use std::fs::File; #[cfg(test)] use std::io::prelude::*; #[cfg(test)] use std::str; macro_rules! try_opt( ($e:expr) => (match $e { Some(e) => e, None => return None }) ); macro_rules! try_opt_void( ($e:expr) => (match $e { Some(e) => e, None => return }) ); #[inline(always)] pub fn bits(b: u16, start: u8, len: u8) -> u8 { bits16(b, start, len) as u8 } #[inline(always)] pub fn bits16(b: u16, start: u8, len: u8) -> u16 { (b >> start & ((1 << len) - 1)) } #[inline(always)] pub fn bit(b: u8, pos: usize) -> u8
#[inline(always)] pub fn bit16(b: u16, pos: usize) -> u8 { ((b >> pos) & 1) as u8 } #[inline(always)] pub fn bitneg(b: u8, pos: usize) -> u8 { !bit(b, pos) & 1 } #[inline(always)] pub fn bitneg16(b: u16, pos: usize) -> u8 { !bit16(b, pos) & 1 } #[cfg(test)] pub fn assemble_to_file(code: &str) -> OsString { let input_name = tmpfile(); let middle_name = tmpfile(); let output_name = tmpfile(); let mut input_file = File::create(input_name.clone()).unwrap(); input_file.write_all(code.as_bytes()).unwrap(); let o = Command::new("avr-gcc") .arg("-s") .arg("-o") .arg(middle_name.clone()) .arg("-Wa,-mmcu=atmega32") .arg(input_name) .output() .expect("avr-gcc failed"); if!o.status.success() { println!("avr-gcc: {:?}, {:?}", str::from_utf8(&o.stdout).unwrap(), str::from_utf8(&o.stderr).unwrap()); } let o = Command::new("avr-objcopy") .arg("-O").arg("binary") .arg(middle_name) .arg(output_name.clone()) .output() .expect("avr-objcopy failed"); if!o.status.success() { println!("avr-objcopy: {:?}, {:?}", str::from_utf8(&o.stdout).unwrap(), str::from_utf8(&o.stderr).unwrap()); } output_name } #[cfg(test)] #[allow(dead_code)] pub fn assemble(code: &str) -> Vec<u8> { let mut output = File::open(assemble_to_file(code)).unwrap(); let mut assembled = Vec::new(); output.read_to_end(&mut assembled).unwrap(); // println!("Assembled: {:?}", assembled); assembled } #[cfg(test)] fn tmpfile() -> OsString { let s = rand::thread_rng() .gen_ascii_chars() .take(10) .collect::<String>(); let mut file = temp_dir(); file.push("vm-".to_string() + &s + ".s"); file.into_os_string() }
{ (b >> pos) & 1 }
identifier_body
util.rs
#[cfg(test)] use std::process::Command; #[cfg(test)] use rand::{self, Rng}; #[cfg(test)] use std::env::temp_dir; #[cfg(test)] use std::ffi::{OsString}; #[cfg(test)] use std::fs::File; #[cfg(test)] use std::io::prelude::*; #[cfg(test)] use std::str; macro_rules! try_opt( ($e:expr) => (match $e { Some(e) => e, None => return None }) ); macro_rules! try_opt_void( ($e:expr) => (match $e { Some(e) => e, None => return }) ); #[inline(always)] pub fn bits(b: u16, start: u8, len: u8) -> u8 { bits16(b, start, len) as u8 } #[inline(always)] pub fn bits16(b: u16, start: u8, len: u8) -> u16 { (b >> start & ((1 << len) - 1)) } #[inline(always)] pub fn bit(b: u8, pos: usize) -> u8 { (b >> pos) & 1 } #[inline(always)] pub fn bit16(b: u16, pos: usize) -> u8 { ((b >> pos) & 1) as u8 } #[inline(always)] pub fn bitneg(b: u8, pos: usize) -> u8 { !bit(b, pos) & 1 } #[inline(always)] pub fn bitneg16(b: u16, pos: usize) -> u8 { !bit16(b, pos) & 1 } #[cfg(test)] pub fn assemble_to_file(code: &str) -> OsString { let input_name = tmpfile(); let middle_name = tmpfile(); let output_name = tmpfile(); let mut input_file = File::create(input_name.clone()).unwrap(); input_file.write_all(code.as_bytes()).unwrap(); let o = Command::new("avr-gcc") .arg("-s") .arg("-o") .arg(middle_name.clone()) .arg("-Wa,-mmcu=atmega32") .arg(input_name) .output() .expect("avr-gcc failed"); if!o.status.success()
let o = Command::new("avr-objcopy") .arg("-O").arg("binary") .arg(middle_name) .arg(output_name.clone()) .output() .expect("avr-objcopy failed"); if!o.status.success() { println!("avr-objcopy: {:?}, {:?}", str::from_utf8(&o.stdout).unwrap(), str::from_utf8(&o.stderr).unwrap()); } output_name } #[cfg(test)] #[allow(dead_code)] pub fn assemble(code: &str) -> Vec<u8> { let mut output = File::open(assemble_to_file(code)).unwrap(); let mut assembled = Vec::new(); output.read_to_end(&mut assembled).unwrap(); // println!("Assembled: {:?}", assembled); assembled } #[cfg(test)] fn tmpfile() -> OsString { let s = rand::thread_rng() .gen_ascii_chars() .take(10) .collect::<String>(); let mut file = temp_dir(); file.push("vm-".to_string() + &s + ".s"); file.into_os_string() }
{ println!("avr-gcc: {:?}, {:?}", str::from_utf8(&o.stdout).unwrap(), str::from_utf8(&o.stderr).unwrap()); }
conditional_block
util.rs
#[cfg(test)] use std::process::Command; #[cfg(test)] use rand::{self, Rng}; #[cfg(test)] use std::env::temp_dir; #[cfg(test)] use std::ffi::{OsString}; #[cfg(test)] use std::fs::File; #[cfg(test)] use std::io::prelude::*; #[cfg(test)] use std::str; macro_rules! try_opt( ($e:expr) => (match $e { Some(e) => e, None => return None }) ); macro_rules! try_opt_void( ($e:expr) => (match $e { Some(e) => e, None => return }) ); #[inline(always)] pub fn bits(b: u16, start: u8, len: u8) -> u8 { bits16(b, start, len) as u8 } #[inline(always)] pub fn bits16(b: u16, start: u8, len: u8) -> u16 { (b >> start & ((1 << len) - 1)) } #[inline(always)] pub fn bit(b: u8, pos: usize) -> u8 { (b >> pos) & 1 } #[inline(always)] pub fn bit16(b: u16, pos: usize) -> u8 { ((b >> pos) & 1) as u8 } #[inline(always)] pub fn
(b: u8, pos: usize) -> u8 { !bit(b, pos) & 1 } #[inline(always)] pub fn bitneg16(b: u16, pos: usize) -> u8 { !bit16(b, pos) & 1 } #[cfg(test)] pub fn assemble_to_file(code: &str) -> OsString { let input_name = tmpfile(); let middle_name = tmpfile(); let output_name = tmpfile(); let mut input_file = File::create(input_name.clone()).unwrap(); input_file.write_all(code.as_bytes()).unwrap(); let o = Command::new("avr-gcc") .arg("-s") .arg("-o") .arg(middle_name.clone()) .arg("-Wa,-mmcu=atmega32") .arg(input_name) .output() .expect("avr-gcc failed"); if!o.status.success() { println!("avr-gcc: {:?}, {:?}", str::from_utf8(&o.stdout).unwrap(), str::from_utf8(&o.stderr).unwrap()); } let o = Command::new("avr-objcopy") .arg("-O").arg("binary") .arg(middle_name) .arg(output_name.clone()) .output() .expect("avr-objcopy failed"); if!o.status.success() { println!("avr-objcopy: {:?}, {:?}", str::from_utf8(&o.stdout).unwrap(), str::from_utf8(&o.stderr).unwrap()); } output_name } #[cfg(test)] #[allow(dead_code)] pub fn assemble(code: &str) -> Vec<u8> { let mut output = File::open(assemble_to_file(code)).unwrap(); let mut assembled = Vec::new(); output.read_to_end(&mut assembled).unwrap(); // println!("Assembled: {:?}", assembled); assembled } #[cfg(test)] fn tmpfile() -> OsString { let s = rand::thread_rng() .gen_ascii_chars() .take(10) .collect::<String>(); let mut file = temp_dir(); file.push("vm-".to_string() + &s + ".s"); file.into_os_string() }
bitneg
identifier_name
util.rs
#[cfg(test)] use std::process::Command; #[cfg(test)] use rand::{self, Rng}; #[cfg(test)] use std::env::temp_dir; #[cfg(test)] use std::ffi::{OsString}; #[cfg(test)] use std::fs::File; #[cfg(test)] use std::io::prelude::*; #[cfg(test)] use std::str; macro_rules! try_opt( ($e:expr) => (match $e { Some(e) => e, None => return None }) ); macro_rules! try_opt_void( ($e:expr) => (match $e { Some(e) => e, None => return }) ); #[inline(always)] pub fn bits(b: u16, start: u8, len: u8) -> u8 { bits16(b, start, len) as u8 } #[inline(always)] pub fn bits16(b: u16, start: u8, len: u8) -> u16 { (b >> start & ((1 << len) - 1)) } #[inline(always)] pub fn bit(b: u8, pos: usize) -> u8 { (b >> pos) & 1 } #[inline(always)]
((b >> pos) & 1) as u8 } #[inline(always)] pub fn bitneg(b: u8, pos: usize) -> u8 { !bit(b, pos) & 1 } #[inline(always)] pub fn bitneg16(b: u16, pos: usize) -> u8 { !bit16(b, pos) & 1 } #[cfg(test)] pub fn assemble_to_file(code: &str) -> OsString { let input_name = tmpfile(); let middle_name = tmpfile(); let output_name = tmpfile(); let mut input_file = File::create(input_name.clone()).unwrap(); input_file.write_all(code.as_bytes()).unwrap(); let o = Command::new("avr-gcc") .arg("-s") .arg("-o") .arg(middle_name.clone()) .arg("-Wa,-mmcu=atmega32") .arg(input_name) .output() .expect("avr-gcc failed"); if!o.status.success() { println!("avr-gcc: {:?}, {:?}", str::from_utf8(&o.stdout).unwrap(), str::from_utf8(&o.stderr).unwrap()); } let o = Command::new("avr-objcopy") .arg("-O").arg("binary") .arg(middle_name) .arg(output_name.clone()) .output() .expect("avr-objcopy failed"); if!o.status.success() { println!("avr-objcopy: {:?}, {:?}", str::from_utf8(&o.stdout).unwrap(), str::from_utf8(&o.stderr).unwrap()); } output_name } #[cfg(test)] #[allow(dead_code)] pub fn assemble(code: &str) -> Vec<u8> { let mut output = File::open(assemble_to_file(code)).unwrap(); let mut assembled = Vec::new(); output.read_to_end(&mut assembled).unwrap(); // println!("Assembled: {:?}", assembled); assembled } #[cfg(test)] fn tmpfile() -> OsString { let s = rand::thread_rng() .gen_ascii_chars() .take(10) .collect::<String>(); let mut file = temp_dir(); file.push("vm-".to_string() + &s + ".s"); file.into_os_string() }
pub fn bit16(b: u16, pos: usize) -> u8 {
random_line_split
content.rs
#![stable] use libc; use std; /// Opaque struct which holds a reference to the underlying Clutter object. #[repr(C)] pub struct ContentRef { opaque: *mut libc::c_void } /// Delegate for painting the content of an actor /// /// Content is an interface to implement types responsible for painting the /// content of an Actor. /// /// Multiple actors can use the same Content instance, in order to share the /// resources associated with painting the same content. /// /// _Since 1.10_ pub trait Content { /// Returns a pointer to the the underlying C object. /// /// Generally only used internally. fn as_content(&self) -> *mut libc::c_void; /// Retrieves the natural size of the content, if any. /// /// The natural size of a Content is defined as the size the content would /// have regardless of the allocation of the actor that is painting it, for /// instance the size of an image data. /// /// _Since 1.10_ fn get_preferred_size(&mut self) -> (bool, f32, f32) { unsafe { let mut width:f32 = std::intrinsics::init(); let mut height:f32 = std::intrinsics::init(); let foreign_result = clutter_content_get_preferred_size(self.as_content(), &mut width, &mut height); return (foreign_result!= 0, width, height); } } /// Invalidates a Content. /// /// This function should be called by Content implementations when they change /// the way the content should be painted regardless of the actor state. /// /// _Since 1.10_ fn invalidate(&mut self) { unsafe {
} } } impl Content for ContentRef { fn as_content(&self) -> *mut libc::c_void { return self.opaque; } } extern { fn clutter_content_get_preferred_size(self_value: *mut libc::c_void, width: *mut f32, height: *mut f32) -> i32; fn clutter_content_invalidate(self_value: *mut libc::c_void); }
clutter_content_invalidate(self.as_content());
random_line_split