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
c_str.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![unstable(feature = "std_misc")] use convert::{Into, From}; use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering}; use error::Error; use fmt; use io; use iter::Iterator; use libc; use mem; #[allow(deprecated)] use old_io; use ops::Deref; use option::Option::{self, Some, None}; use result::Result::{self, Ok, Err}; use slice; use string::String; use vec::Vec; /// A type representing an owned C-compatible string /// /// This type serves the primary purpose of being able to safely generate a /// C-compatible string from a Rust byte slice or vector. An instance of this /// type is a static guarantee that the underlying bytes contain no interior 0 /// bytes and the final byte is 0. /// /// A `CString` is created from either a byte slice or a byte vector. After /// being created, a `CString` predominately inherits all of its methods from /// the `Deref` implementation to `[libc::c_char]`. Note that the underlying /// array is represented as an array of `libc::c_char` as opposed to `u8`. A /// `u8` slice can be obtained with the `as_bytes` method. Slices produced from /// a `CString` do *not* contain the trailing nul terminator unless otherwise /// specified. /// /// # Examples /// /// ```no_run /// # #![feature(libc)] /// # extern crate libc; /// # fn main() { /// use std::ffi::CString; /// use libc; /// /// extern { /// fn my_printer(s: *const libc::c_char); /// } /// /// let to_print = &b"Hello, world!"[..]; /// let c_to_print = CString::new(to_print).unwrap(); /// unsafe { /// my_printer(c_to_print.as_ptr()); /// } /// # } /// ``` #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] #[stable(feature = "rust1", since = "1.0.0")] pub struct CString { inner: Vec<u8>, } /// Representation of a borrowed C string. /// /// This dynamically sized type is only safely constructed via a borrowed /// version of an instance of `CString`. This type can be constructed from a raw /// C string as well and represents a C string borrowed from another location. /// /// Note that this structure is **not** `repr(C)` and is not recommended to be /// placed in the signatures of FFI functions. Instead safe wrappers of FFI /// functions may leverage the unsafe `from_ptr` constructor to provide a safe /// interface to other consumers. /// /// # Examples /// /// Inspecting a foreign C string /// /// ```no_run /// # #![feature(libc)] /// extern crate libc; /// use std::ffi::CStr; /// /// extern { fn my_string() -> *const libc::c_char; } /// /// fn main() { /// unsafe { /// let slice = CStr::from_ptr(my_string()); /// println!("string length: {}", slice.to_bytes().len()); /// } /// } /// ``` /// /// Passing a Rust-originating C string /// /// ```no_run /// # #![feature(libc)] /// extern crate libc; /// use std::ffi::{CString, CStr}; /// /// fn work(data: &CStr) { /// extern { fn work_with(data: *const libc::c_char); } /// /// unsafe { work_with(data.as_ptr()) } /// } /// /// fn main() { /// let s = CString::new("data data data data").unwrap(); /// work(&s); /// } /// ``` #[derive(Hash)] #[stable(feature = "rust1", since = "1.0.0")] pub struct CStr { // FIXME: this should not be represented with a DST slice but rather with // just a raw `libc::c_char` along with some form of marker to make // this an unsized type. Essentially `sizeof(&CStr)` should be the // same as `sizeof(&c_char)` but `CStr` should be an unsized type. inner: [libc::c_char] } /// An error returned from `CString::new` to indicate that a nul byte was found /// in the vector provided. #[derive(Clone, PartialEq, Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub struct NulError(usize, Vec<u8>); impl CString { /// Create a new C-compatible string from a container of bytes. /// /// This method will consume the provided data and use the underlying bytes /// to construct a new string, ensuring that there is a trailing 0 byte. /// /// # Examples /// /// ```no_run /// # #![feature(libc)] /// extern crate libc; /// use std::ffi::CString; /// /// extern { fn puts(s: *const libc::c_char); } /// /// fn main() { /// let to_print = CString::new("Hello!").unwrap(); /// unsafe { /// puts(to_print.as_ptr()); /// } /// } /// ``` /// /// # Errors /// /// This function will return an error if the bytes yielded contain an /// internal 0 byte. The error returned will contain the bytes as well as /// the position of the nul byte. #[stable(feature = "rust1", since = "1.0.0")] pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> { let bytes = t.into(); match bytes.iter().position(|x| *x == 0) { Some(i) => Err(NulError(i, bytes)), None => Ok(unsafe { CString::from_vec_unchecked(bytes) }), } } /// Create a C-compatible string from a byte vector without checking for /// interior 0 bytes. /// /// This method is equivalent to `from_vec` except that no runtime assertion /// is made that `v` contains no 0 bytes. #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString { v.push(0); CString { inner: v } } /// Returns the contents of this `CString` as a slice of bytes. /// /// The returned slice does **not** contain the trailing nul separator and /// it is guaranteed to not have any interior nul bytes. #[stable(feature = "rust1", since = "1.0.0")] pub fn as_bytes(&self) -> &[u8] { &self.inner[..self.inner.len() - 1] } /// Equivalent to the `as_bytes` function except that the returned slice /// includes the trailing nul byte. #[stable(feature = "rust1", since = "1.0.0")] pub fn as_bytes_with_nul(&self) -> &[u8] { &self.inner } } #[stable(feature = "rust1", since = "1.0.0")] impl Deref for CString { type Target = CStr; fn deref(&self) -> &CStr { unsafe { mem::transmute(self.as_bytes_with_nul()) } } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for CString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&String::from_utf8_lossy(self.as_bytes()), f) } } impl NulError { /// Returns the position of the nul byte in the slice that was provided to /// `CString::from_vec`. #[stable(feature = "rust1", since = "1.0.0")] pub fn nul_position(&self) -> usize { self.0 } /// Consumes this error, returning the underlying vector of bytes which /// generated the error in the first place. #[stable(feature = "rust1", since = "1.0.0")] pub fn into_vec(self) -> Vec<u8> { self.1 } } #[stable(feature = "rust1", since = "1.0.0")] impl Error for NulError { fn description(&self) -> &str { "nul byte found in data" } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for NulError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "nul byte found in provided data at position: {}", self.0) } } #[stable(feature = "rust1", since = "1.0.0")] impl From<NulError> for io::Error { fn from(_: NulError) -> io::Error { io::Error::new(io::ErrorKind::InvalidInput, "data provided contains a nul byte") } } #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] impl From<NulError> for old_io::IoError { fn from(_: NulError) -> old_io::IoError { old_io::IoError { kind: old_io::IoErrorKind::InvalidInput, desc: "data provided contains a nul byte", detail: None } } } impl CStr { /// Cast a raw C string to a safe C string wrapper. /// /// This function will cast the provided `ptr` to the `CStr` wrapper which /// allows inspection and interoperation of non-owned C strings. This method /// is unsafe for a number of reasons: /// /// * There is no guarantee to the validity of `ptr` /// * The returned lifetime is not guaranteed to be the actual lifetime of /// `ptr` /// * There is no guarantee that the memory pointed to by `ptr` contains a /// valid nul terminator byte at the end of the string. /// /// > **Note**: This operation is intended to be a 0-cost cast but it is /// > currently implemented with an up-front calculation of the length of /// > the string. This is not guaranteed to always be the case. /// /// # Examples /// /// ```no_run /// # #![feature(libc)] /// # extern crate libc; /// # fn main() { /// use std::ffi::CStr; /// use std::str; /// use libc; /// /// extern { /// fn my_string() -> *const libc::c_char; /// } /// /// unsafe { /// let slice = CStr::from_ptr(my_string()); /// println!("string returned: {}", /// str::from_utf8(slice.to_bytes()).unwrap()); /// } /// # } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_ptr<'a>(ptr: *const libc::c_char) -> &'a CStr { let len = libc::strlen(ptr); mem::transmute(slice::from_raw_parts(ptr, len as usize + 1)) } /// Return the inner pointer to this C string. /// /// The returned pointer will be valid for as long as `self` is and points /// to a contiguous region of memory terminated with a 0 byte to represent /// the end of the string. #[stable(feature = "rust1", since = "1.0.0")] pub fn as_ptr(&self) -> *const libc::c_char { self.inner.as_ptr() } /// Convert this C string to a byte slice. /// /// This function will calculate the length of this string (which normally /// requires a linear amount of work to be done) and then return the /// resulting slice of `u8` elements. /// /// The returned slice will **not** contain the trailing nul that this C /// string has. /// /// > **Note**: This method is currently implemented as a 0-cost cast, but /// > it is planned to alter its definition in the future to perform the /// > length calculation whenever this method is called. #[stable(feature = "rust1", since = "1.0.0")] pub fn to_bytes(&self) -> &[u8] { let bytes = self.to_bytes_with_nul(); &bytes[..bytes.len() - 1] } /// Convert this C string to a byte slice containing the trailing 0 byte. /// /// This function is the equivalent of `to_bytes` except that it will retain /// the trailing nul instead of chopping it off. /// /// > **Note**: This method is currently implemented as a 0-cost cast, but /// > it is planned to alter its definition in the future to perform the /// > length calculation whenever this method is called. #[stable(feature = "rust1", since = "1.0.0")] pub fn to_bytes_with_nul(&self) -> &[u8] { unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&self.inner) } } } #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for CStr { fn eq(&self, other: &CStr) -> bool { self.to_bytes().eq(other.to_bytes()) } } #[stable(feature = "rust1", since = "1.0.0")] impl Eq for CStr {} #[stable(feature = "rust1", since = "1.0.0")] impl PartialOrd for CStr { fn partial_cmp(&self, other: &CStr) -> Option<Ordering> { self.to_bytes().partial_cmp(&other.to_bytes()) } } #[stable(feature = "rust1", since = "1.0.0")] impl Ord for CStr { fn cmp(&self, other: &CStr) -> Ordering { self.to_bytes().cmp(&other.to_bytes()) } } #[cfg(test)] mod tests { use prelude::v1::*; use super::*; use libc; #[test] fn c_to_rust()
#[test] fn simple() { let s = CString::new("1234").unwrap(); assert_eq!(s.as_bytes(), b"1234"); assert_eq!(s.as_bytes_with_nul(), b"1234\0"); } #[test] fn build_with_zero1() { assert!(CString::new(&b"\0"[..]).is_err()); } #[test] fn build_with_zero2() { assert!(CString::new(vec![0]).is_err()); } #[test] fn build_with_zero3() { unsafe { let s = CString::from_vec_unchecked(vec![0]); assert_eq!(s.as_bytes(), b"\0"); } } #[test] fn formatted() { let s = CString::new(&b"12"[..]).unwrap(); assert_eq!(format!("{:?}", s), "\"12\""); } #[test] fn borrowed() { unsafe { let s = CStr::from_ptr(b"12\0".as_ptr() as *const _); assert_eq!(s.to_bytes(), b"12"); assert_eq!(s.to_bytes_with_nul(), b"12\0"); } } }
{ let data = b"123\0"; let ptr = data.as_ptr() as *const libc::c_char; unsafe { assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123"); assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0"); } }
identifier_body
ptr.rs
/*! Typed virtual address. */ use std::{cmp, fmt, hash, mem, str}; use std::marker::PhantomData; use crate::Pod; use super::image::{Va, SignedVa}; /// Typed virtual address. #[repr(transparent)] pub struct Ptr<T:?Sized = ()> { va: Va, marker: PhantomData<fn() -> T> } impl<T:?Sized> Ptr<T> { // Work around unstable const fn features const MARKER: PhantomData<fn() -> T> = PhantomData; /// Null pointer constant. pub const NULL: Ptr<T> = Ptr { va: 0, marker: PhantomData }; /// Creates a null pointer. pub const fn null() -> Ptr<T> { Ptr::NULL } /// Returns true if the pointer is null. pub const fn is_null(self) -> bool { self.va == 0 } /// Constructs a pointer with an offset. pub const fn member(va: Va, offset: u32) -> Ptr<T> { let va = va + offset as Va; Ptr { va, marker: Self::MARKER } } /// Casts the pointer to a different type keeping the pointer address fixed. pub const fn cast<U:?Sized>(self) -> Ptr<U> { Ptr { va: self.va, marker: Ptr::<U>::MARKER } } /// Offsets and casts the pointer. /// /// Because the type of the current and the target may be unrelated, this is a byte offset. /// /// # Examples /// /// ``` /// use pelite::pe64::Ptr; /// /// #[repr(C)] /// struct Composite { /// int: i32, /// float: f32, /// } /// /// let p: Ptr<Composite> = Ptr::from(0x2000); /// let target = p.offset::<f32>(4); /// /// assert_eq!(target, Ptr::from(0x2004)); /// ``` pub const fn offset<U:?Sized>(self, offset: SignedVa) -> Ptr<U> { let va = self.va.wrapping_add(offset as Va); Ptr { va, marker: Ptr::<U>::MARKER } } /// Returns the raw integer, type ascription helper. pub const fn into_raw(self) -> Va { self.va } /// Formats the pointer. fn fmt(self) -> [u8; mem::size_of::<Va>() * 2 + 2] { let mut s = [0; mem::size_of::<Va>() * 2 + 2]; s[0] = b'0'; s[1] = b'x'; let mut va = self.va; for i in 0..mem::size_of::<Va>() * 2 { va = va.rotate_left(4); let digit = (va & 0xf) as u8; let chr = if digit < 10 { b'0' + digit } else { b'a' + (digit - 10) }; s[i + 2] = chr; } return s; } } impl<T> Ptr<[T]> { /// Decays the pointer from `[T]` to `T`. pub const fn decay(self) -> Ptr<T> { Ptr { va: self.va, marker: Ptr::<T>::MARKER } } /// Pointer arithmetic, gets the pointer of an element at the specified index. pub const fn at(self, i: usize) -> Ptr<T> { let va = self.va + (i * mem::size_of::<T>()) as Va; Ptr { va, marker: Ptr::<T>::MARKER } } } unsafe impl<T:?Sized> Pod for Ptr<T> where Ptr<T>:'static {} impl<T:?Sized> Copy for Ptr<T> {} impl<T:?Sized> Clone for Ptr<T> { fn clone(&self) -> Ptr<T> { *self } } impl<T:?Sized> Default for Ptr<T> { fn default() -> Ptr<T> { Ptr::NULL } } impl<T:?Sized> Eq for Ptr<T> {} impl<T:?Sized> PartialEq for Ptr<T> { fn eq(&self, rhs: &Ptr<T>) -> bool { self.va == rhs.va } } impl<T:?Sized> PartialOrd for Ptr<T> { fn partial_cmp(&self, rhs: &Ptr<T>) -> Option<cmp::Ordering> { self.va.partial_cmp(&rhs.va) } } impl<T:?Sized> Ord for Ptr<T> { fn cmp(&self, rhs: &Ptr<T>) -> cmp::Ordering { self.va.cmp(&rhs.va) } } impl<T:?Sized> hash::Hash for Ptr<T> { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.va.hash(state) } } impl<T:?Sized> From<Va> for Ptr<T> { fn from(va: Va) -> Ptr<T> { Ptr { va, marker: PhantomData } } } impl<T:?Sized> From<Ptr<T>> for Va { fn from(ptr: Ptr<T>) -> Va { ptr.va } } impl<T:?Sized> AsRef<Va> for Ptr<T> { fn as_ref(&self) -> &Va { &self.va } } impl<T:?Sized> AsMut<Va> for Ptr<T> { fn as_mut(&mut self) -> &mut Va { &mut self.va } } impl<T:?Sized> fmt::Debug for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let buf = Ptr::fmt(*self); f.write_str(unsafe { str::from_utf8_unchecked(&buf) }) } } impl<T:?Sized> fmt::UpperHex for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.va.fmt(f) } } impl<T:?Sized> fmt::LowerHex for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.va.fmt(f) } }
impl<T:?Sized> fmt::Display for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let buf = Ptr::fmt(*self); f.write_str(unsafe { str::from_utf8_unchecked(&buf) }) } } #[cfg(feature = "serde")] impl<T:?Sized> serde::Serialize for Ptr<T> { fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { branch! { pe32 { serializer.serialize_u32(self.va) } pe64 { serializer.serialize_u64(self.va) } } } }
random_line_split
ptr.rs
/*! Typed virtual address. */ use std::{cmp, fmt, hash, mem, str}; use std::marker::PhantomData; use crate::Pod; use super::image::{Va, SignedVa}; /// Typed virtual address. #[repr(transparent)] pub struct Ptr<T:?Sized = ()> { va: Va, marker: PhantomData<fn() -> T> } impl<T:?Sized> Ptr<T> { // Work around unstable const fn features const MARKER: PhantomData<fn() -> T> = PhantomData; /// Null pointer constant. pub const NULL: Ptr<T> = Ptr { va: 0, marker: PhantomData }; /// Creates a null pointer. pub const fn null() -> Ptr<T> { Ptr::NULL } /// Returns true if the pointer is null. pub const fn is_null(self) -> bool { self.va == 0 } /// Constructs a pointer with an offset. pub const fn member(va: Va, offset: u32) -> Ptr<T> { let va = va + offset as Va; Ptr { va, marker: Self::MARKER } } /// Casts the pointer to a different type keeping the pointer address fixed. pub const fn cast<U:?Sized>(self) -> Ptr<U> { Ptr { va: self.va, marker: Ptr::<U>::MARKER } } /// Offsets and casts the pointer. /// /// Because the type of the current and the target may be unrelated, this is a byte offset. /// /// # Examples /// /// ``` /// use pelite::pe64::Ptr; /// /// #[repr(C)] /// struct Composite { /// int: i32, /// float: f32, /// } /// /// let p: Ptr<Composite> = Ptr::from(0x2000); /// let target = p.offset::<f32>(4); /// /// assert_eq!(target, Ptr::from(0x2004)); /// ``` pub const fn offset<U:?Sized>(self, offset: SignedVa) -> Ptr<U> { let va = self.va.wrapping_add(offset as Va); Ptr { va, marker: Ptr::<U>::MARKER } } /// Returns the raw integer, type ascription helper. pub const fn into_raw(self) -> Va { self.va } /// Formats the pointer. fn fmt(self) -> [u8; mem::size_of::<Va>() * 2 + 2] { let mut s = [0; mem::size_of::<Va>() * 2 + 2]; s[0] = b'0'; s[1] = b'x'; let mut va = self.va; for i in 0..mem::size_of::<Va>() * 2 { va = va.rotate_left(4); let digit = (va & 0xf) as u8; let chr = if digit < 10 { b'0' + digit } else { b'a' + (digit - 10) }; s[i + 2] = chr; } return s; } } impl<T> Ptr<[T]> { /// Decays the pointer from `[T]` to `T`. pub const fn decay(self) -> Ptr<T> { Ptr { va: self.va, marker: Ptr::<T>::MARKER } } /// Pointer arithmetic, gets the pointer of an element at the specified index. pub const fn at(self, i: usize) -> Ptr<T> { let va = self.va + (i * mem::size_of::<T>()) as Va; Ptr { va, marker: Ptr::<T>::MARKER } } } unsafe impl<T:?Sized> Pod for Ptr<T> where Ptr<T>:'static {} impl<T:?Sized> Copy for Ptr<T> {} impl<T:?Sized> Clone for Ptr<T> { fn clone(&self) -> Ptr<T> { *self } } impl<T:?Sized> Default for Ptr<T> { fn default() -> Ptr<T> { Ptr::NULL } } impl<T:?Sized> Eq for Ptr<T> {} impl<T:?Sized> PartialEq for Ptr<T> { fn
(&self, rhs: &Ptr<T>) -> bool { self.va == rhs.va } } impl<T:?Sized> PartialOrd for Ptr<T> { fn partial_cmp(&self, rhs: &Ptr<T>) -> Option<cmp::Ordering> { self.va.partial_cmp(&rhs.va) } } impl<T:?Sized> Ord for Ptr<T> { fn cmp(&self, rhs: &Ptr<T>) -> cmp::Ordering { self.va.cmp(&rhs.va) } } impl<T:?Sized> hash::Hash for Ptr<T> { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.va.hash(state) } } impl<T:?Sized> From<Va> for Ptr<T> { fn from(va: Va) -> Ptr<T> { Ptr { va, marker: PhantomData } } } impl<T:?Sized> From<Ptr<T>> for Va { fn from(ptr: Ptr<T>) -> Va { ptr.va } } impl<T:?Sized> AsRef<Va> for Ptr<T> { fn as_ref(&self) -> &Va { &self.va } } impl<T:?Sized> AsMut<Va> for Ptr<T> { fn as_mut(&mut self) -> &mut Va { &mut self.va } } impl<T:?Sized> fmt::Debug for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let buf = Ptr::fmt(*self); f.write_str(unsafe { str::from_utf8_unchecked(&buf) }) } } impl<T:?Sized> fmt::UpperHex for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.va.fmt(f) } } impl<T:?Sized> fmt::LowerHex for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.va.fmt(f) } } impl<T:?Sized> fmt::Display for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let buf = Ptr::fmt(*self); f.write_str(unsafe { str::from_utf8_unchecked(&buf) }) } } #[cfg(feature = "serde")] impl<T:?Sized> serde::Serialize for Ptr<T> { fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { branch! { pe32 { serializer.serialize_u32(self.va) } pe64 { serializer.serialize_u64(self.va) } } } }
eq
identifier_name
ptr.rs
/*! Typed virtual address. */ use std::{cmp, fmt, hash, mem, str}; use std::marker::PhantomData; use crate::Pod; use super::image::{Va, SignedVa}; /// Typed virtual address. #[repr(transparent)] pub struct Ptr<T:?Sized = ()> { va: Va, marker: PhantomData<fn() -> T> } impl<T:?Sized> Ptr<T> { // Work around unstable const fn features const MARKER: PhantomData<fn() -> T> = PhantomData; /// Null pointer constant. pub const NULL: Ptr<T> = Ptr { va: 0, marker: PhantomData }; /// Creates a null pointer. pub const fn null() -> Ptr<T> { Ptr::NULL } /// Returns true if the pointer is null. pub const fn is_null(self) -> bool { self.va == 0 } /// Constructs a pointer with an offset. pub const fn member(va: Va, offset: u32) -> Ptr<T> { let va = va + offset as Va; Ptr { va, marker: Self::MARKER } } /// Casts the pointer to a different type keeping the pointer address fixed. pub const fn cast<U:?Sized>(self) -> Ptr<U> { Ptr { va: self.va, marker: Ptr::<U>::MARKER } } /// Offsets and casts the pointer. /// /// Because the type of the current and the target may be unrelated, this is a byte offset. /// /// # Examples /// /// ``` /// use pelite::pe64::Ptr; /// /// #[repr(C)] /// struct Composite { /// int: i32, /// float: f32, /// } /// /// let p: Ptr<Composite> = Ptr::from(0x2000); /// let target = p.offset::<f32>(4); /// /// assert_eq!(target, Ptr::from(0x2004)); /// ``` pub const fn offset<U:?Sized>(self, offset: SignedVa) -> Ptr<U> { let va = self.va.wrapping_add(offset as Va); Ptr { va, marker: Ptr::<U>::MARKER } } /// Returns the raw integer, type ascription helper. pub const fn into_raw(self) -> Va { self.va } /// Formats the pointer. fn fmt(self) -> [u8; mem::size_of::<Va>() * 2 + 2] { let mut s = [0; mem::size_of::<Va>() * 2 + 2]; s[0] = b'0'; s[1] = b'x'; let mut va = self.va; for i in 0..mem::size_of::<Va>() * 2 { va = va.rotate_left(4); let digit = (va & 0xf) as u8; let chr = if digit < 10 { b'0' + digit } else { b'a' + (digit - 10) }; s[i + 2] = chr; } return s; } } impl<T> Ptr<[T]> { /// Decays the pointer from `[T]` to `T`. pub const fn decay(self) -> Ptr<T> { Ptr { va: self.va, marker: Ptr::<T>::MARKER } } /// Pointer arithmetic, gets the pointer of an element at the specified index. pub const fn at(self, i: usize) -> Ptr<T> { let va = self.va + (i * mem::size_of::<T>()) as Va; Ptr { va, marker: Ptr::<T>::MARKER } } } unsafe impl<T:?Sized> Pod for Ptr<T> where Ptr<T>:'static {} impl<T:?Sized> Copy for Ptr<T> {} impl<T:?Sized> Clone for Ptr<T> { fn clone(&self) -> Ptr<T> { *self } } impl<T:?Sized> Default for Ptr<T> { fn default() -> Ptr<T>
} impl<T:?Sized> Eq for Ptr<T> {} impl<T:?Sized> PartialEq for Ptr<T> { fn eq(&self, rhs: &Ptr<T>) -> bool { self.va == rhs.va } } impl<T:?Sized> PartialOrd for Ptr<T> { fn partial_cmp(&self, rhs: &Ptr<T>) -> Option<cmp::Ordering> { self.va.partial_cmp(&rhs.va) } } impl<T:?Sized> Ord for Ptr<T> { fn cmp(&self, rhs: &Ptr<T>) -> cmp::Ordering { self.va.cmp(&rhs.va) } } impl<T:?Sized> hash::Hash for Ptr<T> { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.va.hash(state) } } impl<T:?Sized> From<Va> for Ptr<T> { fn from(va: Va) -> Ptr<T> { Ptr { va, marker: PhantomData } } } impl<T:?Sized> From<Ptr<T>> for Va { fn from(ptr: Ptr<T>) -> Va { ptr.va } } impl<T:?Sized> AsRef<Va> for Ptr<T> { fn as_ref(&self) -> &Va { &self.va } } impl<T:?Sized> AsMut<Va> for Ptr<T> { fn as_mut(&mut self) -> &mut Va { &mut self.va } } impl<T:?Sized> fmt::Debug for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let buf = Ptr::fmt(*self); f.write_str(unsafe { str::from_utf8_unchecked(&buf) }) } } impl<T:?Sized> fmt::UpperHex for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.va.fmt(f) } } impl<T:?Sized> fmt::LowerHex for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.va.fmt(f) } } impl<T:?Sized> fmt::Display for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let buf = Ptr::fmt(*self); f.write_str(unsafe { str::from_utf8_unchecked(&buf) }) } } #[cfg(feature = "serde")] impl<T:?Sized> serde::Serialize for Ptr<T> { fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { branch! { pe32 { serializer.serialize_u32(self.va) } pe64 { serializer.serialize_u64(self.va) } } } }
{ Ptr::NULL }
identifier_body
ptr.rs
/*! Typed virtual address. */ use std::{cmp, fmt, hash, mem, str}; use std::marker::PhantomData; use crate::Pod; use super::image::{Va, SignedVa}; /// Typed virtual address. #[repr(transparent)] pub struct Ptr<T:?Sized = ()> { va: Va, marker: PhantomData<fn() -> T> } impl<T:?Sized> Ptr<T> { // Work around unstable const fn features const MARKER: PhantomData<fn() -> T> = PhantomData; /// Null pointer constant. pub const NULL: Ptr<T> = Ptr { va: 0, marker: PhantomData }; /// Creates a null pointer. pub const fn null() -> Ptr<T> { Ptr::NULL } /// Returns true if the pointer is null. pub const fn is_null(self) -> bool { self.va == 0 } /// Constructs a pointer with an offset. pub const fn member(va: Va, offset: u32) -> Ptr<T> { let va = va + offset as Va; Ptr { va, marker: Self::MARKER } } /// Casts the pointer to a different type keeping the pointer address fixed. pub const fn cast<U:?Sized>(self) -> Ptr<U> { Ptr { va: self.va, marker: Ptr::<U>::MARKER } } /// Offsets and casts the pointer. /// /// Because the type of the current and the target may be unrelated, this is a byte offset. /// /// # Examples /// /// ``` /// use pelite::pe64::Ptr; /// /// #[repr(C)] /// struct Composite { /// int: i32, /// float: f32, /// } /// /// let p: Ptr<Composite> = Ptr::from(0x2000); /// let target = p.offset::<f32>(4); /// /// assert_eq!(target, Ptr::from(0x2004)); /// ``` pub const fn offset<U:?Sized>(self, offset: SignedVa) -> Ptr<U> { let va = self.va.wrapping_add(offset as Va); Ptr { va, marker: Ptr::<U>::MARKER } } /// Returns the raw integer, type ascription helper. pub const fn into_raw(self) -> Va { self.va } /// Formats the pointer. fn fmt(self) -> [u8; mem::size_of::<Va>() * 2 + 2] { let mut s = [0; mem::size_of::<Va>() * 2 + 2]; s[0] = b'0'; s[1] = b'x'; let mut va = self.va; for i in 0..mem::size_of::<Va>() * 2 { va = va.rotate_left(4); let digit = (va & 0xf) as u8; let chr = if digit < 10
else { b'a' + (digit - 10) }; s[i + 2] = chr; } return s; } } impl<T> Ptr<[T]> { /// Decays the pointer from `[T]` to `T`. pub const fn decay(self) -> Ptr<T> { Ptr { va: self.va, marker: Ptr::<T>::MARKER } } /// Pointer arithmetic, gets the pointer of an element at the specified index. pub const fn at(self, i: usize) -> Ptr<T> { let va = self.va + (i * mem::size_of::<T>()) as Va; Ptr { va, marker: Ptr::<T>::MARKER } } } unsafe impl<T:?Sized> Pod for Ptr<T> where Ptr<T>:'static {} impl<T:?Sized> Copy for Ptr<T> {} impl<T:?Sized> Clone for Ptr<T> { fn clone(&self) -> Ptr<T> { *self } } impl<T:?Sized> Default for Ptr<T> { fn default() -> Ptr<T> { Ptr::NULL } } impl<T:?Sized> Eq for Ptr<T> {} impl<T:?Sized> PartialEq for Ptr<T> { fn eq(&self, rhs: &Ptr<T>) -> bool { self.va == rhs.va } } impl<T:?Sized> PartialOrd for Ptr<T> { fn partial_cmp(&self, rhs: &Ptr<T>) -> Option<cmp::Ordering> { self.va.partial_cmp(&rhs.va) } } impl<T:?Sized> Ord for Ptr<T> { fn cmp(&self, rhs: &Ptr<T>) -> cmp::Ordering { self.va.cmp(&rhs.va) } } impl<T:?Sized> hash::Hash for Ptr<T> { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.va.hash(state) } } impl<T:?Sized> From<Va> for Ptr<T> { fn from(va: Va) -> Ptr<T> { Ptr { va, marker: PhantomData } } } impl<T:?Sized> From<Ptr<T>> for Va { fn from(ptr: Ptr<T>) -> Va { ptr.va } } impl<T:?Sized> AsRef<Va> for Ptr<T> { fn as_ref(&self) -> &Va { &self.va } } impl<T:?Sized> AsMut<Va> for Ptr<T> { fn as_mut(&mut self) -> &mut Va { &mut self.va } } impl<T:?Sized> fmt::Debug for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let buf = Ptr::fmt(*self); f.write_str(unsafe { str::from_utf8_unchecked(&buf) }) } } impl<T:?Sized> fmt::UpperHex for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.va.fmt(f) } } impl<T:?Sized> fmt::LowerHex for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.va.fmt(f) } } impl<T:?Sized> fmt::Display for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let buf = Ptr::fmt(*self); f.write_str(unsafe { str::from_utf8_unchecked(&buf) }) } } #[cfg(feature = "serde")] impl<T:?Sized> serde::Serialize for Ptr<T> { fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { branch! { pe32 { serializer.serialize_u32(self.va) } pe64 { serializer.serialize_u64(self.va) } } } }
{ b'0' + digit }
conditional_block
sniffer_task.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::comm::{channel, Receiver, Sender}; use std::task::TaskBuilder; use resource_task::{TargetedLoadResponse}; pub type SnifferTask = Sender<TargetedLoadResponse>; pub fn new_sniffer_task() -> SnifferTask { let(sen, rec) = channel(); let builder = TaskBuilder::new().named("SnifferManager"); builder.spawn(proc() { SnifferManager::new(rec).start(); }); sen } struct SnifferManager { data_receiver: Receiver<TargetedLoadResponse>, } impl SnifferManager { fn new(data_receiver: Receiver <TargetedLoadResponse>) -> SnifferManager { SnifferManager { data_receiver: data_receiver, } } } impl SnifferManager { fn start(self) { loop { match self.data_receiver.recv_opt() { Ok(snif_data) => { let _ = snif_data.consumer.send_opt(snif_data.load_response); } Err(_) => break, } } } }
//! A task that sniffs data
random_line_split
sniffer_task.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/. */ //! A task that sniffs data use std::comm::{channel, Receiver, Sender}; use std::task::TaskBuilder; use resource_task::{TargetedLoadResponse}; pub type SnifferTask = Sender<TargetedLoadResponse>; pub fn new_sniffer_task() -> SnifferTask { let(sen, rec) = channel(); let builder = TaskBuilder::new().named("SnifferManager"); builder.spawn(proc() { SnifferManager::new(rec).start(); }); sen } struct SnifferManager { data_receiver: Receiver<TargetedLoadResponse>, } impl SnifferManager { fn new(data_receiver: Receiver <TargetedLoadResponse>) -> SnifferManager { SnifferManager { data_receiver: data_receiver, } } } impl SnifferManager { fn
(self) { loop { match self.data_receiver.recv_opt() { Ok(snif_data) => { let _ = snif_data.consumer.send_opt(snif_data.load_response); } Err(_) => break, } } } }
start
identifier_name
system.rs
use arguments::Arguments; use mcpat; use std::path::Path; use Result; use server::Address; /// A McPAT system. pub struct System { backend: mcpat::System, } impl System { /// Open a system. #[inline] pub fn
<T: AsRef<Path>>(path: T) -> Result<System> { let backend = ok!(mcpat::open(path)); { let system = backend.raw(); if system.number_of_L2s > 0 && system.Private_L2 == 0 { raise!("shared L2 caches are currently not supported"); } } Ok(System { backend: backend }) } /// Configure global parameters. pub fn setup(arguments: &Arguments) -> Result<()> { mcpat::optimize_for_clock_rate(true); if arguments.get::<bool>("caching").unwrap_or(false) { let Address(host, port) = arguments.get::<String>("server") .and_then(|s| Address::parse(&s)) .unwrap_or_else(|| Address::default()); ok!(mcpat::caching::activate(&host, port)); } Ok(()) } /// Perform the computation of area and power. #[inline] pub fn compute<'l>(&'l self) -> Result<mcpat::Processor<'l>> { Ok(ok!(self.backend.compute())) } /// Return the number of cores. pub fn cores(&self) -> usize { let system = self.backend.raw(); if system.homogeneous_cores!= 0 { 1 } else { system.number_of_cores as usize } } /// Return the number of L3 caches. pub fn l3s(&self) -> usize { let system = self.backend.raw(); if system.homogeneous_L3s!= 0 { 1 } else { system.number_of_L3s as usize } } }
open
identifier_name
system.rs
use arguments::Arguments; use mcpat; use std::path::Path; use Result; use server::Address; /// A McPAT system. pub struct System { backend: mcpat::System, } impl System { /// Open a system. #[inline] pub fn open<T: AsRef<Path>>(path: T) -> Result<System> { let backend = ok!(mcpat::open(path)); { let system = backend.raw(); if system.number_of_L2s > 0 && system.Private_L2 == 0 { raise!("shared L2 caches are currently not supported"); } } Ok(System { backend: backend }) } /// Configure global parameters. pub fn setup(arguments: &Arguments) -> Result<()> { mcpat::optimize_for_clock_rate(true); if arguments.get::<bool>("caching").unwrap_or(false) { let Address(host, port) = arguments.get::<String>("server") .and_then(|s| Address::parse(&s)) .unwrap_or_else(|| Address::default()); ok!(mcpat::caching::activate(&host, port)); } Ok(()) } /// Perform the computation of area and power. #[inline]
Ok(ok!(self.backend.compute())) } /// Return the number of cores. pub fn cores(&self) -> usize { let system = self.backend.raw(); if system.homogeneous_cores!= 0 { 1 } else { system.number_of_cores as usize } } /// Return the number of L3 caches. pub fn l3s(&self) -> usize { let system = self.backend.raw(); if system.homogeneous_L3s!= 0 { 1 } else { system.number_of_L3s as usize } } }
pub fn compute<'l>(&'l self) -> Result<mcpat::Processor<'l>> {
random_line_split
system.rs
use arguments::Arguments; use mcpat; use std::path::Path; use Result; use server::Address; /// A McPAT system. pub struct System { backend: mcpat::System, } impl System { /// Open a system. #[inline] pub fn open<T: AsRef<Path>>(path: T) -> Result<System> { let backend = ok!(mcpat::open(path)); { let system = backend.raw(); if system.number_of_L2s > 0 && system.Private_L2 == 0 { raise!("shared L2 caches are currently not supported"); } } Ok(System { backend: backend }) } /// Configure global parameters. pub fn setup(arguments: &Arguments) -> Result<()>
/// Perform the computation of area and power. #[inline] pub fn compute<'l>(&'l self) -> Result<mcpat::Processor<'l>> { Ok(ok!(self.backend.compute())) } /// Return the number of cores. pub fn cores(&self) -> usize { let system = self.backend.raw(); if system.homogeneous_cores!= 0 { 1 } else { system.number_of_cores as usize } } /// Return the number of L3 caches. pub fn l3s(&self) -> usize { let system = self.backend.raw(); if system.homogeneous_L3s!= 0 { 1 } else { system.number_of_L3s as usize } } }
{ mcpat::optimize_for_clock_rate(true); if arguments.get::<bool>("caching").unwrap_or(false) { let Address(host, port) = arguments.get::<String>("server") .and_then(|s| Address::parse(&s)) .unwrap_or_else(|| Address::default()); ok!(mcpat::caching::activate(&host, port)); } Ok(()) }
identifier_body
system.rs
use arguments::Arguments; use mcpat; use std::path::Path; use Result; use server::Address; /// A McPAT system. pub struct System { backend: mcpat::System, } impl System { /// Open a system. #[inline] pub fn open<T: AsRef<Path>>(path: T) -> Result<System> { let backend = ok!(mcpat::open(path)); { let system = backend.raw(); if system.number_of_L2s > 0 && system.Private_L2 == 0 { raise!("shared L2 caches are currently not supported"); } } Ok(System { backend: backend }) } /// Configure global parameters. pub fn setup(arguments: &Arguments) -> Result<()> { mcpat::optimize_for_clock_rate(true); if arguments.get::<bool>("caching").unwrap_or(false) { let Address(host, port) = arguments.get::<String>("server") .and_then(|s| Address::parse(&s)) .unwrap_or_else(|| Address::default()); ok!(mcpat::caching::activate(&host, port)); } Ok(()) } /// Perform the computation of area and power. #[inline] pub fn compute<'l>(&'l self) -> Result<mcpat::Processor<'l>> { Ok(ok!(self.backend.compute())) } /// Return the number of cores. pub fn cores(&self) -> usize { let system = self.backend.raw(); if system.homogeneous_cores!= 0 { 1 } else { system.number_of_cores as usize } } /// Return the number of L3 caches. pub fn l3s(&self) -> usize { let system = self.backend.raw(); if system.homogeneous_L3s!= 0 { 1 } else
} }
{ system.number_of_L3s as usize }
conditional_block
lib.rs
// Copyright 2015 Corey Farwell // // 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. //! Library for serializing the RSS web content syndication format //! //! # Examples //! //! ## Writing //! //! ``` //! use rss::{Channel, Item, Rss}; //! //! let item = Item { //! title: Some(String::from("Ford hires Elon Musk as CEO")), //! pub_date: Some(String::from("01 Apr 2019 07:30:00 GMT")), //! description: Some(String::from("In an unprecedented move, Ford hires Elon Musk.")), //! ..Default::default() //! }; //! //! let channel = Channel { //! title: String::from("TechCrunch"), //! link: String::from("http://techcrunch.com"), //! description: String::from("The latest technology news and information on startups"), //! items: vec![item], //! ..Default::default() //! }; //! //! let rss = Rss(channel); //! //! let rss_string = rss.to_string(); //! ``` //! //! ## Reading //! //! ``` //! use rss::Rss; //! //! let rss_str = r#" //! <?xml version="1.0" encoding="UTF-8"?> //! <rss version="2.0"> //! <channel> //! <title>TechCrunch</title> //! <link>http://techcrunch.com</link> //! <description>The latest technology news and information on startups</description> //! <item> //! <title>Ford hires Elon Musk as CEO</title> //! <pubDate>01 Apr 2019 07:30:00 GMT</pubDate> //! <description>In an unprecedented move, Ford hires Elon Musk.</description> //! </item> //! </channel> //! </rss> //! "#; //! //! let rss = rss_str.parse::<Rss>().unwrap(); //! ``` mod category; mod channel; mod item; mod text_input; extern crate xml; use std::ascii::AsciiExt; use std::str::FromStr; use xml::{Element, ElementBuilder, Parser, Xml}; pub use ::category::Category; pub use ::channel::Channel; pub use ::item::Item; pub use ::text_input::TextInput; trait ElementUtils { fn tag_with_text(&mut self, child_name: &'static str, child_body: &str); fn tag_with_optional_text(&mut self, child_name: &'static str, child_body: &Option<String>); } impl ElementUtils for Element { fn tag_with_text(&mut self, child_name: &'static str, child_body: &str) { self.tag(elem_with_text(child_name, child_body)); } fn tag_with_optional_text(&mut self, child_name: &'static str, child_body: &Option<String>) { if let Some(ref c) = *child_body { self.tag_with_text(child_name, &c); } } } fn elem_with_text(tag_name: &'static str, chars: &str) -> Element { let mut elem = Element::new(tag_name.to_string(), None, vec![]); elem.text(chars.to_string()); elem } trait ViaXml { fn to_xml(&self) -> Element; fn from_xml(elem: Element) -> Result<Self, &'static str>; } /// [RSS 2.0 Specification Β§ What is RSS] /// (http://cyber.law.harvard.edu/rss/rss.html#whatIsRss) #[derive(Default, Debug, Clone)] pub struct Rss(pub Channel); impl ViaXml for Rss { fn to_xml(&self) -> Element { let mut rss = Element::new("rss".to_string(), None, vec![("version".to_string(), None, "2.0".to_string())]); let &Rss(ref channel) = self; rss.tag(channel.to_xml()); rss } fn from_xml(rss_elem: Element) -> Result<Self, &'static str> { if rss_elem.name.to_ascii_lowercase()!= "rss" { return Err("Top element is not <rss>, most likely not an RSS feed"); } let channel_elem = match rss_elem.get_child("channel", None) { Some(elem) => elem, None => return Err("No <channel> element found in <rss>"), }; let channel = try!(ViaXml::from_xml(channel_elem.clone())); Ok(Rss(channel)) } } impl FromStr for Rss { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut parser = Parser::new(); parser.feed_str(&s); let mut builder = ElementBuilder::new(); for event in parser { if let Some(Ok(elem)) = builder.handle_event(event) { return ViaXml::from_xml(elem); } } Err("RSS read error") } } impl ToString for Rss { fn to_string(&self) -> String { let mut ret = format!("{}", Xml::PINode("xml version='1.0' encoding='UTF-8'".to_string())); ret.push_str(&format!("{}", self.to_xml())); ret } } #[cfg(test)] mod test { use std::default::Default; use std::fs::File; use std::io::Read; use std::str::FromStr; use super::{Rss, Item, Channel}; #[test] fn test_basic_to_string() { let item = Item { title: Some("My first post!".to_string()), link: Some("http://myblog.com/post1".to_string()), description: Some("This is my first post".to_string()), ..Default::default() }; let channel = Channel { title: "My Blog".to_string(), link: "http://myblog.com".to_string(), description: "Where I write stuff".to_string(), items: vec![item], ..Default::default() }; let rss = Rss(channel); assert_eq!(rss.to_string(), "<?xml version=\'1.0\' encoding=\'UTF-8\'?><rss version=\'2.0\'><channel><title>My Blog</title><link>http://myblog.com</link><description>Where I write stuff</description><item><title>My first post!</title><link>http://myblog.com/post1</link><description>This is my first post</description></item></channel></rss>"); } #[test] fn test_from_file() { let mut file = File::open("test-data/pinboard.xml").unwrap(); let mut rss_string = String::new(); file.read_to_string(&mut rss_string).unwrap(); let rss = Rss::from_str(&rss_string).unwrap(); assert!(rss.to_string().len() > 0); } #[test] fn test_read_no_channels() { let rss_str = "<rss></rss>"; assert!(Rss::from_str(rss_str).is_err()); } #[test] fn t
) { let rss_str = "\ <rss>\ <channel>\ </channel>\ </rss>"; assert!(Rss::from_str(rss_str).is_err()); } #[test] fn test_read_one_channel() { let rss_str = "\ <rss>\ <channel>\ <title>Hello world!</title>\ <description></description>\ <link></link>\ </channel>\ </rss>"; let Rss(channel) = Rss::from_str(rss_str).unwrap(); assert_eq!("Hello world!", channel.title); } #[test] fn test_read_text_input() { let rss_str = "\ <rss>\ <channel>\ <title></title>\ <description></description>\ <link></link>\ <textInput>\ <title>Foobar</title>\ <description></description>\ <name></name>\ <link></link>\ </textInput>\ </channel>\ </rss>"; let Rss(channel) = Rss::from_str(rss_str).unwrap(); assert_eq!("Foobar", channel.text_input.unwrap().title); } // Ensure reader ignores the PI XML node and continues to parse the RSS #[test] fn test_read_with_pinode() { let rss_str = "\ <?xml version=\'1.0\' encoding=\'UTF-8\'?>\ <rss>\ <channel>\ <title>Title</title>\ <link></link>\ <description></description>\ </channel>\ </rss>"; let Rss(channel) = Rss::from_str(rss_str).unwrap(); assert_eq!("Title", channel.title); } }
est_read_one_channel_no_properties(
identifier_name
lib.rs
// Copyright 2015 Corey Farwell // // 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. //! Library for serializing the RSS web content syndication format //! //! # Examples //! //! ## Writing //! //! ``` //! use rss::{Channel, Item, Rss}; //! //! let item = Item { //! title: Some(String::from("Ford hires Elon Musk as CEO")), //! pub_date: Some(String::from("01 Apr 2019 07:30:00 GMT")), //! description: Some(String::from("In an unprecedented move, Ford hires Elon Musk.")), //! ..Default::default() //! }; //! //! let channel = Channel { //! title: String::from("TechCrunch"), //! link: String::from("http://techcrunch.com"), //! description: String::from("The latest technology news and information on startups"), //! items: vec![item], //! ..Default::default() //! }; //! //! let rss = Rss(channel); //! //! let rss_string = rss.to_string(); //! ``` //! //! ## Reading //! //! ``` //! use rss::Rss; //! //! let rss_str = r#" //! <?xml version="1.0" encoding="UTF-8"?> //! <rss version="2.0"> //! <channel> //! <title>TechCrunch</title> //! <link>http://techcrunch.com</link> //! <description>The latest technology news and information on startups</description> //! <item> //! <title>Ford hires Elon Musk as CEO</title> //! <pubDate>01 Apr 2019 07:30:00 GMT</pubDate> //! <description>In an unprecedented move, Ford hires Elon Musk.</description> //! </item> //! </channel> //! </rss> //! "#; //! //! let rss = rss_str.parse::<Rss>().unwrap(); //! ``` mod category; mod channel; mod item; mod text_input; extern crate xml; use std::ascii::AsciiExt; use std::str::FromStr; use xml::{Element, ElementBuilder, Parser, Xml}; pub use ::category::Category; pub use ::channel::Channel; pub use ::item::Item; pub use ::text_input::TextInput; trait ElementUtils { fn tag_with_text(&mut self, child_name: &'static str, child_body: &str); fn tag_with_optional_text(&mut self, child_name: &'static str, child_body: &Option<String>); } impl ElementUtils for Element { fn tag_with_text(&mut self, child_name: &'static str, child_body: &str) { self.tag(elem_with_text(child_name, child_body)); } fn tag_with_optional_text(&mut self, child_name: &'static str, child_body: &Option<String>) { if let Some(ref c) = *child_body { self.tag_with_text(child_name, &c); } } } fn elem_with_text(tag_name: &'static str, chars: &str) -> Element { let mut elem = Element::new(tag_name.to_string(), None, vec![]); elem.text(chars.to_string()); elem } trait ViaXml { fn to_xml(&self) -> Element; fn from_xml(elem: Element) -> Result<Self, &'static str>; } /// [RSS 2.0 Specification Β§ What is RSS] /// (http://cyber.law.harvard.edu/rss/rss.html#whatIsRss) #[derive(Default, Debug, Clone)] pub struct Rss(pub Channel); impl ViaXml for Rss { fn to_xml(&self) -> Element { let mut rss = Element::new("rss".to_string(), None, vec![("version".to_string(), None, "2.0".to_string())]); let &Rss(ref channel) = self; rss.tag(channel.to_xml()); rss } fn from_xml(rss_elem: Element) -> Result<Self, &'static str> { if rss_elem.name.to_ascii_lowercase()!= "rss" { return Err("Top element is not <rss>, most likely not an RSS feed"); } let channel_elem = match rss_elem.get_child("channel", None) { Some(elem) => elem, None => return Err("No <channel> element found in <rss>"), }; let channel = try!(ViaXml::from_xml(channel_elem.clone())); Ok(Rss(channel)) } } impl FromStr for Rss { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut parser = Parser::new(); parser.feed_str(&s); let mut builder = ElementBuilder::new(); for event in parser { if let Some(Ok(elem)) = builder.handle_event(event) { return ViaXml::from_xml(elem); } } Err("RSS read error") } } impl ToString for Rss { fn to_string(&self) -> String { let mut ret = format!("{}", Xml::PINode("xml version='1.0' encoding='UTF-8'".to_string())); ret.push_str(&format!("{}", self.to_xml())); ret } } #[cfg(test)] mod test { use std::default::Default; use std::fs::File; use std::io::Read; use std::str::FromStr; use super::{Rss, Item, Channel}; #[test] fn test_basic_to_string() { let item = Item { title: Some("My first post!".to_string()), link: Some("http://myblog.com/post1".to_string()), description: Some("This is my first post".to_string()), ..Default::default() }; let channel = Channel { title: "My Blog".to_string(), link: "http://myblog.com".to_string(), description: "Where I write stuff".to_string(), items: vec![item], ..Default::default() };
assert_eq!(rss.to_string(), "<?xml version=\'1.0\' encoding=\'UTF-8\'?><rss version=\'2.0\'><channel><title>My Blog</title><link>http://myblog.com</link><description>Where I write stuff</description><item><title>My first post!</title><link>http://myblog.com/post1</link><description>This is my first post</description></item></channel></rss>"); } #[test] fn test_from_file() { let mut file = File::open("test-data/pinboard.xml").unwrap(); let mut rss_string = String::new(); file.read_to_string(&mut rss_string).unwrap(); let rss = Rss::from_str(&rss_string).unwrap(); assert!(rss.to_string().len() > 0); } #[test] fn test_read_no_channels() { let rss_str = "<rss></rss>"; assert!(Rss::from_str(rss_str).is_err()); } #[test] fn test_read_one_channel_no_properties() { let rss_str = "\ <rss>\ <channel>\ </channel>\ </rss>"; assert!(Rss::from_str(rss_str).is_err()); } #[test] fn test_read_one_channel() { let rss_str = "\ <rss>\ <channel>\ <title>Hello world!</title>\ <description></description>\ <link></link>\ </channel>\ </rss>"; let Rss(channel) = Rss::from_str(rss_str).unwrap(); assert_eq!("Hello world!", channel.title); } #[test] fn test_read_text_input() { let rss_str = "\ <rss>\ <channel>\ <title></title>\ <description></description>\ <link></link>\ <textInput>\ <title>Foobar</title>\ <description></description>\ <name></name>\ <link></link>\ </textInput>\ </channel>\ </rss>"; let Rss(channel) = Rss::from_str(rss_str).unwrap(); assert_eq!("Foobar", channel.text_input.unwrap().title); } // Ensure reader ignores the PI XML node and continues to parse the RSS #[test] fn test_read_with_pinode() { let rss_str = "\ <?xml version=\'1.0\' encoding=\'UTF-8\'?>\ <rss>\ <channel>\ <title>Title</title>\ <link></link>\ <description></description>\ </channel>\ </rss>"; let Rss(channel) = Rss::from_str(rss_str).unwrap(); assert_eq!("Title", channel.title); } }
let rss = Rss(channel);
random_line_split
job.rs
use std::io::{self, BufRead, Read}; use std::marker::PhantomData; use std::ops::Deref; use std::ptr; use crate::{raw, Error}; pub struct JobDriver<R> { input: R, job: Job, input_ended: bool, } pub struct Job(pub *mut raw::rs_job_t); // Wrapper around rs_buffers_t. struct Buffers<'a> { inner: raw::rs_buffers_t, _phantom: PhantomData<&'a u8>, } impl<R: BufRead> JobDriver<R> { pub fn new(input: R, job: Job) -> Self { JobDriver { input, job, input_ended: false, } } pub fn into_inner(self) -> R { self.input } /// Complete the job by working without an output buffer. /// /// If the job needs to write some data, an `ErrorKind::WouldBlock` error is returned. pub fn consume_input(&mut self) -> io::Result<()> { loop { let (res, read, cap) = { let readbuf = self.input.fill_buf()?; let cap = readbuf.len(); if cap == 0 { self.input_ended = true; } // work let mut buffers = Buffers::with_no_out(readbuf, self.input_ended); let res = unsafe { raw::rs_job_iter(*self.job, buffers.as_raw()) }; let read = cap - buffers.available_input(); (res, read, cap - read) }; // update read size self.input.consume(read); // determine result // NOTE: this should be done here, after the input buffer update, because we need to // know if the possible RS_BLOCKED result is due to a full input, or to an empty output // buffer match res { raw::RS_DONE => (), raw::RS_BLOCKED => { if cap > 0 { // the block is due to a missing output buffer return Err(io::Error::new( io::ErrorKind::WouldBlock, "cannot consume input without an output buffer", )); } } _ => { let err = Error::from(res); return Err(io::Error::new(io::ErrorKind::Other, err)); } }; if self.input_ended { return Ok(()); } } } } impl<R: BufRead> Read for JobDriver<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let mut out_pos = 0; let mut out_cap = buf.len(); loop { let (res, read, written) = { let readbuf = self.input.fill_buf()?; let cap = readbuf.len(); if cap == 0 { self.input_ended = true; } // work let mut buffers = Buffers::new(readbuf, &mut buf[out_pos..], self.input_ended); let res = unsafe { raw::rs_job_iter(*self.job, buffers.as_raw()) }; if res!= raw::RS_DONE && res!= raw::RS_BLOCKED { let err = Error::from(res); return Err(io::Error::new(io::ErrorKind::Other, err)); } let read = cap - buffers.available_input(); let written = out_cap - buffers.available_output(); (res, read, written) }; // update read size self.input.consume(read); // update write size out_pos += written; out_cap -= written; if out_cap == 0 || res == raw::RS_DONE { return Ok(out_pos); } } } } unsafe impl Send for Job {} impl Deref for Job { type Target = *mut raw::rs_job_t; fn deref(&self) -> &Self::Target { &self.0 } } impl Drop for Job { fn drop(&mut self) { unsafe { if!self.0.is_null() { raw::rs_job_free(self.0); } } } } impl<'a> Buffers<'a> { pub fn new(in_buf: &'a [u8], out_buf: &'a mut [u8], eof_in: bool) -> Self { Buffers { inner: raw::rs_buffers_t { next_in: in_buf.as_ptr() as *const i8, avail_in: in_buf.len(),
next_out: out_buf.as_mut_ptr() as *mut i8, avail_out: out_buf.len(), }, _phantom: PhantomData, } } pub fn with_no_out(in_buf: &'a [u8], eof_in: bool) -> Self { Buffers { inner: raw::rs_buffers_t { next_in: in_buf.as_ptr() as *const i8, avail_in: in_buf.len(), eof_in: if eof_in { 1 } else { 0 }, next_out: ptr::null_mut(), avail_out: 0, }, _phantom: PhantomData, } } pub fn as_raw(&mut self) -> *mut raw::rs_buffers_t { &mut self.inner } pub fn available_input(&self) -> usize { self.inner.avail_in } pub fn available_output(&self) -> usize { self.inner.avail_out } }
eof_in: if eof_in { 1 } else { 0 },
random_line_split
job.rs
use std::io::{self, BufRead, Read}; use std::marker::PhantomData; use std::ops::Deref; use std::ptr; use crate::{raw, Error}; pub struct JobDriver<R> { input: R, job: Job, input_ended: bool, } pub struct Job(pub *mut raw::rs_job_t); // Wrapper around rs_buffers_t. struct Buffers<'a> { inner: raw::rs_buffers_t, _phantom: PhantomData<&'a u8>, } impl<R: BufRead> JobDriver<R> { pub fn new(input: R, job: Job) -> Self
pub fn into_inner(self) -> R { self.input } /// Complete the job by working without an output buffer. /// /// If the job needs to write some data, an `ErrorKind::WouldBlock` error is returned. pub fn consume_input(&mut self) -> io::Result<()> { loop { let (res, read, cap) = { let readbuf = self.input.fill_buf()?; let cap = readbuf.len(); if cap == 0 { self.input_ended = true; } // work let mut buffers = Buffers::with_no_out(readbuf, self.input_ended); let res = unsafe { raw::rs_job_iter(*self.job, buffers.as_raw()) }; let read = cap - buffers.available_input(); (res, read, cap - read) }; // update read size self.input.consume(read); // determine result // NOTE: this should be done here, after the input buffer update, because we need to // know if the possible RS_BLOCKED result is due to a full input, or to an empty output // buffer match res { raw::RS_DONE => (), raw::RS_BLOCKED => { if cap > 0 { // the block is due to a missing output buffer return Err(io::Error::new( io::ErrorKind::WouldBlock, "cannot consume input without an output buffer", )); } } _ => { let err = Error::from(res); return Err(io::Error::new(io::ErrorKind::Other, err)); } }; if self.input_ended { return Ok(()); } } } } impl<R: BufRead> Read for JobDriver<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let mut out_pos = 0; let mut out_cap = buf.len(); loop { let (res, read, written) = { let readbuf = self.input.fill_buf()?; let cap = readbuf.len(); if cap == 0 { self.input_ended = true; } // work let mut buffers = Buffers::new(readbuf, &mut buf[out_pos..], self.input_ended); let res = unsafe { raw::rs_job_iter(*self.job, buffers.as_raw()) }; if res!= raw::RS_DONE && res!= raw::RS_BLOCKED { let err = Error::from(res); return Err(io::Error::new(io::ErrorKind::Other, err)); } let read = cap - buffers.available_input(); let written = out_cap - buffers.available_output(); (res, read, written) }; // update read size self.input.consume(read); // update write size out_pos += written; out_cap -= written; if out_cap == 0 || res == raw::RS_DONE { return Ok(out_pos); } } } } unsafe impl Send for Job {} impl Deref for Job { type Target = *mut raw::rs_job_t; fn deref(&self) -> &Self::Target { &self.0 } } impl Drop for Job { fn drop(&mut self) { unsafe { if!self.0.is_null() { raw::rs_job_free(self.0); } } } } impl<'a> Buffers<'a> { pub fn new(in_buf: &'a [u8], out_buf: &'a mut [u8], eof_in: bool) -> Self { Buffers { inner: raw::rs_buffers_t { next_in: in_buf.as_ptr() as *const i8, avail_in: in_buf.len(), eof_in: if eof_in { 1 } else { 0 }, next_out: out_buf.as_mut_ptr() as *mut i8, avail_out: out_buf.len(), }, _phantom: PhantomData, } } pub fn with_no_out(in_buf: &'a [u8], eof_in: bool) -> Self { Buffers { inner: raw::rs_buffers_t { next_in: in_buf.as_ptr() as *const i8, avail_in: in_buf.len(), eof_in: if eof_in { 1 } else { 0 }, next_out: ptr::null_mut(), avail_out: 0, }, _phantom: PhantomData, } } pub fn as_raw(&mut self) -> *mut raw::rs_buffers_t { &mut self.inner } pub fn available_input(&self) -> usize { self.inner.avail_in } pub fn available_output(&self) -> usize { self.inner.avail_out } }
{ JobDriver { input, job, input_ended: false, } }
identifier_body
job.rs
use std::io::{self, BufRead, Read}; use std::marker::PhantomData; use std::ops::Deref; use std::ptr; use crate::{raw, Error}; pub struct JobDriver<R> { input: R, job: Job, input_ended: bool, } pub struct Job(pub *mut raw::rs_job_t); // Wrapper around rs_buffers_t. struct Buffers<'a> { inner: raw::rs_buffers_t, _phantom: PhantomData<&'a u8>, } impl<R: BufRead> JobDriver<R> { pub fn new(input: R, job: Job) -> Self { JobDriver { input, job, input_ended: false, } } pub fn into_inner(self) -> R { self.input } /// Complete the job by working without an output buffer. /// /// If the job needs to write some data, an `ErrorKind::WouldBlock` error is returned. pub fn consume_input(&mut self) -> io::Result<()> { loop { let (res, read, cap) = { let readbuf = self.input.fill_buf()?; let cap = readbuf.len(); if cap == 0 { self.input_ended = true; } // work let mut buffers = Buffers::with_no_out(readbuf, self.input_ended); let res = unsafe { raw::rs_job_iter(*self.job, buffers.as_raw()) }; let read = cap - buffers.available_input(); (res, read, cap - read) }; // update read size self.input.consume(read); // determine result // NOTE: this should be done here, after the input buffer update, because we need to // know if the possible RS_BLOCKED result is due to a full input, or to an empty output // buffer match res { raw::RS_DONE => (), raw::RS_BLOCKED => { if cap > 0 { // the block is due to a missing output buffer return Err(io::Error::new( io::ErrorKind::WouldBlock, "cannot consume input without an output buffer", )); } } _ => { let err = Error::from(res); return Err(io::Error::new(io::ErrorKind::Other, err)); } }; if self.input_ended { return Ok(()); } } } } impl<R: BufRead> Read for JobDriver<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let mut out_pos = 0; let mut out_cap = buf.len(); loop { let (res, read, written) = { let readbuf = self.input.fill_buf()?; let cap = readbuf.len(); if cap == 0 { self.input_ended = true; } // work let mut buffers = Buffers::new(readbuf, &mut buf[out_pos..], self.input_ended); let res = unsafe { raw::rs_job_iter(*self.job, buffers.as_raw()) }; if res!= raw::RS_DONE && res!= raw::RS_BLOCKED { let err = Error::from(res); return Err(io::Error::new(io::ErrorKind::Other, err)); } let read = cap - buffers.available_input(); let written = out_cap - buffers.available_output(); (res, read, written) }; // update read size self.input.consume(read); // update write size out_pos += written; out_cap -= written; if out_cap == 0 || res == raw::RS_DONE { return Ok(out_pos); } } } } unsafe impl Send for Job {} impl Deref for Job { type Target = *mut raw::rs_job_t; fn deref(&self) -> &Self::Target { &self.0 } } impl Drop for Job { fn drop(&mut self) { unsafe { if!self.0.is_null() { raw::rs_job_free(self.0); } } } } impl<'a> Buffers<'a> { pub fn new(in_buf: &'a [u8], out_buf: &'a mut [u8], eof_in: bool) -> Self { Buffers { inner: raw::rs_buffers_t { next_in: in_buf.as_ptr() as *const i8, avail_in: in_buf.len(), eof_in: if eof_in { 1 } else { 0 }, next_out: out_buf.as_mut_ptr() as *mut i8, avail_out: out_buf.len(), }, _phantom: PhantomData, } } pub fn with_no_out(in_buf: &'a [u8], eof_in: bool) -> Self { Buffers { inner: raw::rs_buffers_t { next_in: in_buf.as_ptr() as *const i8, avail_in: in_buf.len(), eof_in: if eof_in { 1 } else { 0 }, next_out: ptr::null_mut(), avail_out: 0, }, _phantom: PhantomData, } } pub fn as_raw(&mut self) -> *mut raw::rs_buffers_t { &mut self.inner } pub fn available_input(&self) -> usize { self.inner.avail_in } pub fn
(&self) -> usize { self.inner.avail_out } }
available_output
identifier_name
main.rs
/* --- Day 2: Bathroom Security --- You arrive at Easter Bunny Headquarters under cover of darkness. However, you left in such a rush that you forgot to use the bathroom! Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code. "In order to improve security," the document you find says, "bathroom codes will no longer be written down. Instead, please memorize and follow the procedure below to access the bathrooms." The document goes on to explain that each button to be pressed can be found by starting on the previous button and moving to adjacent buttons on the keypad: U moves up, D moves down, L moves left, and R moves right. Each line of instructions corresponds to one button, starting at the previous button (or, for the first line, the "5" button); press whatever button you're on at the end of each line. If a move doesn't lead to a button, ignore it. You can't hold it much longer, so you decide to figure out the code as you walk to the bathroom. You picture a keypad like this: 1 2 3 4 5 6 7 8 9 Suppose your instructions are: ULL RRDDD LURDL UUUUD You start at "5" and move up (to "2"), left (to "1"), and left (you can't, and stay on "1"), so the first button is 1. Starting from the previous button ("1"), you move right twice (to "3") and then down three times (stopping at "9" after two moves and ignoring the third), ending up with 9. Continuing from "9", you move left, up, right, down, and left, ending with 8. Finally, you move up four times (stopping at "2"), then down once, ending with 5. So, in this example, the bathroom code is 1985. Your puzzle input is the instructions from the document you found at the front desk. What is the bathroom code? --- Part Two --- You finally arrive at the bathroom (it's a several minute walk from the lobby so visitors can behold the many fancy conference rooms and water coolers on this floor) and go to punch in the code. Much to your bladder's dismay, the keypad is not at all like you imagined it. Instead, you are confronted with the result of hundreds of man-hours of bathroom-keypad-design meetings: 1 2 3 4 5 6 7 8 9 A B C D You still start at "5" and stop when you're at an edge, but given the same instructions as above, the outcome is very different: You start at "5" and don't move at all (up and left are both edges), ending at 5. Continuing from "5", you move right twice and down three times (through "6", "7", "B", "D", "D"), ending at D. Then, from "D", you move five more times (through "D", "B", "C", "C", "B"), ending at B. Finally, after five more moves, you end at 3. So, given the actual keypad layout, the code would be 5DB3. Using the same instructions in your puzzle input, what is the correct bathroom code? */ use std::io::prelude::*; use std::fs::File; use std::ops::Rem; #[derive(Debug)] enum Direction { Up, Left, Down, Right, } type Cursor = usize; type Numpad = Vec<Option<char>>; fn main() { // read input from the file let mut f = File::open("input.txt").unwrap(); let mut input = String::new(); f.read_to_string(&mut input).ok(); // split into lines let lines : Vec<&str> = input.split('\n').collect(); let mut digits : Vec<char> = Vec::new(); // recreate the keypad with three rows of three keys // let keypad_part_a : Numpad = vec![Some('1'), Some('2'), Some('3'), // Some('4'), Some('5'), Some('6'), // Some('7'), Some('8'), Some('9')]; let keypad : Numpad = vec![ None, None, Some('1'), None, None, None, Some('2'), Some('3'), Some('4'), None, Some('5'), Some('6'), Some('7'), Some('8'), Some('9'), None, Some('A'), Some('B'), Some('C'), None, None, None, Some('D'), None, None ]; // and lets create our cursor, starting at the Five key let mut cursor : Cursor = 10; // convert characters to directions for line in lines { let sequence : Vec<Direction> = line.chars().map(char_to_direction).collect(); let updated_cursor_after_sequence : Cursor = sequence.iter().fold(cursor, |prev_cursor, dir| { move_cursor(&keypad, &prev_cursor, dir) }); digits.push(digit_for_cursor(&keypad, &updated_cursor_after_sequence)); cursor = updated_cursor_after_sequence; } println!("Digits: {:?}", digits); assert_eq!(digits, vec!['9', '9', '3', '3', '2']); //challange (live) digits } fn
(c : char) -> Direction { match c { 'U' => Direction::Up, 'D' => Direction::Down, 'L' => Direction::Left, 'R' => Direction::Right, _ => Direction::Up, } } fn move_cursor(numpad : &Numpad, cursor: &Cursor, dir : &Direction) -> Cursor { // calculate new position of the cursor, based on the direction // and have it be constraint to the bounds of the numpad let row_length = f32::sqrt(numpad.len() as f32) as usize; match *dir { Direction::Left => { // left most options? Cant move left any further.. if cursor.rem(row_length) == 0 ||!is_valid(&numpad, &(cursor - 1)) { *cursor } else { cursor - 1 } }, Direction::Right => { // right most options? Cant move right any further.. if (cursor).rem(row_length) == row_length - 1 ||!is_valid(&numpad, &(cursor + 1)) { *cursor } else { cursor + 1 } }, Direction::Up => { // only can move up if theres another row up top if *cursor > row_length - 1 && is_valid(&numpad, &(cursor - row_length)) { cursor - row_length } else { *cursor } }, Direction::Down => { // only can move down if theres another row below if *cursor < numpad.len() - row_length && is_valid(&numpad, &(cursor + row_length)){ cursor + row_length } else { *cursor } }, } } fn is_valid(numpad: &Numpad, cursor : &Cursor) -> bool { numpad.get(*cursor).unwrap().is_some() } fn digit_for_cursor(numpad : &Numpad, cursor : &Cursor) -> char { numpad.get(*cursor).unwrap().unwrap().to_owned() }
char_to_direction
identifier_name
main.rs
/* --- Day 2: Bathroom Security --- You arrive at Easter Bunny Headquarters under cover of darkness. However, you left in such a rush that you forgot to use the bathroom! Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code. "In order to improve security," the document you find says, "bathroom codes will no longer be written down. Instead, please memorize and follow the procedure below to access the bathrooms." The document goes on to explain that each button to be pressed can be found by starting on the previous button and moving to adjacent buttons on the keypad: U moves up, D moves down, L moves left, and R moves right. Each line of instructions corresponds to one button, starting at the previous button (or, for the first line, the "5" button); press whatever button you're on at the end of each line. If a move doesn't lead to a button, ignore it. You can't hold it much longer, so you decide to figure out the code as you walk to the bathroom. You picture a keypad like this: 1 2 3 4 5 6 7 8 9 Suppose your instructions are: ULL RRDDD LURDL UUUUD You start at "5" and move up (to "2"), left (to "1"), and left (you can't, and stay on "1"), so the first button is 1. Starting from the previous button ("1"), you move right twice (to "3") and then down three times (stopping at "9" after two moves and ignoring the third), ending up with 9. Continuing from "9", you move left, up, right, down, and left, ending with 8. Finally, you move up four times (stopping at "2"), then down once, ending with 5. So, in this example, the bathroom code is 1985. Your puzzle input is the instructions from the document you found at the front desk. What is the bathroom code? --- Part Two --- You finally arrive at the bathroom (it's a several minute walk from the lobby so visitors can behold the many fancy conference rooms and water coolers on this floor) and go to punch in the code. Much to your bladder's dismay, the keypad is not at all like you imagined it. Instead, you are confronted with the result of hundreds of man-hours of bathroom-keypad-design meetings: 1 2 3 4 5 6 7 8 9 A B C D You still start at "5" and stop when you're at an edge, but given the same instructions as above, the outcome is very different: You start at "5" and don't move at all (up and left are both edges), ending at 5. Continuing from "5", you move right twice and down three times (through "6", "7", "B", "D", "D"), ending at D. Then, from "D", you move five more times (through "D", "B", "C", "C", "B"), ending at B. Finally, after five more moves, you end at 3. So, given the actual keypad layout, the code would be 5DB3. Using the same instructions in your puzzle input, what is the correct bathroom code? */ use std::io::prelude::*; use std::fs::File; use std::ops::Rem; #[derive(Debug)] enum Direction { Up, Left, Down, Right, } type Cursor = usize; type Numpad = Vec<Option<char>>; fn main()
None, Some('A'), Some('B'), Some('C'), None, None, None, Some('D'), None, None ]; // and lets create our cursor, starting at the Five key let mut cursor : Cursor = 10; // convert characters to directions for line in lines { let sequence : Vec<Direction> = line.chars().map(char_to_direction).collect(); let updated_cursor_after_sequence : Cursor = sequence.iter().fold(cursor, |prev_cursor, dir| { move_cursor(&keypad, &prev_cursor, dir) }); digits.push(digit_for_cursor(&keypad, &updated_cursor_after_sequence)); cursor = updated_cursor_after_sequence; } println!("Digits: {:?}", digits); assert_eq!(digits, vec!['9', '9', '3', '3', '2']); //challange (live) digits } fn char_to_direction(c : char) -> Direction { match c { 'U' => Direction::Up, 'D' => Direction::Down, 'L' => Direction::Left, 'R' => Direction::Right, _ => Direction::Up, } } fn move_cursor(numpad : &Numpad, cursor: &Cursor, dir : &Direction) -> Cursor { // calculate new position of the cursor, based on the direction // and have it be constraint to the bounds of the numpad let row_length = f32::sqrt(numpad.len() as f32) as usize; match *dir { Direction::Left => { // left most options? Cant move left any further.. if cursor.rem(row_length) == 0 ||!is_valid(&numpad, &(cursor - 1)) { *cursor } else { cursor - 1 } }, Direction::Right => { // right most options? Cant move right any further.. if (cursor).rem(row_length) == row_length - 1 ||!is_valid(&numpad, &(cursor + 1)) { *cursor } else { cursor + 1 } }, Direction::Up => { // only can move up if theres another row up top if *cursor > row_length - 1 && is_valid(&numpad, &(cursor - row_length)) { cursor - row_length } else { *cursor } }, Direction::Down => { // only can move down if theres another row below if *cursor < numpad.len() - row_length && is_valid(&numpad, &(cursor + row_length)){ cursor + row_length } else { *cursor } }, } } fn is_valid(numpad: &Numpad, cursor : &Cursor) -> bool { numpad.get(*cursor).unwrap().is_some() } fn digit_for_cursor(numpad : &Numpad, cursor : &Cursor) -> char { numpad.get(*cursor).unwrap().unwrap().to_owned() }
{ // read input from the file let mut f = File::open("input.txt").unwrap(); let mut input = String::new(); f.read_to_string(&mut input).ok(); // split into lines let lines : Vec<&str> = input.split('\n').collect(); let mut digits : Vec<char> = Vec::new(); // recreate the keypad with three rows of three keys // let keypad_part_a : Numpad = vec![Some('1'), Some('2'), Some('3'), // Some('4'), Some('5'), Some('6'), // Some('7'), Some('8'), Some('9')]; let keypad : Numpad = vec![ None, None, Some('1'), None, None, None, Some('2'), Some('3'), Some('4'), None, Some('5'), Some('6'), Some('7'), Some('8'), Some('9'),
identifier_body
main.rs
/* --- Day 2: Bathroom Security --- You arrive at Easter Bunny Headquarters under cover of darkness. However, you left in such a rush that you forgot to use the bathroom! Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code. "In order to improve security," the document you find says, "bathroom codes will no longer be written down. Instead, please memorize and follow the procedure below to access the bathrooms." The document goes on to explain that each button to be pressed can be found by starting on the previous button and moving to adjacent buttons on the keypad: U moves up, D moves down, L moves left, and R moves right. Each line of instructions corresponds to one button, starting at the previous button (or, for the first line, the "5" button); press whatever button you're on at the end of each line. If a move doesn't lead to a button, ignore it. You can't hold it much longer, so you decide to figure out the code as you walk to the bathroom. You picture a keypad like this: 1 2 3 4 5 6 7 8 9 Suppose your instructions are: ULL RRDDD LURDL UUUUD You start at "5" and move up (to "2"), left (to "1"), and left (you can't, and stay on "1"), so the first button is 1. Starting from the previous button ("1"), you move right twice (to "3") and then down three times (stopping at "9" after two moves and ignoring the third), ending up with 9. Continuing from "9", you move left, up, right, down, and left, ending with 8. Finally, you move up four times (stopping at "2"), then down once, ending with 5. So, in this example, the bathroom code is 1985. Your puzzle input is the instructions from the document you found at the front desk. What is the bathroom code? --- Part Two --- You finally arrive at the bathroom (it's a several minute walk from the lobby so visitors can behold the many fancy conference rooms and water coolers on this floor) and go to punch in the code. Much to your bladder's dismay, the keypad is not at all like you imagined it. Instead, you are confronted with the result of hundreds of man-hours of bathroom-keypad-design meetings: 1 2 3 4 5 6 7 8 9 A B C D You still start at "5" and stop when you're at an edge, but given the same instructions as above, the outcome is very different: You start at "5" and don't move at all (up and left are both edges), ending at 5. Continuing from "5", you move right twice and down three times (through "6", "7", "B", "D", "D"), ending at D. Then, from "D", you move five more times (through "D", "B", "C", "C", "B"), ending at B. Finally, after five more moves, you end at 3. So, given the actual keypad layout, the code would be 5DB3. Using the same instructions in your puzzle input, what is the correct bathroom code? */ use std::io::prelude::*; use std::fs::File; use std::ops::Rem; #[derive(Debug)] enum Direction { Up, Left, Down, Right, } type Cursor = usize; type Numpad = Vec<Option<char>>; fn main() { // read input from the file let mut f = File::open("input.txt").unwrap(); let mut input = String::new(); f.read_to_string(&mut input).ok(); // split into lines let lines : Vec<&str> = input.split('\n').collect(); let mut digits : Vec<char> = Vec::new(); // recreate the keypad with three rows of three keys // let keypad_part_a : Numpad = vec![Some('1'), Some('2'), Some('3'), // Some('4'), Some('5'), Some('6'), // Some('7'), Some('8'), Some('9')]; let keypad : Numpad = vec![ None, None, Some('1'), None, None, None, Some('2'), Some('3'), Some('4'), None, Some('5'), Some('6'), Some('7'), Some('8'), Some('9'), None, Some('A'), Some('B'), Some('C'), None, None, None, Some('D'), None, None ]; // and lets create our cursor, starting at the Five key let mut cursor : Cursor = 10; // convert characters to directions for line in lines { let sequence : Vec<Direction> = line.chars().map(char_to_direction).collect(); let updated_cursor_after_sequence : Cursor = sequence.iter().fold(cursor, |prev_cursor, dir| { move_cursor(&keypad, &prev_cursor, dir) }); digits.push(digit_for_cursor(&keypad, &updated_cursor_after_sequence)); cursor = updated_cursor_after_sequence; } println!("Digits: {:?}", digits); assert_eq!(digits, vec!['9', '9', '3', '3', '2']); //challange (live) digits } fn char_to_direction(c : char) -> Direction { match c { 'U' => Direction::Up, 'D' => Direction::Down, 'L' => Direction::Left, 'R' => Direction::Right, _ => Direction::Up, } } fn move_cursor(numpad : &Numpad, cursor: &Cursor, dir : &Direction) -> Cursor { // calculate new position of the cursor, based on the direction // and have it be constraint to the bounds of the numpad let row_length = f32::sqrt(numpad.len() as f32) as usize; match *dir { Direction::Left => { // left most options? Cant move left any further.. if cursor.rem(row_length) == 0 ||!is_valid(&numpad, &(cursor - 1)) { *cursor } else { cursor - 1 } }, Direction::Right => { // right most options? Cant move right any further.. if (cursor).rem(row_length) == row_length - 1 ||!is_valid(&numpad, &(cursor + 1)) { *cursor } else { cursor + 1 } }, Direction::Up => { // only can move up if theres another row up top if *cursor > row_length - 1 && is_valid(&numpad, &(cursor - row_length)) { cursor - row_length } else { *cursor } }, Direction::Down => { // only can move down if theres another row below if *cursor < numpad.len() - row_length && is_valid(&numpad, &(cursor + row_length))
else { *cursor } }, } } fn is_valid(numpad: &Numpad, cursor : &Cursor) -> bool { numpad.get(*cursor).unwrap().is_some() } fn digit_for_cursor(numpad : &Numpad, cursor : &Cursor) -> char { numpad.get(*cursor).unwrap().unwrap().to_owned() }
{ cursor + row_length }
conditional_block
main.rs
/* --- Day 2: Bathroom Security --- You arrive at Easter Bunny Headquarters under cover of darkness. However, you left in such a rush that you forgot to use the bathroom! Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code. "In order to improve security," the document you find says, "bathroom codes will no longer be written down. Instead, please memorize and follow the procedure below to access the bathrooms." The document goes on to explain that each button to be pressed can be found by starting on the previous button and moving to adjacent buttons on the keypad: U moves up, D moves down, L moves left, and R moves right. Each line of instructions corresponds to one button, starting at the previous button (or, for the first line, the "5" button); press whatever button you're on at the end of each line. If a move doesn't lead to a button, ignore it. You can't hold it much longer, so you decide to figure out the code as you walk to the bathroom. You picture a keypad like this: 1 2 3 4 5 6 7 8 9 Suppose your instructions are: ULL RRDDD LURDL UUUUD You start at "5" and move up (to "2"), left (to "1"), and left (you can't, and stay on "1"), so the first button is 1. Starting from the previous button ("1"), you move right twice (to "3") and then down three times (stopping at "9" after two moves and ignoring the third), ending up with 9. Continuing from "9", you move left, up, right, down, and left, ending with 8. Finally, you move up four times (stopping at "2"), then down once, ending with 5. So, in this example, the bathroom code is 1985. Your puzzle input is the instructions from the document you found at the front desk. What is the bathroom code? --- Part Two --- You finally arrive at the bathroom (it's a several minute walk from the lobby so visitors can behold the many fancy conference rooms and water coolers on this floor) and go to punch in the code. Much to your bladder's dismay, the keypad is not at all like you imagined it. Instead, you are confronted with the result of hundreds of man-hours of bathroom-keypad-design meetings: 1 2 3 4 5 6 7 8 9 A B C
You still start at "5" and stop when you're at an edge, but given the same instructions as above, the outcome is very different: You start at "5" and don't move at all (up and left are both edges), ending at 5. Continuing from "5", you move right twice and down three times (through "6", "7", "B", "D", "D"), ending at D. Then, from "D", you move five more times (through "D", "B", "C", "C", "B"), ending at B. Finally, after five more moves, you end at 3. So, given the actual keypad layout, the code would be 5DB3. Using the same instructions in your puzzle input, what is the correct bathroom code? */ use std::io::prelude::*; use std::fs::File; use std::ops::Rem; #[derive(Debug)] enum Direction { Up, Left, Down, Right, } type Cursor = usize; type Numpad = Vec<Option<char>>; fn main() { // read input from the file let mut f = File::open("input.txt").unwrap(); let mut input = String::new(); f.read_to_string(&mut input).ok(); // split into lines let lines : Vec<&str> = input.split('\n').collect(); let mut digits : Vec<char> = Vec::new(); // recreate the keypad with three rows of three keys // let keypad_part_a : Numpad = vec![Some('1'), Some('2'), Some('3'), // Some('4'), Some('5'), Some('6'), // Some('7'), Some('8'), Some('9')]; let keypad : Numpad = vec![ None, None, Some('1'), None, None, None, Some('2'), Some('3'), Some('4'), None, Some('5'), Some('6'), Some('7'), Some('8'), Some('9'), None, Some('A'), Some('B'), Some('C'), None, None, None, Some('D'), None, None ]; // and lets create our cursor, starting at the Five key let mut cursor : Cursor = 10; // convert characters to directions for line in lines { let sequence : Vec<Direction> = line.chars().map(char_to_direction).collect(); let updated_cursor_after_sequence : Cursor = sequence.iter().fold(cursor, |prev_cursor, dir| { move_cursor(&keypad, &prev_cursor, dir) }); digits.push(digit_for_cursor(&keypad, &updated_cursor_after_sequence)); cursor = updated_cursor_after_sequence; } println!("Digits: {:?}", digits); assert_eq!(digits, vec!['9', '9', '3', '3', '2']); //challange (live) digits } fn char_to_direction(c : char) -> Direction { match c { 'U' => Direction::Up, 'D' => Direction::Down, 'L' => Direction::Left, 'R' => Direction::Right, _ => Direction::Up, } } fn move_cursor(numpad : &Numpad, cursor: &Cursor, dir : &Direction) -> Cursor { // calculate new position of the cursor, based on the direction // and have it be constraint to the bounds of the numpad let row_length = f32::sqrt(numpad.len() as f32) as usize; match *dir { Direction::Left => { // left most options? Cant move left any further.. if cursor.rem(row_length) == 0 ||!is_valid(&numpad, &(cursor - 1)) { *cursor } else { cursor - 1 } }, Direction::Right => { // right most options? Cant move right any further.. if (cursor).rem(row_length) == row_length - 1 ||!is_valid(&numpad, &(cursor + 1)) { *cursor } else { cursor + 1 } }, Direction::Up => { // only can move up if theres another row up top if *cursor > row_length - 1 && is_valid(&numpad, &(cursor - row_length)) { cursor - row_length } else { *cursor } }, Direction::Down => { // only can move down if theres another row below if *cursor < numpad.len() - row_length && is_valid(&numpad, &(cursor + row_length)){ cursor + row_length } else { *cursor } }, } } fn is_valid(numpad: &Numpad, cursor : &Cursor) -> bool { numpad.get(*cursor).unwrap().is_some() } fn digit_for_cursor(numpad : &Numpad, cursor : &Cursor) -> char { numpad.get(*cursor).unwrap().unwrap().to_owned() }
D
random_line_split
mod.rs
use collections::{Set, set}; use lr1::core::*; use lr1::first::FirstSets; use lr1::state_graph::StateGraph; use grammar::repr::*; mod reduce; mod shift; mod trace_graph; pub struct
<'trace, 'grammar: 'trace> { states: &'trace [LR1State<'grammar>], first_sets: &'trace FirstSets, state_graph: StateGraph, trace_graph: TraceGraph<'grammar>, visited_set: Set<(StateIndex, NonterminalString)>, } impl<'trace, 'grammar> Tracer<'trace, 'grammar> { pub fn new(first_sets: &'trace FirstSets, states: &'trace [LR1State<'grammar>]) -> Self { Tracer { states: states, first_sets: first_sets, state_graph: StateGraph::new(states), trace_graph: TraceGraph::new(), visited_set: set(), } } } pub use self::trace_graph::TraceGraph;
Tracer
identifier_name
mod.rs
use collections::{Set, set}; use lr1::core::*; use lr1::first::FirstSets; use lr1::state_graph::StateGraph; use grammar::repr::*; mod reduce; mod shift; mod trace_graph; pub struct Tracer<'trace, 'grammar: 'trace> { states: &'trace [LR1State<'grammar>], first_sets: &'trace FirstSets, state_graph: StateGraph, trace_graph: TraceGraph<'grammar>, visited_set: Set<(StateIndex, NonterminalString)>, } impl<'trace, 'grammar> Tracer<'trace, 'grammar> { pub fn new(first_sets: &'trace FirstSets, states: &'trace [LR1State<'grammar>]) -> Self
} pub use self::trace_graph::TraceGraph;
{ Tracer { states: states, first_sets: first_sets, state_graph: StateGraph::new(states), trace_graph: TraceGraph::new(), visited_set: set(), } }
identifier_body
mod.rs
use collections::{Set, set}; use lr1::core::*; use lr1::first::FirstSets; use lr1::state_graph::StateGraph;
use grammar::repr::*; mod reduce; mod shift; mod trace_graph; pub struct Tracer<'trace, 'grammar: 'trace> { states: &'trace [LR1State<'grammar>], first_sets: &'trace FirstSets, state_graph: StateGraph, trace_graph: TraceGraph<'grammar>, visited_set: Set<(StateIndex, NonterminalString)>, } impl<'trace, 'grammar> Tracer<'trace, 'grammar> { pub fn new(first_sets: &'trace FirstSets, states: &'trace [LR1State<'grammar>]) -> Self { Tracer { states: states, first_sets: first_sets, state_graph: StateGraph::new(states), trace_graph: TraceGraph::new(), visited_set: set(), } } } pub use self::trace_graph::TraceGraph;
random_line_split
dom.rs
} /// An iterator over the DOM children of a node. pub struct DomChildren<N>(Option<N>); impl<N> Iterator for DomChildren<N> where N: TNode, { type Item = N; fn next(&mut self) -> Option<N> { let n = self.0.take()?; self.0 = n.next_sibling(); Some(n) } } /// An iterator over the DOM descendants of a node in pre-order. pub struct DomDescendants<N> { previous: Option<N>, scope: N, } impl<N> Iterator for DomDescendants<N> where N: TNode, { type Item = N; #[inline] fn next(&mut self) -> Option<N> { let prev = self.previous.take()?; self.previous = prev.next_in_preorder(Some(self.scope)); self.previous } } /// The `TDocument` trait, to represent a document node. pub trait TDocument: Sized + Copy + Clone { /// The concrete `TNode` type. type ConcreteNode: TNode<ConcreteDocument = Self>; /// Get this document as a `TNode`. fn as_node(&self) -> Self::ConcreteNode; /// Returns whether this document is an HTML document. fn is_html_document(&self) -> bool; /// Returns the quirks mode of this document. fn quirks_mode(&self) -> QuirksMode; /// Get a list of elements with a given ID in this document, sorted by /// tree position. /// /// Can return an error to signal that this list is not available, or also /// return an empty slice. fn elements_with_id<'a>( &self, _id: &Atom, ) -> Result<&'a [<Self::ConcreteNode as TNode>::ConcreteElement], ()> where Self: 'a, { Err(()) } } /// The `TNode` trait. This is the main generic trait over which the style /// system can be implemented. pub trait TNode: Sized + Copy + Clone + Debug + NodeInfo + PartialEq { /// The concrete `TElement` type. type ConcreteElement: TElement<ConcreteNode = Self>; /// The concrete `TDocument` type. type ConcreteDocument: TDocument<ConcreteNode = Self>; /// The concrete `TShadowRoot` type. type ConcreteShadowRoot: TShadowRoot<ConcreteNode = Self>; /// Get this node's parent node. fn parent_node(&self) -> Option<Self>; /// Get this node's first child. fn first_child(&self) -> Option<Self>; /// Get this node's first child. fn last_child(&self) -> Option<Self>; /// Get this node's previous sibling. fn prev_sibling(&self) -> Option<Self>; /// Get this node's next sibling. fn next_sibling(&self) -> Option<Self>; /// Get the owner document of this node. fn owner_doc(&self) -> Self::ConcreteDocument; /// Iterate over the DOM children of a node. fn dom_children(&self) -> DomChildren<Self> { DomChildren(self.first_child()) } /// Returns whether the node is attached to a document. fn is_in_document(&self) -> bool; /// Iterate over the DOM children of a node, in preorder. fn dom_descendants(&self) -> DomDescendants<Self> { DomDescendants { previous: Some(*self), scope: *self, } } /// Returns the next children in pre-order, optionally scoped to a subtree /// root. #[inline] fn next_in_preorder(&self, scoped_to: Option<Self>) -> Option<Self> { if let Some(c) = self.first_child() { return Some(c); } if Some(*self) == scoped_to { return None; } let mut current = *self; loop { if let Some(s) = current.next_sibling() { return Some(s); } let parent = current.parent_node(); if parent == scoped_to { return None; } current = parent.expect("Not a descendant of the scope?"); } } /// Get this node's parent element from the perspective of a restyle /// traversal. fn traversal_parent(&self) -> Option<Self::ConcreteElement>; /// Get this node's parent element if present. fn parent_element(&self) -> Option<Self::ConcreteElement> { self.parent_node().and_then(|n| n.as_element()) } /// Converts self into an `OpaqueNode`. fn opaque(&self) -> OpaqueNode; /// A debug id, only useful, mm... for debugging. fn debug_id(self) -> usize; /// Get this node as an element, if it's one. fn as_element(&self) -> Option<Self::ConcreteElement>; /// Get this node as a document, if it's one. fn as_document(&self) -> Option<Self::ConcreteDocument>; /// Get this node as a ShadowRoot, if it's one. fn as_shadow_root(&self) -> Option<Self::ConcreteShadowRoot>; } /// Wrapper to output the subtree rather than the single node when formatting /// for Debug. pub struct ShowSubtree<N: TNode>(pub N); impl<N: TNode> Debug for ShowSubtree<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DOM Subtree:")?; fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1) } } /// Wrapper to output the subtree along with the ElementData when formatting /// for Debug. pub struct ShowSubtreeData<N: TNode>(pub N); impl<N: TNode> Debug for ShowSubtreeData<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DOM Subtree:")?; fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1) } } /// Wrapper to output the subtree along with the ElementData and primary /// ComputedValues when formatting for Debug. This is extremely verbose. #[cfg(feature = "servo")] pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N); #[cfg(feature = "servo")] impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DOM Subtree:")?; fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1) } } fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result { if let Some(el) = n.as_element() { write!( f, "{:?} dd={} aodd={} data={:?}", el, el.has_dirty_descendants(), el.has_animation_only_dirty_descendants(), el.borrow_data(), ) } else { write!(f, "{:?}", n) } } #[cfg(feature = "servo")] fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result { if let Some(el) = n.as_element() { let dd = el.has_dirty_descendants(); let aodd = el.has_animation_only_dirty_descendants(); let data = el.borrow_data(); let values = data.as_ref().and_then(|d| d.styles.get_primary()); write!( f, "{:?} dd={} aodd={} data={:?} values={:?}", el, dd, aodd, &data, values ) } else { write!(f, "{:?}", n) } } fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32) -> fmt::Result where F: Fn(&mut fmt::Formatter, N) -> fmt::Result, { for _ in 0..indent { write!(f, " ")?; } stringify(f, n)?; if let Some(e) = n.as_element() { for kid in e.traversal_children() { writeln!(f, "")?; fmt_subtree(f, stringify, kid, indent + 1)?; } } Ok(()) } /// The ShadowRoot trait. pub trait TShadowRoot: Sized + Copy + Clone + PartialEq { /// The concrete node type. type ConcreteNode: TNode<ConcreteShadowRoot = Self>; /// Get this ShadowRoot as a node. fn as_node(&self) -> Self::ConcreteNode; /// Get the shadow host that hosts this ShadowRoot. fn host(&self) -> <Self::ConcreteNode as TNode>::ConcreteElement; /// Get the style data for this ShadowRoot. fn style_data<'a>(&self) -> Option<&'a CascadeData> where Self: 'a; /// Get a list of elements with a given ID in this shadow root, sorted by /// tree position. /// /// Can return an error to signal that this list is not available, or also /// return an empty slice. fn elements_with_id<'a>( &self, _id: &Atom, ) -> Result<&'a [<Self::ConcreteNode as TNode>::ConcreteElement], ()> where Self: 'a, { Err(()) } } /// The element trait, the main abstraction the style crate acts over. pub trait TElement: Eq + PartialEq + Debug + Hash + Sized + Copy + Clone + SelectorsElement<Impl = SelectorImpl> { /// The concrete node type. type ConcreteNode: TNode<ConcreteElement = Self>; /// A concrete children iterator type in order to iterate over the `Node`s. /// /// TODO(emilio): We should eventually replace this with the `impl Trait` /// syntax. type TraversalChildrenIterator: Iterator<Item = Self::ConcreteNode>; /// Type of the font metrics provider /// /// XXXManishearth It would be better to make this a type parameter on /// ThreadLocalStyleContext and StyleContext type FontMetricsProvider: FontMetricsProvider + Send; /// Get this element as a node. fn as_node(&self) -> Self::ConcreteNode; /// A debug-only check that the device's owner doc matches the actual doc /// we're the root of. /// /// Otherwise we may set document-level state incorrectly, like the root /// font-size used for rem units. fn owner_doc_matches_for_testing(&self, _: &Device) -> bool { true } /// Whether this element should match user and author rules. /// /// We use this for Native Anonymous Content in Gecko. fn matches_user_and_author_rules(&self) -> bool { true } /// Returns the depth of this element in the DOM. fn depth(&self) -> usize { let mut depth = 0; let mut curr = *self; while let Some(parent) = curr.traversal_parent() { depth += 1; curr = parent; } depth } /// Get this node's parent element from the perspective of a restyle /// traversal. fn traversal_parent(&self) -> Option<Self> { self.as_node().traversal_parent() } /// Get this node's children from the perspective of a restyle traversal. fn traversal_children(&self) -> LayoutIterator<Self::TraversalChildrenIterator>; /// Returns the parent element we should inherit from. /// /// This is pretty much always the parent element itself, except in the case /// of Gecko's Native Anonymous Content, which uses the traversal parent /// (i.e. the flattened tree parent) and which also may need to find the /// closest non-NAC ancestor. fn inheritance_parent(&self) -> Option<Self> { self.parent_element() } /// The ::before pseudo-element of this element, if it exists. fn before_pseudo_element(&self) -> Option<Self> { None } /// The ::after pseudo-element of this element, if it exists. fn after_pseudo_element(&self) -> Option<Self> { None } /// The ::marker pseudo-element of this element, if it exists. fn marker_pseudo_element(&self) -> Option<Self> { None } /// Execute `f` for each anonymous content child (apart from ::before and /// ::after) whose originating element is `self`. fn each_anonymous_content_child<F>(&self, _f: F) where F: FnMut(Self), { } /// Return whether this element is an element in the HTML namespace. fn is_html_element(&self) -> bool; /// Return whether this element is an element in the MathML namespace. fn is_mathml_element(&self) -> bool; /// Return whether this element is an element in the SVG namespace. fn is_svg_element(&self) -> bool; /// Return whether this element is an element in the XUL namespace. fn is_xul_element(&self) -> bool { false } /// Return the list of slotted nodes of this node. fn slotted_nodes(&self) -> &[Self::ConcreteNode] { &[] } /// Get this element's style attribute. fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>; /// Unset the style attribute's dirty bit. /// Servo doesn't need to manage ditry bit for style attribute. fn unset_dirty_style_attribute(&self) {} /// Get this element's SMIL override declarations. fn smil_override(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>> { None } /// Get the combined animation and transition rules. /// /// FIXME(emilio): Is this really useful? fn animation_rules(&self) -> AnimationRules { if!self.may_have_animations() { return AnimationRules(None, None); } AnimationRules(self.animation_rule(), self.transition_rule()) } /// Get this element's animation rule. fn animation_rule(&self) -> Option<Arc<Locked<PropertyDeclarationBlock>>> { None } /// Get this element's transition rule. fn transition_rule(&self) -> Option<Arc<Locked<PropertyDeclarationBlock>>> { None } /// Get this element's state, for non-tree-structural pseudos. fn state(&self) -> ElementState; /// Whether this element has an attribute with a given namespace. fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool; /// The ID for this element. fn id(&self) -> Option<&WeakAtom>; /// Internal iterator for the classes of this element. fn each_class<F>(&self, callback: F) where F: FnMut(&Atom); /// Whether a given element may generate a pseudo-element. /// /// This is useful to avoid computing, for example, pseudo styles for /// `::-first-line` or `::-first-letter`, when we know it won't affect us. /// /// TODO(emilio, bz): actually implement the logic for it. fn may_generate_pseudo(&self, pseudo: &PseudoElement, _primary_style: &ComputedValues) -> bool { // ::before/::after are always supported for now, though we could try to // optimize out leaf elements. // ::first-letter and ::first-line are only supported for block-inside // things, and only in Gecko, not Servo. Unfortunately, Gecko has // block-inside things that might have any computed display value due to // things like fieldsets, legends, etc. Need to figure out how this // should work. debug_assert!( pseudo.is_eager(), "Someone called may_generate_pseudo with a non-eager pseudo." ); true } /// Returns true if this element may have a descendant needing style processing. /// /// Note that we cannot guarantee the existence of such an element, because /// it may have been removed from the DOM between marking it for restyle and /// the actual restyle traversal. fn has_dirty_descendants(&self) -> bool; /// Returns whether state or attributes that may change style have changed /// on the element, and thus whether the element has been snapshotted to do /// restyle hint computation. fn has_snapshot(&self) -> bool; /// Returns whether the current snapshot if present has been handled. fn handled_snapshot(&self) -> bool; /// Flags this element as having handled already its snapshot. unsafe fn set_handled_snapshot(&self); /// Returns whether the element's styles are up-to-date for |traversal_flags|. fn has_current_styles_for_traversal( &self, data: &ElementData, traversal_flags: TraversalFlags, ) -> bool { if traversal_flags.for_animation_only() { // In animation-only restyle we never touch snapshots and don't // care about them. But we can't assert '!self.handled_snapshot()' // here since there are some cases that a second animation-only // restyle which is a result of normal restyle (e.g. setting // animation-name in normal restyle and creating a new CSS // animation in a SequentialTask) is processed after the normal // traversal in that we had elements that handled snapshot. return data.has_styles() &&!data.hint.has_animation_hint_or_recascade(); } if self.has_snapshot() &&!self.handled_snapshot() { return false; } data.has_styles() &&!data.hint.has_non_animation_invalidations() } /// Returns whether the element's styles are up-to-date after traversal /// (i.e. in post traversal). fn has_current_styles(&self, data: &ElementData) -> bool { if self.has_snapshot() &&!self.handled_snapshot() { return false; } data.has_styles() && // TODO(hiro): When an animating element moved into subtree of // contenteditable element, there remains animation restyle hints in // post traversal. It's generally harmless since the hints will be // processed in a next styling but ideally it should be processed soon. // // Without this, we get failures in: // layout/style/crashtests/1383319.html // layout/style/crashtests/1383001.html // // https://bugzilla.mozilla.org/show_bug.cgi?id=1389675 tracks fixing // this. !data.hint.has_non_animation_invalidations() } /// Flag that this element has a descendant for style processing. /// /// Only safe to call with exclusive access to the element. unsafe fn set_dirty_descendants(&self); /// Flag that this element has no descendant for style processing. /// /// Only safe to call with exclusive access to the element. unsafe fn unset_dirty_descendants(&self); /// Similar to the dirty_descendants but for representing a descendant of /// the element needs to be updated in animation-only traversal. fn has_animation_only_dirty_descendants(&self) -> bool { false } /// Flag that this element has a descendant for animation-only restyle /// processing. /// /// Only safe to call with exclusive access to the element. unsafe fn set_animation_only_dirty_descendants(&self) {} /// Flag that this element has no descendant for animation-only restyle processing. /// /// Only safe to call with exclusive access to the element. unsafe fn unset_animation_only_dirty_descendants(&self) {} /// Clear all bits related describing the dirtiness of descendants. /// /// In Gecko, this corresponds to the regular dirty descendants bit, the /// animation-only dirty descendants bit, and the lazy frame construction /// descendants bit. unsafe fn clear_descendant_bits(&self) { self.unset_dirty_descendants(); } /// Returns true if this element is a visited link. /// /// Servo doesn't support visited styles yet. fn is_visited_link(&self) -> bool { false } /// Returns true if this element is in a native anonymous subtree. fn is_in_native_anonymous_subtree(&self) -> bool { false } /// Returns the pseudo-element implemented by this element, if any. /// /// Gecko traverses pseudo-elements during the style traversal, and we need /// to know this so we can properly grab the pseudo-element style from the /// parent element. /// /// Note that we still need to compute the pseudo-elements before-hand, /// given otherwise we don't know if we need to create an element or not. /// /// Servo doesn't have to deal with this. fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None } /// Atomically stores the number of children of this node that we will /// need to process during bottom-up traversal. fn store_children_to_process(&self, n: isize); /// Atomically notes that a child has been processed during bottom-up /// traversal. Returns the number of children left to process. fn did_process_child(&self) -> isize; /// Gets a reference to the ElementData container, or creates one. /// /// Unsafe because it can race to allocate and leak if not used with /// exclusive access to the element. unsafe fn ensure_data(&self) -> AtomicRefMut<ElementData>; /// Clears the element data reference, if any. /// /// Unsafe following the same reasoning as ensure_data. unsafe fn clear_data(&self); /// Gets a reference to the ElementData container. fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>; /// Immutably borrows the ElementData. fn borrow_data(&self) -> Option<AtomicRef<ElementData>> { self.get_data().map(|x| x.borrow()) } /// Mutably borrows the ElementData. fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> { self.get_data().map(|x| x.borrow_mut()) } /// Whether we should skip any root- or item-based display property /// blockification on this element. (This function exists so that Gecko /// native anonymous content can opt out of this style fixup.) fn skip_item_display_fixup(&self) -> bool; /// Sets selector flags, which indicate what kinds of selectors may have /// matched on this element and therefore what kind of work may need to /// be performed when DOM state changes. /// /// This is unsafe, like all the flag-setting methods, because it's only safe /// to call with exclusive access to the element. When setting flags on the /// parent during parallel traversal, we use SequentialTask to queue up the /// set to run after the threads join. unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags); /// Returns true if the element has all the specified selector flags. fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool; /// In Gecko, element has a flag that represents the element may have /// any type of animations or not to bail out animation stuff early. /// Whereas Servo doesn't have such flag. fn may_have_animations(&self) -> bool { false } /// Creates a task to update various animation state on a given (pseudo-)element. #[cfg(feature = "gecko")] fn update_animations( &self, before_change_style: Option<Arc<ComputedValues>>, tasks: UpdateAnimationsTasks, ); /// Creates a task to process post animation on a given element. #[cfg(feature = "gecko")] fn process_post_animation(&self, tasks: PostAnimationTasks); /// Returns true if the element has relevant animations. Relevant /// animations are those animations that are affecting the element's style /// or are scheduled to do so in the future. fn has_animations(&self) -> bool; /// Returns true if the element has a CSS animation. fn has_css_animations(&self) -> bool; /// Returns true if the element has a CSS transition (including running transitions and /// completed transitions). fn has_css_transitions(&self) -> bool; /// Returns true if the element has animation restyle hints. fn has_animation_restyle_hints(&self) -> bool {
{ loop { let n = self.0.next()?; // Filter out nodes that layout should ignore. if n.is_text_node() || n.is_element() { return Some(n); } } }
identifier_body
dom.rs
#[cfg_attr(feature = "servo", derive(MallocSizeOf, Deserialize, Serialize))] pub struct OpaqueNode(pub usize); impl OpaqueNode { /// Returns the address of this node, for debugging purposes. #[inline] pub fn id(&self) -> usize { self.0 } } /// Simple trait to provide basic information about the type of an element. /// /// We avoid exposing the full type id, since computing it in the general case /// would be difficult for Gecko nodes. pub trait NodeInfo { /// Whether this node is an element. fn is_element(&self) -> bool; /// Whether this node is a text node. fn is_text_node(&self) -> bool; } /// A node iterator that only returns node that don't need layout. pub struct LayoutIterator<T>(pub T); impl<T, N> Iterator for LayoutIterator<T> where T: Iterator<Item = N>, N: NodeInfo, { type Item = N; fn next(&mut self) -> Option<N> { loop { let n = self.0.next()?; // Filter out nodes that layout should ignore. if n.is_text_node() || n.is_element() { return Some(n); } } } } /// An iterator over the DOM children of a node. pub struct DomChildren<N>(Option<N>); impl<N> Iterator for DomChildren<N> where N: TNode, { type Item = N; fn next(&mut self) -> Option<N> { let n = self.0.take()?; self.0 = n.next_sibling(); Some(n) } } /// An iterator over the DOM descendants of a node in pre-order. pub struct DomDescendants<N> { previous: Option<N>, scope: N, } impl<N> Iterator for DomDescendants<N> where N: TNode, { type Item = N; #[inline] fn next(&mut self) -> Option<N> { let prev = self.previous.take()?; self.previous = prev.next_in_preorder(Some(self.scope)); self.previous } } /// The `TDocument` trait, to represent a document node. pub trait TDocument: Sized + Copy + Clone { /// The concrete `TNode` type. type ConcreteNode: TNode<ConcreteDocument = Self>; /// Get this document as a `TNode`. fn as_node(&self) -> Self::ConcreteNode; /// Returns whether this document is an HTML document. fn is_html_document(&self) -> bool; /// Returns the quirks mode of this document. fn quirks_mode(&self) -> QuirksMode; /// Get a list of elements with a given ID in this document, sorted by /// tree position. /// /// Can return an error to signal that this list is not available, or also /// return an empty slice. fn elements_with_id<'a>( &self, _id: &Atom, ) -> Result<&'a [<Self::ConcreteNode as TNode>::ConcreteElement], ()> where Self: 'a, { Err(()) } } /// The `TNode` trait. This is the main generic trait over which the style /// system can be implemented. pub trait TNode: Sized + Copy + Clone + Debug + NodeInfo + PartialEq { /// The concrete `TElement` type. type ConcreteElement: TElement<ConcreteNode = Self>; /// The concrete `TDocument` type. type ConcreteDocument: TDocument<ConcreteNode = Self>; /// The concrete `TShadowRoot` type. type ConcreteShadowRoot: TShadowRoot<ConcreteNode = Self>; /// Get this node's parent node. fn parent_node(&self) -> Option<Self>; /// Get this node's first child. fn first_child(&self) -> Option<Self>; /// Get this node's first child. fn last_child(&self) -> Option<Self>; /// Get this node's previous sibling. fn prev_sibling(&self) -> Option<Self>; /// Get this node's next sibling. fn next_sibling(&self) -> Option<Self>; /// Get the owner document of this node. fn owner_doc(&self) -> Self::ConcreteDocument; /// Iterate over the DOM children of a node. fn dom_children(&self) -> DomChildren<Self> { DomChildren(self.first_child()) } /// Returns whether the node is attached to a document. fn is_in_document(&self) -> bool; /// Iterate over the DOM children of a node, in preorder. fn dom_descendants(&self) -> DomDescendants<Self> { DomDescendants { previous: Some(*self), scope: *self, } } /// Returns the next children in pre-order, optionally scoped to a subtree /// root. #[inline] fn next_in_preorder(&self, scoped_to: Option<Self>) -> Option<Self> { if let Some(c) = self.first_child() { return Some(c); } if Some(*self) == scoped_to { return None; } let mut current = *self; loop { if let Some(s) = current.next_sibling() { return Some(s); } let parent = current.parent_node(); if parent == scoped_to { return None; } current = parent.expect("Not a descendant of the scope?"); } } /// Get this node's parent element from the perspective of a restyle /// traversal. fn traversal_parent(&self) -> Option<Self::ConcreteElement>; /// Get this node's parent element if present. fn parent_element(&self) -> Option<Self::ConcreteElement> { self.parent_node().and_then(|n| n.as_element()) } /// Converts self into an `OpaqueNode`. fn opaque(&self) -> OpaqueNode; /// A debug id, only useful, mm... for debugging. fn debug_id(self) -> usize; /// Get this node as an element, if it's one. fn as_element(&self) -> Option<Self::ConcreteElement>; /// Get this node as a document, if it's one. fn as_document(&self) -> Option<Self::ConcreteDocument>; /// Get this node as a ShadowRoot, if it's one. fn as_shadow_root(&self) -> Option<Self::ConcreteShadowRoot>; } /// Wrapper to output the subtree rather than the single node when formatting /// for Debug. pub struct ShowSubtree<N: TNode>(pub N); impl<N: TNode> Debug for ShowSubtree<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DOM Subtree:")?; fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1) } } /// Wrapper to output the subtree along with the ElementData when formatting /// for Debug. pub struct ShowSubtreeData<N: TNode>(pub N); impl<N: TNode> Debug for ShowSubtreeData<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DOM Subtree:")?; fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1) } } /// Wrapper to output the subtree along with the ElementData and primary /// ComputedValues when formatting for Debug. This is extremely verbose. #[cfg(feature = "servo")] pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N); #[cfg(feature = "servo")] impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DOM Subtree:")?; fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1) } } fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result { if let Some(el) = n.as_element() { write!( f, "{:?} dd={} aodd={} data={:?}", el, el.has_dirty_descendants(), el.has_animation_only_dirty_descendants(), el.borrow_data(), ) } else { write!(f, "{:?}", n) } } #[cfg(feature = "servo")] fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result { if let Some(el) = n.as_element() { let dd = el.has_dirty_descendants(); let aodd = el.has_animation_only_dirty_descendants(); let data = el.borrow_data(); let values = data.as_ref().and_then(|d| d.styles.get_primary()); write!( f, "{:?} dd={} aodd={} data={:?} values={:?}", el, dd, aodd, &data, values ) } else { write!(f, "{:?}", n) } } fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32) -> fmt::Result where F: Fn(&mut fmt::Formatter, N) -> fmt::Result, { for _ in 0..indent { write!(f, " ")?; } stringify(f, n)?; if let Some(e) = n.as_element() { for kid in e.traversal_children() { writeln!(f, "")?; fmt_subtree(f, stringify, kid, indent + 1)?; } } Ok(()) } /// The ShadowRoot trait. pub trait TShadowRoot: Sized + Copy + Clone + PartialEq { /// The concrete node type. type ConcreteNode: TNode<ConcreteShadowRoot = Self>; /// Get this ShadowRoot as a node. fn as_node(&self) -> Self::ConcreteNode; /// Get the shadow host that hosts this ShadowRoot. fn host(&self) -> <Self::ConcreteNode as TNode>::ConcreteElement; /// Get the style data for this ShadowRoot. fn style_data<'a>(&self) -> Option<&'a CascadeData> where Self: 'a; /// Get a list of elements with a given ID in this shadow root, sorted by /// tree position. /// /// Can return an error to signal that this list is not available, or also /// return an empty slice. fn elements_with_id<'a>( &self, _id: &Atom, ) -> Result<&'a [<Self::ConcreteNode as TNode>::ConcreteElement], ()> where Self: 'a, { Err(()) } } /// The element trait, the main abstraction the style crate acts over. pub trait TElement: Eq + PartialEq + Debug + Hash + Sized + Copy + Clone + SelectorsElement<Impl = SelectorImpl> { /// The concrete node type. type ConcreteNode: TNode<ConcreteElement = Self>; /// A concrete children iterator type in order to iterate over the `Node`s. /// /// TODO(emilio): We should eventually replace this with the `impl Trait` /// syntax. type TraversalChildrenIterator: Iterator<Item = Self::ConcreteNode>; /// Type of the font metrics provider /// /// XXXManishearth It would be better to make this a type parameter on /// ThreadLocalStyleContext and StyleContext type FontMetricsProvider: FontMetricsProvider + Send; /// Get this element as a node. fn as_node(&self) -> Self::ConcreteNode; /// A debug-only check that the device's owner doc matches the actual doc /// we're the root of. /// /// Otherwise we may set document-level state incorrectly, like the root /// font-size used for rem units. fn owner_doc_matches_for_testing(&self, _: &Device) -> bool { true } /// Whether this element should match user and author rules. /// /// We use this for Native Anonymous Content in Gecko. fn matches_user_and_author_rules(&self) -> bool { true } /// Returns the depth of this element in the DOM. fn depth(&self) -> usize { let mut depth = 0; let mut curr = *self; while let Some(parent) = curr.traversal_parent() { depth += 1; curr = parent; } depth } /// Get this node's parent element from the perspective of a restyle /// traversal. fn traversal_parent(&self) -> Option<Self> { self.as_node().traversal_parent() } /// Get this node's children from the perspective of a restyle traversal. fn traversal_children(&self) -> LayoutIterator<Self::TraversalChildrenIterator>; /// Returns the parent element we should inherit from. /// /// This is pretty much always the parent element itself, except in the case /// of Gecko's Native Anonymous Content, which uses the traversal parent /// (i.e. the flattened tree parent) and which also may need to find the /// closest non-NAC ancestor. fn inheritance_parent(&self) -> Option<Self> { self.parent_element() } /// The ::before pseudo-element of this element, if it exists. fn before_pseudo_element(&self) -> Option<Self> { None } /// The ::after pseudo-element of this element, if it exists. fn after_pseudo_element(&self) -> Option<Self> { None } /// The ::marker pseudo-element of this element, if it exists. fn marker_pseudo_element(&self) -> Option<Self> { None } /// Execute `f` for each anonymous content child (apart from ::before and /// ::after) whose originating element is `self`. fn each_anonymous_content_child<F>(&self, _f: F) where F: FnMut(Self), { } /// Return whether this element is an element in the HTML namespace. fn is_html_element(&self) -> bool; /// Return whether this element is an element in the MathML namespace. fn is_mathml_element(&self) -> bool; /// Return whether this element is an element in the SVG namespace. fn is_svg_element(&self) -> bool; /// Return whether this element is an element in the XUL namespace. fn is_xul_element(&self) -> bool { false } /// Return the list of slotted nodes of this node. fn slotted_nodes(&self) -> &[Self::ConcreteNode] { &[] } /// Get this element's style attribute. fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>; /// Unset the style attribute's dirty bit. /// Servo doesn't need to manage ditry bit for style attribute. fn unset_dirty_style_attribute(&self) {} /// Get this element's SMIL override declarations. fn smil_override(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>> { None } /// Get the combined animation and transition rules. /// /// FIXME(emilio): Is this really useful? fn animation_rules(&self) -> AnimationRules { if!self.may_have_animations() { return AnimationRules(None, None); } AnimationRules(self.animation_rule(), self.transition_rule()) } /// Get this element's animation rule. fn animation_rule(&self) -> Option<Arc<Locked<PropertyDeclarationBlock>>> { None } /// Get this element's transition rule. fn transition_rule(&self) -> Option<Arc<Locked<PropertyDeclarationBlock>>> { None } /// Get this element's state, for non-tree-structural pseudos. fn state(&self) -> ElementState; /// Whether this element has an attribute with a given namespace. fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool; /// The ID for this element. fn id(&self) -> Option<&WeakAtom>; /// Internal iterator for the classes of this element. fn each_class<F>(&self, callback: F) where F: FnMut(&Atom); /// Whether a given element may generate a pseudo-element. /// /// This is useful to avoid computing, for example, pseudo styles for /// `::-first-line` or `::-first-letter`, when we know it won't affect us. /// /// TODO(emilio, bz): actually implement the logic for it. fn may_generate_pseudo(&self, pseudo: &PseudoElement, _primary_style: &ComputedValues) -> bool { // ::before/::after are always supported for now, though we could try to // optimize out leaf elements. // ::first-letter and ::first-line are only supported for block-inside // things, and only in Gecko, not Servo. Unfortunately, Gecko has // block-inside things that might have any computed display value due to // things like fieldsets, legends, etc. Need to figure out how this // should work. debug_assert!( pseudo.is_eager(), "Someone called may_generate_pseudo with a non-eager pseudo." ); true } /// Returns true if this element may have a descendant needing style processing. /// /// Note that we cannot guarantee the existence of such an element, because /// it may have been removed from the DOM between marking it for restyle and /// the actual restyle traversal. fn has_dirty_descendants(&self) -> bool; /// Returns whether state or attributes that may change style have changed /// on the element, and thus whether the element has been snapshotted to do /// restyle hint computation. fn has_snapshot(&self) -> bool; /// Returns whether the current snapshot if present has been handled. fn handled_snapshot(&self) -> bool; /// Flags this element as having handled already its snapshot. unsafe fn set_handled_snapshot(&self); /// Returns whether the element's styles are up-to-date for |traversal_flags|. fn has_current_styles_for_traversal( &self, data: &ElementData, traversal_flags: TraversalFlags, ) -> bool { if traversal_flags.for_animation_only() { // In animation-only restyle we never touch snapshots and don't // care about them. But we can't assert '!self.handled_snapshot()' // here since there are some cases that a second animation-only // restyle which is a result of normal restyle (e.g. setting // animation-name in normal restyle and creating a new CSS // animation in a SequentialTask) is processed after the normal // traversal in that we had elements that handled snapshot. return data.has_styles() &&!data.hint.has_animation_hint_or_recascade(); } if self.has_snapshot() &&!self.handled_snapshot() { return false; } data.has_styles() &&!data.hint.has_non_animation_invalidations() } /// Returns whether the element's styles are up-to-date after traversal /// (i.e. in post traversal). fn has_current_styles(&self, data: &ElementData) -> bool { if self.has_snapshot() &&!self.handled_snapshot() { return false; } data.has_styles() && // TODO(hiro): When an animating element moved into subtree of // contenteditable element, there remains animation restyle hints in // post traversal. It's generally harmless since the hints will be // processed in a next styling but ideally it should be processed soon. // // Without this, we get failures in: // layout/style/crashtests/1383319.html // layout/style/crashtests/1383001.html // // https://bugzilla.mozilla.org/show_bug.cgi?id=1389675 tracks fixing // this. !data.hint.has_non_animation_invalidations() } /// Flag that this element has a descendant for style processing. /// /// Only safe to call with exclusive access to the element. unsafe fn set_dirty_descendants(&self); /// Flag that this element has no descendant for style processing. /// /// Only safe to call with exclusive access to the element. unsafe fn unset_dirty_descendants(&self); /// Similar to the dirty_descendants but for representing a descendant of /// the element needs to be updated in animation-only traversal. fn has_animation_only_dirty_descendants(&self) -> bool { false } /// Flag that this element has a descendant for animation-only restyle /// processing. /// /// Only safe to call with exclusive access to the element. unsafe fn set_animation_only_dirty_descendants(&self) {} /// Flag that this element has no descendant for animation-only restyle processing. /// /// Only safe to call with exclusive access to the element. unsafe fn unset_animation_only_dirty_descendants(&self) {} /// Clear all bits related describing the dirtiness of descendants. /// /// In Gecko, this corresponds to the regular dirty descendants bit, the /// animation-only dirty descendants bit, and the lazy frame construction /// descendants bit. unsafe fn clear_descendant_bits(&self) { self.unset_dirty_descendants(); } /// Returns true if this element is a visited link. /// /// Servo doesn't support visited styles yet. fn is_visited_link(&self) -> bool { false } /// Returns true if this element is in a native anonymous subtree. fn is_in_native_anonymous_subtree(&self) -> bool { false } /// Returns the pseudo-element implemented by this element, if any. /// /// Gecko traverses pseudo-elements during the style traversal, and we need /// to know this so we can properly grab the pseudo-element style from the /// parent element. /// /// Note that we still need to compute the pseudo-elements before-hand, /// given otherwise we don't know if we need to create an element or not. /// /// Servo doesn't have to deal with this. fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None } /// Atomically stores the number of children of this node that we will /// need to process during bottom-up traversal. fn store_children_to_process(&self, n: isize); /// Atomically notes that a child has been processed during bottom-up /// traversal. Returns the number of children left to process. fn did_process_child(&self) -> isize; /// Gets a reference to the ElementData container, or creates one. /// /// Unsafe because it can race to allocate and leak if not used with /// exclusive access to the element. unsafe fn ensure_data(&self) -> AtomicRefMut<ElementData>; /// Clears the element data reference, if any. /// /// Unsafe following the same reasoning as ensure_data. unsafe fn clear_data(&self); /// Gets a reference to the ElementData container. fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>; /// Immutably borrows the ElementData. fn borrow_data(&self) -> Option<AtomicRef<ElementData>> { self.get_data().map(|x| x.borrow()) } /// Mutably borrows the ElementData. fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> { self.get_data().map(|x| x.borrow_mut()) } /// Whether we should skip any root- or item-based display property /// blockification on this element. (This function exists so that Gecko /// native anonymous content can opt out of this style fixup.) fn skip_item_display_fixup(&self) -> bool; /// Sets selector flags, which indicate what kinds of selectors may have /// matched on this element and therefore what kind of work may need to /// be performed when DOM state changes. /// /// This is unsafe, like all the flag-setting methods, because it's only safe /// to call with exclusive access to the element. When setting flags on the /// parent during parallel traversal, we use SequentialTask to queue up the /// set to run after the threads join. unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags); /// Returns true if the element has all the specified selector flags. fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool; /// In Gecko, element has a flag that represents the element may have /// any type of animations or not to bail out animation stuff early. /// Whereas Servo
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout /// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for /// locality reasons. Using `OpaqueNode` enforces this invariant. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
random_line_split
dom.rs
Option<N>); impl<N> Iterator for DomChildren<N> where N: TNode, { type Item = N; fn next(&mut self) -> Option<N> { let n = self.0.take()?; self.0 = n.next_sibling(); Some(n) } } /// An iterator over the DOM descendants of a node in pre-order. pub struct DomDescendants<N> { previous: Option<N>, scope: N, } impl<N> Iterator for DomDescendants<N> where N: TNode, { type Item = N; #[inline] fn next(&mut self) -> Option<N> { let prev = self.previous.take()?; self.previous = prev.next_in_preorder(Some(self.scope)); self.previous } } /// The `TDocument` trait, to represent a document node. pub trait TDocument: Sized + Copy + Clone { /// The concrete `TNode` type. type ConcreteNode: TNode<ConcreteDocument = Self>; /// Get this document as a `TNode`. fn as_node(&self) -> Self::ConcreteNode; /// Returns whether this document is an HTML document. fn is_html_document(&self) -> bool; /// Returns the quirks mode of this document. fn quirks_mode(&self) -> QuirksMode; /// Get a list of elements with a given ID in this document, sorted by /// tree position. /// /// Can return an error to signal that this list is not available, or also /// return an empty slice. fn elements_with_id<'a>( &self, _id: &Atom, ) -> Result<&'a [<Self::ConcreteNode as TNode>::ConcreteElement], ()> where Self: 'a, { Err(()) } } /// The `TNode` trait. This is the main generic trait over which the style /// system can be implemented. pub trait TNode: Sized + Copy + Clone + Debug + NodeInfo + PartialEq { /// The concrete `TElement` type. type ConcreteElement: TElement<ConcreteNode = Self>; /// The concrete `TDocument` type. type ConcreteDocument: TDocument<ConcreteNode = Self>; /// The concrete `TShadowRoot` type. type ConcreteShadowRoot: TShadowRoot<ConcreteNode = Self>; /// Get this node's parent node. fn parent_node(&self) -> Option<Self>; /// Get this node's first child. fn first_child(&self) -> Option<Self>; /// Get this node's first child. fn last_child(&self) -> Option<Self>; /// Get this node's previous sibling. fn prev_sibling(&self) -> Option<Self>; /// Get this node's next sibling. fn next_sibling(&self) -> Option<Self>; /// Get the owner document of this node. fn owner_doc(&self) -> Self::ConcreteDocument; /// Iterate over the DOM children of a node. fn
(&self) -> DomChildren<Self> { DomChildren(self.first_child()) } /// Returns whether the node is attached to a document. fn is_in_document(&self) -> bool; /// Iterate over the DOM children of a node, in preorder. fn dom_descendants(&self) -> DomDescendants<Self> { DomDescendants { previous: Some(*self), scope: *self, } } /// Returns the next children in pre-order, optionally scoped to a subtree /// root. #[inline] fn next_in_preorder(&self, scoped_to: Option<Self>) -> Option<Self> { if let Some(c) = self.first_child() { return Some(c); } if Some(*self) == scoped_to { return None; } let mut current = *self; loop { if let Some(s) = current.next_sibling() { return Some(s); } let parent = current.parent_node(); if parent == scoped_to { return None; } current = parent.expect("Not a descendant of the scope?"); } } /// Get this node's parent element from the perspective of a restyle /// traversal. fn traversal_parent(&self) -> Option<Self::ConcreteElement>; /// Get this node's parent element if present. fn parent_element(&self) -> Option<Self::ConcreteElement> { self.parent_node().and_then(|n| n.as_element()) } /// Converts self into an `OpaqueNode`. fn opaque(&self) -> OpaqueNode; /// A debug id, only useful, mm... for debugging. fn debug_id(self) -> usize; /// Get this node as an element, if it's one. fn as_element(&self) -> Option<Self::ConcreteElement>; /// Get this node as a document, if it's one. fn as_document(&self) -> Option<Self::ConcreteDocument>; /// Get this node as a ShadowRoot, if it's one. fn as_shadow_root(&self) -> Option<Self::ConcreteShadowRoot>; } /// Wrapper to output the subtree rather than the single node when formatting /// for Debug. pub struct ShowSubtree<N: TNode>(pub N); impl<N: TNode> Debug for ShowSubtree<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DOM Subtree:")?; fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1) } } /// Wrapper to output the subtree along with the ElementData when formatting /// for Debug. pub struct ShowSubtreeData<N: TNode>(pub N); impl<N: TNode> Debug for ShowSubtreeData<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DOM Subtree:")?; fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1) } } /// Wrapper to output the subtree along with the ElementData and primary /// ComputedValues when formatting for Debug. This is extremely verbose. #[cfg(feature = "servo")] pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N); #[cfg(feature = "servo")] impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DOM Subtree:")?; fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1) } } fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result { if let Some(el) = n.as_element() { write!( f, "{:?} dd={} aodd={} data={:?}", el, el.has_dirty_descendants(), el.has_animation_only_dirty_descendants(), el.borrow_data(), ) } else { write!(f, "{:?}", n) } } #[cfg(feature = "servo")] fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result { if let Some(el) = n.as_element() { let dd = el.has_dirty_descendants(); let aodd = el.has_animation_only_dirty_descendants(); let data = el.borrow_data(); let values = data.as_ref().and_then(|d| d.styles.get_primary()); write!( f, "{:?} dd={} aodd={} data={:?} values={:?}", el, dd, aodd, &data, values ) } else { write!(f, "{:?}", n) } } fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32) -> fmt::Result where F: Fn(&mut fmt::Formatter, N) -> fmt::Result, { for _ in 0..indent { write!(f, " ")?; } stringify(f, n)?; if let Some(e) = n.as_element() { for kid in e.traversal_children() { writeln!(f, "")?; fmt_subtree(f, stringify, kid, indent + 1)?; } } Ok(()) } /// The ShadowRoot trait. pub trait TShadowRoot: Sized + Copy + Clone + PartialEq { /// The concrete node type. type ConcreteNode: TNode<ConcreteShadowRoot = Self>; /// Get this ShadowRoot as a node. fn as_node(&self) -> Self::ConcreteNode; /// Get the shadow host that hosts this ShadowRoot. fn host(&self) -> <Self::ConcreteNode as TNode>::ConcreteElement; /// Get the style data for this ShadowRoot. fn style_data<'a>(&self) -> Option<&'a CascadeData> where Self: 'a; /// Get a list of elements with a given ID in this shadow root, sorted by /// tree position. /// /// Can return an error to signal that this list is not available, or also /// return an empty slice. fn elements_with_id<'a>( &self, _id: &Atom, ) -> Result<&'a [<Self::ConcreteNode as TNode>::ConcreteElement], ()> where Self: 'a, { Err(()) } } /// The element trait, the main abstraction the style crate acts over. pub trait TElement: Eq + PartialEq + Debug + Hash + Sized + Copy + Clone + SelectorsElement<Impl = SelectorImpl> { /// The concrete node type. type ConcreteNode: TNode<ConcreteElement = Self>; /// A concrete children iterator type in order to iterate over the `Node`s. /// /// TODO(emilio): We should eventually replace this with the `impl Trait` /// syntax. type TraversalChildrenIterator: Iterator<Item = Self::ConcreteNode>; /// Type of the font metrics provider /// /// XXXManishearth It would be better to make this a type parameter on /// ThreadLocalStyleContext and StyleContext type FontMetricsProvider: FontMetricsProvider + Send; /// Get this element as a node. fn as_node(&self) -> Self::ConcreteNode; /// A debug-only check that the device's owner doc matches the actual doc /// we're the root of. /// /// Otherwise we may set document-level state incorrectly, like the root /// font-size used for rem units. fn owner_doc_matches_for_testing(&self, _: &Device) -> bool { true } /// Whether this element should match user and author rules. /// /// We use this for Native Anonymous Content in Gecko. fn matches_user_and_author_rules(&self) -> bool { true } /// Returns the depth of this element in the DOM. fn depth(&self) -> usize { let mut depth = 0; let mut curr = *self; while let Some(parent) = curr.traversal_parent() { depth += 1; curr = parent; } depth } /// Get this node's parent element from the perspective of a restyle /// traversal. fn traversal_parent(&self) -> Option<Self> { self.as_node().traversal_parent() } /// Get this node's children from the perspective of a restyle traversal. fn traversal_children(&self) -> LayoutIterator<Self::TraversalChildrenIterator>; /// Returns the parent element we should inherit from. /// /// This is pretty much always the parent element itself, except in the case /// of Gecko's Native Anonymous Content, which uses the traversal parent /// (i.e. the flattened tree parent) and which also may need to find the /// closest non-NAC ancestor. fn inheritance_parent(&self) -> Option<Self> { self.parent_element() } /// The ::before pseudo-element of this element, if it exists. fn before_pseudo_element(&self) -> Option<Self> { None } /// The ::after pseudo-element of this element, if it exists. fn after_pseudo_element(&self) -> Option<Self> { None } /// The ::marker pseudo-element of this element, if it exists. fn marker_pseudo_element(&self) -> Option<Self> { None } /// Execute `f` for each anonymous content child (apart from ::before and /// ::after) whose originating element is `self`. fn each_anonymous_content_child<F>(&self, _f: F) where F: FnMut(Self), { } /// Return whether this element is an element in the HTML namespace. fn is_html_element(&self) -> bool; /// Return whether this element is an element in the MathML namespace. fn is_mathml_element(&self) -> bool; /// Return whether this element is an element in the SVG namespace. fn is_svg_element(&self) -> bool; /// Return whether this element is an element in the XUL namespace. fn is_xul_element(&self) -> bool { false } /// Return the list of slotted nodes of this node. fn slotted_nodes(&self) -> &[Self::ConcreteNode] { &[] } /// Get this element's style attribute. fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>; /// Unset the style attribute's dirty bit. /// Servo doesn't need to manage ditry bit for style attribute. fn unset_dirty_style_attribute(&self) {} /// Get this element's SMIL override declarations. fn smil_override(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>> { None } /// Get the combined animation and transition rules. /// /// FIXME(emilio): Is this really useful? fn animation_rules(&self) -> AnimationRules { if!self.may_have_animations() { return AnimationRules(None, None); } AnimationRules(self.animation_rule(), self.transition_rule()) } /// Get this element's animation rule. fn animation_rule(&self) -> Option<Arc<Locked<PropertyDeclarationBlock>>> { None } /// Get this element's transition rule. fn transition_rule(&self) -> Option<Arc<Locked<PropertyDeclarationBlock>>> { None } /// Get this element's state, for non-tree-structural pseudos. fn state(&self) -> ElementState; /// Whether this element has an attribute with a given namespace. fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool; /// The ID for this element. fn id(&self) -> Option<&WeakAtom>; /// Internal iterator for the classes of this element. fn each_class<F>(&self, callback: F) where F: FnMut(&Atom); /// Whether a given element may generate a pseudo-element. /// /// This is useful to avoid computing, for example, pseudo styles for /// `::-first-line` or `::-first-letter`, when we know it won't affect us. /// /// TODO(emilio, bz): actually implement the logic for it. fn may_generate_pseudo(&self, pseudo: &PseudoElement, _primary_style: &ComputedValues) -> bool { // ::before/::after are always supported for now, though we could try to // optimize out leaf elements. // ::first-letter and ::first-line are only supported for block-inside // things, and only in Gecko, not Servo. Unfortunately, Gecko has // block-inside things that might have any computed display value due to // things like fieldsets, legends, etc. Need to figure out how this // should work. debug_assert!( pseudo.is_eager(), "Someone called may_generate_pseudo with a non-eager pseudo." ); true } /// Returns true if this element may have a descendant needing style processing. /// /// Note that we cannot guarantee the existence of such an element, because /// it may have been removed from the DOM between marking it for restyle and /// the actual restyle traversal. fn has_dirty_descendants(&self) -> bool; /// Returns whether state or attributes that may change style have changed /// on the element, and thus whether the element has been snapshotted to do /// restyle hint computation. fn has_snapshot(&self) -> bool; /// Returns whether the current snapshot if present has been handled. fn handled_snapshot(&self) -> bool; /// Flags this element as having handled already its snapshot. unsafe fn set_handled_snapshot(&self); /// Returns whether the element's styles are up-to-date for |traversal_flags|. fn has_current_styles_for_traversal( &self, data: &ElementData, traversal_flags: TraversalFlags, ) -> bool { if traversal_flags.for_animation_only() { // In animation-only restyle we never touch snapshots and don't // care about them. But we can't assert '!self.handled_snapshot()' // here since there are some cases that a second animation-only // restyle which is a result of normal restyle (e.g. setting // animation-name in normal restyle and creating a new CSS // animation in a SequentialTask) is processed after the normal // traversal in that we had elements that handled snapshot. return data.has_styles() &&!data.hint.has_animation_hint_or_recascade(); } if self.has_snapshot() &&!self.handled_snapshot() { return false; } data.has_styles() &&!data.hint.has_non_animation_invalidations() } /// Returns whether the element's styles are up-to-date after traversal /// (i.e. in post traversal). fn has_current_styles(&self, data: &ElementData) -> bool { if self.has_snapshot() &&!self.handled_snapshot() { return false; } data.has_styles() && // TODO(hiro): When an animating element moved into subtree of // contenteditable element, there remains animation restyle hints in // post traversal. It's generally harmless since the hints will be // processed in a next styling but ideally it should be processed soon. // // Without this, we get failures in: // layout/style/crashtests/1383319.html // layout/style/crashtests/1383001.html // // https://bugzilla.mozilla.org/show_bug.cgi?id=1389675 tracks fixing // this. !data.hint.has_non_animation_invalidations() } /// Flag that this element has a descendant for style processing. /// /// Only safe to call with exclusive access to the element. unsafe fn set_dirty_descendants(&self); /// Flag that this element has no descendant for style processing. /// /// Only safe to call with exclusive access to the element. unsafe fn unset_dirty_descendants(&self); /// Similar to the dirty_descendants but for representing a descendant of /// the element needs to be updated in animation-only traversal. fn has_animation_only_dirty_descendants(&self) -> bool { false } /// Flag that this element has a descendant for animation-only restyle /// processing. /// /// Only safe to call with exclusive access to the element. unsafe fn set_animation_only_dirty_descendants(&self) {} /// Flag that this element has no descendant for animation-only restyle processing. /// /// Only safe to call with exclusive access to the element. unsafe fn unset_animation_only_dirty_descendants(&self) {} /// Clear all bits related describing the dirtiness of descendants. /// /// In Gecko, this corresponds to the regular dirty descendants bit, the /// animation-only dirty descendants bit, and the lazy frame construction /// descendants bit. unsafe fn clear_descendant_bits(&self) { self.unset_dirty_descendants(); } /// Returns true if this element is a visited link. /// /// Servo doesn't support visited styles yet. fn is_visited_link(&self) -> bool { false } /// Returns true if this element is in a native anonymous subtree. fn is_in_native_anonymous_subtree(&self) -> bool { false } /// Returns the pseudo-element implemented by this element, if any. /// /// Gecko traverses pseudo-elements during the style traversal, and we need /// to know this so we can properly grab the pseudo-element style from the /// parent element. /// /// Note that we still need to compute the pseudo-elements before-hand, /// given otherwise we don't know if we need to create an element or not. /// /// Servo doesn't have to deal with this. fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None } /// Atomically stores the number of children of this node that we will /// need to process during bottom-up traversal. fn store_children_to_process(&self, n: isize); /// Atomically notes that a child has been processed during bottom-up /// traversal. Returns the number of children left to process. fn did_process_child(&self) -> isize; /// Gets a reference to the ElementData container, or creates one. /// /// Unsafe because it can race to allocate and leak if not used with /// exclusive access to the element. unsafe fn ensure_data(&self) -> AtomicRefMut<ElementData>; /// Clears the element data reference, if any. /// /// Unsafe following the same reasoning as ensure_data. unsafe fn clear_data(&self); /// Gets a reference to the ElementData container. fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>; /// Immutably borrows the ElementData. fn borrow_data(&self) -> Option<AtomicRef<ElementData>> { self.get_data().map(|x| x.borrow()) } /// Mutably borrows the ElementData. fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> { self.get_data().map(|x| x.borrow_mut()) } /// Whether we should skip any root- or item-based display property /// blockification on this element. (This function exists so that Gecko /// native anonymous content can opt out of this style fixup.) fn skip_item_display_fixup(&self) -> bool; /// Sets selector flags, which indicate what kinds of selectors may have /// matched on this element and therefore what kind of work may need to /// be performed when DOM state changes. /// /// This is unsafe, like all the flag-setting methods, because it's only safe /// to call with exclusive access to the element. When setting flags on the /// parent during parallel traversal, we use SequentialTask to queue up the /// set to run after the threads join. unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags); /// Returns true if the element has all the specified selector flags. fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool; /// In Gecko, element has a flag that represents the element may have /// any type of animations or not to bail out animation stuff early. /// Whereas Servo doesn't have such flag. fn may_have_animations(&self) -> bool { false } /// Creates a task to update various animation state on a given (pseudo-)element. #[cfg(feature = "gecko")] fn update_animations( &self, before_change_style: Option<Arc<ComputedValues>>, tasks: UpdateAnimationsTasks, ); /// Creates a task to process post animation on a given element. #[cfg(feature = "gecko")] fn process_post_animation(&self, tasks: PostAnimationTasks); /// Returns true if the element has relevant animations. Relevant /// animations are those animations that are affecting the element's style /// or are scheduled to do so in the future. fn has_animations(&self) -> bool; /// Returns true if the element has a CSS animation. fn has_css_animations(&self) -> bool; /// Returns true if the element has a CSS transition (including running transitions and /// completed transitions). fn has_css_transitions(&self) -> bool; /// Returns true if the element has animation restyle hints. fn has_animation_restyle_hints(&self) -> bool { let data = match self.borrow_data() { Some(d) => d, None => return false, }; return data.hint.has_animation_hint(); } /// Returns the anonymous content for the current element's XBL binding, /// given if any. /// /// This is used in Gecko for XBL. fn xbl_binding_anonymous_content(&self) -> Option<Self::Concrete
dom_children
identifier_name
main.rs
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2015-2022 Christian Krause * * * * Christian Krause <[email protected]> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file is part of strace-analyzer. * * * * strace-analyzer is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the license, or any * * later version. * * * * strace-analyzer is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with strace-analyzer. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #![deny(clippy::all)] #![warn(clippy::pedantic, clippy::nursery, clippy::cargo)] mod analysis; mod cli; mod config; mod log; mod output; mod summary; use anyhow::Result; use crate::config::Config; fn
() -> Result<()> { let args = cli::build().get_matches(); let config = Config::try_from(&args)?; let input = args.value_of("input").unwrap(); analysis::run(input, config) }
main
identifier_name
main.rs
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2015-2022 Christian Krause * * * * Christian Krause <[email protected]> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file is part of strace-analyzer. * * * * strace-analyzer is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the license, or any * * later version. * * * * strace-analyzer is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with strace-analyzer. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#![warn(clippy::pedantic, clippy::nursery, clippy::cargo)] mod analysis; mod cli; mod config; mod log; mod output; mod summary; use anyhow::Result; use crate::config::Config; fn main() -> Result<()> { let args = cli::build().get_matches(); let config = Config::try_from(&args)?; let input = args.value_of("input").unwrap(); analysis::run(input, config) }
#![deny(clippy::all)]
random_line_split
main.rs
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2015-2022 Christian Krause * * * * Christian Krause <[email protected]> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file is part of strace-analyzer. * * * * strace-analyzer is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the license, or any * * later version. * * * * strace-analyzer is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with strace-analyzer. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #![deny(clippy::all)] #![warn(clippy::pedantic, clippy::nursery, clippy::cargo)] mod analysis; mod cli; mod config; mod log; mod output; mod summary; use anyhow::Result; use crate::config::Config; fn main() -> Result<()>
{ let args = cli::build().get_matches(); let config = Config::try_from(&args)?; let input = args.value_of("input").unwrap(); analysis::run(input, config) }
identifier_body
meth.rs
method: &ast::method, param_substs: Option<@param_substs>, llfn: ValueRef) { // figure out how self is being passed let self_arg = match method.explicit_self.node { ast::sty_static => { no_self } _ => { // determine the (monomorphized) type that `self` maps to for // this method let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id); let self_ty = match param_substs { None => self_ty, Some(@param_substs {tys: ref tys, self_ty: ref self_sub,..}) => { ty::subst_tps(ccx.tcx, *tys, *self_sub, self_ty) } }; debug!("calling trans_fn with self_ty {}", self_ty.repr(ccx.tcx)); match method.explicit_self.node { ast::sty_value(_) => impl_self(self_ty, ty::ByRef), _ => impl_self(self_ty, ty::ByCopy), } } }; // generate the actual code trans_fn(ccx, path, method.decl, method.body, llfn, self_arg, param_substs, method.id, []); } pub fn trans_self_arg(bcx: @mut Block, base: &ast::Expr, temp_cleanups: &mut ~[ValueRef], mentry: typeck::method_map_entry) -> Result { let _icx = push_ctxt("impl::trans_self_arg"); // self is passed as an opaque box in the environment slot let self_ty = ty::mk_opaque_box(bcx.tcx()); trans_arg_expr(bcx, self_ty, mentry.self_mode, base, temp_cleanups, DontAutorefArg) } pub fn trans_method_callee(bcx: @mut Block, callee_id: ast::NodeId, this: &ast::Expr, mentry: typeck::method_map_entry) -> Callee { let _icx = push_ctxt("impl::trans_method_callee"); debug!("trans_method_callee(callee_id={:?}, this={}, mentry={})", callee_id, bcx.expr_to_str(this), mentry.repr(bcx.tcx())); match mentry.origin { typeck::method_static(did) => { let callee_fn = callee::trans_fn_ref(bcx, did, callee_id); let mut temp_cleanups = ~[]; let Result {bcx, val} = trans_self_arg(bcx, this, &mut temp_cleanups, mentry); Callee { bcx: bcx, data: Method(MethodData { llfn: callee_fn.llfn, llself: val, temp_cleanup: temp_cleanups.head_opt().map(|v| *v), self_mode: mentry.self_mode, }) } } typeck::method_param(typeck::method_param { trait_id: trait_id, method_num: off, param_num: p, bound_num: b }) => { match bcx.fcx.param_substs { Some(substs) => { ty::populate_implementations_for_trait_if_necessary( bcx.tcx(), trait_id); let vtbl = find_vtable(bcx.tcx(), substs, p, b); trans_monomorphized_callee(bcx, callee_id, this, mentry, trait_id, off, vtbl) } // how to get rid of this? None => fail!("trans_method_callee: missing param_substs") } } typeck::method_object(ref mt) => { trans_trait_callee(bcx, callee_id, mt.real_index, this) } } } pub fn trans_static_method_callee(bcx: @mut Block, method_id: ast::DefId, trait_id: ast::DefId, callee_id: ast::NodeId) -> FnData { let _icx = push_ctxt("impl::trans_static_method_callee"); let ccx = bcx.ccx(); debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \ callee_id={:?})", method_id, ty::item_path_str(bcx.tcx(), trait_id), callee_id); let _indenter = indenter(); ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trait_id); // When we translate a static fn defined in a trait like: // // trait<T1...Tn> Trait { // fn foo<M1...Mn>(...) {...} // } // // this winds up being translated as something like: // // fn foo<T1...Tn,self: Trait<T1...Tn>,M1...Mn>(...) {...} // // So when we see a call to this function foo, we have to figure // out which impl the `Trait<T1...Tn>` bound on the type `self` was // bound to. let bound_index = ty::lookup_trait_def(bcx.tcx(), trait_id). generics.type_param_defs.len(); let mname = if method_id.crate == ast::LOCAL_CRATE { match bcx.tcx().items.get_copy(&method_id.node) { ast_map::node_trait_method(trait_method, _, _) => { ast_util::trait_method_to_ty_method(trait_method).ident } _ => fail!("callee is not a trait method") } } else { let path = csearch::get_item_path(bcx.tcx(), method_id); match path[path.len()-1] { path_pretty_name(s, _) | path_name(s) => { s } path_mod(_) => { fail!("path doesn't have a name?") } } }; debug!("trans_static_method_callee: method_id={:?}, callee_id={:?}, \ name={}", method_id, callee_id, ccx.sess.str_of(mname)); let vtbls = resolve_vtables_in_fn_ctxt( bcx.fcx, ccx.maps.vtable_map.get_copy(&callee_id)); match vtbls[bound_index][0] { typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => { assert!(rcvr_substs.iter().all(|t|!ty::type_needs_infer(*t))); let mth_id = method_with_name(bcx.ccx(), impl_did, mname.name); let (callee_substs, callee_origins) = combine_impl_and_methods_tps( bcx, mth_id, callee_id, *rcvr_substs, rcvr_origins); let FnData {llfn: lval} = trans_fn_ref_with_vtables(bcx, mth_id, callee_id, callee_substs, Some(callee_origins)); let callee_ty = node_id_type(bcx, callee_id); let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to(); FnData {llfn: PointerCast(bcx, lval, llty)} } _ => { fail!("vtable_param left in monomorphized \ function's vtable substs"); } } } pub fn method_with_name(ccx: &mut CrateContext, impl_id: ast::DefId, name: ast::Name) -> ast::DefId { let meth_id_opt = ccx.impl_method_cache.find_copy(&(impl_id, name)); match meth_id_opt { Some(m) => return m, None => {} } let imp = ccx.tcx.impls.find(&impl_id) .expect("could not find impl while translating"); let meth = imp.methods.iter().find(|m| m.ident.name == name) .expect("could not find method while translating"); ccx.impl_method_cache.insert((impl_id, name), meth.def_id); meth.def_id } pub fn trans_monomorphized_callee(bcx: @mut Block, callee_id: ast::NodeId, base: &ast::Expr, mentry: typeck::method_map_entry, trait_id: ast::DefId, n_method: uint, vtbl: typeck::vtable_origin) -> Callee { let _icx = push_ctxt("impl::trans_monomorphized_callee"); return match vtbl { typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => { let ccx = bcx.ccx(); let mname = ty::trait_method(ccx.tcx, trait_id, n_method).ident; let mth_id = method_with_name(bcx.ccx(), impl_did, mname.name); // obtain the `self` value: let mut temp_cleanups = ~[]; let Result {bcx, val: llself_val} = trans_self_arg(bcx, base, &mut temp_cleanups, mentry); // create a concatenated set of substitutions which includes // those from the impl and those from the method: let (callee_substs, callee_origins) = combine_impl_and_methods_tps( bcx, mth_id, callee_id, *rcvr_substs, rcvr_origins); // translate the function let callee = trans_fn_ref_with_vtables(bcx, mth_id, callee_id, callee_substs, Some(callee_origins)); // create a llvalue that represents the fn ptr let fn_ty = node_id_type(bcx, callee_id); let llfn_ty = type_of_fn_from_ty(ccx, fn_ty).ptr_to(); let llfn_val = PointerCast(bcx, callee.llfn, llfn_ty); // combine the self environment with the rest Callee { bcx: bcx, data: Method(MethodData { llfn: llfn_val, llself: llself_val, temp_cleanup: temp_cleanups.head_opt().map(|v| *v), self_mode: mentry.self_mode, }) } } typeck::vtable_param(..) => { fail!("vtable_param left in monomorphized function's vtable substs"); } }; } pub fn
(bcx: @mut Block, mth_did: ast::DefId, callee_id: ast::NodeId, rcvr_substs: &[ty::t], rcvr_origins: typeck::vtable_res) -> (~[ty::t], typeck::vtable_res) { /*! * * Creates a concatenated set of substitutions which includes * those from the impl and those from the method. This are * some subtle complications here. Statically, we have a list * of type parameters like `[T0, T1, T2, M1, M2, M3]` where * `Tn` are type parameters that appear on the receiver. For * example, if the receiver is a method parameter `A` with a * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`. * * The weird part is that the type `A` might now be bound to * any other type, such as `foo<X>`. In that case, the vector * we want is: `[X, M1, M2, M3]`. Therefore, what we do now is * to slice off the method type parameters and append them to * the type parameters from the type that the receiver is * mapped to. */ let ccx = bcx.ccx(); let method = ty::method(ccx.tcx, mth_did); let n_m_tps = method.generics.type_param_defs.len(); let node_substs = node_id_type_params(bcx, callee_id); debug!("rcvr_substs={:?}", rcvr_substs.repr(ccx.tcx)); let ty_substs = vec::append(rcvr_substs.to_owned(), node_substs.tailn(node_substs.len() - n_m_tps)); debug!("n_m_tps={:?}", n_m_tps); debug!("node_substs={:?}", node_substs.repr(ccx.tcx)); debug!("ty_substs={:?}", ty_substs.repr(ccx.tcx)); // Now, do the same work for the vtables. The vtables might not // exist, in which case we need to make them. let r_m_origins = match node_vtables(bcx, callee_id) { Some(vt) => vt, None => @vec::from_elem(node_substs.len(), @~[]) }; let vtables = @vec::append(rcvr_origins.to_owned(), r_m_origins.tailn(r_m_origins.len() - n_m_tps)); return (ty_substs, vtables); } pub fn trans_trait_callee(bcx: @mut Block, callee_id: ast::NodeId, n_method: uint, self_expr: &ast::Expr) -> Callee { /*! * Create a method callee where the method is coming from a trait * object (e.g., @Trait type). In this case, we must pull the fn * pointer out of the vtable that is packaged up with the object. * Objects are represented as a pair, so we first evaluate the self * expression and then extract the self data and vtable out of the * pair. */ let _icx = push_ctxt("impl::trans_trait_callee"); let mut bcx = bcx; // make a local copy for trait if needed let self_ty = expr_ty_adjusted(bcx, self_expr); let self_scratch = match ty::get(self_ty).sty { ty::ty_trait(_, _, ty::RegionTraitStore(..), _, _) => { unpack_datum!(bcx, expr::trans_to_datum(bcx, self_expr)) } _ => { let d = scratch_datum(bcx, self_ty, "__trait_callee", false); bcx = expr::trans_into(bcx, self_expr, expr::SaveIn(d.val)); // Arrange a temporary cleanup for the object in case something // should go wrong before the method is actually *invoked*. d.add_clean(bcx); d } }; let callee_ty = node_id_type(bcx, callee_id); trans_trait_callee_from_llval(bcx, callee_ty, n_method, self_scratch.val, Some(self_scratch.val)) } pub fn trans_trait_callee_from_llval(bcx: @mut Block, callee_ty: ty::t, n_method: uint, llpair: ValueRef, temp_cleanup: Option<ValueRef>) -> Callee { /*! * Same as `trans_trait_callee()` above, except that it is given * a by-ref pointer to the object pair. */ let _icx = push_ctxt("impl::trans_trait_callee"); let ccx = bcx.ccx(); // Load the data pointer from the object. debug!("(translating trait callee) loading second index from pair"); let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]); let llbox = Load(bcx, llboxptr); let llself = PointerCast(bcx, llbox, Type::opaque_box(ccx).ptr_to()); // Load the function from the vtable and cast it to the expected type. debug!("(translating trait callee) loading method"); let llcallee_ty = type_of_fn_from_ty(ccx, callee_ty); let llvtable = Load(bcx, PointerCast(bcx, GEPi(bcx, llpair, [0u, abi::trt_field_vtable]), Type::vtable().ptr_to().ptr_to())); let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + 1])); let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to()); return Callee { bcx: bcx, data: Method(MethodData { llfn: mptr, llself: llself,
combine_impl_and_methods_tps
identifier_name
meth.rs
use lib; use metadata::csearch; use middle::trans::base::*; use middle::trans::build::*; use middle::trans::callee::*; use middle::trans::callee; use middle::trans::common::*; use middle::trans::datum::*; use middle::trans::expr::{SaveIn, Ignore}; use middle::trans::expr; use middle::trans::glue; use middle::trans::monomorphize; use middle::trans::type_of::*; use middle::ty; use middle::typeck; use util::common::indenter; use util::ppaux::Repr; use middle::trans::type_::Type; use std::c_str::ToCStr; use std::vec; use syntax::ast_map::{path, path_mod, path_name, path_pretty_name}; use syntax::ast_util; use syntax::{ast, ast_map}; use syntax::parse::token; use syntax::visit; /** The main "translation" pass for methods. Generates code for non-monomorphized methods only. Other methods will be generated once they are invoked with specific type parameters, see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`. */ pub fn trans_impl(ccx: @mut CrateContext, path: path, name: ast::Ident, methods: &[@ast::method], generics: &ast::Generics, id: ast::NodeId) { let _icx = push_ctxt("impl::trans_impl"); let tcx = ccx.tcx; debug!("trans_impl(path={}, name={}, id={:?})", path.repr(tcx), name.repr(tcx), id); // Both here and below with generic methods, be sure to recurse and look for // items that we need to translate. if!generics.ty_params.is_empty() { let mut v = TransItemVisitor{ ccx: ccx }; for method in methods.iter() { visit::walk_method_helper(&mut v, *method, ()); } return; } let sub_path = vec::append_one(path, path_name(name)); for method in methods.iter() { if method.generics.ty_params.len() == 0u { let llfn = get_item_val(ccx, method.id); let path = vec::append_one(sub_path.clone(), path_name(method.ident)); trans_method(ccx, path, *method, None, llfn); } else { let mut v = TransItemVisitor{ ccx: ccx }; visit::walk_method_helper(&mut v, *method, ()); } } } /// Translates a (possibly monomorphized) method body. /// /// Parameters: /// * `path`: the path to the method /// * `method`: the AST node for the method /// * `param_substs`: if this is a generic method, the current values for /// type parameters and so forth, else none /// * `llfn`: the LLVM ValueRef for the method /// * `impl_id`: the node ID of the impl this method is inside /// /// XXX(pcwalton) Can we take `path` by reference? pub fn trans_method(ccx: @mut CrateContext, path: path, method: &ast::method, param_substs: Option<@param_substs>, llfn: ValueRef) { // figure out how self is being passed let self_arg = match method.explicit_self.node { ast::sty_static => { no_self } _ => { // determine the (monomorphized) type that `self` maps to for // this method let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id); let self_ty = match param_substs { None => self_ty, Some(@param_substs {tys: ref tys, self_ty: ref self_sub,..}) => { ty::subst_tps(ccx.tcx, *tys, *self_sub, self_ty) } }; debug!("calling trans_fn with self_ty {}", self_ty.repr(ccx.tcx)); match method.explicit_self.node { ast::sty_value(_) => impl_self(self_ty, ty::ByRef), _ => impl_self(self_ty, ty::ByCopy), } } }; // generate the actual code trans_fn(ccx, path, method.decl, method.body, llfn, self_arg, param_substs, method.id, []); } pub fn trans_self_arg(bcx: @mut Block, base: &ast::Expr, temp_cleanups: &mut ~[ValueRef], mentry: typeck::method_map_entry) -> Result { let _icx = push_ctxt("impl::trans_self_arg"); // self is passed as an opaque box in the environment slot let self_ty = ty::mk_opaque_box(bcx.tcx()); trans_arg_expr(bcx, self_ty, mentry.self_mode, base, temp_cleanups, DontAutorefArg) } pub fn trans_method_callee(bcx: @mut Block, callee_id: ast::NodeId, this: &ast::Expr, mentry: typeck::method_map_entry) -> Callee { let _icx = push_ctxt("impl::trans_method_callee"); debug!("trans_method_callee(callee_id={:?}, this={}, mentry={})", callee_id, bcx.expr_to_str(this), mentry.repr(bcx.tcx())); match mentry.origin { typeck::method_static(did) => { let callee_fn = callee::trans_fn_ref(bcx, did, callee_id); let mut temp_cleanups = ~[]; let Result {bcx, val} = trans_self_arg(bcx, this, &mut temp_cleanups, mentry); Callee { bcx: bcx, data: Method(MethodData { llfn: callee_fn.llfn, llself: val, temp_cleanup: temp_cleanups.head_opt().map(|v| *v), self_mode: mentry.self_mode, }) } } typeck::method_param(typeck::method_param { trait_id: trait_id, method_num: off, param_num: p, bound_num: b }) => { match bcx.fcx.param_substs { Some(substs) => { ty::populate_implementations_for_trait_if_necessary( bcx.tcx(), trait_id); let vtbl = find_vtable(bcx.tcx(), substs, p, b); trans_monomorphized_callee(bcx, callee_id, this, mentry, trait_id, off, vtbl) } // how to get rid of this? None => fail!("trans_method_callee: missing param_substs") } } typeck::method_object(ref mt) => { trans_trait_callee(bcx, callee_id, mt.real_index, this) } } } pub fn trans_static_method_callee(bcx: @mut Block, method_id: ast::DefId, trait_id: ast::DefId, callee_id: ast::NodeId) -> FnData { let _icx = push_ctxt("impl::trans_static_method_callee"); let ccx = bcx.ccx(); debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \ callee_id={:?})", method_id, ty::item_path_str(bcx.tcx(), trait_id), callee_id); let _indenter = indenter(); ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trait_id); // When we translate a static fn defined in a trait like: // // trait<T1...Tn> Trait { // fn foo<M1...Mn>(...) {...} // } // // this winds up being translated as something like: // // fn foo<T1...Tn,self: Trait<T1...Tn>,M1...Mn>(...) {...} // // So when we see a call to this function foo, we have to figure // out which impl the `Trait<T1...Tn>` bound on the type `self` was // bound to. let bound_index = ty::lookup_trait_def(bcx.tcx(), trait_id). generics.type_param_defs.len(); let mname = if method_id.crate == ast::LOCAL_CRATE { match bcx.tcx().items.get_copy(&method_id.node) { ast_map::node_trait_method(trait_method, _, _) => { ast_util::trait_method_to_ty_method(trait_method).ident } _ => fail!("callee is not a trait method") } } else { let path = csearch::get_item_path(bcx.tcx(), method_id); match path[path.len()-1] { path_pretty_name(s, _) | path_name(s) => { s } path_mod(_) => { fail!("path doesn't have a name?") } } }; debug!("trans_static_method_callee: method_id={:?}, callee_id={:?}, \ name={}", method_id, callee_id, ccx.sess.str_of(mname)); let vtbls = resolve_vtables_in_fn_ctxt( bcx.fcx, ccx.maps.vtable_map.get_copy(&callee_id)); match vtbls[bound_index][0] { typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => { assert!(rcvr_substs.iter().all(|t|!ty::type_needs_infer(*t))); let mth_id = method_with_name(bcx.ccx(), impl_did, mname.name); let (callee_substs, callee_origins) = combine_impl_and_methods_tps( bcx, mth_id, callee_id, *rcvr_substs, rcvr_origins); let FnData {llfn: lval} = trans_fn_ref_with_vtables(bcx, mth_id, callee_id, callee_substs, Some(callee_origins)); let callee_ty = node_id_type(bcx, callee_id); let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to(); FnData {llfn: PointerCast(bcx, lval, llty)} } _ => { fail!("vtable_param left in monomorphized \ function's vtable substs"); } } } pub fn method_with_name(ccx: &mut CrateContext, impl_id: ast::DefId, name: ast::Name) -> ast::DefId { let meth_id_opt = ccx.impl_method_cache.find_copy(&(impl_id, name)); match meth_id_opt { Some(m) => return m, None => {} } let imp = ccx.tcx.impls.find(&impl_id) .expect("could not find impl while translating"); let meth = imp.methods.iter().find(|m| m.ident.name == name) .expect("could not find method while translating"); ccx.impl_method_cache.insert((impl_id, name), meth.def_id); meth.def_id } pub fn trans_monomorphized_callee(bcx: @mut Block, callee_id: ast::NodeId, base: &ast::Expr, mentry: typeck::method_map_entry, trait_id: ast::DefId, n_method: uint, vtbl: typeck::vtable_origin) -> Callee { let _icx = push_ctxt("impl::trans_monomorphized_callee"); return match vtbl { typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => { let ccx = bcx.ccx(); let mname = ty::trait_method(ccx.tcx, trait_id, n_method).ident; let mth_id = method_with_name(bcx.ccx(), impl_did, mname.name); // obtain the `self` value: let mut temp_cleanups = ~[]; let Result {bcx, val: llself_val} = trans_self_arg(bcx, base, &mut temp_cleanups, mentry); // create a concatenated set of substitutions which includes // those from the impl and those from the method: let (callee_substs, callee_origins) = combine_impl_and_methods_tps( bcx, mth_id, callee_id, *rcvr_substs, rcvr_origins); // translate the function let callee = trans_fn_ref_with_vtables(bcx, mth_id, callee_id, callee_substs, Some(callee_origins)); // create a llvalue that represents the fn ptr let fn_ty = node_id_type(bcx, callee_id); let llfn_ty = type_of_fn_from_ty(ccx, fn_ty).ptr_to(); let llfn_val = PointerCast(bcx, callee.llfn, llfn_ty); // combine the self environment with the rest Callee { bcx: bcx, data: Method(MethodData { llfn: llfn_val, llself: llself_val, temp_cleanup: temp_cleanups.head_opt().map(|v| *v), self_mode: mentry.self_mode, }) } } typeck::vtable_param(..) => { fail!("vtable_param left in monomorphized function's vtable substs"); } }; } pub fn combine_impl_and_methods_tps(bcx: @mut Block, mth_did: ast::DefId, callee_id: ast::NodeId, rcvr_substs: &[ty::t], rcvr_origins: typeck::vtable_res) -> (~[ty::t], typeck::vtable_res) { /*! * * Creates a concatenated set of substitutions which includes * those from the impl and those from the method. This are * some subtle complications here. Statically, we have a list * of type parameters like `[T0, T1, T2, M1, M2, M3]` where * `Tn` are type parameters that appear on the receiver. For * example, if the receiver is a method parameter `A` with a * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`. * * The weird part is that the type `A` might now be bound to * any other type, such as `foo<X>`. In that case, the vector * we want is: `[X, M1, M2, M3]`. Therefore, what we do now is * to slice off the method type parameters and append them to * the type parameters from the type that the receiver is * mapped to. */ let ccx = bcx.ccx(); let method = ty::method(ccx.tcx, mth_did); let n_m_tps = method.generics.type_param_defs.len(); let node_substs = node_id_type_params(bcx, callee_id); debug!("rcvr_substs={:?}", rcvr_substs.repr(ccx.tcx)); let ty_substs = vec::append(rcvr_substs.to_owned(), node_substs.tailn(node_substs.len() - n_m_tps)); debug!("n_m_tps={:?}", n_m_tps); debug!("node_substs={:?}", node_substs.repr(ccx.tcx)); debug!("ty_substs={:?}", ty_substs.repr(ccx.tcx)); // Now, do the same work for the vtables. The vtables might not // exist, in which case we need to make them. let r_m_origins = match node_vtables(bcx, callee_id) { Some(vt) => vt, None => @vec::from_elem(node_substs.len(), @~[]) }; let vtables = @vec::append(rcvr_origins.to_owned(), r_m_origins.tailn(r_m_origins.len() - n_m_tps)); return (ty_substs, vtables); } pub fn trans_trait_callee(bcx: @mut Block, callee_id: ast::NodeId, n_method: uint, self_expr: &ast::Expr) -> Callee { /*! * Create a method callee where the method is coming from a trait * object (e.g., @Trait type). In this case, we must pull the fn * pointer out of the vtable that is packaged up with the object. * Objects are represented as a pair, so we first evaluate the self * expression and then extract the self data and vtable out of the * pair. */ let _icx = push_ctxt("impl::trans_trait_callee"); let mut bcx = bcx; // make a local copy for trait if needed let self_ty = expr_ty_adjusted(bcx, self_expr); let self_scratch = match ty::get(self_ty).sty { ty::ty_trait(_, _, ty::RegionTraitStore(..), _, _) => { unpack_datum!(bcx, expr::trans_to_
use back::abi; use lib::llvm::llvm; use lib::llvm::ValueRef;
random_line_split
meth.rs
method: &ast::method, param_substs: Option<@param_substs>, llfn: ValueRef) { // figure out how self is being passed let self_arg = match method.explicit_self.node { ast::sty_static => { no_self } _ => { // determine the (monomorphized) type that `self` maps to for // this method let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id); let self_ty = match param_substs { None => self_ty, Some(@param_substs {tys: ref tys, self_ty: ref self_sub,..}) => { ty::subst_tps(ccx.tcx, *tys, *self_sub, self_ty) } }; debug!("calling trans_fn with self_ty {}", self_ty.repr(ccx.tcx)); match method.explicit_self.node { ast::sty_value(_) => impl_self(self_ty, ty::ByRef), _ => impl_self(self_ty, ty::ByCopy), } } }; // generate the actual code trans_fn(ccx, path, method.decl, method.body, llfn, self_arg, param_substs, method.id, []); } pub fn trans_self_arg(bcx: @mut Block, base: &ast::Expr, temp_cleanups: &mut ~[ValueRef], mentry: typeck::method_map_entry) -> Result { let _icx = push_ctxt("impl::trans_self_arg"); // self is passed as an opaque box in the environment slot let self_ty = ty::mk_opaque_box(bcx.tcx()); trans_arg_expr(bcx, self_ty, mentry.self_mode, base, temp_cleanups, DontAutorefArg) } pub fn trans_method_callee(bcx: @mut Block, callee_id: ast::NodeId, this: &ast::Expr, mentry: typeck::method_map_entry) -> Callee { let _icx = push_ctxt("impl::trans_method_callee"); debug!("trans_method_callee(callee_id={:?}, this={}, mentry={})", callee_id, bcx.expr_to_str(this), mentry.repr(bcx.tcx())); match mentry.origin { typeck::method_static(did) => { let callee_fn = callee::trans_fn_ref(bcx, did, callee_id); let mut temp_cleanups = ~[]; let Result {bcx, val} = trans_self_arg(bcx, this, &mut temp_cleanups, mentry); Callee { bcx: bcx, data: Method(MethodData { llfn: callee_fn.llfn, llself: val, temp_cleanup: temp_cleanups.head_opt().map(|v| *v), self_mode: mentry.self_mode, }) } } typeck::method_param(typeck::method_param { trait_id: trait_id, method_num: off, param_num: p, bound_num: b }) => { match bcx.fcx.param_substs { Some(substs) => { ty::populate_implementations_for_trait_if_necessary( bcx.tcx(), trait_id); let vtbl = find_vtable(bcx.tcx(), substs, p, b); trans_monomorphized_callee(bcx, callee_id, this, mentry, trait_id, off, vtbl) } // how to get rid of this? None => fail!("trans_method_callee: missing param_substs") } } typeck::method_object(ref mt) => { trans_trait_callee(bcx, callee_id, mt.real_index, this) } } } pub fn trans_static_method_callee(bcx: @mut Block, method_id: ast::DefId, trait_id: ast::DefId, callee_id: ast::NodeId) -> FnData
// // fn foo<T1...Tn,self: Trait<T1...Tn>,M1...Mn>(...) {...} // // So when we see a call to this function foo, we have to figure // out which impl the `Trait<T1...Tn>` bound on the type `self` was // bound to. let bound_index = ty::lookup_trait_def(bcx.tcx(), trait_id). generics.type_param_defs.len(); let mname = if method_id.crate == ast::LOCAL_CRATE { match bcx.tcx().items.get_copy(&method_id.node) { ast_map::node_trait_method(trait_method, _, _) => { ast_util::trait_method_to_ty_method(trait_method).ident } _ => fail!("callee is not a trait method") } } else { let path = csearch::get_item_path(bcx.tcx(), method_id); match path[path.len()-1] { path_pretty_name(s, _) | path_name(s) => { s } path_mod(_) => { fail!("path doesn't have a name?") } } }; debug!("trans_static_method_callee: method_id={:?}, callee_id={:?}, \ name={}", method_id, callee_id, ccx.sess.str_of(mname)); let vtbls = resolve_vtables_in_fn_ctxt( bcx.fcx, ccx.maps.vtable_map.get_copy(&callee_id)); match vtbls[bound_index][0] { typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => { assert!(rcvr_substs.iter().all(|t|!ty::type_needs_infer(*t))); let mth_id = method_with_name(bcx.ccx(), impl_did, mname.name); let (callee_substs, callee_origins) = combine_impl_and_methods_tps( bcx, mth_id, callee_id, *rcvr_substs, rcvr_origins); let FnData {llfn: lval} = trans_fn_ref_with_vtables(bcx, mth_id, callee_id, callee_substs, Some(callee_origins)); let callee_ty = node_id_type(bcx, callee_id); let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to(); FnData {llfn: PointerCast(bcx, lval, llty)} } _ => { fail!("vtable_param left in monomorphized \ function's vtable substs"); } } } pub fn method_with_name(ccx: &mut CrateContext, impl_id: ast::DefId, name: ast::Name) -> ast::DefId { let meth_id_opt = ccx.impl_method_cache.find_copy(&(impl_id, name)); match meth_id_opt { Some(m) => return m, None => {} } let imp = ccx.tcx.impls.find(&impl_id) .expect("could not find impl while translating"); let meth = imp.methods.iter().find(|m| m.ident.name == name) .expect("could not find method while translating"); ccx.impl_method_cache.insert((impl_id, name), meth.def_id); meth.def_id } pub fn trans_monomorphized_callee(bcx: @mut Block, callee_id: ast::NodeId, base: &ast::Expr, mentry: typeck::method_map_entry, trait_id: ast::DefId, n_method: uint, vtbl: typeck::vtable_origin) -> Callee { let _icx = push_ctxt("impl::trans_monomorphized_callee"); return match vtbl { typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => { let ccx = bcx.ccx(); let mname = ty::trait_method(ccx.tcx, trait_id, n_method).ident; let mth_id = method_with_name(bcx.ccx(), impl_did, mname.name); // obtain the `self` value: let mut temp_cleanups = ~[]; let Result {bcx, val: llself_val} = trans_self_arg(bcx, base, &mut temp_cleanups, mentry); // create a concatenated set of substitutions which includes // those from the impl and those from the method: let (callee_substs, callee_origins) = combine_impl_and_methods_tps( bcx, mth_id, callee_id, *rcvr_substs, rcvr_origins); // translate the function let callee = trans_fn_ref_with_vtables(bcx, mth_id, callee_id, callee_substs, Some(callee_origins)); // create a llvalue that represents the fn ptr let fn_ty = node_id_type(bcx, callee_id); let llfn_ty = type_of_fn_from_ty(ccx, fn_ty).ptr_to(); let llfn_val = PointerCast(bcx, callee.llfn, llfn_ty); // combine the self environment with the rest Callee { bcx: bcx, data: Method(MethodData { llfn: llfn_val, llself: llself_val, temp_cleanup: temp_cleanups.head_opt().map(|v| *v), self_mode: mentry.self_mode, }) } } typeck::vtable_param(..) => { fail!("vtable_param left in monomorphized function's vtable substs"); } }; } pub fn combine_impl_and_methods_tps(bcx: @mut Block, mth_did: ast::DefId, callee_id: ast::NodeId, rcvr_substs: &[ty::t], rcvr_origins: typeck::vtable_res) -> (~[ty::t], typeck::vtable_res) { /*! * * Creates a concatenated set of substitutions which includes * those from the impl and those from the method. This are * some subtle complications here. Statically, we have a list * of type parameters like `[T0, T1, T2, M1, M2, M3]` where * `Tn` are type parameters that appear on the receiver. For * example, if the receiver is a method parameter `A` with a * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`. * * The weird part is that the type `A` might now be bound to * any other type, such as `foo<X>`. In that case, the vector * we want is: `[X, M1, M2, M3]`. Therefore, what we do now is * to slice off the method type parameters and append them to * the type parameters from the type that the receiver is * mapped to. */ let ccx = bcx.ccx(); let method = ty::method(ccx.tcx, mth_did); let n_m_tps = method.generics.type_param_defs.len(); let node_substs = node_id_type_params(bcx, callee_id); debug!("rcvr_substs={:?}", rcvr_substs.repr(ccx.tcx)); let ty_substs = vec::append(rcvr_substs.to_owned(), node_substs.tailn(node_substs.len() - n_m_tps)); debug!("n_m_tps={:?}", n_m_tps); debug!("node_substs={:?}", node_substs.repr(ccx.tcx)); debug!("ty_substs={:?}", ty_substs.repr(ccx.tcx)); // Now, do the same work for the vtables. The vtables might not // exist, in which case we need to make them. let r_m_origins = match node_vtables(bcx, callee_id) { Some(vt) => vt, None => @vec::from_elem(node_substs.len(), @~[]) }; let vtables = @vec::append(rcvr_origins.to_owned(), r_m_origins.tailn(r_m_origins.len() - n_m_tps)); return (ty_substs, vtables); } pub fn trans_trait_callee(bcx: @mut Block, callee_id: ast::NodeId, n_method: uint, self_expr: &ast::Expr) -> Callee { /*! * Create a method callee where the method is coming from a trait * object (e.g., @Trait type). In this case, we must pull the fn * pointer out of the vtable that is packaged up with the object. * Objects are represented as a pair, so we first evaluate the self * expression and then extract the self data and vtable out of the * pair. */ let _icx = push_ctxt("impl::trans_trait_callee"); let mut bcx = bcx; // make a local copy for trait if needed let self_ty = expr_ty_adjusted(bcx, self_expr); let self_scratch = match ty::get(self_ty).sty { ty::ty_trait(_, _, ty::RegionTraitStore(..), _, _) => { unpack_datum!(bcx, expr::trans_to_datum(bcx, self_expr)) } _ => { let d = scratch_datum(bcx, self_ty, "__trait_callee", false); bcx = expr::trans_into(bcx, self_expr, expr::SaveIn(d.val)); // Arrange a temporary cleanup for the object in case something // should go wrong before the method is actually *invoked*. d.add_clean(bcx); d } }; let callee_ty = node_id_type(bcx, callee_id); trans_trait_callee_from_llval(bcx, callee_ty, n_method, self_scratch.val, Some(self_scratch.val)) } pub fn trans_trait_callee_from_llval(bcx: @mut Block, callee_ty: ty::t, n_method: uint, llpair: ValueRef, temp_cleanup: Option<ValueRef>) -> Callee { /*! * Same as `trans_trait_callee()` above, except that it is given * a by-ref pointer to the object pair. */ let _icx = push_ctxt("impl::trans_trait_callee"); let ccx = bcx.ccx(); // Load the data pointer from the object. debug!("(translating trait callee) loading second index from pair"); let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]); let llbox = Load(bcx, llboxptr); let llself = PointerCast(bcx, llbox, Type::opaque_box(ccx).ptr_to()); // Load the function from the vtable and cast it to the expected type. debug!("(translating trait callee) loading method"); let llcallee_ty = type_of_fn_from_ty(ccx, callee_ty); let llvtable = Load(bcx, PointerCast(bcx, GEPi(bcx, llpair, [0u, abi::trt_field_vtable]), Type::vtable().ptr_to().ptr_to())); let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + 1])); let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to()); return Callee { bcx: bcx, data: Method(MethodData { llfn: mptr, llself: llself,
{ let _icx = push_ctxt("impl::trans_static_method_callee"); let ccx = bcx.ccx(); debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \ callee_id={:?})", method_id, ty::item_path_str(bcx.tcx(), trait_id), callee_id); let _indenter = indenter(); ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trait_id); // When we translate a static fn defined in a trait like: // // trait<T1...Tn> Trait { // fn foo<M1...Mn>(...) {...} // } // // this winds up being translated as something like:
identifier_body
rotate_turn.rs
use rune_vm::Rune; use game_state::GameState; use minion_card::UID; use ::tags_list::*; use runes::remove_tag::RemoveTag; use runes::set_base_mana::SetBaseMana; use runes::set_mana::SetMana; use runes::deal_card::DealCard; use controller::EControllerState; use hlua; #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct RotateTurn {} impl RotateTurn { pub fn new() -> RotateTurn { RotateTurn {} } } implement_for_lua!(RotateTurn, |mut _metatable| {}); impl Rune for RotateTurn { fn execute_rune(&self, mut game_state: &mut GameState) { let mut turn_index = game_state.get_on_turn_player().clone(); let in_play = game_state.get_controller_by_index(turn_index as usize).get_copy_of_in_play(); let mut remove_tag_runes = vec![]; for uids in in_play { let minion = game_state.get_minion(uids).unwrap(); if minion.has_tag(SUMMONING_SICKNESS.to_string()) { remove_tag_runes.push(RemoveTag::new(uids.clone(), SUMMONING_SICKNESS.to_string().clone())); } } for rune in remove_tag_runes { game_state.execute_rune(Box::new(rune)); } game_state.get_mut_controller_by_index(turn_index as usize) .set_controller_state(EControllerState::WaitingForTurn); turn_index += 1; if turn_index == 2
game_state.set_on_turn_player(turn_index); let new_mana = game_state.get_controller_by_index(turn_index as usize).get_base_mana().clone() + 1; let sbm = SetBaseMana::new(game_state.get_controller_by_index(turn_index as usize) .get_uid() .clone(), new_mana); let sm = SetMana::new(game_state.get_controller_by_index(turn_index as usize).get_uid(), new_mana); game_state.execute_rune(Box::new(sbm)); game_state.execute_rune(Box::new(sm)); let uids = game_state.get_controller_by_index(turn_index as usize) .get_n_card_uids_from_deck(1) .clone(); let dc = DealCard::new(uids[0].clone(), game_state.get_controller_by_index(turn_index as usize) .get_uid() .clone()); game_state.execute_rune(Box::new(dc)); } fn can_see(&self, _controller: UID, _game_state: &GameState) -> bool { return true; } fn to_json(&self) -> String { "{\"runeType\":\"RotateTurn\"}".to_string() } fn into_box(&self) -> Box<Rune> { Box::new(self.clone()) } }
{ turn_index = 0; }
conditional_block
rotate_turn.rs
use rune_vm::Rune; use game_state::GameState; use minion_card::UID; use ::tags_list::*; use runes::remove_tag::RemoveTag; use runes::set_base_mana::SetBaseMana; use runes::set_mana::SetMana; use runes::deal_card::DealCard; use controller::EControllerState; use hlua; #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct RotateTurn {}
} } implement_for_lua!(RotateTurn, |mut _metatable| {}); impl Rune for RotateTurn { fn execute_rune(&self, mut game_state: &mut GameState) { let mut turn_index = game_state.get_on_turn_player().clone(); let in_play = game_state.get_controller_by_index(turn_index as usize).get_copy_of_in_play(); let mut remove_tag_runes = vec![]; for uids in in_play { let minion = game_state.get_minion(uids).unwrap(); if minion.has_tag(SUMMONING_SICKNESS.to_string()) { remove_tag_runes.push(RemoveTag::new(uids.clone(), SUMMONING_SICKNESS.to_string().clone())); } } for rune in remove_tag_runes { game_state.execute_rune(Box::new(rune)); } game_state.get_mut_controller_by_index(turn_index as usize) .set_controller_state(EControllerState::WaitingForTurn); turn_index += 1; if turn_index == 2 { turn_index = 0; } game_state.set_on_turn_player(turn_index); let new_mana = game_state.get_controller_by_index(turn_index as usize).get_base_mana().clone() + 1; let sbm = SetBaseMana::new(game_state.get_controller_by_index(turn_index as usize) .get_uid() .clone(), new_mana); let sm = SetMana::new(game_state.get_controller_by_index(turn_index as usize).get_uid(), new_mana); game_state.execute_rune(Box::new(sbm)); game_state.execute_rune(Box::new(sm)); let uids = game_state.get_controller_by_index(turn_index as usize) .get_n_card_uids_from_deck(1) .clone(); let dc = DealCard::new(uids[0].clone(), game_state.get_controller_by_index(turn_index as usize) .get_uid() .clone()); game_state.execute_rune(Box::new(dc)); } fn can_see(&self, _controller: UID, _game_state: &GameState) -> bool { return true; } fn to_json(&self) -> String { "{\"runeType\":\"RotateTurn\"}".to_string() } fn into_box(&self) -> Box<Rune> { Box::new(self.clone()) } }
impl RotateTurn { pub fn new() -> RotateTurn { RotateTurn {}
random_line_split
rotate_turn.rs
use rune_vm::Rune; use game_state::GameState; use minion_card::UID; use ::tags_list::*; use runes::remove_tag::RemoveTag; use runes::set_base_mana::SetBaseMana; use runes::set_mana::SetMana; use runes::deal_card::DealCard; use controller::EControllerState; use hlua; #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct RotateTurn {} impl RotateTurn { pub fn new() -> RotateTurn { RotateTurn {} } } implement_for_lua!(RotateTurn, |mut _metatable| {}); impl Rune for RotateTurn { fn execute_rune(&self, mut game_state: &mut GameState) { let mut turn_index = game_state.get_on_turn_player().clone(); let in_play = game_state.get_controller_by_index(turn_index as usize).get_copy_of_in_play(); let mut remove_tag_runes = vec![]; for uids in in_play { let minion = game_state.get_minion(uids).unwrap(); if minion.has_tag(SUMMONING_SICKNESS.to_string()) { remove_tag_runes.push(RemoveTag::new(uids.clone(), SUMMONING_SICKNESS.to_string().clone())); } } for rune in remove_tag_runes { game_state.execute_rune(Box::new(rune)); } game_state.get_mut_controller_by_index(turn_index as usize) .set_controller_state(EControllerState::WaitingForTurn); turn_index += 1; if turn_index == 2 { turn_index = 0; } game_state.set_on_turn_player(turn_index); let new_mana = game_state.get_controller_by_index(turn_index as usize).get_base_mana().clone() + 1; let sbm = SetBaseMana::new(game_state.get_controller_by_index(turn_index as usize) .get_uid() .clone(), new_mana); let sm = SetMana::new(game_state.get_controller_by_index(turn_index as usize).get_uid(), new_mana); game_state.execute_rune(Box::new(sbm)); game_state.execute_rune(Box::new(sm)); let uids = game_state.get_controller_by_index(turn_index as usize) .get_n_card_uids_from_deck(1) .clone(); let dc = DealCard::new(uids[0].clone(), game_state.get_controller_by_index(turn_index as usize) .get_uid() .clone()); game_state.execute_rune(Box::new(dc)); } fn
(&self, _controller: UID, _game_state: &GameState) -> bool { return true; } fn to_json(&self) -> String { "{\"runeType\":\"RotateTurn\"}".to_string() } fn into_box(&self) -> Box<Rune> { Box::new(self.clone()) } }
can_see
identifier_name
main.rs
extern crate log; extern crate env_logger; extern crate clap; extern crate ctrlc; extern crate gauc; extern crate iron; extern crate urlencoded; use clap::{App, Arg}; use gauc::cli; use gauc::web; use gauc::client::Client; use std::env; use std::process::exit; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, Ordering}; const DESCRIPTION: &'static str = "Couchbase Rust Adapter / CLI / REST Interface"; const VERSION: &'static str = env!("CARGO_PKG_VERSION"); //const DEFAULT_HOST: &'static str = "localhost"; //const DEFAULT_BUCKET: &'static str = "default"; const DEFAULT_URI: &'static str = "couchbase://localhost/default"; /// Handler of Ctrl+C fn install_ctrl_c_handler() { let running = Arc::new(AtomicBool::new(true)); let r = Arc::clone(&running); let _ = ctrlc::set_handler(move || { println!(""); println!(""); println!("Received ctrl+c, exiting..."); r.store(false, Ordering::SeqCst); exit(0); }); } /// Web Server Entrypoint fn main() { install_ctrl_c_handler(); let couchbase_uri = match env::var("COUCHBASE_URI") { Ok(uri) => uri, Err(_) => DEFAULT_URI.to_string() }; // Specify program options let matches = App::new(DESCRIPTION) .version(VERSION) .author("Tomas Korcak <[email protected]>") .arg(Arg::with_name("interactive") .help("Interactive mode") .short("i") .long("interactive") ) .arg(Arg::with_name("rest") .help("Run REST Server") .short("r") .long("rest") ) .arg(Arg::with_name("rest-port") .help("REST Port") .short("p") .long("rest-port") .default_value("5000") ) .arg(Arg::with_name("url") .help("URI - connection string") .short("u") .long("uri") .default_value(&couchbase_uri[..]) ) .arg(Arg::with_name("verbose") .help("Verbose mode") .short("v") .long("verbose") .multiple(true) ) .get_matches(); match matches.occurrences_of("verbose") { 1 => env::set_var("RUST_LOG", "warn"), 2 => env::set_var("RUST_LOG", "info"), 3 => env::set_var("RUST_LOG", "debug"), _ => {} } env_logger::init().unwrap(); if matches.is_present("interactive") { if let Ok(mut client) = Client::connect(matches.value_of("url").unwrap()) { cli::main(&matches, &mut client); } } let port: u16 = matches.value_of("rest-port").unwrap().to_string().parse::<u16>().unwrap(); if matches.is_present("rest") {
} }
if let Ok(client) = Client::connect(matches.value_of("url").unwrap()) { web::start_web(&Arc::new(Mutex::new(client)), port); }
random_line_split
main.rs
extern crate log; extern crate env_logger; extern crate clap; extern crate ctrlc; extern crate gauc; extern crate iron; extern crate urlencoded; use clap::{App, Arg}; use gauc::cli; use gauc::web; use gauc::client::Client; use std::env; use std::process::exit; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, Ordering}; const DESCRIPTION: &'static str = "Couchbase Rust Adapter / CLI / REST Interface"; const VERSION: &'static str = env!("CARGO_PKG_VERSION"); //const DEFAULT_HOST: &'static str = "localhost"; //const DEFAULT_BUCKET: &'static str = "default"; const DEFAULT_URI: &'static str = "couchbase://localhost/default"; /// Handler of Ctrl+C fn install_ctrl_c_handler()
/// Web Server Entrypoint fn main() { install_ctrl_c_handler(); let couchbase_uri = match env::var("COUCHBASE_URI") { Ok(uri) => uri, Err(_) => DEFAULT_URI.to_string() }; // Specify program options let matches = App::new(DESCRIPTION) .version(VERSION) .author("Tomas Korcak <[email protected]>") .arg(Arg::with_name("interactive") .help("Interactive mode") .short("i") .long("interactive") ) .arg(Arg::with_name("rest") .help("Run REST Server") .short("r") .long("rest") ) .arg(Arg::with_name("rest-port") .help("REST Port") .short("p") .long("rest-port") .default_value("5000") ) .arg(Arg::with_name("url") .help("URI - connection string") .short("u") .long("uri") .default_value(&couchbase_uri[..]) ) .arg(Arg::with_name("verbose") .help("Verbose mode") .short("v") .long("verbose") .multiple(true) ) .get_matches(); match matches.occurrences_of("verbose") { 1 => env::set_var("RUST_LOG", "warn"), 2 => env::set_var("RUST_LOG", "info"), 3 => env::set_var("RUST_LOG", "debug"), _ => {} } env_logger::init().unwrap(); if matches.is_present("interactive") { if let Ok(mut client) = Client::connect(matches.value_of("url").unwrap()) { cli::main(&matches, &mut client); } } let port: u16 = matches.value_of("rest-port").unwrap().to_string().parse::<u16>().unwrap(); if matches.is_present("rest") { if let Ok(client) = Client::connect(matches.value_of("url").unwrap()) { web::start_web(&Arc::new(Mutex::new(client)), port); } } }
{ let running = Arc::new(AtomicBool::new(true)); let r = Arc::clone(&running); let _ = ctrlc::set_handler(move || { println!(""); println!(""); println!("Received ctrl+c, exiting ..."); r.store(false, Ordering::SeqCst); exit(0); }); }
identifier_body
main.rs
extern crate log; extern crate env_logger; extern crate clap; extern crate ctrlc; extern crate gauc; extern crate iron; extern crate urlencoded; use clap::{App, Arg}; use gauc::cli; use gauc::web; use gauc::client::Client; use std::env; use std::process::exit; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, Ordering}; const DESCRIPTION: &'static str = "Couchbase Rust Adapter / CLI / REST Interface"; const VERSION: &'static str = env!("CARGO_PKG_VERSION"); //const DEFAULT_HOST: &'static str = "localhost"; //const DEFAULT_BUCKET: &'static str = "default"; const DEFAULT_URI: &'static str = "couchbase://localhost/default"; /// Handler of Ctrl+C fn install_ctrl_c_handler() { let running = Arc::new(AtomicBool::new(true)); let r = Arc::clone(&running); let _ = ctrlc::set_handler(move || { println!(""); println!(""); println!("Received ctrl+c, exiting..."); r.store(false, Ordering::SeqCst); exit(0); }); } /// Web Server Entrypoint fn main() { install_ctrl_c_handler(); let couchbase_uri = match env::var("COUCHBASE_URI") { Ok(uri) => uri, Err(_) => DEFAULT_URI.to_string() }; // Specify program options let matches = App::new(DESCRIPTION) .version(VERSION) .author("Tomas Korcak <[email protected]>") .arg(Arg::with_name("interactive") .help("Interactive mode") .short("i") .long("interactive") ) .arg(Arg::with_name("rest") .help("Run REST Server") .short("r") .long("rest") ) .arg(Arg::with_name("rest-port") .help("REST Port") .short("p") .long("rest-port") .default_value("5000") ) .arg(Arg::with_name("url") .help("URI - connection string") .short("u") .long("uri") .default_value(&couchbase_uri[..]) ) .arg(Arg::with_name("verbose") .help("Verbose mode") .short("v") .long("verbose") .multiple(true) ) .get_matches(); match matches.occurrences_of("verbose") { 1 => env::set_var("RUST_LOG", "warn"), 2 => env::set_var("RUST_LOG", "info"), 3 => env::set_var("RUST_LOG", "debug"), _ => {} } env_logger::init().unwrap(); if matches.is_present("interactive")
let port: u16 = matches.value_of("rest-port").unwrap().to_string().parse::<u16>().unwrap(); if matches.is_present("rest") { if let Ok(client) = Client::connect(matches.value_of("url").unwrap()) { web::start_web(&Arc::new(Mutex::new(client)), port); } } }
{ if let Ok(mut client) = Client::connect(matches.value_of("url").unwrap()) { cli::main(&matches, &mut client); } }
conditional_block
main.rs
extern crate log; extern crate env_logger; extern crate clap; extern crate ctrlc; extern crate gauc; extern crate iron; extern crate urlencoded; use clap::{App, Arg}; use gauc::cli; use gauc::web; use gauc::client::Client; use std::env; use std::process::exit; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, Ordering}; const DESCRIPTION: &'static str = "Couchbase Rust Adapter / CLI / REST Interface"; const VERSION: &'static str = env!("CARGO_PKG_VERSION"); //const DEFAULT_HOST: &'static str = "localhost"; //const DEFAULT_BUCKET: &'static str = "default"; const DEFAULT_URI: &'static str = "couchbase://localhost/default"; /// Handler of Ctrl+C fn install_ctrl_c_handler() { let running = Arc::new(AtomicBool::new(true)); let r = Arc::clone(&running); let _ = ctrlc::set_handler(move || { println!(""); println!(""); println!("Received ctrl+c, exiting..."); r.store(false, Ordering::SeqCst); exit(0); }); } /// Web Server Entrypoint fn
() { install_ctrl_c_handler(); let couchbase_uri = match env::var("COUCHBASE_URI") { Ok(uri) => uri, Err(_) => DEFAULT_URI.to_string() }; // Specify program options let matches = App::new(DESCRIPTION) .version(VERSION) .author("Tomas Korcak <[email protected]>") .arg(Arg::with_name("interactive") .help("Interactive mode") .short("i") .long("interactive") ) .arg(Arg::with_name("rest") .help("Run REST Server") .short("r") .long("rest") ) .arg(Arg::with_name("rest-port") .help("REST Port") .short("p") .long("rest-port") .default_value("5000") ) .arg(Arg::with_name("url") .help("URI - connection string") .short("u") .long("uri") .default_value(&couchbase_uri[..]) ) .arg(Arg::with_name("verbose") .help("Verbose mode") .short("v") .long("verbose") .multiple(true) ) .get_matches(); match matches.occurrences_of("verbose") { 1 => env::set_var("RUST_LOG", "warn"), 2 => env::set_var("RUST_LOG", "info"), 3 => env::set_var("RUST_LOG", "debug"), _ => {} } env_logger::init().unwrap(); if matches.is_present("interactive") { if let Ok(mut client) = Client::connect(matches.value_of("url").unwrap()) { cli::main(&matches, &mut client); } } let port: u16 = matches.value_of("rest-port").unwrap().to_string().parse::<u16>().unwrap(); if matches.is_present("rest") { if let Ok(client) = Client::connect(matches.value_of("url").unwrap()) { web::start_web(&Arc::new(Mutex::new(client)), port); } } }
main
identifier_name
task.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::str::FromStr; use chrono::NaiveDate; use todo_txt::Task as RawTask; /// A Task with its metadata #[derive(Clone, Debug, PartialEq)] pub struct Task { pub subject: String, pub priority: u8, pub creation_date: Option<NaiveDate>, pub status: Status, pub threshold_date: Option<NaiveDate>, pub due_date: Option<NaiveDate>, pub contexts: Vec<String>, pub projects: Vec<String>, pub hashtags: Vec<String>, pub tags: BTreeMap<String, String>, } impl Task { /// Parse a Task from some string pub fn parse(txt: impl Borrow<str>) -> Task { // For this unwrap, see https://github.com/sanpii/todo-txt/issues/10 RawTask::from_str(txt.borrow()).unwrap().into() } /// Check if the task is done pub fn is_done(&self) -> bool { if let Status::Finished(_) = self.status { true } else { false } } } /// Possible status of a Task #[derive(Clone, Debug, PartialEq)] pub enum Status { /// The task is started Started, /// The task is finished, with an optional finish date Finished(Option<NaiveDate>), } impl ::std::convert::From<RawTask> for Task { fn from(t: RawTask) -> Task { // compute status let status = if t.finished { Status::Finished(t.finish_date) } else
; Task { subject: t.subject, priority: t.priority, creation_date: t.create_date, status, threshold_date: t.threshold_date, due_date: t.due_date, contexts: t.contexts, projects: t.projects, hashtags: t.hashtags, tags: t.tags, } } } impl ::std::convert::Into<RawTask> for Task { fn into(self) -> RawTask { let (finished, finish_date) = match self.status { Status::Started => (false, None), Status::Finished(date) => (true, date), }; RawTask { subject: self.subject, priority: self.priority, create_date: self.creation_date, finished, finish_date, threshold_date: self.threshold_date, due_date: self.due_date, contexts: self.contexts, projects: self.projects, hashtags: self.hashtags, tags: self.tags, } } }
{ Status::Started }
conditional_block
task.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::str::FromStr; use chrono::NaiveDate; use todo_txt::Task as RawTask; /// A Task with its metadata #[derive(Clone, Debug, PartialEq)] pub struct Task { pub subject: String, pub priority: u8, pub creation_date: Option<NaiveDate>, pub status: Status, pub threshold_date: Option<NaiveDate>, pub due_date: Option<NaiveDate>, pub contexts: Vec<String>, pub projects: Vec<String>, pub hashtags: Vec<String>, pub tags: BTreeMap<String, String>, } impl Task { /// Parse a Task from some string pub fn parse(txt: impl Borrow<str>) -> Task { // For this unwrap, see https://github.com/sanpii/todo-txt/issues/10 RawTask::from_str(txt.borrow()).unwrap().into() } /// Check if the task is done pub fn is_done(&self) -> bool { if let Status::Finished(_) = self.status { true } else { false } } } /// Possible status of a Task #[derive(Clone, Debug, PartialEq)] pub enum Status { /// The task is started Started, /// The task is finished, with an optional finish date Finished(Option<NaiveDate>), } impl ::std::convert::From<RawTask> for Task { fn from(t: RawTask) -> Task { // compute status let status = if t.finished { Status::Finished(t.finish_date) } else { Status::Started }; Task { subject: t.subject, priority: t.priority, creation_date: t.create_date, status, threshold_date: t.threshold_date, due_date: t.due_date, contexts: t.contexts, projects: t.projects, hashtags: t.hashtags, tags: t.tags, } } } impl ::std::convert::Into<RawTask> for Task { fn into(self) -> RawTask { let (finished, finish_date) = match self.status { Status::Started => (false, None), Status::Finished(date) => (true, date), }; RawTask { subject: self.subject, priority: self.priority,
due_date: self.due_date, contexts: self.contexts, projects: self.projects, hashtags: self.hashtags, tags: self.tags, } } }
create_date: self.creation_date, finished, finish_date, threshold_date: self.threshold_date,
random_line_split
task.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::str::FromStr; use chrono::NaiveDate; use todo_txt::Task as RawTask; /// A Task with its metadata #[derive(Clone, Debug, PartialEq)] pub struct Task { pub subject: String, pub priority: u8, pub creation_date: Option<NaiveDate>, pub status: Status, pub threshold_date: Option<NaiveDate>, pub due_date: Option<NaiveDate>, pub contexts: Vec<String>, pub projects: Vec<String>, pub hashtags: Vec<String>, pub tags: BTreeMap<String, String>, } impl Task { /// Parse a Task from some string pub fn
(txt: impl Borrow<str>) -> Task { // For this unwrap, see https://github.com/sanpii/todo-txt/issues/10 RawTask::from_str(txt.borrow()).unwrap().into() } /// Check if the task is done pub fn is_done(&self) -> bool { if let Status::Finished(_) = self.status { true } else { false } } } /// Possible status of a Task #[derive(Clone, Debug, PartialEq)] pub enum Status { /// The task is started Started, /// The task is finished, with an optional finish date Finished(Option<NaiveDate>), } impl ::std::convert::From<RawTask> for Task { fn from(t: RawTask) -> Task { // compute status let status = if t.finished { Status::Finished(t.finish_date) } else { Status::Started }; Task { subject: t.subject, priority: t.priority, creation_date: t.create_date, status, threshold_date: t.threshold_date, due_date: t.due_date, contexts: t.contexts, projects: t.projects, hashtags: t.hashtags, tags: t.tags, } } } impl ::std::convert::Into<RawTask> for Task { fn into(self) -> RawTask { let (finished, finish_date) = match self.status { Status::Started => (false, None), Status::Finished(date) => (true, date), }; RawTask { subject: self.subject, priority: self.priority, create_date: self.creation_date, finished, finish_date, threshold_date: self.threshold_date, due_date: self.due_date, contexts: self.contexts, projects: self.projects, hashtags: self.hashtags, tags: self.tags, } } }
parse
identifier_name
task.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::str::FromStr; use chrono::NaiveDate; use todo_txt::Task as RawTask; /// A Task with its metadata #[derive(Clone, Debug, PartialEq)] pub struct Task { pub subject: String, pub priority: u8, pub creation_date: Option<NaiveDate>, pub status: Status, pub threshold_date: Option<NaiveDate>, pub due_date: Option<NaiveDate>, pub contexts: Vec<String>, pub projects: Vec<String>, pub hashtags: Vec<String>, pub tags: BTreeMap<String, String>, } impl Task { /// Parse a Task from some string pub fn parse(txt: impl Borrow<str>) -> Task { // For this unwrap, see https://github.com/sanpii/todo-txt/issues/10 RawTask::from_str(txt.borrow()).unwrap().into() } /// Check if the task is done pub fn is_done(&self) -> bool { if let Status::Finished(_) = self.status { true } else { false } } } /// Possible status of a Task #[derive(Clone, Debug, PartialEq)] pub enum Status { /// The task is started Started, /// The task is finished, with an optional finish date Finished(Option<NaiveDate>), } impl ::std::convert::From<RawTask> for Task { fn from(t: RawTask) -> Task
} } impl ::std::convert::Into<RawTask> for Task { fn into(self) -> RawTask { let (finished, finish_date) = match self.status { Status::Started => (false, None), Status::Finished(date) => (true, date), }; RawTask { subject: self.subject, priority: self.priority, create_date: self.creation_date, finished, finish_date, threshold_date: self.threshold_date, due_date: self.due_date, contexts: self.contexts, projects: self.projects, hashtags: self.hashtags, tags: self.tags, } } }
{ // compute status let status = if t.finished { Status::Finished(t.finish_date) } else { Status::Started }; Task { subject: t.subject, priority: t.priority, creation_date: t.create_date, status, threshold_date: t.threshold_date, due_date: t.due_date, contexts: t.contexts, projects: t.projects, hashtags: t.hashtags, tags: t.tags, }
identifier_body
timeout.rs
#[macro_use] extern crate holmes; use holmes::simple::*; use std::time::{Duration, Instant}; // The whole point of this test is to take an excessively long execution // and make sure it terminates about on time if a limiter is provided #[test] pub fn infinity()
}
{ single(&|holmes: &mut Engine, core: &mut Core| { // Amount of time holmes gets let limit = Duration::new(2, 0); // Wiggle room to shut things down let wiggle = Duration::new(1, 0); holmes.limit_time(limit.clone()); let start = Instant::now(); try!(holmes_exec!(holmes, { predicate!(count(uint64)); fact!(count(0)); func!(let inc: uint64 -> uint64 = |i: &u64| *i + 1); rule!(inc: count(n_plus_one) <= count(n), { let n_plus_one = {inc([n])} }) })); core.run(holmes.quiesce()).unwrap(); assert!(start.elapsed() < limit + wiggle); Ok(()) })
identifier_body
timeout.rs
#[macro_use] extern crate holmes; use holmes::simple::*; use std::time::{Duration, Instant}; // The whole point of this test is to take an excessively long execution // and make sure it terminates about on time if a limiter is provided #[test] pub fn infinity() { single(&|holmes: &mut Engine, core: &mut Core| { // Amount of time holmes gets let limit = Duration::new(2, 0); // Wiggle room to shut things down let wiggle = Duration::new(1, 0);
holmes.limit_time(limit.clone()); let start = Instant::now(); try!(holmes_exec!(holmes, { predicate!(count(uint64)); fact!(count(0)); func!(let inc: uint64 -> uint64 = |i: &u64| *i + 1); rule!(inc: count(n_plus_one) <= count(n), { let n_plus_one = {inc([n])} }) })); core.run(holmes.quiesce()).unwrap(); assert!(start.elapsed() < limit + wiggle); Ok(()) }) }
random_line_split
timeout.rs
#[macro_use] extern crate holmes; use holmes::simple::*; use std::time::{Duration, Instant}; // The whole point of this test is to take an excessively long execution // and make sure it terminates about on time if a limiter is provided #[test] pub fn
() { single(&|holmes: &mut Engine, core: &mut Core| { // Amount of time holmes gets let limit = Duration::new(2, 0); // Wiggle room to shut things down let wiggle = Duration::new(1, 0); holmes.limit_time(limit.clone()); let start = Instant::now(); try!(holmes_exec!(holmes, { predicate!(count(uint64)); fact!(count(0)); func!(let inc: uint64 -> uint64 = |i: &u64| *i + 1); rule!(inc: count(n_plus_one) <= count(n), { let n_plus_one = {inc([n])} }) })); core.run(holmes.quiesce()).unwrap(); assert!(start.elapsed() < limit + wiggle); Ok(()) }) }
infinity
identifier_name
cell_renderer_toggle.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! Renders a toggle button in a cell use ffi; use glib::{to_bool, to_gboolean}; struct_Widget!(CellRendererToggle); impl CellRendererToggle { pub fn new() -> Option<CellRendererToggle> { let tmp_pointer = unsafe { ffi::gtk_cell_renderer_toggle_new() as *mut ffi::C_GtkWidget }; check_pointer!(tmp_pointer, CellRendererToggle) } pub fn get_radio(&self) -> bool { unsafe { to_bool(ffi::gtk_cell_renderer_toggle_get_radio( self.pointer as *mut ffi::C_GtkCellRendererToggle)) } } pub fn set_radio(&self, radio: bool) -> () { unsafe { ffi::gtk_cell_renderer_toggle_set_radio( self.pointer as *mut ffi::C_GtkCellRendererToggle, to_gboolean(radio)); } } pub fn get_active(&self) -> bool { unsafe { to_bool(ffi::gtk_cell_renderer_toggle_get_active( self.pointer as *mut ffi::C_GtkCellRendererToggle)) } } pub fn set_active(&self, active: bool) -> () {
} } impl_drop!(CellRendererToggle); impl_TraitWidget!(CellRendererToggle); impl ::CellRendererTrait for CellRendererToggle {}
unsafe { ffi::gtk_cell_renderer_toggle_set_active( self.pointer as *mut ffi::C_GtkCellRendererToggle, to_gboolean(active)); }
random_line_split
cell_renderer_toggle.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! Renders a toggle button in a cell use ffi; use glib::{to_bool, to_gboolean}; struct_Widget!(CellRendererToggle); impl CellRendererToggle { pub fn new() -> Option<CellRendererToggle>
pub fn get_radio(&self) -> bool { unsafe { to_bool(ffi::gtk_cell_renderer_toggle_get_radio( self.pointer as *mut ffi::C_GtkCellRendererToggle)) } } pub fn set_radio(&self, radio: bool) -> () { unsafe { ffi::gtk_cell_renderer_toggle_set_radio( self.pointer as *mut ffi::C_GtkCellRendererToggle, to_gboolean(radio)); } } pub fn get_active(&self) -> bool { unsafe { to_bool(ffi::gtk_cell_renderer_toggle_get_active( self.pointer as *mut ffi::C_GtkCellRendererToggle)) } } pub fn set_active(&self, active: bool) -> () { unsafe { ffi::gtk_cell_renderer_toggle_set_active( self.pointer as *mut ffi::C_GtkCellRendererToggle, to_gboolean(active)); } } } impl_drop!(CellRendererToggle); impl_TraitWidget!(CellRendererToggle); impl ::CellRendererTrait for CellRendererToggle {}
{ let tmp_pointer = unsafe { ffi::gtk_cell_renderer_toggle_new() as *mut ffi::C_GtkWidget }; check_pointer!(tmp_pointer, CellRendererToggle) }
identifier_body
cell_renderer_toggle.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! Renders a toggle button in a cell use ffi; use glib::{to_bool, to_gboolean}; struct_Widget!(CellRendererToggle); impl CellRendererToggle { pub fn
() -> Option<CellRendererToggle> { let tmp_pointer = unsafe { ffi::gtk_cell_renderer_toggle_new() as *mut ffi::C_GtkWidget }; check_pointer!(tmp_pointer, CellRendererToggle) } pub fn get_radio(&self) -> bool { unsafe { to_bool(ffi::gtk_cell_renderer_toggle_get_radio( self.pointer as *mut ffi::C_GtkCellRendererToggle)) } } pub fn set_radio(&self, radio: bool) -> () { unsafe { ffi::gtk_cell_renderer_toggle_set_radio( self.pointer as *mut ffi::C_GtkCellRendererToggle, to_gboolean(radio)); } } pub fn get_active(&self) -> bool { unsafe { to_bool(ffi::gtk_cell_renderer_toggle_get_active( self.pointer as *mut ffi::C_GtkCellRendererToggle)) } } pub fn set_active(&self, active: bool) -> () { unsafe { ffi::gtk_cell_renderer_toggle_set_active( self.pointer as *mut ffi::C_GtkCellRendererToggle, to_gboolean(active)); } } } impl_drop!(CellRendererToggle); impl_TraitWidget!(CellRendererToggle); impl ::CellRendererTrait for CellRendererToggle {}
new
identifier_name
sendfn-generic-fn.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. // xfail-fast use std::task; pub fn main() { test05(); } struct Pair<A,B> { a: A, b: B } fn make_generic_record<A:Copy,B:Copy>(a: A, b: B) -> Pair<A,B> { return Pair {a: a, b: b}; } fn test05_start(f: &~fn(v: float, v: ~str) -> Pair<float, ~str>) { let p = (*f)(22.22f, ~"Hi"); info!(copy p); assert!(p.a == 22.22f); assert!(p.b == ~"Hi"); let q = (*f)(44.44f, ~"Ho"); info!(copy q); assert!(q.a == 44.44f); assert!(q.b == ~"Ho"); }
fn spawn<A:Copy,B:Copy>(f: extern fn(&~fn(A,B)->Pair<A,B>)) { let arg: ~fn(A, B) -> Pair<A,B> = |a, b| make_generic_record(a, b); task::spawn(|| f(&arg)); } fn test05() { spawn::<float,~str>(test05_start); }
random_line_split
sendfn-generic-fn.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. // xfail-fast use std::task; pub fn main() { test05(); } struct Pair<A,B> { a: A, b: B } fn make_generic_record<A:Copy,B:Copy>(a: A, b: B) -> Pair<A,B> { return Pair {a: a, b: b}; } fn
(f: &~fn(v: float, v: ~str) -> Pair<float, ~str>) { let p = (*f)(22.22f, ~"Hi"); info!(copy p); assert!(p.a == 22.22f); assert!(p.b == ~"Hi"); let q = (*f)(44.44f, ~"Ho"); info!(copy q); assert!(q.a == 44.44f); assert!(q.b == ~"Ho"); } fn spawn<A:Copy,B:Copy>(f: extern fn(&~fn(A,B)->Pair<A,B>)) { let arg: ~fn(A, B) -> Pair<A,B> = |a, b| make_generic_record(a, b); task::spawn(|| f(&arg)); } fn test05() { spawn::<float,~str>(test05_start); }
test05_start
identifier_name
sendfn-generic-fn.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. // xfail-fast use std::task; pub fn main()
struct Pair<A,B> { a: A, b: B } fn make_generic_record<A:Copy,B:Copy>(a: A, b: B) -> Pair<A,B> { return Pair {a: a, b: b}; } fn test05_start(f: &~fn(v: float, v: ~str) -> Pair<float, ~str>) { let p = (*f)(22.22f, ~"Hi"); info!(copy p); assert!(p.a == 22.22f); assert!(p.b == ~"Hi"); let q = (*f)(44.44f, ~"Ho"); info!(copy q); assert!(q.a == 44.44f); assert!(q.b == ~"Ho"); } fn spawn<A:Copy,B:Copy>(f: extern fn(&~fn(A,B)->Pair<A,B>)) { let arg: ~fn(A, B) -> Pair<A,B> = |a, b| make_generic_record(a, b); task::spawn(|| f(&arg)); } fn test05() { spawn::<float,~str>(test05_start); }
{ test05(); }
identifier_body
dragon.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Almost direct (but slightly optimized) Rust translation of Figure 3 of [1]. [1] Burger, R. G. and Dybvig, R. K. 1996. Printing floating-point numbers quickly and accurately. SIGPLAN Not. 31, 5 (May. 1996), 108-116. */ use prelude::v1::*; use cmp::Ordering; use num::flt2dec::{Decoded, MAX_SIG_DIGITS, round_up}; use num::flt2dec::estimator::estimate_scaling_factor; use num::flt2dec::bignum::Digit32 as Digit; use num::flt2dec::bignum::Big32x40 as Big; static POW10: [Digit; 10] = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]; static TWOPOW10: [Digit; 10] = [2, 20, 200, 2000, 20000, 200000, 2000000, 20000000, 200000000, 2000000000]; // precalculated arrays of `Digit`s for 10^(2^n) static POW10TO16: [Digit; 2] = [0x6fc10000, 0x2386f2]; static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee]; static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03]; static POW10TO128: [Digit; 14] = [0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, 0xa6337f19, 0xe91f2603, 0x24e]; static POW10TO256: [Digit; 27] = [0, 0, 0, 0, 0, 0, 0, 0, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7]; #[doc(hidden)] pub fn mul_pow10<'a>(x: &'a mut Big, n: usize) -> &'a mut Big { debug_assert!(n < 512); if n & 7!= 0 { x.mul_small(POW10[n & 7]); } if n & 8!= 0 { x.mul_small(POW10[8]); } if n & 16!= 0 { x.mul_digits(&POW10TO16); } if n & 32!= 0 { x.mul_digits(&POW10TO32); } if n & 64!= 0 { x.mul_digits(&POW10TO64); } if n & 128!= 0 { x.mul_digits(&POW10TO128); } if n & 256!= 0 { x.mul_digits(&POW10TO256); } x } fn div_2pow10<'a>(x: &'a mut Big, mut n: usize) -> &'a mut Big { let largest = POW10.len() - 1; while n > largest { x.div_rem_small(POW10[largest]); n -= largest; } x.div_rem_small(TWOPOW10[n]); x } // only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)` fn div_rem_upto_16<'a>(x: &'a mut Big, scale: &Big, scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) { let mut d = 0; if *x >= *scale8 { x.sub(scale8); d += 8; } if *x >= *scale4 { x.sub(scale4); d += 4; } if *x >= *scale2 { x.sub(scale2); d += 2; } if *x >= *scale { x.sub(scale); d += 1; } debug_assert!(*x < *scale); (d, x) } /// The shortest mode implementation for Dragon. pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp*/ i16) { // the number `v` to format is known to be: // - equal to `mant * 2^exp`; // - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and // - followed by `(mant + 2 * plus) * 2^exp` in the original type. // // obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.) // also we assume that at least one digit is generated, i.e. `mant` cannot be zero too. // // this also means that any number between `low = (mant - minus) * 2^exp` and // `high = (mant + plus) * 2^exp` will map to this exact floating point number, // with bounds included when the original mantissa was even (i.e. `!mant_was_odd`). assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); assert!(buf.len() >= MAX_SIG_DIGITS); // `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}` let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal}; // estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`. // the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later. let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp); // convert `{mant, plus, minus} * 2^exp` into the fractional form so that: // - `v = mant / scale` // - `low = (mant - minus) / scale` // - `high = (mant + plus) / scale` let mut mant = Big::from_u64(d.mant); let mut minus = Big::from_u64(d.minus); let mut plus = Big::from_u64(d.plus); let mut scale = Big::from_small(1); if d.exp < 0
else { mant.mul_pow2(d.exp as usize); minus.mul_pow2(d.exp as usize); plus.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); mul_pow10(&mut minus, -k as usize); mul_pow10(&mut plus, -k as usize); } // fixup when `mant + plus > scale` (or `>=`). // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // now `scale < mant + plus <= scale * 10` and we are ready to generate digits. // // note that `d[0]` *can* be zero, when `scale - plus < mant < scale`. // in this case rounding-up condition (`up` below) will be triggered immediately. if scale.cmp(mant.clone().add(&plus)) < rounding { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // cache `(2, 4, 8) * scale` for digit generation. let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); let mut down; let mut up; let mut i = 0; loop { // invariants, where `d[0..n-1]` are digits generated so far: // - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n-1)` // - `high - v = plus / scale * 10^(k-n-1)` // - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`) // where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) +... + d[j-1] * 10 + d[j]`. // generate one digit: `d[n] = floor(mant / scale) < 10`. let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8); debug_assert!(d < 10); buf[i] = b'0' + d; i += 1; // this is a simplified description of the modified Dragon algorithm. // many intermediate derivations and completeness arguments are omitted for convenience. // // start with modified invariants, as we've updated `n`: // - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n)` // - `high - v = plus / scale * 10^(k-n)` // // assume that `d[0..n-1]` is the shortest representation between `low` and `high`, // i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't: // - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and // - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct). // // the second condition simplifies to `2 * mant <= scale`. // solving invariants in terms of `mant`, `low` and `high` yields // a simpler version of the first condition: `-plus < mant < minus`. // since `-plus < 0 <= mant`, we have the correct shortest representation // when `mant < minus` and `2 * mant <= scale`. // (the former becomes `mant <= minus` when the original mantissa is even.) // // when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit. // this is enough for restoring that condition: we already know that // the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`. // in this case, the first condition becomes `-plus < mant - scale < minus`. // since `mant < scale` after the generation, we have `scale < mant + plus`. // (again, this becomes `scale <= mant + plus` when the original mantissa is even.) // // in short: // - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`). // - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`). // - keep generating otherwise. down = mant.cmp(&minus) < rounding; up = scale.cmp(mant.clone().add(&plus)) < rounding; if down || up { break; } // we have the shortest representation, proceed to the rounding // restore the invariants. // this makes the algorithm always terminating: `minus` and `plus` always increases, // but `mant` is clipped modulo `scale` and `scale` is fixed. mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // rounding up happens when // i) only the rounding-up condition was triggered, or // ii) both conditions were triggered and tie breaking prefers rounding up. if up && (!down || *mant.mul_pow2(1) >= scale) { // if rounding up changes the length, the exponent should also change. // it seems that this condition is very hard to satisfy (possibly impossible), // but we are just being safe and consistent here. if let Some(c) = round_up(buf, i) { buf[i] = c; i += 1; k += 1; } } (i, k) } /// The exact and fixed mode implementation for Dragon. pub fn format_exact(d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usize, /*exp*/ i16) { assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); // estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`. let mut k = estimate_scaling_factor(d.mant, d.exp); // `v = mant / scale`. let mut mant = Big::from_u64(d.mant); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); } // fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`. // in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`. // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // again with the shortest algorithm, `d[0]` can be zero but will be eventually rounded up. if *div_2pow10(&mut scale.clone(), buf.len()).add(&mant) >= scale { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); } // if we are working with the last-digit limitation, we need to shorten the buffer // before the actual rendering in order to avoid double rounding. // note that we have to enlarge the buffer again when rounding up happens! let mut len = if k < limit { // oops, we cannot even produce *one* digit. // this is possible when, say, we've got something like 9.5 and it's being rounded to 10. // we return an empty buffer, with an exception of the later rounding-up case // which occurs when `k == limit` and has to produce exactly one digit. 0 } else if ((k as i32 - limit as i32) as usize) < buf.len() { (k - limit) as usize } else { buf.len() }; if len > 0 { // cache `(2, 4, 8) * scale` for digit generation. // (this can be expensive, so do not calculate them when the buffer is empty.) let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); for i in 0..len { if mant.is_zero() { // following digits are all zeroes, we stop here // do *not* try to perform rounding! rather, fill remaining digits. for c in &mut buf[i..len] { *c = b'0'; } return (len, k); } let mut d = 0; if mant >= scale8 { mant.sub(&scale8); d += 8; } if mant >= scale4 { mant.sub(&scale4); d += 4; } if mant >= scale2 { mant.sub(&scale2); d += 2; } if mant >= scale { mant.sub(&scale); d += 1; } debug_assert!(mant < scale); debug_assert!(d < 10); buf[i] = b'0' + d; mant.mul_small(10); } } // rounding up if we stop in the middle of digits // if the following digits are exactly 5000..., check the prior digit and try to // round to even (i.e. avoid rounding up when the prior digit is even). let order = mant.cmp(scale.mul_small(5)); if order == Ordering::Greater || (order == Ordering::Equal && (len == 0 || buf[len-1] & 1 == 1)) { // if rounding up changes the length, the exponent should also change. // but we've been requested a fixed number of digits, so do not alter the buffer... if let Some(c) = round_up(buf, len) { //...unless we've been requested the fixed precision instead. // we also need to check that, if the original buffer was empty, // the additional digit can only be added when `k == limit` (edge case). k += 1; if k > limit && len < buf.len() { buf[len] = c; len += 1; } } } (len, k) }
{ scale.mul_pow2(-d.exp as usize); }
conditional_block
dragon.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Almost direct (but slightly optimized) Rust translation of Figure 3 of [1]. [1] Burger, R. G. and Dybvig, R. K. 1996. Printing floating-point numbers quickly and accurately. SIGPLAN Not. 31, 5 (May. 1996), 108-116. */ use prelude::v1::*; use cmp::Ordering; use num::flt2dec::{Decoded, MAX_SIG_DIGITS, round_up}; use num::flt2dec::estimator::estimate_scaling_factor; use num::flt2dec::bignum::Digit32 as Digit; use num::flt2dec::bignum::Big32x40 as Big; static POW10: [Digit; 10] = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]; static TWOPOW10: [Digit; 10] = [2, 20, 200, 2000, 20000, 200000, 2000000, 20000000, 200000000, 2000000000]; // precalculated arrays of `Digit`s for 10^(2^n) static POW10TO16: [Digit; 2] = [0x6fc10000, 0x2386f2]; static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee]; static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03]; static POW10TO128: [Digit; 14] = [0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, 0xa6337f19, 0xe91f2603, 0x24e]; static POW10TO256: [Digit; 27] = [0, 0, 0, 0, 0, 0, 0, 0, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7]; #[doc(hidden)] pub fn mul_pow10<'a>(x: &'a mut Big, n: usize) -> &'a mut Big { debug_assert!(n < 512); if n & 7!= 0 { x.mul_small(POW10[n & 7]); } if n & 8!= 0 { x.mul_small(POW10[8]); } if n & 16!= 0 { x.mul_digits(&POW10TO16); } if n & 32!= 0 { x.mul_digits(&POW10TO32); } if n & 64!= 0 { x.mul_digits(&POW10TO64); } if n & 128!= 0 { x.mul_digits(&POW10TO128); } if n & 256!= 0 { x.mul_digits(&POW10TO256); } x } fn div_2pow10<'a>(x: &'a mut Big, mut n: usize) -> &'a mut Big { let largest = POW10.len() - 1; while n > largest { x.div_rem_small(POW10[largest]); n -= largest; } x.div_rem_small(TWOPOW10[n]); x } // only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)` fn
<'a>(x: &'a mut Big, scale: &Big, scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) { let mut d = 0; if *x >= *scale8 { x.sub(scale8); d += 8; } if *x >= *scale4 { x.sub(scale4); d += 4; } if *x >= *scale2 { x.sub(scale2); d += 2; } if *x >= *scale { x.sub(scale); d += 1; } debug_assert!(*x < *scale); (d, x) } /// The shortest mode implementation for Dragon. pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp*/ i16) { // the number `v` to format is known to be: // - equal to `mant * 2^exp`; // - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and // - followed by `(mant + 2 * plus) * 2^exp` in the original type. // // obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.) // also we assume that at least one digit is generated, i.e. `mant` cannot be zero too. // // this also means that any number between `low = (mant - minus) * 2^exp` and // `high = (mant + plus) * 2^exp` will map to this exact floating point number, // with bounds included when the original mantissa was even (i.e. `!mant_was_odd`). assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); assert!(buf.len() >= MAX_SIG_DIGITS); // `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}` let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal}; // estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`. // the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later. let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp); // convert `{mant, plus, minus} * 2^exp` into the fractional form so that: // - `v = mant / scale` // - `low = (mant - minus) / scale` // - `high = (mant + plus) / scale` let mut mant = Big::from_u64(d.mant); let mut minus = Big::from_u64(d.minus); let mut plus = Big::from_u64(d.plus); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); minus.mul_pow2(d.exp as usize); plus.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); mul_pow10(&mut minus, -k as usize); mul_pow10(&mut plus, -k as usize); } // fixup when `mant + plus > scale` (or `>=`). // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // now `scale < mant + plus <= scale * 10` and we are ready to generate digits. // // note that `d[0]` *can* be zero, when `scale - plus < mant < scale`. // in this case rounding-up condition (`up` below) will be triggered immediately. if scale.cmp(mant.clone().add(&plus)) < rounding { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // cache `(2, 4, 8) * scale` for digit generation. let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); let mut down; let mut up; let mut i = 0; loop { // invariants, where `d[0..n-1]` are digits generated so far: // - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n-1)` // - `high - v = plus / scale * 10^(k-n-1)` // - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`) // where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) +... + d[j-1] * 10 + d[j]`. // generate one digit: `d[n] = floor(mant / scale) < 10`. let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8); debug_assert!(d < 10); buf[i] = b'0' + d; i += 1; // this is a simplified description of the modified Dragon algorithm. // many intermediate derivations and completeness arguments are omitted for convenience. // // start with modified invariants, as we've updated `n`: // - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n)` // - `high - v = plus / scale * 10^(k-n)` // // assume that `d[0..n-1]` is the shortest representation between `low` and `high`, // i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't: // - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and // - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct). // // the second condition simplifies to `2 * mant <= scale`. // solving invariants in terms of `mant`, `low` and `high` yields // a simpler version of the first condition: `-plus < mant < minus`. // since `-plus < 0 <= mant`, we have the correct shortest representation // when `mant < minus` and `2 * mant <= scale`. // (the former becomes `mant <= minus` when the original mantissa is even.) // // when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit. // this is enough for restoring that condition: we already know that // the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`. // in this case, the first condition becomes `-plus < mant - scale < minus`. // since `mant < scale` after the generation, we have `scale < mant + plus`. // (again, this becomes `scale <= mant + plus` when the original mantissa is even.) // // in short: // - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`). // - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`). // - keep generating otherwise. down = mant.cmp(&minus) < rounding; up = scale.cmp(mant.clone().add(&plus)) < rounding; if down || up { break; } // we have the shortest representation, proceed to the rounding // restore the invariants. // this makes the algorithm always terminating: `minus` and `plus` always increases, // but `mant` is clipped modulo `scale` and `scale` is fixed. mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // rounding up happens when // i) only the rounding-up condition was triggered, or // ii) both conditions were triggered and tie breaking prefers rounding up. if up && (!down || *mant.mul_pow2(1) >= scale) { // if rounding up changes the length, the exponent should also change. // it seems that this condition is very hard to satisfy (possibly impossible), // but we are just being safe and consistent here. if let Some(c) = round_up(buf, i) { buf[i] = c; i += 1; k += 1; } } (i, k) } /// The exact and fixed mode implementation for Dragon. pub fn format_exact(d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usize, /*exp*/ i16) { assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); // estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`. let mut k = estimate_scaling_factor(d.mant, d.exp); // `v = mant / scale`. let mut mant = Big::from_u64(d.mant); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); } // fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`. // in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`. // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // again with the shortest algorithm, `d[0]` can be zero but will be eventually rounded up. if *div_2pow10(&mut scale.clone(), buf.len()).add(&mant) >= scale { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); } // if we are working with the last-digit limitation, we need to shorten the buffer // before the actual rendering in order to avoid double rounding. // note that we have to enlarge the buffer again when rounding up happens! let mut len = if k < limit { // oops, we cannot even produce *one* digit. // this is possible when, say, we've got something like 9.5 and it's being rounded to 10. // we return an empty buffer, with an exception of the later rounding-up case // which occurs when `k == limit` and has to produce exactly one digit. 0 } else if ((k as i32 - limit as i32) as usize) < buf.len() { (k - limit) as usize } else { buf.len() }; if len > 0 { // cache `(2, 4, 8) * scale` for digit generation. // (this can be expensive, so do not calculate them when the buffer is empty.) let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); for i in 0..len { if mant.is_zero() { // following digits are all zeroes, we stop here // do *not* try to perform rounding! rather, fill remaining digits. for c in &mut buf[i..len] { *c = b'0'; } return (len, k); } let mut d = 0; if mant >= scale8 { mant.sub(&scale8); d += 8; } if mant >= scale4 { mant.sub(&scale4); d += 4; } if mant >= scale2 { mant.sub(&scale2); d += 2; } if mant >= scale { mant.sub(&scale); d += 1; } debug_assert!(mant < scale); debug_assert!(d < 10); buf[i] = b'0' + d; mant.mul_small(10); } } // rounding up if we stop in the middle of digits // if the following digits are exactly 5000..., check the prior digit and try to // round to even (i.e. avoid rounding up when the prior digit is even). let order = mant.cmp(scale.mul_small(5)); if order == Ordering::Greater || (order == Ordering::Equal && (len == 0 || buf[len-1] & 1 == 1)) { // if rounding up changes the length, the exponent should also change. // but we've been requested a fixed number of digits, so do not alter the buffer... if let Some(c) = round_up(buf, len) { //...unless we've been requested the fixed precision instead. // we also need to check that, if the original buffer was empty, // the additional digit can only be added when `k == limit` (edge case). k += 1; if k > limit && len < buf.len() { buf[len] = c; len += 1; } } } (len, k) }
div_rem_upto_16
identifier_name
dragon.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Almost direct (but slightly optimized) Rust translation of Figure 3 of [1]. [1] Burger, R. G. and Dybvig, R. K. 1996. Printing floating-point numbers quickly and accurately. SIGPLAN Not. 31, 5 (May. 1996), 108-116. */ use prelude::v1::*; use cmp::Ordering; use num::flt2dec::{Decoded, MAX_SIG_DIGITS, round_up}; use num::flt2dec::estimator::estimate_scaling_factor; use num::flt2dec::bignum::Digit32 as Digit; use num::flt2dec::bignum::Big32x40 as Big; static POW10: [Digit; 10] = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]; static TWOPOW10: [Digit; 10] = [2, 20, 200, 2000, 20000, 200000, 2000000, 20000000, 200000000, 2000000000]; // precalculated arrays of `Digit`s for 10^(2^n) static POW10TO16: [Digit; 2] = [0x6fc10000, 0x2386f2]; static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee]; static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03]; static POW10TO128: [Digit; 14] = [0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, 0xa6337f19, 0xe91f2603, 0x24e]; static POW10TO256: [Digit; 27] = [0, 0, 0, 0, 0, 0, 0, 0, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7]; #[doc(hidden)] pub fn mul_pow10<'a>(x: &'a mut Big, n: usize) -> &'a mut Big { debug_assert!(n < 512); if n & 7!= 0 { x.mul_small(POW10[n & 7]); } if n & 8!= 0 { x.mul_small(POW10[8]); } if n & 16!= 0 { x.mul_digits(&POW10TO16); } if n & 32!= 0 { x.mul_digits(&POW10TO32); } if n & 64!= 0 { x.mul_digits(&POW10TO64); } if n & 128!= 0 { x.mul_digits(&POW10TO128); } if n & 256!= 0 { x.mul_digits(&POW10TO256); } x } fn div_2pow10<'a>(x: &'a mut Big, mut n: usize) -> &'a mut Big { let largest = POW10.len() - 1; while n > largest { x.div_rem_small(POW10[largest]); n -= largest; } x.div_rem_small(TWOPOW10[n]); x } // only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)` fn div_rem_upto_16<'a>(x: &'a mut Big, scale: &Big, scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) { let mut d = 0; if *x >= *scale8 { x.sub(scale8); d += 8; } if *x >= *scale4 { x.sub(scale4); d += 4; } if *x >= *scale2 { x.sub(scale2); d += 2; } if *x >= *scale { x.sub(scale); d += 1; } debug_assert!(*x < *scale); (d, x) } /// The shortest mode implementation for Dragon. pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp*/ i16) { // the number `v` to format is known to be: // - equal to `mant * 2^exp`; // - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and // - followed by `(mant + 2 * plus) * 2^exp` in the original type. // // obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.) // also we assume that at least one digit is generated, i.e. `mant` cannot be zero too. // // this also means that any number between `low = (mant - minus) * 2^exp` and // `high = (mant + plus) * 2^exp` will map to this exact floating point number, // with bounds included when the original mantissa was even (i.e. `!mant_was_odd`). assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); assert!(buf.len() >= MAX_SIG_DIGITS); // `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}` let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal}; // estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`. // the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later. let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp); // convert `{mant, plus, minus} * 2^exp` into the fractional form so that: // - `v = mant / scale` // - `low = (mant - minus) / scale` // - `high = (mant + plus) / scale` let mut mant = Big::from_u64(d.mant); let mut minus = Big::from_u64(d.minus); let mut plus = Big::from_u64(d.plus); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); minus.mul_pow2(d.exp as usize); plus.mul_pow2(d.exp as usize);
} else { mul_pow10(&mut mant, -k as usize); mul_pow10(&mut minus, -k as usize); mul_pow10(&mut plus, -k as usize); } // fixup when `mant + plus > scale` (or `>=`). // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // now `scale < mant + plus <= scale * 10` and we are ready to generate digits. // // note that `d[0]` *can* be zero, when `scale - plus < mant < scale`. // in this case rounding-up condition (`up` below) will be triggered immediately. if scale.cmp(mant.clone().add(&plus)) < rounding { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // cache `(2, 4, 8) * scale` for digit generation. let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); let mut down; let mut up; let mut i = 0; loop { // invariants, where `d[0..n-1]` are digits generated so far: // - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n-1)` // - `high - v = plus / scale * 10^(k-n-1)` // - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`) // where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) +... + d[j-1] * 10 + d[j]`. // generate one digit: `d[n] = floor(mant / scale) < 10`. let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8); debug_assert!(d < 10); buf[i] = b'0' + d; i += 1; // this is a simplified description of the modified Dragon algorithm. // many intermediate derivations and completeness arguments are omitted for convenience. // // start with modified invariants, as we've updated `n`: // - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n)` // - `high - v = plus / scale * 10^(k-n)` // // assume that `d[0..n-1]` is the shortest representation between `low` and `high`, // i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't: // - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and // - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct). // // the second condition simplifies to `2 * mant <= scale`. // solving invariants in terms of `mant`, `low` and `high` yields // a simpler version of the first condition: `-plus < mant < minus`. // since `-plus < 0 <= mant`, we have the correct shortest representation // when `mant < minus` and `2 * mant <= scale`. // (the former becomes `mant <= minus` when the original mantissa is even.) // // when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit. // this is enough for restoring that condition: we already know that // the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`. // in this case, the first condition becomes `-plus < mant - scale < minus`. // since `mant < scale` after the generation, we have `scale < mant + plus`. // (again, this becomes `scale <= mant + plus` when the original mantissa is even.) // // in short: // - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`). // - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`). // - keep generating otherwise. down = mant.cmp(&minus) < rounding; up = scale.cmp(mant.clone().add(&plus)) < rounding; if down || up { break; } // we have the shortest representation, proceed to the rounding // restore the invariants. // this makes the algorithm always terminating: `minus` and `plus` always increases, // but `mant` is clipped modulo `scale` and `scale` is fixed. mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // rounding up happens when // i) only the rounding-up condition was triggered, or // ii) both conditions were triggered and tie breaking prefers rounding up. if up && (!down || *mant.mul_pow2(1) >= scale) { // if rounding up changes the length, the exponent should also change. // it seems that this condition is very hard to satisfy (possibly impossible), // but we are just being safe and consistent here. if let Some(c) = round_up(buf, i) { buf[i] = c; i += 1; k += 1; } } (i, k) } /// The exact and fixed mode implementation for Dragon. pub fn format_exact(d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usize, /*exp*/ i16) { assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); // estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`. let mut k = estimate_scaling_factor(d.mant, d.exp); // `v = mant / scale`. let mut mant = Big::from_u64(d.mant); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); } // fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`. // in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`. // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // again with the shortest algorithm, `d[0]` can be zero but will be eventually rounded up. if *div_2pow10(&mut scale.clone(), buf.len()).add(&mant) >= scale { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); } // if we are working with the last-digit limitation, we need to shorten the buffer // before the actual rendering in order to avoid double rounding. // note that we have to enlarge the buffer again when rounding up happens! let mut len = if k < limit { // oops, we cannot even produce *one* digit. // this is possible when, say, we've got something like 9.5 and it's being rounded to 10. // we return an empty buffer, with an exception of the later rounding-up case // which occurs when `k == limit` and has to produce exactly one digit. 0 } else if ((k as i32 - limit as i32) as usize) < buf.len() { (k - limit) as usize } else { buf.len() }; if len > 0 { // cache `(2, 4, 8) * scale` for digit generation. // (this can be expensive, so do not calculate them when the buffer is empty.) let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); for i in 0..len { if mant.is_zero() { // following digits are all zeroes, we stop here // do *not* try to perform rounding! rather, fill remaining digits. for c in &mut buf[i..len] { *c = b'0'; } return (len, k); } let mut d = 0; if mant >= scale8 { mant.sub(&scale8); d += 8; } if mant >= scale4 { mant.sub(&scale4); d += 4; } if mant >= scale2 { mant.sub(&scale2); d += 2; } if mant >= scale { mant.sub(&scale); d += 1; } debug_assert!(mant < scale); debug_assert!(d < 10); buf[i] = b'0' + d; mant.mul_small(10); } } // rounding up if we stop in the middle of digits // if the following digits are exactly 5000..., check the prior digit and try to // round to even (i.e. avoid rounding up when the prior digit is even). let order = mant.cmp(scale.mul_small(5)); if order == Ordering::Greater || (order == Ordering::Equal && (len == 0 || buf[len-1] & 1 == 1)) { // if rounding up changes the length, the exponent should also change. // but we've been requested a fixed number of digits, so do not alter the buffer... if let Some(c) = round_up(buf, len) { //...unless we've been requested the fixed precision instead. // we also need to check that, if the original buffer was empty, // the additional digit can only be added when `k == limit` (edge case). k += 1; if k > limit && len < buf.len() { buf[len] = c; len += 1; } } } (len, k) }
} // divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize);
random_line_split
dragon.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Almost direct (but slightly optimized) Rust translation of Figure 3 of [1]. [1] Burger, R. G. and Dybvig, R. K. 1996. Printing floating-point numbers quickly and accurately. SIGPLAN Not. 31, 5 (May. 1996), 108-116. */ use prelude::v1::*; use cmp::Ordering; use num::flt2dec::{Decoded, MAX_SIG_DIGITS, round_up}; use num::flt2dec::estimator::estimate_scaling_factor; use num::flt2dec::bignum::Digit32 as Digit; use num::flt2dec::bignum::Big32x40 as Big; static POW10: [Digit; 10] = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]; static TWOPOW10: [Digit; 10] = [2, 20, 200, 2000, 20000, 200000, 2000000, 20000000, 200000000, 2000000000]; // precalculated arrays of `Digit`s for 10^(2^n) static POW10TO16: [Digit; 2] = [0x6fc10000, 0x2386f2]; static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee]; static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03]; static POW10TO128: [Digit; 14] = [0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, 0xa6337f19, 0xe91f2603, 0x24e]; static POW10TO256: [Digit; 27] = [0, 0, 0, 0, 0, 0, 0, 0, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7]; #[doc(hidden)] pub fn mul_pow10<'a>(x: &'a mut Big, n: usize) -> &'a mut Big { debug_assert!(n < 512); if n & 7!= 0 { x.mul_small(POW10[n & 7]); } if n & 8!= 0 { x.mul_small(POW10[8]); } if n & 16!= 0 { x.mul_digits(&POW10TO16); } if n & 32!= 0 { x.mul_digits(&POW10TO32); } if n & 64!= 0 { x.mul_digits(&POW10TO64); } if n & 128!= 0 { x.mul_digits(&POW10TO128); } if n & 256!= 0 { x.mul_digits(&POW10TO256); } x } fn div_2pow10<'a>(x: &'a mut Big, mut n: usize) -> &'a mut Big { let largest = POW10.len() - 1; while n > largest { x.div_rem_small(POW10[largest]); n -= largest; } x.div_rem_small(TWOPOW10[n]); x } // only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)` fn div_rem_upto_16<'a>(x: &'a mut Big, scale: &Big, scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) { let mut d = 0; if *x >= *scale8 { x.sub(scale8); d += 8; } if *x >= *scale4 { x.sub(scale4); d += 4; } if *x >= *scale2 { x.sub(scale2); d += 2; } if *x >= *scale { x.sub(scale); d += 1; } debug_assert!(*x < *scale); (d, x) } /// The shortest mode implementation for Dragon. pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp*/ i16) { // the number `v` to format is known to be: // - equal to `mant * 2^exp`; // - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and // - followed by `(mant + 2 * plus) * 2^exp` in the original type. // // obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.) // also we assume that at least one digit is generated, i.e. `mant` cannot be zero too. // // this also means that any number between `low = (mant - minus) * 2^exp` and // `high = (mant + plus) * 2^exp` will map to this exact floating point number, // with bounds included when the original mantissa was even (i.e. `!mant_was_odd`). assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); assert!(buf.len() >= MAX_SIG_DIGITS); // `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}` let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal}; // estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`. // the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later. let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp); // convert `{mant, plus, minus} * 2^exp` into the fractional form so that: // - `v = mant / scale` // - `low = (mant - minus) / scale` // - `high = (mant + plus) / scale` let mut mant = Big::from_u64(d.mant); let mut minus = Big::from_u64(d.minus); let mut plus = Big::from_u64(d.plus); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); minus.mul_pow2(d.exp as usize); plus.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); mul_pow10(&mut minus, -k as usize); mul_pow10(&mut plus, -k as usize); } // fixup when `mant + plus > scale` (or `>=`). // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // now `scale < mant + plus <= scale * 10` and we are ready to generate digits. // // note that `d[0]` *can* be zero, when `scale - plus < mant < scale`. // in this case rounding-up condition (`up` below) will be triggered immediately. if scale.cmp(mant.clone().add(&plus)) < rounding { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // cache `(2, 4, 8) * scale` for digit generation. let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); let mut down; let mut up; let mut i = 0; loop { // invariants, where `d[0..n-1]` are digits generated so far: // - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n-1)` // - `high - v = plus / scale * 10^(k-n-1)` // - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`) // where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) +... + d[j-1] * 10 + d[j]`. // generate one digit: `d[n] = floor(mant / scale) < 10`. let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8); debug_assert!(d < 10); buf[i] = b'0' + d; i += 1; // this is a simplified description of the modified Dragon algorithm. // many intermediate derivations and completeness arguments are omitted for convenience. // // start with modified invariants, as we've updated `n`: // - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n)` // - `high - v = plus / scale * 10^(k-n)` // // assume that `d[0..n-1]` is the shortest representation between `low` and `high`, // i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't: // - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and // - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct). // // the second condition simplifies to `2 * mant <= scale`. // solving invariants in terms of `mant`, `low` and `high` yields // a simpler version of the first condition: `-plus < mant < minus`. // since `-plus < 0 <= mant`, we have the correct shortest representation // when `mant < minus` and `2 * mant <= scale`. // (the former becomes `mant <= minus` when the original mantissa is even.) // // when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit. // this is enough for restoring that condition: we already know that // the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`. // in this case, the first condition becomes `-plus < mant - scale < minus`. // since `mant < scale` after the generation, we have `scale < mant + plus`. // (again, this becomes `scale <= mant + plus` when the original mantissa is even.) // // in short: // - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`). // - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`). // - keep generating otherwise. down = mant.cmp(&minus) < rounding; up = scale.cmp(mant.clone().add(&plus)) < rounding; if down || up { break; } // we have the shortest representation, proceed to the rounding // restore the invariants. // this makes the algorithm always terminating: `minus` and `plus` always increases, // but `mant` is clipped modulo `scale` and `scale` is fixed. mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // rounding up happens when // i) only the rounding-up condition was triggered, or // ii) both conditions were triggered and tie breaking prefers rounding up. if up && (!down || *mant.mul_pow2(1) >= scale) { // if rounding up changes the length, the exponent should also change. // it seems that this condition is very hard to satisfy (possibly impossible), // but we are just being safe and consistent here. if let Some(c) = round_up(buf, i) { buf[i] = c; i += 1; k += 1; } } (i, k) } /// The exact and fixed mode implementation for Dragon. pub fn format_exact(d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usize, /*exp*/ i16)
if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); } // fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`. // in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`. // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // again with the shortest algorithm, `d[0]` can be zero but will be eventually rounded up. if *div_2pow10(&mut scale.clone(), buf.len()).add(&mant) >= scale { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); } // if we are working with the last-digit limitation, we need to shorten the buffer // before the actual rendering in order to avoid double rounding. // note that we have to enlarge the buffer again when rounding up happens! let mut len = if k < limit { // oops, we cannot even produce *one* digit. // this is possible when, say, we've got something like 9.5 and it's being rounded to 10. // we return an empty buffer, with an exception of the later rounding-up case // which occurs when `k == limit` and has to produce exactly one digit. 0 } else if ((k as i32 - limit as i32) as usize) < buf.len() { (k - limit) as usize } else { buf.len() }; if len > 0 { // cache `(2, 4, 8) * scale` for digit generation. // (this can be expensive, so do not calculate them when the buffer is empty.) let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); for i in 0..len { if mant.is_zero() { // following digits are all zeroes, we stop here // do *not* try to perform rounding! rather, fill remaining digits. for c in &mut buf[i..len] { *c = b'0'; } return (len, k); } let mut d = 0; if mant >= scale8 { mant.sub(&scale8); d += 8; } if mant >= scale4 { mant.sub(&scale4); d += 4; } if mant >= scale2 { mant.sub(&scale2); d += 2; } if mant >= scale { mant.sub(&scale); d += 1; } debug_assert!(mant < scale); debug_assert!(d < 10); buf[i] = b'0' + d; mant.mul_small(10); } } // rounding up if we stop in the middle of digits // if the following digits are exactly 5000..., check the prior digit and try to // round to even (i.e. avoid rounding up when the prior digit is even). let order = mant.cmp(scale.mul_small(5)); if order == Ordering::Greater || (order == Ordering::Equal && (len == 0 || buf[len-1] & 1 == 1)) { // if rounding up changes the length, the exponent should also change. // but we've been requested a fixed number of digits, so do not alter the buffer... if let Some(c) = round_up(buf, len) { //...unless we've been requested the fixed precision instead. // we also need to check that, if the original buffer was empty, // the additional digit can only be added when `k == limit` (edge case). k += 1; if k > limit && len < buf.len() { buf[len] = c; len += 1; } } } (len, k) }
{ assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); // estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`. let mut k = estimate_scaling_factor(d.mant, d.exp); // `v = mant / scale`. let mut mant = Big::from_u64(d.mant); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant <= scale * 10`.
identifier_body
mod.rs
use crate::{config::WorkMode, env::Env, file_saver::*}; use std::path::Path; mod alias; mod child_properties; mod constants; mod doc; mod enums; mod flags; pub mod function; mod function_body_chunk; mod functions; mod general; mod object; mod objects; mod parameter; mod properties; mod property_body; mod record; mod records; mod return_value; mod signal; mod signal_body; mod sys; mod trait_impls; mod trampoline; mod trampoline_from_glib; mod trampoline_to_glib; pub mod translate_from_glib; pub mod translate_to_glib; pub fn generate(env: &Env) { match env.config.work_mode { WorkMode::Normal => normal_generate(env), WorkMode::Sys => sys::generate(env), WorkMode::Doc => doc::generate(env), WorkMode::DisplayNotBound => {} } } fn normal_generate(env: &Env) { let mut mod_rs: Vec<String> = Vec::new(); let mut traits: Vec<String> = Vec::new(); let root_path = env.config.auto_path.as_path();
records::generate(env, root_path, &mut mod_rs); enums::generate(env, root_path, &mut mod_rs); flags::generate(env, root_path, &mut mod_rs); alias::generate(env, root_path, &mut mod_rs); functions::generate(env, root_path, &mut mod_rs); constants::generate(env, root_path, &mut mod_rs); generate_mod_rs(env, root_path, &mod_rs, &traits); } pub fn generate_mod_rs(env: &Env, root_path: &Path, mod_rs: &[String], traits: &[String]) { let path = root_path.join("mod.rs"); save_to_file(path, env.config.make_backup, |w| { general::start_comments(w, &env.config)?; general::write_vec(w, mod_rs)?; writeln!(w)?; writeln!(w, "#[doc(hidden)]")?; writeln!(w, "pub mod traits {{")?; general::write_vec(w, traits)?; writeln!(w, "}}") }); } pub fn generate_single_version_file(env: &Env) { if let Some(ref path) = env.config.single_version_file { save_to_file(path, env.config.make_backup, |w| { general::single_version_file(w, &env.config) }); } }
generate_single_version_file(env); objects::generate(env, root_path, &mut mod_rs, &mut traits);
random_line_split
mod.rs
use crate::{config::WorkMode, env::Env, file_saver::*}; use std::path::Path; mod alias; mod child_properties; mod constants; mod doc; mod enums; mod flags; pub mod function; mod function_body_chunk; mod functions; mod general; mod object; mod objects; mod parameter; mod properties; mod property_body; mod record; mod records; mod return_value; mod signal; mod signal_body; mod sys; mod trait_impls; mod trampoline; mod trampoline_from_glib; mod trampoline_to_glib; pub mod translate_from_glib; pub mod translate_to_glib; pub fn generate(env: &Env) { match env.config.work_mode { WorkMode::Normal => normal_generate(env), WorkMode::Sys => sys::generate(env), WorkMode::Doc => doc::generate(env), WorkMode::DisplayNotBound => {} } } fn normal_generate(env: &Env) { let mut mod_rs: Vec<String> = Vec::new(); let mut traits: Vec<String> = Vec::new(); let root_path = env.config.auto_path.as_path(); generate_single_version_file(env); objects::generate(env, root_path, &mut mod_rs, &mut traits); records::generate(env, root_path, &mut mod_rs); enums::generate(env, root_path, &mut mod_rs); flags::generate(env, root_path, &mut mod_rs); alias::generate(env, root_path, &mut mod_rs); functions::generate(env, root_path, &mut mod_rs); constants::generate(env, root_path, &mut mod_rs); generate_mod_rs(env, root_path, &mod_rs, &traits); } pub fn generate_mod_rs(env: &Env, root_path: &Path, mod_rs: &[String], traits: &[String]) { let path = root_path.join("mod.rs"); save_to_file(path, env.config.make_backup, |w| { general::start_comments(w, &env.config)?; general::write_vec(w, mod_rs)?; writeln!(w)?; writeln!(w, "#[doc(hidden)]")?; writeln!(w, "pub mod traits {{")?; general::write_vec(w, traits)?; writeln!(w, "}}") }); } pub fn
(env: &Env) { if let Some(ref path) = env.config.single_version_file { save_to_file(path, env.config.make_backup, |w| { general::single_version_file(w, &env.config) }); } }
generate_single_version_file
identifier_name
mod.rs
use crate::{config::WorkMode, env::Env, file_saver::*}; use std::path::Path; mod alias; mod child_properties; mod constants; mod doc; mod enums; mod flags; pub mod function; mod function_body_chunk; mod functions; mod general; mod object; mod objects; mod parameter; mod properties; mod property_body; mod record; mod records; mod return_value; mod signal; mod signal_body; mod sys; mod trait_impls; mod trampoline; mod trampoline_from_glib; mod trampoline_to_glib; pub mod translate_from_glib; pub mod translate_to_glib; pub fn generate(env: &Env) { match env.config.work_mode { WorkMode::Normal => normal_generate(env), WorkMode::Sys => sys::generate(env), WorkMode::Doc => doc::generate(env), WorkMode::DisplayNotBound => {} } } fn normal_generate(env: &Env)
pub fn generate_mod_rs(env: &Env, root_path: &Path, mod_rs: &[String], traits: &[String]) { let path = root_path.join("mod.rs"); save_to_file(path, env.config.make_backup, |w| { general::start_comments(w, &env.config)?; general::write_vec(w, mod_rs)?; writeln!(w)?; writeln!(w, "#[doc(hidden)]")?; writeln!(w, "pub mod traits {{")?; general::write_vec(w, traits)?; writeln!(w, "}}") }); } pub fn generate_single_version_file(env: &Env) { if let Some(ref path) = env.config.single_version_file { save_to_file(path, env.config.make_backup, |w| { general::single_version_file(w, &env.config) }); } }
{ let mut mod_rs: Vec<String> = Vec::new(); let mut traits: Vec<String> = Vec::new(); let root_path = env.config.auto_path.as_path(); generate_single_version_file(env); objects::generate(env, root_path, &mut mod_rs, &mut traits); records::generate(env, root_path, &mut mod_rs); enums::generate(env, root_path, &mut mod_rs); flags::generate(env, root_path, &mut mod_rs); alias::generate(env, root_path, &mut mod_rs); functions::generate(env, root_path, &mut mod_rs); constants::generate(env, root_path, &mut mod_rs); generate_mod_rs(env, root_path, &mod_rs, &traits); }
identifier_body
mod.rs
use crate::{config::WorkMode, env::Env, file_saver::*}; use std::path::Path; mod alias; mod child_properties; mod constants; mod doc; mod enums; mod flags; pub mod function; mod function_body_chunk; mod functions; mod general; mod object; mod objects; mod parameter; mod properties; mod property_body; mod record; mod records; mod return_value; mod signal; mod signal_body; mod sys; mod trait_impls; mod trampoline; mod trampoline_from_glib; mod trampoline_to_glib; pub mod translate_from_glib; pub mod translate_to_glib; pub fn generate(env: &Env) { match env.config.work_mode { WorkMode::Normal => normal_generate(env), WorkMode::Sys => sys::generate(env), WorkMode::Doc => doc::generate(env), WorkMode::DisplayNotBound => {} } } fn normal_generate(env: &Env) { let mut mod_rs: Vec<String> = Vec::new(); let mut traits: Vec<String> = Vec::new(); let root_path = env.config.auto_path.as_path(); generate_single_version_file(env); objects::generate(env, root_path, &mut mod_rs, &mut traits); records::generate(env, root_path, &mut mod_rs); enums::generate(env, root_path, &mut mod_rs); flags::generate(env, root_path, &mut mod_rs); alias::generate(env, root_path, &mut mod_rs); functions::generate(env, root_path, &mut mod_rs); constants::generate(env, root_path, &mut mod_rs); generate_mod_rs(env, root_path, &mod_rs, &traits); } pub fn generate_mod_rs(env: &Env, root_path: &Path, mod_rs: &[String], traits: &[String]) { let path = root_path.join("mod.rs"); save_to_file(path, env.config.make_backup, |w| { general::start_comments(w, &env.config)?; general::write_vec(w, mod_rs)?; writeln!(w)?; writeln!(w, "#[doc(hidden)]")?; writeln!(w, "pub mod traits {{")?; general::write_vec(w, traits)?; writeln!(w, "}}") }); } pub fn generate_single_version_file(env: &Env) { if let Some(ref path) = env.config.single_version_file
}
{ save_to_file(path, env.config.make_backup, |w| { general::single_version_file(w, &env.config) }); }
conditional_block
portal.rs
use app; use components::*; use specs::Join; use specs; use levels; #[derive(Clone)] pub struct Portal { destination: levels::Level, } impl specs::Component for Portal { type Storage = specs::VecStorage<Self>; } impl Portal { pub fn new(destination: levels::Level) -> Self
} pub struct PortalSystem; impl specs::System<app::UpdateContext> for PortalSystem { fn run(&mut self, arg: specs::RunArg, context: app::UpdateContext) { let (grid_squares, players, states, portals, entities) = arg.fetch(|world| { ( world.read::<GridSquare>(), world.read::<PlayerControl>(), world.read::<PhysicState>(), world.read::<Portal>(), world.entities() ) }); let mut player_pos = None; for (_, state) in (&players, &states).iter() { player_pos = Some(state.position); break; } if let Some(player_pos) = player_pos { for (portal,entity) in (&portals, &entities).iter() { let pos = grid_squares.get(entity).expect("portal expect grid square component").position; if (player_pos[0] - pos[0]).powi(2) + (player_pos[1] - pos[1]).powi(2) < 0.01 { context.control_tx.send(app::Control::GotoLevel(portal.destination.clone())).unwrap(); } } } } }
{ Portal { destination: destination, } }
identifier_body
portal.rs
use app; use components::*; use specs::Join; use specs; use levels; #[derive(Clone)] pub struct Portal { destination: levels::Level, } impl specs::Component for Portal { type Storage = specs::VecStorage<Self>; } impl Portal { pub fn new(destination: levels::Level) -> Self { Portal { destination: destination, } } } pub struct PortalSystem; impl specs::System<app::UpdateContext> for PortalSystem { fn run(&mut self, arg: specs::RunArg, context: app::UpdateContext) { let (grid_squares, players, states, portals, entities) = arg.fetch(|world| { ( world.read::<GridSquare>(), world.read::<PlayerControl>(), world.read::<PhysicState>(), world.read::<Portal>(), world.entities() ) }); let mut player_pos = None; for (_, state) in (&players, &states).iter() { player_pos = Some(state.position); break; } if let Some(player_pos) = player_pos { for (portal,entity) in (&portals, &entities).iter() { let pos = grid_squares.get(entity).expect("portal expect grid square component").position; if (player_pos[0] - pos[0]).powi(2) + (player_pos[1] - pos[1]).powi(2) < 0.01
} } } }
{ context.control_tx.send(app::Control::GotoLevel(portal.destination.clone())).unwrap(); }
conditional_block
portal.rs
use app; use components::*; use specs::Join; use specs; use levels; #[derive(Clone)] pub struct Portal { destination: levels::Level, } impl specs::Component for Portal { type Storage = specs::VecStorage<Self>; } impl Portal { pub fn new(destination: levels::Level) -> Self { Portal { destination: destination, } } } pub struct PortalSystem; impl specs::System<app::UpdateContext> for PortalSystem { fn run(&mut self, arg: specs::RunArg, context: app::UpdateContext) { let (grid_squares, players, states, portals, entities) = arg.fetch(|world| { ( world.read::<GridSquare>(), world.read::<PlayerControl>(), world.read::<PhysicState>(), world.read::<Portal>(), world.entities() ) }); let mut player_pos = None; for (_, state) in (&players, &states).iter() { player_pos = Some(state.position); break; } if let Some(player_pos) = player_pos {
if (player_pos[0] - pos[0]).powi(2) + (player_pos[1] - pos[1]).powi(2) < 0.01 { context.control_tx.send(app::Control::GotoLevel(portal.destination.clone())).unwrap(); } } } } }
for (portal,entity) in (&portals, &entities).iter() { let pos = grid_squares.get(entity).expect("portal expect grid square component").position;
random_line_split
portal.rs
use app; use components::*; use specs::Join; use specs; use levels; #[derive(Clone)] pub struct
{ destination: levels::Level, } impl specs::Component for Portal { type Storage = specs::VecStorage<Self>; } impl Portal { pub fn new(destination: levels::Level) -> Self { Portal { destination: destination, } } } pub struct PortalSystem; impl specs::System<app::UpdateContext> for PortalSystem { fn run(&mut self, arg: specs::RunArg, context: app::UpdateContext) { let (grid_squares, players, states, portals, entities) = arg.fetch(|world| { ( world.read::<GridSquare>(), world.read::<PlayerControl>(), world.read::<PhysicState>(), world.read::<Portal>(), world.entities() ) }); let mut player_pos = None; for (_, state) in (&players, &states).iter() { player_pos = Some(state.position); break; } if let Some(player_pos) = player_pos { for (portal,entity) in (&portals, &entities).iter() { let pos = grid_squares.get(entity).expect("portal expect grid square component").position; if (player_pos[0] - pos[0]).powi(2) + (player_pos[1] - pos[1]).powi(2) < 0.01 { context.control_tx.send(app::Control::GotoLevel(portal.destination.clone())).unwrap(); } } } } }
Portal
identifier_name
base64.rs
// Copyright 2012-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. //! Base64 binary-to-text encoding use std::str; use std::fmt; /// Available encoding character sets pub enum CharacterSet { /// The standard character set (uses `+` and `/`) Standard, /// The URL safe character set (uses `-` and `_`) UrlSafe } /// Contains configuration parameters for `to_base64`. pub struct Config { /// Character set to use pub char_set: CharacterSet, /// True to pad output with `=` characters pub pad: bool, /// `Some(len)` to wrap lines at `len`, `None` to disable line wrapping pub line_length: Option<uint> } /// Configuration for RFC 4648 standard base64 encoding pub static STANDARD: Config = Config {char_set: Standard, pad: true, line_length: None}; /// Configuration for RFC 4648 base64url encoding pub static URL_SAFE: Config = Config {char_set: UrlSafe, pad: false, line_length: None}; /// Configuration for RFC 2045 MIME base64 encoding pub static MIME: Config = Config {char_set: Standard, pad: true, line_length: Some(76)}; static STANDARD_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789+/"); static URLSAFE_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789-_"); /// A trait for converting a value to base64 encoding. pub trait ToBase64 { /// Converts the value of `self` to a base64 value following the specified /// format configuration, returning the owned string. fn to_base64(&self, config: Config) -> StrBuf; } impl<'a> ToBase64 for &'a [u8] { /** * Turn a vector of `u8` bytes into a base64 string. * * # Example * * ```rust * extern crate serialize; * use serialize::base64::{ToBase64, STANDARD}; * * fn main () { * let str = [52,32].to_base64(STANDARD); * println!("base 64 output: {}", str); * } * ``` */ fn to_base64(&self, config: Config) -> StrBuf { let bytes = match config.char_set { Standard => STANDARD_CHARS, UrlSafe => URLSAFE_CHARS }; let mut v = Vec::new(); let mut i = 0; let mut cur_length = 0; let len = self.len(); while i < len - (len % 3) { match config.line_length { Some(line_length) => if cur_length >= line_length { v.push('\r' as u8); v.push('\n' as u8); cur_length = 0; }, None => () } let n = (self[i] as u32) << 16 | (self[i + 1] as u32) << 8 | (self[i + 2] as u32); // This 24-bit number gets separated into four 6-bit numbers. v.push(bytes[((n >> 18) & 63) as uint]); v.push(bytes[((n >> 12) & 63) as uint]); v.push(bytes[((n >> 6 ) & 63) as uint]); v.push(bytes[(n & 63) as uint]); cur_length += 4; i += 3; } if len % 3!= 0 { match config.line_length { Some(line_length) => if cur_length >= line_length { v.push('\r' as u8); v.push('\n' as u8); }, None => () } } // Heh, would be cool if we knew this was exhaustive // (the dream of bounded integer types) match len % 3 { 0 => (), 1 => { let n = (self[i] as u32) << 16; v.push(bytes[((n >> 18) & 63) as uint]); v.push(bytes[((n >> 12) & 63) as uint]); if config.pad { v.push('=' as u8); v.push('=' as u8); } } 2 => { let n = (self[i] as u32) << 16 | (self[i + 1u] as u32) << 8; v.push(bytes[((n >> 18) & 63) as uint]); v.push(bytes[((n >> 12) & 63) as uint]); v.push(bytes[((n >> 6 ) & 63) as uint]); if config.pad { v.push('=' as u8); } } _ => fail!("Algebra is broken, please alert the math police") } unsafe { str::raw::from_utf8(v.as_slice()).to_strbuf() } } } /// A trait for converting from base64 encoded values. pub trait FromBase64 { /// Converts the value of `self`, interpreted as base64 encoded data, into /// an owned vector of bytes, returning the vector. fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error>; } /// Errors that can occur when decoding a base64 encoded string pub enum FromBase64Error { /// The input contained a character not part of the base64 format InvalidBase64Character(char, uint), /// The input had an invalid length InvalidBase64Length, } impl fmt::Show for FromBase64Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { InvalidBase64Character(ch, idx) => write!(f, "Invalid character '{}' at position {}", ch, idx), InvalidBase64Length => write!(f, "Invalid length"), } } } impl<'a> FromBase64 for &'a str { /** * Convert any base64 encoded string (literal, `@`, `&`, or `~`) * to the byte values it encodes. * * You can use the `StrBuf::from_utf8` function in `std::strbuf` to turn a * `Vec<u8>` into a string with characters corresponding to those values.
* # Example * * This converts a string literal to base64 and back. * * ```rust * extern crate serialize; * use serialize::base64::{ToBase64, FromBase64, STANDARD}; * * fn main () { * let hello_str = bytes!("Hello, World").to_base64(STANDARD); * println!("base64 output: {}", hello_str); * let res = hello_str.as_slice().from_base64(); * if res.is_ok() { * let opt_bytes = StrBuf::from_utf8(res.unwrap()); * if opt_bytes.is_ok() { * println!("decoded from base64: {}", opt_bytes.unwrap()); * } * } * } * ``` */ fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> { let mut r = Vec::new(); let mut buf: u32 = 0; let mut modulus = 0; let mut it = self.bytes().enumerate(); for (idx, byte) in it { let val = byte as u32; match byte as char { 'A'..'Z' => buf |= val - 0x41, 'a'..'z' => buf |= val - 0x47, '0'..'9' => buf |= val + 0x04, '+'|'-' => buf |= 0x3E, '/'|'_' => buf |= 0x3F, '\r'|'\n' => continue, '=' => break, _ => return Err(InvalidBase64Character(self.char_at(idx), idx)), } buf <<= 6; modulus += 1; if modulus == 4 { modulus = 0; r.push((buf >> 22) as u8); r.push((buf >> 14) as u8); r.push((buf >> 6 ) as u8); } } for (idx, byte) in it { match byte as char { '='|'\r'|'\n' => continue, _ => return Err(InvalidBase64Character(self.char_at(idx), idx)), } } match modulus { 2 => { r.push((buf >> 10) as u8); } 3 => { r.push((buf >> 16) as u8); r.push((buf >> 8 ) as u8); } 0 => (), _ => return Err(InvalidBase64Length), } Ok(r) } } #[cfg(test)] mod tests { extern crate test; extern crate rand; use self::test::Bencher; use base64::{Config, FromBase64, ToBase64, STANDARD, URL_SAFE}; #[test] fn test_to_base64_basic() { assert_eq!("".as_bytes().to_base64(STANDARD), "".to_strbuf()); assert_eq!("f".as_bytes().to_base64(STANDARD), "Zg==".to_strbuf()); assert_eq!("fo".as_bytes().to_base64(STANDARD), "Zm8=".to_strbuf()); assert_eq!("foo".as_bytes().to_base64(STANDARD), "Zm9v".to_strbuf()); assert_eq!("foob".as_bytes().to_base64(STANDARD), "Zm9vYg==".to_strbuf()); assert_eq!("fooba".as_bytes().to_base64(STANDARD), "Zm9vYmE=".to_strbuf()); assert_eq!("foobar".as_bytes().to_base64(STANDARD), "Zm9vYmFy".to_strbuf()); } #[test] fn test_to_base64_line_break() { assert!(![0u8,..1000].to_base64(Config {line_length: None,..STANDARD}) .as_slice() .contains("\r\n")); assert_eq!("foobar".as_bytes().to_base64(Config {line_length: Some(4), ..STANDARD}), "Zm9v\r\nYmFy".to_strbuf()); } #[test] fn test_to_base64_padding() { assert_eq!("f".as_bytes().to_base64(Config {pad: false,..STANDARD}), "Zg".to_strbuf()); assert_eq!("fo".as_bytes().to_base64(Config {pad: false,..STANDARD}), "Zm8".to_strbuf()); } #[test] fn test_to_base64_url_safe() { assert_eq!([251, 255].to_base64(URL_SAFE), "-_8".to_strbuf()); assert_eq!([251, 255].to_base64(STANDARD), "+/8=".to_strbuf()); } #[test] fn test_from_base64_basic() { assert_eq!("".from_base64().unwrap().as_slice(), "".as_bytes()); assert_eq!("Zg==".from_base64().unwrap().as_slice(), "f".as_bytes()); assert_eq!("Zm8=".from_base64().unwrap().as_slice(), "fo".as_bytes()); assert_eq!("Zm9v".from_base64().unwrap().as_slice(), "foo".as_bytes()); assert_eq!("Zm9vYg==".from_base64().unwrap().as_slice(), "foob".as_bytes()); assert_eq!("Zm9vYmE=".from_base64().unwrap().as_slice(), "fooba".as_bytes()); assert_eq!("Zm9vYmFy".from_base64().unwrap().as_slice(), "foobar".as_bytes()); } #[test] fn test_from_base64_newlines() { assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap().as_slice(), "foobar".as_bytes()); assert_eq!("Zm9vYg==\r\n".from_base64().unwrap().as_slice(), "foob".as_bytes()); } #[test] fn test_from_base64_urlsafe() { assert_eq!("-_8".from_base64().unwrap(), "+/8=".from_base64().unwrap()); } #[test] fn test_from_base64_invalid_char() { assert!("Zm$=".from_base64().is_err()) assert!("Zg==$".from_base64().is_err()); } #[test] fn test_from_base64_invalid_padding() { assert!("Z===".from_base64().is_err()); } #[test] fn test_base64_random() { use self::rand::{task_rng, random, Rng}; for _ in range(0, 1000) { let times = task_rng().gen_range(1u, 100); let v = Vec::from_fn(times, |_| random::<u8>()); assert_eq!(v.as_slice() .to_base64(STANDARD) .as_slice() .from_base64() .unwrap() .as_slice(), v.as_slice()); } } #[bench] pub fn bench_to_base64(b: &mut Bencher) { let s = "γ‚€γƒ­γƒγƒ‹γƒ›γƒ˜γƒˆ チγƒͺγƒŒγƒ«γƒ² ワカヨタレソ γƒ„γƒγƒŠγƒ©γƒ  \ γ‚¦γƒ°γƒŽγ‚ͺγ‚―γƒ€γƒž ケフコエテ γ‚’γ‚΅γ‚­γƒ¦γƒ‘γƒŸγ‚· ヱヒヒセスン"; b.iter(|| { s.as_bytes().to_base64(STANDARD); }); b.bytes = s.len() as u64; } #[bench] pub fn bench_from_base64(b: &mut Bencher) { let s = "γ‚€γƒ­γƒγƒ‹γƒ›γƒ˜γƒˆ チγƒͺγƒŒγƒ«γƒ² ワカヨタレソ γƒ„γƒγƒŠγƒ©γƒ  \ γ‚¦γƒ°γƒŽγ‚ͺγ‚―γƒ€γƒž ケフコエテ γ‚’γ‚΅γ‚­γƒ¦γƒ‘γƒŸγ‚· ヱヒヒセスン"; let sb = s.as_bytes().to_base64(STANDARD); b.iter(|| { sb.as_slice().from_base64().unwrap(); }); b.bytes = sb.len() as u64; } }
*
random_line_split
base64.rs
// Copyright 2012-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. //! Base64 binary-to-text encoding use std::str; use std::fmt; /// Available encoding character sets pub enum CharacterSet { /// The standard character set (uses `+` and `/`) Standard, /// The URL safe character set (uses `-` and `_`) UrlSafe } /// Contains configuration parameters for `to_base64`. pub struct Config { /// Character set to use pub char_set: CharacterSet, /// True to pad output with `=` characters pub pad: bool, /// `Some(len)` to wrap lines at `len`, `None` to disable line wrapping pub line_length: Option<uint> } /// Configuration for RFC 4648 standard base64 encoding pub static STANDARD: Config = Config {char_set: Standard, pad: true, line_length: None}; /// Configuration for RFC 4648 base64url encoding pub static URL_SAFE: Config = Config {char_set: UrlSafe, pad: false, line_length: None}; /// Configuration for RFC 2045 MIME base64 encoding pub static MIME: Config = Config {char_set: Standard, pad: true, line_length: Some(76)}; static STANDARD_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789+/"); static URLSAFE_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789-_"); /// A trait for converting a value to base64 encoding. pub trait ToBase64 { /// Converts the value of `self` to a base64 value following the specified /// format configuration, returning the owned string. fn to_base64(&self, config: Config) -> StrBuf; } impl<'a> ToBase64 for &'a [u8] { /** * Turn a vector of `u8` bytes into a base64 string. * * # Example * * ```rust * extern crate serialize; * use serialize::base64::{ToBase64, STANDARD}; * * fn main () { * let str = [52,32].to_base64(STANDARD); * println!("base 64 output: {}", str); * } * ``` */ fn to_base64(&self, config: Config) -> StrBuf { let bytes = match config.char_set { Standard => STANDARD_CHARS, UrlSafe => URLSAFE_CHARS }; let mut v = Vec::new(); let mut i = 0; let mut cur_length = 0; let len = self.len(); while i < len - (len % 3) { match config.line_length { Some(line_length) => if cur_length >= line_length { v.push('\r' as u8); v.push('\n' as u8); cur_length = 0; }, None => () } let n = (self[i] as u32) << 16 | (self[i + 1] as u32) << 8 | (self[i + 2] as u32); // This 24-bit number gets separated into four 6-bit numbers. v.push(bytes[((n >> 18) & 63) as uint]); v.push(bytes[((n >> 12) & 63) as uint]); v.push(bytes[((n >> 6 ) & 63) as uint]); v.push(bytes[(n & 63) as uint]); cur_length += 4; i += 3; } if len % 3!= 0 { match config.line_length { Some(line_length) => if cur_length >= line_length { v.push('\r' as u8); v.push('\n' as u8); }, None => () } } // Heh, would be cool if we knew this was exhaustive // (the dream of bounded integer types) match len % 3 { 0 => (), 1 => { let n = (self[i] as u32) << 16; v.push(bytes[((n >> 18) & 63) as uint]); v.push(bytes[((n >> 12) & 63) as uint]); if config.pad { v.push('=' as u8); v.push('=' as u8); } } 2 => { let n = (self[i] as u32) << 16 | (self[i + 1u] as u32) << 8; v.push(bytes[((n >> 18) & 63) as uint]); v.push(bytes[((n >> 12) & 63) as uint]); v.push(bytes[((n >> 6 ) & 63) as uint]); if config.pad { v.push('=' as u8); } } _ => fail!("Algebra is broken, please alert the math police") } unsafe { str::raw::from_utf8(v.as_slice()).to_strbuf() } } } /// A trait for converting from base64 encoded values. pub trait FromBase64 { /// Converts the value of `self`, interpreted as base64 encoded data, into /// an owned vector of bytes, returning the vector. fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error>; } /// Errors that can occur when decoding a base64 encoded string pub enum FromBase64Error { /// The input contained a character not part of the base64 format InvalidBase64Character(char, uint), /// The input had an invalid length InvalidBase64Length, } impl fmt::Show for FromBase64Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { InvalidBase64Character(ch, idx) => write!(f, "Invalid character '{}' at position {}", ch, idx), InvalidBase64Length => write!(f, "Invalid length"), } } } impl<'a> FromBase64 for &'a str { /** * Convert any base64 encoded string (literal, `@`, `&`, or `~`) * to the byte values it encodes. * * You can use the `StrBuf::from_utf8` function in `std::strbuf` to turn a * `Vec<u8>` into a string with characters corresponding to those values. * * # Example * * This converts a string literal to base64 and back. * * ```rust * extern crate serialize; * use serialize::base64::{ToBase64, FromBase64, STANDARD}; * * fn main () { * let hello_str = bytes!("Hello, World").to_base64(STANDARD); * println!("base64 output: {}", hello_str); * let res = hello_str.as_slice().from_base64(); * if res.is_ok() { * let opt_bytes = StrBuf::from_utf8(res.unwrap()); * if opt_bytes.is_ok() { * println!("decoded from base64: {}", opt_bytes.unwrap()); * } * } * } * ``` */ fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> { let mut r = Vec::new(); let mut buf: u32 = 0; let mut modulus = 0; let mut it = self.bytes().enumerate(); for (idx, byte) in it { let val = byte as u32; match byte as char { 'A'..'Z' => buf |= val - 0x41, 'a'..'z' => buf |= val - 0x47, '0'..'9' => buf |= val + 0x04, '+'|'-' => buf |= 0x3E, '/'|'_' => buf |= 0x3F, '\r'|'\n' => continue, '=' => break, _ => return Err(InvalidBase64Character(self.char_at(idx), idx)), } buf <<= 6; modulus += 1; if modulus == 4 { modulus = 0; r.push((buf >> 22) as u8); r.push((buf >> 14) as u8); r.push((buf >> 6 ) as u8); } } for (idx, byte) in it { match byte as char { '='|'\r'|'\n' => continue, _ => return Err(InvalidBase64Character(self.char_at(idx), idx)), } } match modulus { 2 => { r.push((buf >> 10) as u8); } 3 => { r.push((buf >> 16) as u8); r.push((buf >> 8 ) as u8); } 0 => (), _ => return Err(InvalidBase64Length), } Ok(r) } } #[cfg(test)] mod tests { extern crate test; extern crate rand; use self::test::Bencher; use base64::{Config, FromBase64, ToBase64, STANDARD, URL_SAFE}; #[test] fn test_to_base64_basic() { assert_eq!("".as_bytes().to_base64(STANDARD), "".to_strbuf()); assert_eq!("f".as_bytes().to_base64(STANDARD), "Zg==".to_strbuf()); assert_eq!("fo".as_bytes().to_base64(STANDARD), "Zm8=".to_strbuf()); assert_eq!("foo".as_bytes().to_base64(STANDARD), "Zm9v".to_strbuf()); assert_eq!("foob".as_bytes().to_base64(STANDARD), "Zm9vYg==".to_strbuf()); assert_eq!("fooba".as_bytes().to_base64(STANDARD), "Zm9vYmE=".to_strbuf()); assert_eq!("foobar".as_bytes().to_base64(STANDARD), "Zm9vYmFy".to_strbuf()); } #[test] fn test_to_base64_line_break() { assert!(![0u8,..1000].to_base64(Config {line_length: None,..STANDARD}) .as_slice() .contains("\r\n")); assert_eq!("foobar".as_bytes().to_base64(Config {line_length: Some(4), ..STANDARD}), "Zm9v\r\nYmFy".to_strbuf()); } #[test] fn test_to_base64_padding()
#[test] fn test_to_base64_url_safe() { assert_eq!([251, 255].to_base64(URL_SAFE), "-_8".to_strbuf()); assert_eq!([251, 255].to_base64(STANDARD), "+/8=".to_strbuf()); } #[test] fn test_from_base64_basic() { assert_eq!("".from_base64().unwrap().as_slice(), "".as_bytes()); assert_eq!("Zg==".from_base64().unwrap().as_slice(), "f".as_bytes()); assert_eq!("Zm8=".from_base64().unwrap().as_slice(), "fo".as_bytes()); assert_eq!("Zm9v".from_base64().unwrap().as_slice(), "foo".as_bytes()); assert_eq!("Zm9vYg==".from_base64().unwrap().as_slice(), "foob".as_bytes()); assert_eq!("Zm9vYmE=".from_base64().unwrap().as_slice(), "fooba".as_bytes()); assert_eq!("Zm9vYmFy".from_base64().unwrap().as_slice(), "foobar".as_bytes()); } #[test] fn test_from_base64_newlines() { assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap().as_slice(), "foobar".as_bytes()); assert_eq!("Zm9vYg==\r\n".from_base64().unwrap().as_slice(), "foob".as_bytes()); } #[test] fn test_from_base64_urlsafe() { assert_eq!("-_8".from_base64().unwrap(), "+/8=".from_base64().unwrap()); } #[test] fn test_from_base64_invalid_char() { assert!("Zm$=".from_base64().is_err()) assert!("Zg==$".from_base64().is_err()); } #[test] fn test_from_base64_invalid_padding() { assert!("Z===".from_base64().is_err()); } #[test] fn test_base64_random() { use self::rand::{task_rng, random, Rng}; for _ in range(0, 1000) { let times = task_rng().gen_range(1u, 100); let v = Vec::from_fn(times, |_| random::<u8>()); assert_eq!(v.as_slice() .to_base64(STANDARD) .as_slice() .from_base64() .unwrap() .as_slice(), v.as_slice()); } } #[bench] pub fn bench_to_base64(b: &mut Bencher) { let s = "γ‚€γƒ­γƒγƒ‹γƒ›γƒ˜γƒˆ チγƒͺγƒŒγƒ«γƒ² ワカヨタレソ γƒ„γƒγƒŠγƒ©γƒ  \ γ‚¦γƒ°γƒŽγ‚ͺγ‚―γƒ€γƒž ケフコエテ γ‚’γ‚΅γ‚­γƒ¦γƒ‘γƒŸγ‚· ヱヒヒセスン"; b.iter(|| { s.as_bytes().to_base64(STANDARD); }); b.bytes = s.len() as u64; } #[bench] pub fn bench_from_base64(b: &mut Bencher) { let s = "γ‚€γƒ­γƒγƒ‹γƒ›γƒ˜γƒˆ チγƒͺγƒŒγƒ«γƒ² ワカヨタレソ γƒ„γƒγƒŠγƒ©γƒ  \ γ‚¦γƒ°γƒŽγ‚ͺγ‚―γƒ€γƒž ケフコエテ γ‚’γ‚΅γ‚­γƒ¦γƒ‘γƒŸγ‚· ヱヒヒセスン"; let sb = s.as_bytes().to_base64(STANDARD); b.iter(|| { sb.as_slice().from_base64().unwrap(); }); b.bytes = sb.len() as u64; } }
{ assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zg".to_strbuf()); assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zm8".to_strbuf()); }
identifier_body
base64.rs
// Copyright 2012-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. //! Base64 binary-to-text encoding use std::str; use std::fmt; /// Available encoding character sets pub enum CharacterSet { /// The standard character set (uses `+` and `/`) Standard, /// The URL safe character set (uses `-` and `_`) UrlSafe } /// Contains configuration parameters for `to_base64`. pub struct Config { /// Character set to use pub char_set: CharacterSet, /// True to pad output with `=` characters pub pad: bool, /// `Some(len)` to wrap lines at `len`, `None` to disable line wrapping pub line_length: Option<uint> } /// Configuration for RFC 4648 standard base64 encoding pub static STANDARD: Config = Config {char_set: Standard, pad: true, line_length: None}; /// Configuration for RFC 4648 base64url encoding pub static URL_SAFE: Config = Config {char_set: UrlSafe, pad: false, line_length: None}; /// Configuration for RFC 2045 MIME base64 encoding pub static MIME: Config = Config {char_set: Standard, pad: true, line_length: Some(76)}; static STANDARD_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789+/"); static URLSAFE_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789-_"); /// A trait for converting a value to base64 encoding. pub trait ToBase64 { /// Converts the value of `self` to a base64 value following the specified /// format configuration, returning the owned string. fn to_base64(&self, config: Config) -> StrBuf; } impl<'a> ToBase64 for &'a [u8] { /** * Turn a vector of `u8` bytes into a base64 string. * * # Example * * ```rust * extern crate serialize; * use serialize::base64::{ToBase64, STANDARD}; * * fn main () { * let str = [52,32].to_base64(STANDARD); * println!("base 64 output: {}", str); * } * ``` */ fn to_base64(&self, config: Config) -> StrBuf { let bytes = match config.char_set { Standard => STANDARD_CHARS, UrlSafe => URLSAFE_CHARS }; let mut v = Vec::new(); let mut i = 0; let mut cur_length = 0; let len = self.len(); while i < len - (len % 3) { match config.line_length { Some(line_length) => if cur_length >= line_length { v.push('\r' as u8); v.push('\n' as u8); cur_length = 0; }, None => () } let n = (self[i] as u32) << 16 | (self[i + 1] as u32) << 8 | (self[i + 2] as u32); // This 24-bit number gets separated into four 6-bit numbers. v.push(bytes[((n >> 18) & 63) as uint]); v.push(bytes[((n >> 12) & 63) as uint]); v.push(bytes[((n >> 6 ) & 63) as uint]); v.push(bytes[(n & 63) as uint]); cur_length += 4; i += 3; } if len % 3!= 0 { match config.line_length { Some(line_length) => if cur_length >= line_length { v.push('\r' as u8); v.push('\n' as u8); }, None => () } } // Heh, would be cool if we knew this was exhaustive // (the dream of bounded integer types) match len % 3 { 0 => (), 1 => { let n = (self[i] as u32) << 16; v.push(bytes[((n >> 18) & 63) as uint]); v.push(bytes[((n >> 12) & 63) as uint]); if config.pad { v.push('=' as u8); v.push('=' as u8); } } 2 => { let n = (self[i] as u32) << 16 | (self[i + 1u] as u32) << 8; v.push(bytes[((n >> 18) & 63) as uint]); v.push(bytes[((n >> 12) & 63) as uint]); v.push(bytes[((n >> 6 ) & 63) as uint]); if config.pad { v.push('=' as u8); } } _ => fail!("Algebra is broken, please alert the math police") } unsafe { str::raw::from_utf8(v.as_slice()).to_strbuf() } } } /// A trait for converting from base64 encoded values. pub trait FromBase64 { /// Converts the value of `self`, interpreted as base64 encoded data, into /// an owned vector of bytes, returning the vector. fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error>; } /// Errors that can occur when decoding a base64 encoded string pub enum FromBase64Error { /// The input contained a character not part of the base64 format InvalidBase64Character(char, uint), /// The input had an invalid length InvalidBase64Length, } impl fmt::Show for FromBase64Error { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { InvalidBase64Character(ch, idx) => write!(f, "Invalid character '{}' at position {}", ch, idx), InvalidBase64Length => write!(f, "Invalid length"), } } } impl<'a> FromBase64 for &'a str { /** * Convert any base64 encoded string (literal, `@`, `&`, or `~`) * to the byte values it encodes. * * You can use the `StrBuf::from_utf8` function in `std::strbuf` to turn a * `Vec<u8>` into a string with characters corresponding to those values. * * # Example * * This converts a string literal to base64 and back. * * ```rust * extern crate serialize; * use serialize::base64::{ToBase64, FromBase64, STANDARD}; * * fn main () { * let hello_str = bytes!("Hello, World").to_base64(STANDARD); * println!("base64 output: {}", hello_str); * let res = hello_str.as_slice().from_base64(); * if res.is_ok() { * let opt_bytes = StrBuf::from_utf8(res.unwrap()); * if opt_bytes.is_ok() { * println!("decoded from base64: {}", opt_bytes.unwrap()); * } * } * } * ``` */ fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> { let mut r = Vec::new(); let mut buf: u32 = 0; let mut modulus = 0; let mut it = self.bytes().enumerate(); for (idx, byte) in it { let val = byte as u32; match byte as char { 'A'..'Z' => buf |= val - 0x41, 'a'..'z' => buf |= val - 0x47, '0'..'9' => buf |= val + 0x04, '+'|'-' => buf |= 0x3E, '/'|'_' => buf |= 0x3F, '\r'|'\n' => continue, '=' => break, _ => return Err(InvalidBase64Character(self.char_at(idx), idx)), } buf <<= 6; modulus += 1; if modulus == 4 { modulus = 0; r.push((buf >> 22) as u8); r.push((buf >> 14) as u8); r.push((buf >> 6 ) as u8); } } for (idx, byte) in it { match byte as char { '='|'\r'|'\n' => continue, _ => return Err(InvalidBase64Character(self.char_at(idx), idx)), } } match modulus { 2 => { r.push((buf >> 10) as u8); } 3 => { r.push((buf >> 16) as u8); r.push((buf >> 8 ) as u8); } 0 => (), _ => return Err(InvalidBase64Length), } Ok(r) } } #[cfg(test)] mod tests { extern crate test; extern crate rand; use self::test::Bencher; use base64::{Config, FromBase64, ToBase64, STANDARD, URL_SAFE}; #[test] fn test_to_base64_basic() { assert_eq!("".as_bytes().to_base64(STANDARD), "".to_strbuf()); assert_eq!("f".as_bytes().to_base64(STANDARD), "Zg==".to_strbuf()); assert_eq!("fo".as_bytes().to_base64(STANDARD), "Zm8=".to_strbuf()); assert_eq!("foo".as_bytes().to_base64(STANDARD), "Zm9v".to_strbuf()); assert_eq!("foob".as_bytes().to_base64(STANDARD), "Zm9vYg==".to_strbuf()); assert_eq!("fooba".as_bytes().to_base64(STANDARD), "Zm9vYmE=".to_strbuf()); assert_eq!("foobar".as_bytes().to_base64(STANDARD), "Zm9vYmFy".to_strbuf()); } #[test] fn test_to_base64_line_break() { assert!(![0u8,..1000].to_base64(Config {line_length: None,..STANDARD}) .as_slice() .contains("\r\n")); assert_eq!("foobar".as_bytes().to_base64(Config {line_length: Some(4), ..STANDARD}), "Zm9v\r\nYmFy".to_strbuf()); } #[test] fn test_to_base64_padding() { assert_eq!("f".as_bytes().to_base64(Config {pad: false,..STANDARD}), "Zg".to_strbuf()); assert_eq!("fo".as_bytes().to_base64(Config {pad: false,..STANDARD}), "Zm8".to_strbuf()); } #[test] fn test_to_base64_url_safe() { assert_eq!([251, 255].to_base64(URL_SAFE), "-_8".to_strbuf()); assert_eq!([251, 255].to_base64(STANDARD), "+/8=".to_strbuf()); } #[test] fn test_from_base64_basic() { assert_eq!("".from_base64().unwrap().as_slice(), "".as_bytes()); assert_eq!("Zg==".from_base64().unwrap().as_slice(), "f".as_bytes()); assert_eq!("Zm8=".from_base64().unwrap().as_slice(), "fo".as_bytes()); assert_eq!("Zm9v".from_base64().unwrap().as_slice(), "foo".as_bytes()); assert_eq!("Zm9vYg==".from_base64().unwrap().as_slice(), "foob".as_bytes()); assert_eq!("Zm9vYmE=".from_base64().unwrap().as_slice(), "fooba".as_bytes()); assert_eq!("Zm9vYmFy".from_base64().unwrap().as_slice(), "foobar".as_bytes()); } #[test] fn test_from_base64_newlines() { assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap().as_slice(), "foobar".as_bytes()); assert_eq!("Zm9vYg==\r\n".from_base64().unwrap().as_slice(), "foob".as_bytes()); } #[test] fn test_from_base64_urlsafe() { assert_eq!("-_8".from_base64().unwrap(), "+/8=".from_base64().unwrap()); } #[test] fn test_from_base64_invalid_char() { assert!("Zm$=".from_base64().is_err()) assert!("Zg==$".from_base64().is_err()); } #[test] fn test_from_base64_invalid_padding() { assert!("Z===".from_base64().is_err()); } #[test] fn test_base64_random() { use self::rand::{task_rng, random, Rng}; for _ in range(0, 1000) { let times = task_rng().gen_range(1u, 100); let v = Vec::from_fn(times, |_| random::<u8>()); assert_eq!(v.as_slice() .to_base64(STANDARD) .as_slice() .from_base64() .unwrap() .as_slice(), v.as_slice()); } } #[bench] pub fn bench_to_base64(b: &mut Bencher) { let s = "γ‚€γƒ­γƒγƒ‹γƒ›γƒ˜γƒˆ チγƒͺγƒŒγƒ«γƒ² ワカヨタレソ γƒ„γƒγƒŠγƒ©γƒ  \ γ‚¦γƒ°γƒŽγ‚ͺγ‚―γƒ€γƒž ケフコエテ γ‚’γ‚΅γ‚­γƒ¦γƒ‘γƒŸγ‚· ヱヒヒセスン"; b.iter(|| { s.as_bytes().to_base64(STANDARD); }); b.bytes = s.len() as u64; } #[bench] pub fn bench_from_base64(b: &mut Bencher) { let s = "γ‚€γƒ­γƒγƒ‹γƒ›γƒ˜γƒˆ チγƒͺγƒŒγƒ«γƒ² ワカヨタレソ γƒ„γƒγƒŠγƒ©γƒ  \ γ‚¦γƒ°γƒŽγ‚ͺγ‚―γƒ€γƒž ケフコエテ γ‚’γ‚΅γ‚­γƒ¦γƒ‘γƒŸγ‚· ヱヒヒセスン"; let sb = s.as_bytes().to_base64(STANDARD); b.iter(|| { sb.as_slice().from_base64().unwrap(); }); b.bytes = sb.len() as u64; } }
fmt
identifier_name
lib.rs
const u8 { self.data.borrow().as_ptr() } } /// A slower reflection-based arena that can allocate objects of any type. /// /// This arena uses `Vec<u8>` as a backing store to allocate objects from. For /// each allocated object, the arena stores a pointer to the type descriptor /// followed by the object (potentially with alignment padding after each /// element). When the arena is destroyed, it iterates through all of its /// chunks, and uses the tydesc information to trace through the objects, /// calling the destructors on them. One subtle point that needs to be /// addressed is how to handle panics while running the user provided /// initializer function. It is important to not run the destructor on /// uninitialized objects, but how to detect them is somewhat subtle. Since /// `alloc()` can be invoked recursively, it is not sufficient to simply exclude /// the most recent object. To solve this without requiring extra space, we /// use the low order bit of the tydesc pointer to encode whether the object /// it describes has been fully initialized. /// /// As an optimization, objects with destructors are stored in different chunks /// than objects without destructors. This reduces overhead when initializing /// plain-old-data (`Copy` types) and means we don't need to waste time running /// their destructors. pub struct Arena<'longer_than_self> { // The head is separated out from the list as a unbenchmarked // microoptimization, to avoid needing to case on the list to access the // head. head: RefCell<Chunk>, copy_head: RefCell<Chunk>, chunks: RefCell<Vec<Chunk>>, _marker: marker::PhantomData<*mut &'longer_than_self()>, } impl<'a> Arena<'a> { /// Allocates a new Arena with 32 bytes preallocated. pub fn new() -> Arena<'a> { Arena::new_with_size(32) } /// Allocates a new Arena with `initial_size` bytes preallocated. pub fn new_with_size(initial_size: usize) -> Arena<'a> { Arena { head: RefCell::new(chunk(initial_size, false)), copy_head: RefCell::new(chunk(initial_size, true)), chunks: RefCell::new(Vec::new()), _marker: marker::PhantomData, } } } fn chunk(size: usize, is_copy: bool) -> Chunk { Chunk { data: Rc::new(RefCell::new(Vec::with_capacity(size))), fill: Cell::new(0), is_copy: Cell::new(is_copy), } } impl<'longer_than_self> Drop for Arena<'longer_than_self> { fn drop(&mut self) { unsafe { destroy_chunk(&*self.head.borrow()); for chunk in self.chunks.borrow().iter() { if!chunk.is_copy.get() { destroy_chunk(chunk); } } } } } #[inline] fn round_up(base: usize, align: usize) -> usize { (base.checked_add(align - 1)).unwrap() &!(align - 1) } // Walk down a chunk, running the destructors for any objects stored // in it. unsafe fn destroy_chunk(chunk: &Chunk) { let mut idx = 0; let buf = chunk.as_ptr(); let fill = chunk.fill.get(); while idx < fill { let tydesc_data = buf.offset(idx as isize) as *const usize; let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data); let (size, align) = ((*tydesc).size, (*tydesc).align); let after_tydesc = idx + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}", // start, size, align, is_done); if is_done { ((*tydesc).drop_glue)(buf.offset(start as isize) as *const i8); } // Find where the next tydesc lives idx = round_up(start + size, mem::align_of::<*const TyDesc>()); } } // We encode whether the object a tydesc describes has been // initialized in the arena in the low bit of the tydesc pointer. This // is necessary in order to properly do cleanup if a panic occurs // during an initializer. #[inline] fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> usize { p as usize | (is_done as usize) } #[inline] fn un_bitpack_tydesc_ptr(p: usize) -> (*const TyDesc, bool) { ((p &!1) as *const TyDesc, p & 1 == 1) } // HACK(eddyb) TyDesc replacement using a trait object vtable. // This could be replaced in the future with a custom DST layout, // or `&'static (drop_glue, size, align)` created by a `const fn`. struct TyDesc { drop_glue: fn(*const i8), size: usize, align: usize } trait AllTypes { fn dummy(&self) { } } impl<T:?Sized> AllTypes for T { } unsafe fn get_tydesc<T>() -> *const TyDesc { use std::raw::TraitObject; let ptr = &*(1 as *const T); // Can use any trait that is implemented for all types. let obj = mem::transmute::<&AllTypes, TraitObject>(ptr); obj.vtable as *const TyDesc } impl<'longer_than_self> Arena<'longer_than_self> { fn chunk_size(&self) -> usize { self.copy_head.borrow().capacity() } // Functions for the POD part of the arena fn alloc_copy_grow(&self, n_bytes: usize, align: usize) -> *const u8 { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.copy_head.borrow().clone()); *self.copy_head.borrow_mut() = chunk((new_min_chunk_size + 1).next_power_of_two(), true); return self.alloc_copy_inner(n_bytes, align); } #[inline] fn alloc_copy_inner(&self, n_bytes: usize, align: usize) -> *const u8 { let start = round_up(self.copy_head.borrow().fill.get(), align); let end = start + n_bytes; if end > self.chunk_size() { return self.alloc_copy_grow(n_bytes, align); } let copy_head = self.copy_head.borrow(); copy_head.fill.set(end); unsafe { copy_head.as_ptr().offset(start as isize) } } #[inline] fn alloc_copy<T, F>(&self, op: F) -> &mut T where F: FnOnce() -> T { unsafe { let ptr = self.alloc_copy_inner(mem::size_of::<T>(), mem::align_of::<T>()); let ptr = ptr as *mut T; ptr::write(&mut (*ptr), op()); return &mut *ptr; } } // Functions for the non-POD part of the arena fn alloc_noncopy_grow(&self, n_bytes: usize, align: usize) -> (*const u8, *const u8) { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.head.borrow().clone()); *self.head.borrow_mut() = chunk((new_min_chunk_size + 1).next_power_of_two(), false); return self.alloc_noncopy_inner(n_bytes, align); } #[inline] fn alloc_noncopy_inner(&self, n_bytes: usize, align: usize) -> (*const u8, *const u8) { // Be careful to not maintain any `head` borrows active, because // `alloc_noncopy_grow` borrows it mutably. let (start, end, tydesc_start, head_capacity) = { let head = self.head.borrow(); let fill = head.fill.get(); let tydesc_start = fill; let after_tydesc = fill + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); let end = start + n_bytes; (start, end, tydesc_start, head.capacity()) }; if end > head_capacity { return self.alloc_noncopy_grow(n_bytes, align); } let head = self.head.borrow(); head.fill.set(round_up(end, mem::align_of::<*const TyDesc>())); unsafe { let buf = head.as_ptr(); return (buf.offset(tydesc_start as isize), buf.offset(start as isize)); } } #[inline] fn alloc_noncopy<T, F>(&self, op: F) -> &mut T where F: FnOnce() -> T { unsafe { let tydesc = get_tydesc::<T>(); let (ty_ptr, ptr) = self.alloc_noncopy_inner(mem::size_of::<T>(), mem::align_of::<T>()); let ty_ptr = ty_ptr as *mut usize; let ptr = ptr as *mut T; // Write in our tydesc along with a bit indicating that it // has *not* been initialized yet. *ty_ptr = bitpack_tydesc_ptr(tydesc, false); // Actually initialize it ptr::write(&mut(*ptr), op()); // Now that we are done, update the tydesc to indicate that // the object is there. *ty_ptr = bitpack_tydesc_ptr(tydesc, true); return &mut *ptr; } } /// Allocates a new item in the arena, using `op` to initialize the value, /// and returns a reference to it. #[inline] pub fn alloc<T:'longer_than_self, F>(&self, op: F) -> &mut T where F: FnOnce() -> T { unsafe { if intrinsics::needs_drop::<T>() { self.alloc_noncopy(op) } else { self.alloc_copy(op) } } } } #[test] fn test_arena_destructors() { let arena = Arena::new(); for i in 0..10 { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| Rc::new(i)); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| [0u8, 1u8, 2u8]); } } #[test] #[should_panic] fn test_arena_destructors_fail() { let arena = Arena::new(); // Put some stuff in the arena. for i in 0..10 { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| { Rc::new(i) }); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| { [0u8, 1, 2] }); } // Now, panic while allocating arena.alloc::<Rc<i32>, _>(|| { panic!(); }); } /// A faster arena that can hold objects of only one type. pub struct TypedArena<T> { /// A pointer to the next object to be allocated. ptr: Cell<*const T>, /// A pointer to the end of the allocated area. When this pointer is /// reached, a new chunk is allocated. end: Cell<*const T>, /// A pointer to the first arena segment. first: RefCell<*mut TypedArenaChunk<T>>, /// Marker indicating that dropping the arena causes its owned /// instances of `T` to be dropped. _own: marker::PhantomData<T>, } struct TypedArenaChunk<T> { marker: marker::PhantomData<T>, /// Pointer to the next arena segment. next: *mut TypedArenaChunk<T>, /// The number of elements that this chunk can hold. capacity: usize, // Objects follow here, suitably aligned. } fn calculate_size<T>(capacity: usize) -> usize { let mut size = mem::size_of::<TypedArenaChunk<T>>(); size = round_up(size, mem::align_of::<T>()); let elem_size = mem::size_of::<T>(); let elems_size = elem_size.checked_mul(capacity).unwrap(); size = size.checked_add(elems_size).unwrap(); size } impl<T> TypedArenaChunk<T> { #[inline] unsafe fn new(next: *mut TypedArenaChunk<T>, capacity: usize) -> *mut TypedArenaChunk<T> { let size = calculate_size::<T>(capacity); let chunk = allocate(size, mem::align_of::<TypedArenaChunk<T>>()) as *mut TypedArenaChunk<T>; if chunk.is_null() { alloc::oom() } (*chunk).next = next; (*chunk).capacity = capacity; chunk } /// Destroys this arena chunk. If the type descriptor is supplied, the /// drop glue is called; otherwise, drop glue is not called. #[inline] unsafe fn destroy(&mut self, len: usize) { // Destroy all the allocated objects. if intrinsics::needs_drop::<T>() { let mut start = self.start(); for _ in 0..len { ptr::read(start as *const T); // run the destructor on the pointer start = start.offset(mem::size_of::<T>() as isize) } } // Destroy the next chunk. let next = self.next; let size = calculate_size::<T>(self.capacity); let self_ptr: *mut TypedArenaChunk<T> = self; deallocate(self_ptr as *mut u8, size, mem::align_of::<TypedArenaChunk<T>>()); if!next.is_null() { let capacity = (*next).capacity; (*next).destroy(capacity); } } // Returns a pointer to the first allocated object. #[inline] fn start(&self) -> *const u8 { let this: *const TypedArenaChunk<T> = self; unsafe { round_up(this.offset(1) as usize, mem::align_of::<T>()) as *const u8 } } // Returns a pointer to the end of the allocated space. #[inline] fn end(&self) -> *const u8 { unsafe { let size = mem::size_of::<T>().checked_mul(self.capacity).unwrap(); self.start().offset(size as isize) } } } impl<T> TypedArena<T> { /// Creates a new `TypedArena` with preallocated space for eight objects. #[inline] pub fn new() -> TypedArena<T> { TypedArena::with_capacity(8) } /// Creates a new `TypedArena` with preallocated space for the given number of /// objects. #[inline] pub fn with_capacity(capacity: usize) -> TypedArena<T> { unsafe { let chunk = TypedArenaChunk::<T>::new(ptr::null_mut(), capacity); TypedArena { ptr: Cell::new((*chunk).start() as *const T), end: Cell::new((*chunk).end() as *const T), first: RefCell::new(chunk), _own: marker::PhantomData, } } } /// Allocates an object in the `TypedArena`, returning a reference to it. #[inline] pub fn alloc(&self, object: T) -> &mut T { if self.ptr == self.end { self.grow() } let ptr: &mut T = unsafe { let ptr: &mut T = &mut *(self.ptr.get() as *mut T); ptr::write(ptr, object); self.ptr.set(self.ptr.get().offset(1)); ptr }; ptr } /// Grows the arena. #[inline(never)] fn grow(&self) { unsafe { let chunk = *self.first.borrow_mut(); let new_capacity = (*chunk).capacity.checked_mul(2).unwrap(); let chunk = TypedArenaChunk::<T>::new(chunk, new_capacity); self.ptr.set((*chunk).start() as *const T); self.end.set((*chunk).end() as *const T); *self.first.borrow_mut() = chunk } } } impl<T> Drop for TypedArena<T> { fn drop(&mut self) { unsafe { // Determine how much was filled. let start = self.first.borrow().as_ref().unwrap().start() as usize; let end = self.ptr.get() as usize; let diff = (end - start) / mem::size_of::<T>(); // Pass that to the `destroy` method. (**self.first.borrow_mut()).destroy(diff) } } } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use super::{Arena, TypedArena}; #[allow(dead_code)] struct Point { x: i32, y: i32, z: i32, } #[test] fn test_arena_alloc_nested() { struct Inner { value: u8 } struct Outer<'a> { inner: &'a Inner } enum EI<'e> { I(Inner), O(Outer<'e>) } struct Wrap<'a>(TypedArena<EI<'a>>); impl<'a> Wrap<'a> { fn alloc_inner<F:Fn() -> Inner>(&self, f: F) -> &Inner { let r: &EI = self.0.alloc(EI::I(f())); if let &EI::I(ref i) = r { i } else { panic!("mismatch"); } } fn alloc_outer<F:Fn() -> Outer<'a>>(&self, f: F) -> &Outer { let r: &EI = self.0.alloc(EI::O(f())); if let &EI::O(ref o) = r { o } else { panic!("mismatch"); } } } let arena = Wrap(TypedArena::new()); let result = arena.alloc_outer(|| Outer { inner: arena.alloc_inner(|| Inner { value: 10 }) }); assert_eq!(result.inner.value, 10); } #[test] pub fn test_copy() { let arena = TypedArena::new(); for _ in 0..100000 { arena.alloc(Point { x: 1, y: 2, z: 3, }); } } #[bench] pub fn bench_copy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| { arena.alloc(Point { x: 1, y: 2, z: 3, }) }) } #[bench] pub fn bench_copy_nonarena(b: &mut Bencher) { b.iter(|| { let _: Box<_> = box Point { x: 1, y: 2, z: 3, }; }) } #[bench] pub fn bench_copy_old_arena(b: &mut Bencher) { let arena = Arena::new(); b.iter(|| { arena.alloc(|| { Point { x: 1, y: 2, z: 3, } }) }) } #[allow(dead_code)] struct Noncopy { string: String, array: Vec<i32>, } #[test] pub fn test_noncopy() { let arena = TypedArena::new(); for _ in 0..100000 { arena.alloc(Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), }); } } #[bench] pub fn bench_noncopy(b: &mut Bencher)
{ let arena = TypedArena::new(); b.iter(|| { arena.alloc(Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), }) }) }
identifier_body
lib.rs
= "27812")] #![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "https://doc.rust-lang.org/favicon.ico", html_root_url = "https://doc.rust-lang.org/nightly/")] #![feature(alloc)] #![feature(box_syntax)] #![feature(core_intrinsics)] #![feature(heap_api)] #![feature(oom)] #![feature(ptr_as_ref)] #![feature(raw)] #![feature(staged_api)] #![cfg_attr(test, feature(test))] extern crate alloc; use std::cell::{Cell, RefCell}; use std::cmp; use std::intrinsics; use std::marker; use std::mem; use std::ptr; use std::rc::Rc; use std::rt::heap::{allocate, deallocate}; // The way arena uses arrays is really deeply awful. The arrays are // allocated, and have capacities reserved, but the fill for the array // will always stay at 0. #[derive(Clone, PartialEq)] struct Chunk { data: Rc<RefCell<Vec<u8>>>, fill: Cell<usize>, is_copy: Cell<bool>, } impl Chunk { fn capacity(&self) -> usize { self.data.borrow().capacity() } unsafe fn as_ptr(&self) -> *const u8 { self.data.borrow().as_ptr() } } /// A slower reflection-based arena that can allocate objects of any type. /// /// This arena uses `Vec<u8>` as a backing store to allocate objects from. For /// each allocated object, the arena stores a pointer to the type descriptor /// followed by the object (potentially with alignment padding after each /// element). When the arena is destroyed, it iterates through all of its /// chunks, and uses the tydesc information to trace through the objects, /// calling the destructors on them. One subtle point that needs to be /// addressed is how to handle panics while running the user provided /// initializer function. It is important to not run the destructor on /// uninitialized objects, but how to detect them is somewhat subtle. Since /// `alloc()` can be invoked recursively, it is not sufficient to simply exclude /// the most recent object. To solve this without requiring extra space, we /// use the low order bit of the tydesc pointer to encode whether the object /// it describes has been fully initialized. /// /// As an optimization, objects with destructors are stored in different chunks /// than objects without destructors. This reduces overhead when initializing /// plain-old-data (`Copy` types) and means we don't need to waste time running /// their destructors. pub struct Arena<'longer_than_self> { // The head is separated out from the list as a unbenchmarked // microoptimization, to avoid needing to case on the list to access the // head. head: RefCell<Chunk>, copy_head: RefCell<Chunk>, chunks: RefCell<Vec<Chunk>>, _marker: marker::PhantomData<*mut &'longer_than_self()>, } impl<'a> Arena<'a> { /// Allocates a new Arena with 32 bytes preallocated. pub fn new() -> Arena<'a> { Arena::new_with_size(32) } /// Allocates a new Arena with `initial_size` bytes preallocated. pub fn new_with_size(initial_size: usize) -> Arena<'a> { Arena { head: RefCell::new(chunk(initial_size, false)), copy_head: RefCell::new(chunk(initial_size, true)), chunks: RefCell::new(Vec::new()), _marker: marker::PhantomData, } } } fn chunk(size: usize, is_copy: bool) -> Chunk { Chunk { data: Rc::new(RefCell::new(Vec::with_capacity(size))), fill: Cell::new(0), is_copy: Cell::new(is_copy), } } impl<'longer_than_self> Drop for Arena<'longer_than_self> { fn drop(&mut self) { unsafe { destroy_chunk(&*self.head.borrow()); for chunk in self.chunks.borrow().iter() { if!chunk.is_copy.get() { destroy_chunk(chunk); } } } } } #[inline] fn round_up(base: usize, align: usize) -> usize { (base.checked_add(align - 1)).unwrap() &!(align - 1) } // Walk down a chunk, running the destructors for any objects stored // in it. unsafe fn destroy_chunk(chunk: &Chunk) { let mut idx = 0; let buf = chunk.as_ptr(); let fill = chunk.fill.get(); while idx < fill { let tydesc_data = buf.offset(idx as isize) as *const usize; let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data); let (size, align) = ((*tydesc).size, (*tydesc).align); let after_tydesc = idx + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}", // start, size, align, is_done); if is_done { ((*tydesc).drop_glue)(buf.offset(start as isize) as *const i8); } // Find where the next tydesc lives idx = round_up(start + size, mem::align_of::<*const TyDesc>()); } } // We encode whether the object a tydesc describes has been // initialized in the arena in the low bit of the tydesc pointer. This // is necessary in order to properly do cleanup if a panic occurs // during an initializer. #[inline] fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> usize { p as usize | (is_done as usize) } #[inline] fn un_bitpack_tydesc_ptr(p: usize) -> (*const TyDesc, bool) { ((p &!1) as *const TyDesc, p & 1 == 1) } // HACK(eddyb) TyDesc replacement using a trait object vtable. // This could be replaced in the future with a custom DST layout, // or `&'static (drop_glue, size, align)` created by a `const fn`. struct TyDesc { drop_glue: fn(*const i8), size: usize, align: usize } trait AllTypes { fn dummy(&self) { } } impl<T:?Sized> AllTypes for T { } unsafe fn get_tydesc<T>() -> *const TyDesc { use std::raw::TraitObject; let ptr = &*(1 as *const T); // Can use any trait that is implemented for all types. let obj = mem::transmute::<&AllTypes, TraitObject>(ptr); obj.vtable as *const TyDesc } impl<'longer_than_self> Arena<'longer_than_self> { fn chunk_size(&self) -> usize { self.copy_head.borrow().capacity() } // Functions for the POD part of the arena fn alloc_copy_grow(&self, n_bytes: usize, align: usize) -> *const u8 { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.copy_head.borrow().clone()); *self.copy_head.borrow_mut() = chunk((new_min_chunk_size + 1).next_power_of_two(), true); return self.alloc_copy_inner(n_bytes, align); } #[inline] fn alloc_copy_inner(&self, n_bytes: usize, align: usize) -> *const u8 { let start = round_up(self.copy_head.borrow().fill.get(), align); let end = start + n_bytes; if end > self.chunk_size() { return self.alloc_copy_grow(n_bytes, align); } let copy_head = self.copy_head.borrow(); copy_head.fill.set(end); unsafe { copy_head.as_ptr().offset(start as isize) } } #[inline] fn alloc_copy<T, F>(&self, op: F) -> &mut T where F: FnOnce() -> T { unsafe { let ptr = self.alloc_copy_inner(mem::size_of::<T>(), mem::align_of::<T>()); let ptr = ptr as *mut T; ptr::write(&mut (*ptr), op()); return &mut *ptr; } } // Functions for the non-POD part of the arena fn alloc_noncopy_grow(&self, n_bytes: usize, align: usize) -> (*const u8, *const u8) { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.head.borrow().clone()); *self.head.borrow_mut() = chunk((new_min_chunk_size + 1).next_power_of_two(), false); return self.alloc_noncopy_inner(n_bytes, align); } #[inline] fn alloc_noncopy_inner(&self, n_bytes: usize, align: usize) -> (*const u8, *const u8) { // Be careful to not maintain any `head` borrows active, because // `alloc_noncopy_grow` borrows it mutably. let (start, end, tydesc_start, head_capacity) = { let head = self.head.borrow(); let fill = head.fill.get(); let tydesc_start = fill; let after_tydesc = fill + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); let end = start + n_bytes; (start, end, tydesc_start, head.capacity()) }; if end > head_capacity { return self.alloc_noncopy_grow(n_bytes, align); } let head = self.head.borrow(); head.fill.set(round_up(end, mem::align_of::<*const TyDesc>())); unsafe { let buf = head.as_ptr(); return (buf.offset(tydesc_start as isize), buf.offset(start as isize)); } } #[inline] fn alloc_noncopy<T, F>(&self, op: F) -> &mut T where F: FnOnce() -> T { unsafe { let tydesc = get_tydesc::<T>(); let (ty_ptr, ptr) = self.alloc_noncopy_inner(mem::size_of::<T>(), mem::align_of::<T>()); let ty_ptr = ty_ptr as *mut usize; let ptr = ptr as *mut T; // Write in our tydesc along with a bit indicating that it // has *not* been initialized yet. *ty_ptr = bitpack_tydesc_ptr(tydesc, false); // Actually initialize it ptr::write(&mut(*ptr), op()); // Now that we are done, update the tydesc to indicate that // the object is there. *ty_ptr = bitpack_tydesc_ptr(tydesc, true); return &mut *ptr; } } /// Allocates a new item in the arena, using `op` to initialize the value, /// and returns a reference to it. #[inline] pub fn alloc<T:'longer_than_self, F>(&self, op: F) -> &mut T where F: FnOnce() -> T { unsafe { if intrinsics::needs_drop::<T>() { self.alloc_noncopy(op) } else { self.alloc_copy(op) } } } } #[test] fn test_arena_destructors() { let arena = Arena::new(); for i in 0..10 { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| Rc::new(i)); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| [0u8, 1u8, 2u8]); } } #[test] #[should_panic] fn test_arena_destructors_fail() { let arena = Arena::new(); // Put some stuff in the arena. for i in 0..10 { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| { Rc::new(i) }); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| { [0u8, 1, 2] }); } // Now, panic while allocating arena.alloc::<Rc<i32>, _>(|| { panic!(); }); } /// A faster arena that can hold objects of only one type. pub struct TypedArena<T> { /// A pointer to the next object to be allocated. ptr: Cell<*const T>, /// A pointer to the end of the allocated area. When this pointer is /// reached, a new chunk is allocated. end: Cell<*const T>, /// A pointer to the first arena segment. first: RefCell<*mut TypedArenaChunk<T>>, /// Marker indicating that dropping the arena causes its owned /// instances of `T` to be dropped. _own: marker::PhantomData<T>, } struct TypedArenaChunk<T> { marker: marker::PhantomData<T>, /// Pointer to the next arena segment. next: *mut TypedArenaChunk<T>, /// The number of elements that this chunk can hold. capacity: usize, // Objects follow here, suitably aligned. } fn calculate_size<T>(capacity: usize) -> usize { let mut size = mem::size_of::<TypedArenaChunk<T>>(); size = round_up(size, mem::align_of::<T>()); let elem_size = mem::size_of::<T>(); let elems_size = elem_size.checked_mul(capacity).unwrap(); size = size.checked_add(elems_size).unwrap(); size } impl<T> TypedArenaChunk<T> { #[inline] unsafe fn new(next: *mut TypedArenaChunk<T>, capacity: usize) -> *mut TypedArenaChunk<T> { let size = calculate_size::<T>(capacity); let chunk = allocate(size, mem::align_of::<TypedArenaChunk<T>>()) as *mut TypedArenaChunk<T>; if chunk.is_null() { alloc::oom() } (*chunk).next = next; (*chunk).capacity = capacity; chunk } /// Destroys this arena chunk. If the type descriptor is supplied, the /// drop glue is called; otherwise, drop glue is not called. #[inline] unsafe fn destroy(&mut self, len: usize) { // Destroy all the allocated objects. if intrinsics::needs_drop::<T>() { let mut start = self.start(); for _ in 0..len { ptr::read(start as *const T); // run the destructor on the pointer start = start.offset(mem::size_of::<T>() as isize) } } // Destroy the next chunk. let next = self.next; let size = calculate_size::<T>(self.capacity); let self_ptr: *mut TypedArenaChunk<T> = self; deallocate(self_ptr as *mut u8, size, mem::align_of::<TypedArenaChunk<T>>()); if!next.is_null() { let capacity = (*next).capacity; (*next).destroy(capacity); } } // Returns a pointer to the first allocated object. #[inline] fn start(&self) -> *const u8 { let this: *const TypedArenaChunk<T> = self; unsafe { round_up(this.offset(1) as usize, mem::align_of::<T>()) as *const u8 } } // Returns a pointer to the end of the allocated space. #[inline] fn end(&self) -> *const u8 { unsafe { let size = mem::size_of::<T>().checked_mul(self.capacity).unwrap(); self.start().offset(size as isize) } } } impl<T> TypedArena<T> { /// Creates a new `TypedArena` with preallocated space for eight objects. #[inline] pub fn new() -> TypedArena<T> { TypedArena::with_capacity(8) } /// Creates a new `TypedArena` with preallocated space for the given number of /// objects. #[inline] pub fn with_capacity(capacity: usize) -> TypedArena<T> { unsafe { let chunk = TypedArenaChunk::<T>::new(ptr::null_mut(), capacity); TypedArena { ptr: Cell::new((*chunk).start() as *const T), end: Cell::new((*chunk).end() as *const T), first: RefCell::new(chunk), _own: marker::PhantomData, } } } /// Allocates an object in the `TypedArena`, returning a reference to it. #[inline] pub fn alloc(&self, object: T) -> &mut T { if self.ptr == self.end
let ptr: &mut T = unsafe { let ptr: &mut T = &mut *(self.ptr.get() as *mut T); ptr::write(ptr, object); self.ptr.set(self.ptr.get().offset(1)); ptr }; ptr } /// Grows the arena. #[inline(never)] fn grow(&self) { unsafe { let chunk = *self.first.borrow_mut(); let new_capacity = (*chunk).capacity.checked_mul(2).unwrap(); let chunk = TypedArenaChunk::<T>::new(chunk, new_capacity); self.ptr.set((*chunk).start() as *const T); self.end.set((*chunk).end() as *const T); *self.first.borrow_mut() = chunk } } } impl<T> Drop for TypedArena<T> { fn drop(&mut self) { unsafe { // Determine how much was filled. let start = self.first.borrow().as_ref().unwrap().start() as usize; let end = self.ptr.get() as usize; let diff = (end - start) / mem::size_of::<T>(); // Pass that to the `destroy` method. (**self.first.borrow_mut()).destroy(diff) } } } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use super::{Arena, TypedArena}; #[allow(dead_code)] struct Point { x: i32, y: i32, z: i32, } #[test] fn test_arena_alloc_nested() { struct Inner { value: u8 } struct Outer<'a> { inner: &'a Inner } enum EI<'e> { I(Inner), O(Outer<'e>) } struct Wrap<'a>(TypedArena<EI<'a>>); impl<'a> Wrap<'a> { fn alloc_inner<F:Fn() -> Inner>(&self, f: F) -> &Inner { let r: &EI = self.0.alloc(EI::I(f())); if let &EI::I(ref i) = r { i } else { panic!("mismatch"); } } fn alloc_outer<F:Fn() -> Outer<'a>>(&self, f: F) -> &Outer { let r: &EI = self.0.alloc(EI::O(f())); if let &EI::O(ref o) = r { o } else { panic!("mismatch"); } } } let arena = Wrap(TypedArena::new()); let result = arena.alloc_outer(|| Outer { inner: arena.alloc_inner(|| Inner { value: 10 }) }); assert_eq!(result.inner.value, 10); } #[test] pub fn test_copy() { let arena = TypedArena::new(); for _ in 0..100000 { arena.alloc(Point { x: 1, y: 2, z: 3, }); } } #[bench] pub fn bench_copy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| { arena.alloc(Point { x: 1, y: 2, z: 3, }) }) } #[bench] pub fn bench_copy_nonarena(b: &mut Bencher) { b.iter(|| { let _: Box<_> = box Point { x: 1, y: 2, z: 3, }; }) } #[bench] pub fn bench_copy_old_arena(b: &mut Bencher) { let arena = Arena::new(); b.iter(|| { arena.alloc(|| { Point { x: 1, y: 2,
{ self.grow() }
conditional_block
lib.rs
= "27812")] #![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "https://doc.rust-lang.org/favicon.ico", html_root_url = "https://doc.rust-lang.org/nightly/")] #![feature(alloc)] #![feature(box_syntax)] #![feature(core_intrinsics)] #![feature(heap_api)] #![feature(oom)] #![feature(ptr_as_ref)] #![feature(raw)] #![feature(staged_api)] #![cfg_attr(test, feature(test))] extern crate alloc; use std::cell::{Cell, RefCell}; use std::cmp; use std::intrinsics; use std::marker; use std::mem; use std::ptr; use std::rc::Rc; use std::rt::heap::{allocate, deallocate}; // The way arena uses arrays is really deeply awful. The arrays are // allocated, and have capacities reserved, but the fill for the array // will always stay at 0. #[derive(Clone, PartialEq)] struct Chunk { data: Rc<RefCell<Vec<u8>>>, fill: Cell<usize>, is_copy: Cell<bool>, } impl Chunk { fn capacity(&self) -> usize { self.data.borrow().capacity() } unsafe fn as_ptr(&self) -> *const u8 { self.data.borrow().as_ptr() } } /// A slower reflection-based arena that can allocate objects of any type. /// /// This arena uses `Vec<u8>` as a backing store to allocate objects from. For /// each allocated object, the arena stores a pointer to the type descriptor /// followed by the object (potentially with alignment padding after each /// element). When the arena is destroyed, it iterates through all of its /// chunks, and uses the tydesc information to trace through the objects, /// calling the destructors on them. One subtle point that needs to be /// addressed is how to handle panics while running the user provided /// initializer function. It is important to not run the destructor on /// uninitialized objects, but how to detect them is somewhat subtle. Since /// `alloc()` can be invoked recursively, it is not sufficient to simply exclude /// the most recent object. To solve this without requiring extra space, we /// use the low order bit of the tydesc pointer to encode whether the object /// it describes has been fully initialized. /// /// As an optimization, objects with destructors are stored in different chunks /// than objects without destructors. This reduces overhead when initializing /// plain-old-data (`Copy` types) and means we don't need to waste time running /// their destructors. pub struct Arena<'longer_than_self> { // The head is separated out from the list as a unbenchmarked // microoptimization, to avoid needing to case on the list to access the // head. head: RefCell<Chunk>, copy_head: RefCell<Chunk>, chunks: RefCell<Vec<Chunk>>, _marker: marker::PhantomData<*mut &'longer_than_self()>, } impl<'a> Arena<'a> { /// Allocates a new Arena with 32 bytes preallocated. pub fn new() -> Arena<'a> { Arena::new_with_size(32) } /// Allocates a new Arena with `initial_size` bytes preallocated. pub fn new_with_size(initial_size: usize) -> Arena<'a> { Arena { head: RefCell::new(chunk(initial_size, false)), copy_head: RefCell::new(chunk(initial_size, true)), chunks: RefCell::new(Vec::new()), _marker: marker::PhantomData, } } } fn chunk(size: usize, is_copy: bool) -> Chunk { Chunk { data: Rc::new(RefCell::new(Vec::with_capacity(size))), fill: Cell::new(0), is_copy: Cell::new(is_copy), } } impl<'longer_than_self> Drop for Arena<'longer_than_self> { fn drop(&mut self) { unsafe { destroy_chunk(&*self.head.borrow()); for chunk in self.chunks.borrow().iter() { if!chunk.is_copy.get() { destroy_chunk(chunk); } } } } } #[inline] fn round_up(base: usize, align: usize) -> usize { (base.checked_add(align - 1)).unwrap() &!(align - 1) } // Walk down a chunk, running the destructors for any objects stored // in it. unsafe fn destroy_chunk(chunk: &Chunk) { let mut idx = 0; let buf = chunk.as_ptr(); let fill = chunk.fill.get(); while idx < fill { let tydesc_data = buf.offset(idx as isize) as *const usize; let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data); let (size, align) = ((*tydesc).size, (*tydesc).align); let after_tydesc = idx + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}", // start, size, align, is_done); if is_done { ((*tydesc).drop_glue)(buf.offset(start as isize) as *const i8); } // Find where the next tydesc lives idx = round_up(start + size, mem::align_of::<*const TyDesc>()); } } // We encode whether the object a tydesc describes has been // initialized in the arena in the low bit of the tydesc pointer. This // is necessary in order to properly do cleanup if a panic occurs // during an initializer. #[inline] fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> usize { p as usize | (is_done as usize) } #[inline] fn un_bitpack_tydesc_ptr(p: usize) -> (*const TyDesc, bool) { ((p &!1) as *const TyDesc, p & 1 == 1) } // HACK(eddyb) TyDesc replacement using a trait object vtable. // This could be replaced in the future with a custom DST layout, // or `&'static (drop_glue, size, align)` created by a `const fn`. struct TyDesc { drop_glue: fn(*const i8), size: usize, align: usize } trait AllTypes { fn dummy(&self) { } } impl<T:?Sized> AllTypes for T { } unsafe fn get_tydesc<T>() -> *const TyDesc { use std::raw::TraitObject; let ptr = &*(1 as *const T); // Can use any trait that is implemented for all types. let obj = mem::transmute::<&AllTypes, TraitObject>(ptr); obj.vtable as *const TyDesc } impl<'longer_than_self> Arena<'longer_than_self> { fn chunk_size(&self) -> usize { self.copy_head.borrow().capacity() } // Functions for the POD part of the arena fn alloc_copy_grow(&self, n_bytes: usize, align: usize) -> *const u8 { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.copy_head.borrow().clone()); *self.copy_head.borrow_mut() = chunk((new_min_chunk_size + 1).next_power_of_two(), true); return self.alloc_copy_inner(n_bytes, align); } #[inline] fn alloc_copy_inner(&self, n_bytes: usize, align: usize) -> *const u8 { let start = round_up(self.copy_head.borrow().fill.get(), align); let end = start + n_bytes; if end > self.chunk_size() { return self.alloc_copy_grow(n_bytes, align); } let copy_head = self.copy_head.borrow(); copy_head.fill.set(end); unsafe { copy_head.as_ptr().offset(start as isize) } } #[inline] fn alloc_copy<T, F>(&self, op: F) -> &mut T where F: FnOnce() -> T { unsafe { let ptr = self.alloc_copy_inner(mem::size_of::<T>(), mem::align_of::<T>()); let ptr = ptr as *mut T; ptr::write(&mut (*ptr), op()); return &mut *ptr; } } // Functions for the non-POD part of the arena fn alloc_noncopy_grow(&self, n_bytes: usize, align: usize) -> (*const u8, *const u8) { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.head.borrow().clone()); *self.head.borrow_mut() = chunk((new_min_chunk_size + 1).next_power_of_two(), false); return self.alloc_noncopy_inner(n_bytes, align); } #[inline] fn alloc_noncopy_inner(&self, n_bytes: usize, align: usize) -> (*const u8, *const u8) { // Be careful to not maintain any `head` borrows active, because // `alloc_noncopy_grow` borrows it mutably. let (start, end, tydesc_start, head_capacity) = { let head = self.head.borrow(); let fill = head.fill.get(); let tydesc_start = fill; let after_tydesc = fill + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); let end = start + n_bytes; (start, end, tydesc_start, head.capacity()) }; if end > head_capacity { return self.alloc_noncopy_grow(n_bytes, align); } let head = self.head.borrow(); head.fill.set(round_up(end, mem::align_of::<*const TyDesc>())); unsafe { let buf = head.as_ptr(); return (buf.offset(tydesc_start as isize), buf.offset(start as isize)); } } #[inline] fn alloc_noncopy<T, F>(&self, op: F) -> &mut T where F: FnOnce() -> T { unsafe { let tydesc = get_tydesc::<T>(); let (ty_ptr, ptr) = self.alloc_noncopy_inner(mem::size_of::<T>(), mem::align_of::<T>()); let ty_ptr = ty_ptr as *mut usize; let ptr = ptr as *mut T; // Write in our tydesc along with a bit indicating that it // has *not* been initialized yet. *ty_ptr = bitpack_tydesc_ptr(tydesc, false); // Actually initialize it ptr::write(&mut(*ptr), op()); // Now that we are done, update the tydesc to indicate that // the object is there. *ty_ptr = bitpack_tydesc_ptr(tydesc, true); return &mut *ptr; } } /// Allocates a new item in the arena, using `op` to initialize the value, /// and returns a reference to it. #[inline] pub fn alloc<T:'longer_than_self, F>(&self, op: F) -> &mut T where F: FnOnce() -> T { unsafe { if intrinsics::needs_drop::<T>() { self.alloc_noncopy(op) } else { self.alloc_copy(op) } } } } #[test] fn test_arena_destructors() { let arena = Arena::new(); for i in 0..10 { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| Rc::new(i)); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| [0u8, 1u8, 2u8]); } } #[test] #[should_panic] fn test_arena_destructors_fail() { let arena = Arena::new(); // Put some stuff in the arena. for i in 0..10 { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| { Rc::new(i) }); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| { [0u8, 1, 2] }); } // Now, panic while allocating arena.alloc::<Rc<i32>, _>(|| { panic!(); }); } /// A faster arena that can hold objects of only one type. pub struct
<T> { /// A pointer to the next object to be allocated. ptr: Cell<*const T>, /// A pointer to the end of the allocated area. When this pointer is /// reached, a new chunk is allocated. end: Cell<*const T>, /// A pointer to the first arena segment. first: RefCell<*mut TypedArenaChunk<T>>, /// Marker indicating that dropping the arena causes its owned /// instances of `T` to be dropped. _own: marker::PhantomData<T>, } struct TypedArenaChunk<T> { marker: marker::PhantomData<T>, /// Pointer to the next arena segment. next: *mut TypedArenaChunk<T>, /// The number of elements that this chunk can hold. capacity: usize, // Objects follow here, suitably aligned. } fn calculate_size<T>(capacity: usize) -> usize { let mut size = mem::size_of::<TypedArenaChunk<T>>(); size = round_up(size, mem::align_of::<T>()); let elem_size = mem::size_of::<T>(); let elems_size = elem_size.checked_mul(capacity).unwrap(); size = size.checked_add(elems_size).unwrap(); size } impl<T> TypedArenaChunk<T> { #[inline] unsafe fn new(next: *mut TypedArenaChunk<T>, capacity: usize) -> *mut TypedArenaChunk<T> { let size = calculate_size::<T>(capacity); let chunk = allocate(size, mem::align_of::<TypedArenaChunk<T>>()) as *mut TypedArenaChunk<T>; if chunk.is_null() { alloc::oom() } (*chunk).next = next; (*chunk).capacity = capacity; chunk } /// Destroys this arena chunk. If the type descriptor is supplied, the /// drop glue is called; otherwise, drop glue is not called. #[inline] unsafe fn destroy(&mut self, len: usize) { // Destroy all the allocated objects. if intrinsics::needs_drop::<T>() { let mut start = self.start(); for _ in 0..len { ptr::read(start as *const T); // run the destructor on the pointer start = start.offset(mem::size_of::<T>() as isize) } } // Destroy the next chunk. let next = self.next; let size = calculate_size::<T>(self.capacity); let self_ptr: *mut TypedArenaChunk<T> = self; deallocate(self_ptr as *mut u8, size, mem::align_of::<TypedArenaChunk<T>>()); if!next.is_null() { let capacity = (*next).capacity; (*next).destroy(capacity); } } // Returns a pointer to the first allocated object. #[inline] fn start(&self) -> *const u8 { let this: *const TypedArenaChunk<T> = self; unsafe { round_up(this.offset(1) as usize, mem::align_of::<T>()) as *const u8 } } // Returns a pointer to the end of the allocated space. #[inline] fn end(&self) -> *const u8 { unsafe { let size = mem::size_of::<T>().checked_mul(self.capacity).unwrap(); self.start().offset(size as isize) } } } impl<T> TypedArena<T> { /// Creates a new `TypedArena` with preallocated space for eight objects. #[inline] pub fn new() -> TypedArena<T> { TypedArena::with_capacity(8) } /// Creates a new `TypedArena` with preallocated space for the given number of /// objects. #[inline] pub fn with_capacity(capacity: usize) -> TypedArena<T> { unsafe { let chunk = TypedArenaChunk::<T>::new(ptr::null_mut(), capacity); TypedArena { ptr: Cell::new((*chunk).start() as *const T), end: Cell::new((*chunk).end() as *const T), first: RefCell::new(chunk), _own: marker::PhantomData, } } } /// Allocates an object in the `TypedArena`, returning a reference to it. #[inline] pub fn alloc(&self, object: T) -> &mut T { if self.ptr == self.end { self.grow() } let ptr: &mut T = unsafe { let ptr: &mut T = &mut *(self.ptr.get() as *mut T); ptr::write(ptr, object); self.ptr.set(self.ptr.get().offset(1)); ptr }; ptr } /// Grows the arena. #[inline(never)] fn grow(&self) { unsafe { let chunk = *self.first.borrow_mut(); let new_capacity = (*chunk).capacity.checked_mul(2).unwrap(); let chunk = TypedArenaChunk::<T>::new(chunk, new_capacity); self.ptr.set((*chunk).start() as *const T); self.end.set((*chunk).end() as *const T); *self.first.borrow_mut() = chunk } } } impl<T> Drop for TypedArena<T> { fn drop(&mut self) { unsafe { // Determine how much was filled. let start = self.first.borrow().as_ref().unwrap().start() as usize; let end = self.ptr.get() as usize; let diff = (end - start) / mem::size_of::<T>(); // Pass that to the `destroy` method. (**self.first.borrow_mut()).destroy(diff) } } } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use super::{Arena, TypedArena}; #[allow(dead_code)] struct Point { x: i32, y: i32, z: i32, } #[test] fn test_arena_alloc_nested() { struct Inner { value: u8 } struct Outer<'a> { inner: &'a Inner } enum EI<'e> { I(Inner), O(Outer<'e>) } struct Wrap<'a>(TypedArena<EI<'a>>); impl<'a> Wrap<'a> { fn alloc_inner<F:Fn() -> Inner>(&self, f: F) -> &Inner { let r: &EI = self.0.alloc(EI::I(f())); if let &EI::I(ref i) = r { i } else { panic!("mismatch"); } } fn alloc_outer<F:Fn() -> Outer<'a>>(&self, f: F) -> &Outer { let r: &EI = self.0.alloc(EI::O(f())); if let &EI::O(ref o) = r { o } else { panic!("mismatch"); } } } let arena = Wrap(TypedArena::new()); let result = arena.alloc_outer(|| Outer { inner: arena.alloc_inner(|| Inner { value: 10 }) }); assert_eq!(result.inner.value, 10); } #[test] pub fn test_copy() { let arena = TypedArena::new(); for _ in 0..100000 { arena.alloc(Point { x: 1, y: 2, z: 3, }); } } #[bench] pub fn bench_copy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| { arena.alloc(Point { x: 1, y: 2, z: 3, }) }) } #[bench] pub fn bench_copy_nonarena(b: &mut Bencher) { b.iter(|| { let _: Box<_> = box Point { x: 1, y: 2, z: 3, }; }) } #[bench] pub fn bench_copy_old_arena(b: &mut Bencher) { let arena = Arena::new(); b.iter(|| { arena.alloc(|| { Point { x: 1, y: 2,
TypedArena
identifier_name
lib.rs
Rc; use std::rt::heap::{allocate, deallocate}; // The way arena uses arrays is really deeply awful. The arrays are // allocated, and have capacities reserved, but the fill for the array // will always stay at 0. #[derive(Clone, PartialEq)] struct Chunk { data: Rc<RefCell<Vec<u8>>>, fill: Cell<usize>, is_copy: Cell<bool>, } impl Chunk { fn capacity(&self) -> usize { self.data.borrow().capacity() } unsafe fn as_ptr(&self) -> *const u8 { self.data.borrow().as_ptr() } } /// A slower reflection-based arena that can allocate objects of any type. /// /// This arena uses `Vec<u8>` as a backing store to allocate objects from. For /// each allocated object, the arena stores a pointer to the type descriptor /// followed by the object (potentially with alignment padding after each /// element). When the arena is destroyed, it iterates through all of its /// chunks, and uses the tydesc information to trace through the objects, /// calling the destructors on them. One subtle point that needs to be /// addressed is how to handle panics while running the user provided /// initializer function. It is important to not run the destructor on /// uninitialized objects, but how to detect them is somewhat subtle. Since /// `alloc()` can be invoked recursively, it is not sufficient to simply exclude /// the most recent object. To solve this without requiring extra space, we /// use the low order bit of the tydesc pointer to encode whether the object /// it describes has been fully initialized. /// /// As an optimization, objects with destructors are stored in different chunks /// than objects without destructors. This reduces overhead when initializing /// plain-old-data (`Copy` types) and means we don't need to waste time running /// their destructors. pub struct Arena<'longer_than_self> { // The head is separated out from the list as a unbenchmarked // microoptimization, to avoid needing to case on the list to access the // head. head: RefCell<Chunk>, copy_head: RefCell<Chunk>, chunks: RefCell<Vec<Chunk>>, _marker: marker::PhantomData<*mut &'longer_than_self()>, } impl<'a> Arena<'a> { /// Allocates a new Arena with 32 bytes preallocated. pub fn new() -> Arena<'a> { Arena::new_with_size(32) } /// Allocates a new Arena with `initial_size` bytes preallocated. pub fn new_with_size(initial_size: usize) -> Arena<'a> { Arena { head: RefCell::new(chunk(initial_size, false)), copy_head: RefCell::new(chunk(initial_size, true)), chunks: RefCell::new(Vec::new()), _marker: marker::PhantomData, } } } fn chunk(size: usize, is_copy: bool) -> Chunk { Chunk { data: Rc::new(RefCell::new(Vec::with_capacity(size))), fill: Cell::new(0), is_copy: Cell::new(is_copy), } } impl<'longer_than_self> Drop for Arena<'longer_than_self> { fn drop(&mut self) { unsafe { destroy_chunk(&*self.head.borrow()); for chunk in self.chunks.borrow().iter() { if!chunk.is_copy.get() { destroy_chunk(chunk); } } } } } #[inline] fn round_up(base: usize, align: usize) -> usize { (base.checked_add(align - 1)).unwrap() &!(align - 1) } // Walk down a chunk, running the destructors for any objects stored // in it. unsafe fn destroy_chunk(chunk: &Chunk) { let mut idx = 0; let buf = chunk.as_ptr(); let fill = chunk.fill.get(); while idx < fill { let tydesc_data = buf.offset(idx as isize) as *const usize; let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data); let (size, align) = ((*tydesc).size, (*tydesc).align); let after_tydesc = idx + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}", // start, size, align, is_done); if is_done { ((*tydesc).drop_glue)(buf.offset(start as isize) as *const i8); } // Find where the next tydesc lives idx = round_up(start + size, mem::align_of::<*const TyDesc>()); } } // We encode whether the object a tydesc describes has been // initialized in the arena in the low bit of the tydesc pointer. This // is necessary in order to properly do cleanup if a panic occurs // during an initializer. #[inline] fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> usize { p as usize | (is_done as usize) } #[inline] fn un_bitpack_tydesc_ptr(p: usize) -> (*const TyDesc, bool) { ((p &!1) as *const TyDesc, p & 1 == 1) } // HACK(eddyb) TyDesc replacement using a trait object vtable. // This could be replaced in the future with a custom DST layout, // or `&'static (drop_glue, size, align)` created by a `const fn`. struct TyDesc { drop_glue: fn(*const i8), size: usize, align: usize } trait AllTypes { fn dummy(&self) { } } impl<T:?Sized> AllTypes for T { } unsafe fn get_tydesc<T>() -> *const TyDesc { use std::raw::TraitObject; let ptr = &*(1 as *const T); // Can use any trait that is implemented for all types. let obj = mem::transmute::<&AllTypes, TraitObject>(ptr); obj.vtable as *const TyDesc } impl<'longer_than_self> Arena<'longer_than_self> { fn chunk_size(&self) -> usize { self.copy_head.borrow().capacity() } // Functions for the POD part of the arena fn alloc_copy_grow(&self, n_bytes: usize, align: usize) -> *const u8 { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.copy_head.borrow().clone()); *self.copy_head.borrow_mut() = chunk((new_min_chunk_size + 1).next_power_of_two(), true); return self.alloc_copy_inner(n_bytes, align); } #[inline] fn alloc_copy_inner(&self, n_bytes: usize, align: usize) -> *const u8 { let start = round_up(self.copy_head.borrow().fill.get(), align); let end = start + n_bytes; if end > self.chunk_size() { return self.alloc_copy_grow(n_bytes, align); } let copy_head = self.copy_head.borrow(); copy_head.fill.set(end); unsafe { copy_head.as_ptr().offset(start as isize) } } #[inline] fn alloc_copy<T, F>(&self, op: F) -> &mut T where F: FnOnce() -> T { unsafe { let ptr = self.alloc_copy_inner(mem::size_of::<T>(), mem::align_of::<T>()); let ptr = ptr as *mut T; ptr::write(&mut (*ptr), op()); return &mut *ptr; } } // Functions for the non-POD part of the arena fn alloc_noncopy_grow(&self, n_bytes: usize, align: usize) -> (*const u8, *const u8) { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.head.borrow().clone()); *self.head.borrow_mut() = chunk((new_min_chunk_size + 1).next_power_of_two(), false); return self.alloc_noncopy_inner(n_bytes, align); } #[inline] fn alloc_noncopy_inner(&self, n_bytes: usize, align: usize) -> (*const u8, *const u8) { // Be careful to not maintain any `head` borrows active, because // `alloc_noncopy_grow` borrows it mutably. let (start, end, tydesc_start, head_capacity) = { let head = self.head.borrow(); let fill = head.fill.get(); let tydesc_start = fill; let after_tydesc = fill + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); let end = start + n_bytes; (start, end, tydesc_start, head.capacity()) }; if end > head_capacity { return self.alloc_noncopy_grow(n_bytes, align); } let head = self.head.borrow(); head.fill.set(round_up(end, mem::align_of::<*const TyDesc>())); unsafe { let buf = head.as_ptr(); return (buf.offset(tydesc_start as isize), buf.offset(start as isize)); } } #[inline] fn alloc_noncopy<T, F>(&self, op: F) -> &mut T where F: FnOnce() -> T { unsafe { let tydesc = get_tydesc::<T>(); let (ty_ptr, ptr) = self.alloc_noncopy_inner(mem::size_of::<T>(), mem::align_of::<T>()); let ty_ptr = ty_ptr as *mut usize; let ptr = ptr as *mut T; // Write in our tydesc along with a bit indicating that it // has *not* been initialized yet. *ty_ptr = bitpack_tydesc_ptr(tydesc, false); // Actually initialize it ptr::write(&mut(*ptr), op()); // Now that we are done, update the tydesc to indicate that // the object is there. *ty_ptr = bitpack_tydesc_ptr(tydesc, true); return &mut *ptr; } } /// Allocates a new item in the arena, using `op` to initialize the value, /// and returns a reference to it. #[inline] pub fn alloc<T:'longer_than_self, F>(&self, op: F) -> &mut T where F: FnOnce() -> T { unsafe { if intrinsics::needs_drop::<T>() { self.alloc_noncopy(op) } else { self.alloc_copy(op) } } } } #[test] fn test_arena_destructors() { let arena = Arena::new(); for i in 0..10 { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| Rc::new(i)); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| [0u8, 1u8, 2u8]); } } #[test] #[should_panic] fn test_arena_destructors_fail() { let arena = Arena::new(); // Put some stuff in the arena. for i in 0..10 { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| { Rc::new(i) }); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| { [0u8, 1, 2] }); } // Now, panic while allocating arena.alloc::<Rc<i32>, _>(|| { panic!(); }); } /// A faster arena that can hold objects of only one type. pub struct TypedArena<T> { /// A pointer to the next object to be allocated. ptr: Cell<*const T>, /// A pointer to the end of the allocated area. When this pointer is /// reached, a new chunk is allocated. end: Cell<*const T>, /// A pointer to the first arena segment. first: RefCell<*mut TypedArenaChunk<T>>, /// Marker indicating that dropping the arena causes its owned /// instances of `T` to be dropped. _own: marker::PhantomData<T>, } struct TypedArenaChunk<T> { marker: marker::PhantomData<T>, /// Pointer to the next arena segment. next: *mut TypedArenaChunk<T>, /// The number of elements that this chunk can hold. capacity: usize, // Objects follow here, suitably aligned. } fn calculate_size<T>(capacity: usize) -> usize { let mut size = mem::size_of::<TypedArenaChunk<T>>(); size = round_up(size, mem::align_of::<T>()); let elem_size = mem::size_of::<T>(); let elems_size = elem_size.checked_mul(capacity).unwrap(); size = size.checked_add(elems_size).unwrap(); size } impl<T> TypedArenaChunk<T> { #[inline] unsafe fn new(next: *mut TypedArenaChunk<T>, capacity: usize) -> *mut TypedArenaChunk<T> { let size = calculate_size::<T>(capacity); let chunk = allocate(size, mem::align_of::<TypedArenaChunk<T>>()) as *mut TypedArenaChunk<T>; if chunk.is_null() { alloc::oom() } (*chunk).next = next; (*chunk).capacity = capacity; chunk } /// Destroys this arena chunk. If the type descriptor is supplied, the /// drop glue is called; otherwise, drop glue is not called. #[inline] unsafe fn destroy(&mut self, len: usize) { // Destroy all the allocated objects. if intrinsics::needs_drop::<T>() { let mut start = self.start(); for _ in 0..len { ptr::read(start as *const T); // run the destructor on the pointer start = start.offset(mem::size_of::<T>() as isize) } } // Destroy the next chunk. let next = self.next; let size = calculate_size::<T>(self.capacity); let self_ptr: *mut TypedArenaChunk<T> = self; deallocate(self_ptr as *mut u8, size, mem::align_of::<TypedArenaChunk<T>>()); if!next.is_null() { let capacity = (*next).capacity; (*next).destroy(capacity); } } // Returns a pointer to the first allocated object. #[inline] fn start(&self) -> *const u8 { let this: *const TypedArenaChunk<T> = self; unsafe { round_up(this.offset(1) as usize, mem::align_of::<T>()) as *const u8 } } // Returns a pointer to the end of the allocated space. #[inline] fn end(&self) -> *const u8 { unsafe { let size = mem::size_of::<T>().checked_mul(self.capacity).unwrap(); self.start().offset(size as isize) } } } impl<T> TypedArena<T> { /// Creates a new `TypedArena` with preallocated space for eight objects. #[inline] pub fn new() -> TypedArena<T> { TypedArena::with_capacity(8) } /// Creates a new `TypedArena` with preallocated space for the given number of /// objects. #[inline] pub fn with_capacity(capacity: usize) -> TypedArena<T> { unsafe { let chunk = TypedArenaChunk::<T>::new(ptr::null_mut(), capacity); TypedArena { ptr: Cell::new((*chunk).start() as *const T), end: Cell::new((*chunk).end() as *const T), first: RefCell::new(chunk), _own: marker::PhantomData, } } } /// Allocates an object in the `TypedArena`, returning a reference to it. #[inline] pub fn alloc(&self, object: T) -> &mut T { if self.ptr == self.end { self.grow() } let ptr: &mut T = unsafe { let ptr: &mut T = &mut *(self.ptr.get() as *mut T); ptr::write(ptr, object); self.ptr.set(self.ptr.get().offset(1)); ptr }; ptr } /// Grows the arena. #[inline(never)] fn grow(&self) { unsafe { let chunk = *self.first.borrow_mut(); let new_capacity = (*chunk).capacity.checked_mul(2).unwrap(); let chunk = TypedArenaChunk::<T>::new(chunk, new_capacity); self.ptr.set((*chunk).start() as *const T); self.end.set((*chunk).end() as *const T); *self.first.borrow_mut() = chunk } } } impl<T> Drop for TypedArena<T> { fn drop(&mut self) { unsafe { // Determine how much was filled. let start = self.first.borrow().as_ref().unwrap().start() as usize; let end = self.ptr.get() as usize; let diff = (end - start) / mem::size_of::<T>(); // Pass that to the `destroy` method. (**self.first.borrow_mut()).destroy(diff) } } } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use super::{Arena, TypedArena}; #[allow(dead_code)] struct Point { x: i32, y: i32, z: i32, } #[test] fn test_arena_alloc_nested() { struct Inner { value: u8 } struct Outer<'a> { inner: &'a Inner } enum EI<'e> { I(Inner), O(Outer<'e>) } struct Wrap<'a>(TypedArena<EI<'a>>); impl<'a> Wrap<'a> { fn alloc_inner<F:Fn() -> Inner>(&self, f: F) -> &Inner { let r: &EI = self.0.alloc(EI::I(f())); if let &EI::I(ref i) = r { i } else { panic!("mismatch"); } } fn alloc_outer<F:Fn() -> Outer<'a>>(&self, f: F) -> &Outer { let r: &EI = self.0.alloc(EI::O(f())); if let &EI::O(ref o) = r { o } else { panic!("mismatch"); } } } let arena = Wrap(TypedArena::new()); let result = arena.alloc_outer(|| Outer { inner: arena.alloc_inner(|| Inner { value: 10 }) }); assert_eq!(result.inner.value, 10); } #[test] pub fn test_copy() { let arena = TypedArena::new(); for _ in 0..100000 { arena.alloc(Point { x: 1, y: 2, z: 3, }); } } #[bench] pub fn bench_copy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| { arena.alloc(Point { x: 1, y: 2, z: 3, }) }) } #[bench] pub fn bench_copy_nonarena(b: &mut Bencher) { b.iter(|| { let _: Box<_> = box Point { x: 1, y: 2, z: 3, }; }) } #[bench] pub fn bench_copy_old_arena(b: &mut Bencher) { let arena = Arena::new(); b.iter(|| { arena.alloc(|| { Point { x: 1, y: 2, z: 3, } }) }) } #[allow(dead_code)] struct Noncopy { string: String, array: Vec<i32>, } #[test] pub fn test_noncopy() { let arena = TypedArena::new(); for _ in 0..100000 { arena.alloc(Noncopy { string: "hello world".to_string(),
array: vec!( 1, 2, 3, 4, 5 ), }); } }
random_line_split
rom_nist256_32.rs
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Fixed Data in ROM - Field and Curve parameters */ use nist256::big::NLEN; use super::super::arch::Chunk; use types::{ModType, CurveType, CurvePairingType, SexticTwist, SignOfX}; // Base Bits= 28 // Base Bits= 28 // nist256 modulus pub const MODULUS: [Chunk; NLEN] = [ 0xFFFFFFF, 0xFFFFFFF, 0xFFFFFFF, 0xFFF, 0x0, 0x0, 0x1000000, 0x0, 0xFFFFFFF, 0xF, ]; pub const R2MODP: [Chunk; NLEN] = [ 0x50000, 0x300000, 0x0, 0x0, 0xFFFFFFA, 0xFFFFFBF, 0xFFFFEFF, 0xFFFAFFF, 0x2FFFF, 0x0, ]; pub const MCONST: Chunk = 0x1; // nist256 curve pub const CURVE_COF_I: isize = 1; pub const CURVE_A: isize = -3; pub const CURVE_B_I: isize = 0; pub const CURVE_COF: [Chunk; NLEN] = [0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]; pub const CURVE_B: [Chunk; NLEN] = [ 0x7D2604B, 0xCE3C3E2, 0x3B0F63B, 0x6B0CC5, 0x6BC651D, 0x5576988, 0x7B3EBBD, 0xAA3A93E, 0xAC635D8, 0x5, ]; pub const CURVE_ORDER: [Chunk; NLEN] = [ 0xC632551, 0xB9CAC2F, 0x79E84F3, 0xFAADA71, 0xFFFBCE6, 0xFFFFFFF, 0xFFFFFF, 0x0, 0xFFFFFFF, 0xF, ]; pub const CURVE_GX: [Chunk; NLEN] = [ 0x898C296, 0xA13945D, 0xB33A0F4, 0x7D812DE, 0xF27703, 0xE563A44, 0x7F8BCE6, 0xE12C424, 0xB17D1F2, 0x6, ]; pub const CURVE_GY: [Chunk; NLEN] = [ 0x7BF51F5, 0xB640683, 0x15ECECB, 0x33576B3, 0xE162BCE, 0x4A7C0F9, 0xB8EE7EB, 0xFE1A7F9, 0xFE342E2, 0x4, ]; pub const MODBYTES: usize = 32; pub const BASEBITS: usize = 28; pub const MODBITS: usize = 256; pub const MOD8: usize = 7; pub const MODTYPE: ModType = ModType::NOT_SPECIAL; pub const SH: usize = 14; pub const CURVETYPE: CurveType = CurveType::WEIERSTRASS; pub const CURVE_PAIRING_TYPE: CurvePairingType = CurvePairingType::NOT; pub const SEXTIC_TWIST: SexticTwist = SexticTwist::NOT; pub const ATE_BITS: usize = 0;
pub const AESKEY: usize = 16;
pub const SIGN_OF_X: SignOfX = SignOfX::NOT; pub const HASH_TYPE: usize = 32;
random_line_split
shootout-nbody.rs
use std::f64; use std::from_str::FromStr; use std::os; use std::uint::range; use std::vec; static PI: f64 = 3.141592653589793; static SOLAR_MASS: f64 = 4.0 * PI * PI; static YEAR: f64 = 365.24; static N_BODIES: uint = 5; static BODIES: [Planet,..N_BODIES] = [ // Sun Planet { x: [ 0.0, 0.0, 0.0 ], v: [ 0.0, 0.0, 0.0 ], mass: SOLAR_MASS, }, // Jupiter Planet { x: [ 4.84143144246472090e+00, -1.16032004402742839e+00, -1.03622044471123109e-01, ], v: [ 1.66007664274403694e-03 * YEAR, 7.69901118419740425e-03 * YEAR, -6.90460016972063023e-05 * YEAR, ], mass: 9.54791938424326609e-04 * SOLAR_MASS, }, // Saturn Planet { x: [ 8.34336671824457987e+00, 4.12479856412430479e+00, -4.03523417114321381e-01, ], v: [ -2.76742510726862411e-03 * YEAR, 4.99852801234917238e-03 * YEAR, 2.30417297573763929e-05 * YEAR, ], mass: 2.85885980666130812e-04 * SOLAR_MASS, }, // Uranus Planet { x: [ 1.28943695621391310e+01, -1.51111514016986312e+01, -2.23307578892655734e-01, ], v: [ 2.96460137564761618e-03 * YEAR, 2.37847173959480950e-03 * YEAR, -2.96589568540237556e-05 * YEAR, ], mass: 4.36624404335156298e-05 * SOLAR_MASS, }, // Neptune Planet { x: [ 1.53796971148509165e+01, -2.59193146099879641e+01, 1.79258772950371181e-01, ], v: [ 2.68067772490389322e-03 * YEAR, 1.62824170038242295e-03 * YEAR, -9.51592254519715870e-05 * YEAR, ], mass: 5.15138902046611451e-05 * SOLAR_MASS, }, ]; struct Planet { x: [f64,..3], v: [f64,..3], mass: f64, } fn advance(bodies: &mut [Planet,..N_BODIES], dt: f64, steps: i32) { let mut d = [ 0.0,..3 ]; for (steps as uint).times {
d[2] = bodies[i].x[2] - bodies[j].x[2]; let d2 = d[0]*d[0] + d[1]*d[1] + d[2]*d[2]; let mag = dt / (d2 * f64::sqrt(d2)); let a_mass = bodies[i].mass; let b_mass = bodies[j].mass; bodies[i].v[0] -= d[0] * b_mass * mag; bodies[i].v[1] -= d[1] * b_mass * mag; bodies[i].v[2] -= d[2] * b_mass * mag; bodies[j].v[0] += d[0] * a_mass * mag; bodies[j].v[1] += d[1] * a_mass * mag; bodies[j].v[2] += d[2] * a_mass * mag; } } for bodies.mut_iter().advance |a| { a.x[0] += dt * a.v[0]; a.x[1] += dt * a.v[1]; a.x[2] += dt * a.v[2]; } } } fn energy(bodies: &[Planet,..N_BODIES]) -> f64 { let mut e = 0.0; let mut d = [ 0.0,..3 ]; for range(0, N_BODIES) |i| { for range(0, 3) |k| { e += bodies[i].mass * bodies[i].v[k] * bodies[i].v[k] / 2.0; } for range(i + 1, N_BODIES) |j| { for range(0, 3) |k| { d[k] = bodies[i].x[k] - bodies[j].x[k]; } let dist = f64::sqrt(d[0]*d[0] + d[1]*d[1] + d[2]*d[2]); e -= bodies[i].mass * bodies[j].mass / dist; } } e } fn offset_momentum(bodies: &mut [Planet,..N_BODIES]) { for range(0, N_BODIES) |i| { for range(0, 3) |k| { bodies[0].v[k] -= bodies[i].v[k] * bodies[i].mass / SOLAR_MASS; } } } fn main() { let n: i32 = FromStr::from_str(os::args()[1]).get(); let mut bodies = BODIES; offset_momentum(&mut bodies); println(fmt!("%.9f", energy(&bodies) as float)); advance(&mut bodies, 0.01, n); println(fmt!("%.9f", energy(&bodies) as float)); }
for range(0, N_BODIES) |i| { for range(i + 1, N_BODIES) |j| { d[0] = bodies[i].x[0] - bodies[j].x[0]; d[1] = bodies[i].x[1] - bodies[j].x[1];
random_line_split
shootout-nbody.rs
use std::f64; use std::from_str::FromStr; use std::os; use std::uint::range; use std::vec; static PI: f64 = 3.141592653589793; static SOLAR_MASS: f64 = 4.0 * PI * PI; static YEAR: f64 = 365.24; static N_BODIES: uint = 5; static BODIES: [Planet,..N_BODIES] = [ // Sun Planet { x: [ 0.0, 0.0, 0.0 ], v: [ 0.0, 0.0, 0.0 ], mass: SOLAR_MASS, }, // Jupiter Planet { x: [ 4.84143144246472090e+00, -1.16032004402742839e+00, -1.03622044471123109e-01, ], v: [ 1.66007664274403694e-03 * YEAR, 7.69901118419740425e-03 * YEAR, -6.90460016972063023e-05 * YEAR, ], mass: 9.54791938424326609e-04 * SOLAR_MASS, }, // Saturn Planet { x: [ 8.34336671824457987e+00, 4.12479856412430479e+00, -4.03523417114321381e-01, ], v: [ -2.76742510726862411e-03 * YEAR, 4.99852801234917238e-03 * YEAR, 2.30417297573763929e-05 * YEAR, ], mass: 2.85885980666130812e-04 * SOLAR_MASS, }, // Uranus Planet { x: [ 1.28943695621391310e+01, -1.51111514016986312e+01, -2.23307578892655734e-01, ], v: [ 2.96460137564761618e-03 * YEAR, 2.37847173959480950e-03 * YEAR, -2.96589568540237556e-05 * YEAR, ], mass: 4.36624404335156298e-05 * SOLAR_MASS, }, // Neptune Planet { x: [ 1.53796971148509165e+01, -2.59193146099879641e+01, 1.79258772950371181e-01, ], v: [ 2.68067772490389322e-03 * YEAR, 1.62824170038242295e-03 * YEAR, -9.51592254519715870e-05 * YEAR, ], mass: 5.15138902046611451e-05 * SOLAR_MASS, }, ]; struct Planet { x: [f64,..3], v: [f64,..3], mass: f64, } fn advance(bodies: &mut [Planet,..N_BODIES], dt: f64, steps: i32)
bodies[j].v[2] += d[2] * a_mass * mag; } } for bodies.mut_iter().advance |a| { a.x[0] += dt * a.v[0]; a.x[1] += dt * a.v[1]; a.x[2] += dt * a.v[2]; } } } fn energy(bodies: &[Planet,..N_BODIES]) -> f64 { let mut e = 0.0; let mut d = [ 0.0,..3 ]; for range(0, N_BODIES) |i| { for range(0, 3) |k| { e += bodies[i].mass * bodies[i].v[k] * bodies[i].v[k] / 2.0; } for range(i + 1, N_BODIES) |j| { for range(0, 3) |k| { d[k] = bodies[i].x[k] - bodies[j].x[k]; } let dist = f64::sqrt(d[0]*d[0] + d[1]*d[1] + d[2]*d[2]); e -= bodies[i].mass * bodies[j].mass / dist; } } e } fn offset_momentum(bodies: &mut [Planet,..N_BODIES]) { for range(0, N_BODIES) |i| { for range(0, 3) |k| { bodies[0].v[k] -= bodies[i].v[k] * bodies[i].mass / SOLAR_MASS; } } } fn main() { let n: i32 = FromStr::from_str(os::args()[1]).get(); let mut bodies = BODIES; offset_momentum(&mut bodies); println(fmt!("%.9f", energy(&bodies) as float)); advance(&mut bodies, 0.01, n); println(fmt!("%.9f", energy(&bodies) as float)); }
{ let mut d = [ 0.0, ..3 ]; for (steps as uint).times { for range(0, N_BODIES) |i| { for range(i + 1, N_BODIES) |j| { d[0] = bodies[i].x[0] - bodies[j].x[0]; d[1] = bodies[i].x[1] - bodies[j].x[1]; d[2] = bodies[i].x[2] - bodies[j].x[2]; let d2 = d[0]*d[0] + d[1]*d[1] + d[2]*d[2]; let mag = dt / (d2 * f64::sqrt(d2)); let a_mass = bodies[i].mass; let b_mass = bodies[j].mass; bodies[i].v[0] -= d[0] * b_mass * mag; bodies[i].v[1] -= d[1] * b_mass * mag; bodies[i].v[2] -= d[2] * b_mass * mag; bodies[j].v[0] += d[0] * a_mass * mag; bodies[j].v[1] += d[1] * a_mass * mag;
identifier_body
shootout-nbody.rs
use std::f64; use std::from_str::FromStr; use std::os; use std::uint::range; use std::vec; static PI: f64 = 3.141592653589793; static SOLAR_MASS: f64 = 4.0 * PI * PI; static YEAR: f64 = 365.24; static N_BODIES: uint = 5; static BODIES: [Planet,..N_BODIES] = [ // Sun Planet { x: [ 0.0, 0.0, 0.0 ], v: [ 0.0, 0.0, 0.0 ], mass: SOLAR_MASS, }, // Jupiter Planet { x: [ 4.84143144246472090e+00, -1.16032004402742839e+00, -1.03622044471123109e-01, ], v: [ 1.66007664274403694e-03 * YEAR, 7.69901118419740425e-03 * YEAR, -6.90460016972063023e-05 * YEAR, ], mass: 9.54791938424326609e-04 * SOLAR_MASS, }, // Saturn Planet { x: [ 8.34336671824457987e+00, 4.12479856412430479e+00, -4.03523417114321381e-01, ], v: [ -2.76742510726862411e-03 * YEAR, 4.99852801234917238e-03 * YEAR, 2.30417297573763929e-05 * YEAR, ], mass: 2.85885980666130812e-04 * SOLAR_MASS, }, // Uranus Planet { x: [ 1.28943695621391310e+01, -1.51111514016986312e+01, -2.23307578892655734e-01, ], v: [ 2.96460137564761618e-03 * YEAR, 2.37847173959480950e-03 * YEAR, -2.96589568540237556e-05 * YEAR, ], mass: 4.36624404335156298e-05 * SOLAR_MASS, }, // Neptune Planet { x: [ 1.53796971148509165e+01, -2.59193146099879641e+01, 1.79258772950371181e-01, ], v: [ 2.68067772490389322e-03 * YEAR, 1.62824170038242295e-03 * YEAR, -9.51592254519715870e-05 * YEAR, ], mass: 5.15138902046611451e-05 * SOLAR_MASS, }, ]; struct Planet { x: [f64,..3], v: [f64,..3], mass: f64, } fn advance(bodies: &mut [Planet,..N_BODIES], dt: f64, steps: i32) { let mut d = [ 0.0,..3 ]; for (steps as uint).times { for range(0, N_BODIES) |i| { for range(i + 1, N_BODIES) |j| { d[0] = bodies[i].x[0] - bodies[j].x[0]; d[1] = bodies[i].x[1] - bodies[j].x[1]; d[2] = bodies[i].x[2] - bodies[j].x[2]; let d2 = d[0]*d[0] + d[1]*d[1] + d[2]*d[2]; let mag = dt / (d2 * f64::sqrt(d2)); let a_mass = bodies[i].mass; let b_mass = bodies[j].mass; bodies[i].v[0] -= d[0] * b_mass * mag; bodies[i].v[1] -= d[1] * b_mass * mag; bodies[i].v[2] -= d[2] * b_mass * mag; bodies[j].v[0] += d[0] * a_mass * mag; bodies[j].v[1] += d[1] * a_mass * mag; bodies[j].v[2] += d[2] * a_mass * mag; } } for bodies.mut_iter().advance |a| { a.x[0] += dt * a.v[0]; a.x[1] += dt * a.v[1]; a.x[2] += dt * a.v[2]; } } } fn energy(bodies: &[Planet,..N_BODIES]) -> f64 { let mut e = 0.0; let mut d = [ 0.0,..3 ]; for range(0, N_BODIES) |i| { for range(0, 3) |k| { e += bodies[i].mass * bodies[i].v[k] * bodies[i].v[k] / 2.0; } for range(i + 1, N_BODIES) |j| { for range(0, 3) |k| { d[k] = bodies[i].x[k] - bodies[j].x[k]; } let dist = f64::sqrt(d[0]*d[0] + d[1]*d[1] + d[2]*d[2]); e -= bodies[i].mass * bodies[j].mass / dist; } } e } fn offset_momentum(bodies: &mut [Planet,..N_BODIES]) { for range(0, N_BODIES) |i| { for range(0, 3) |k| { bodies[0].v[k] -= bodies[i].v[k] * bodies[i].mass / SOLAR_MASS; } } } fn
() { let n: i32 = FromStr::from_str(os::args()[1]).get(); let mut bodies = BODIES; offset_momentum(&mut bodies); println(fmt!("%.9f", energy(&bodies) as float)); advance(&mut bodies, 0.01, n); println(fmt!("%.9f", energy(&bodies) as float)); }
main
identifier_name
sdl.rs
#![allow(non_camel_case_types)] #![allow(dead_code)] use std::os::raw::{c_int, c_uint, c_char, c_void}; pub type Uint8 = u8; pub type Uint32 = u32; pub type Sint32 = i32; pub type Uint16 = i16; pub type SDL_Keycode = Sint32; #[repr(u32)] #[derive(Copy,Clone)] pub enum SDL_BlendMode{ NONE = 0x00000000, BLEND = 0x00000001, ADD = 0x00000002, MOD = 0x00000004 } #[repr(u32)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum SDL_Scancode { UNKNOWN = 0, A = 4, B = 5, C = 6, D = 7, E = 8, F = 9, G = 10, H = 11, I = 12, J = 13, K = 14, L = 15, M = 16, N = 17, O = 18, P = 19, Q = 20, R = 21, S = 22, T = 23, U = 24, V = 25, W = 26, X = 27, Y = 28, Z = 29, N1 = 30, N2 = 31, N3 = 32, N4 = 33, N5 = 34, N6 = 35, N7 = 36, N8 = 37, N9 = 38, N0 = 39, RETURN = 40, ESCAPE = 41, BACKSPACE = 42, TAB = 43, SPACE = 44, MINUS = 45, EQUALS = 46, LEFTBRACKET = 47, RIGHTBRACKET = 48,
COMMA = 54, PERIOD = 55, SLASH = 56, CAPSLOCK = 57, F1 = 58, F2 = 59, F3 = 60, F4 = 61, F5 = 62, F6 = 63, F7 = 64, F8 = 65, F9 = 66, F10 = 67, F11 = 68, F12 = 69, PRINTSCREEN = 70, SCROLLLOCK = 71, PAUSE = 72, INSERT = 73, HOME = 74, PAGEUP = 75, DELETE = 76, END = 77, PAGEDOWN = 78, RIGHT = 79, LEFT = 80, DOWN = 81, UP = 82, NUMLOCKCLEAR = 83, KP_DIVIDE = 84, KP_MULTIPLY = 85, KP_MINUS = 86, KP_PLUS = 87, KP_ENTER = 88, KP_1 = 89, KP_2 = 90, KP_3 = 91, KP_4 = 92, KP_5 = 93, KP_6 = 94, KP_7 = 95, KP_8 = 96, KP_9 = 97, KP_0 = 98, KP_PERIOD = 99, NONUSBACKSLASH = 100, APPLICATION = 101, POWER = 102, KP_EQUALS = 103, F13 = 104, F14 = 105, F15 = 106, F16 = 107, F17 = 108, F18 = 109, F19 = 110, F20 = 111, F21 = 112, F22 = 113, F23 = 114, F24 = 115, EXECUTE = 116, HELP = 117, MENU = 118, SELECT = 119, STOP = 120, AGAIN = 121, UNDO = 122, CUT = 123, COPY = 124, PASTE = 125, FIND = 126, MUTE = 127, VOLUMEUP = 128, VOLUMEDOWN = 129, KP_COMMA = 133, KP_EQUALSAS400 = 134, INTERNATIONAL1 = 135, INTERNATIONAL2 = 136, INTERNATIONAL3 = 137, INTERNATIONAL4 = 138, INTERNATIONAL5 = 139, INTERNATIONAL6 = 140, INTERNATIONAL7 = 141, INTERNATIONAL8 = 142, INTERNATIONAL9 = 143, LANG1 = 144, LANG2 = 145, LANG3 = 146, LANG4 = 147, LANG5 = 148, LANG6 = 149, LANG7 = 150, LANG8 = 151, LANG9 = 152, ALTERASE = 153, SYSREQ = 154, CANCEL = 155, CLEAR = 156, PRIOR = 157, RETURN2 = 158, SEPARATOR = 159, OUT = 160, OPER = 161, CLEARAGAIN = 162, CRSEL = 163, EXSEL = 164, KP_00 = 176, KP_000 = 177, THOUSANDSSEPARATOR = 178, DECIMALSEPARATOR = 179, CURRENCYUNIT = 180, CURRENCYSUBUNIT = 181, KP_LEFTPAREN = 182, KP_RIGHTPAREN = 183, KP_LEFTBRACE = 184, KP_RIGHTBRACE = 185, KP_TAB = 186, KP_BACKSPACE = 187, KP_A = 188, KP_B = 189, KP_C = 190, KP_D = 191, KP_E = 192, KP_F = 193, KP_XOR = 194, KP_POWER = 195, KP_PERCENT = 196, KP_LESS = 197, KP_GREATER = 198, KP_AMPERSAND = 199, KP_DBLAMPERSAND = 200, KP_VERTICALBAR = 201, KP_DBLVERTICALBAR = 202, KP_COLON = 203, KP_HASH = 204, KP_SPACE = 205, KP_AT = 206, KP_EXCLAM = 207, KP_MEMSTORE = 208, KP_MEMRECALL = 209, KP_MEMCLEAR = 210, KP_MEMADD = 211, KP_MEMSUBTRACT = 212, KP_MEMMULTIPLY = 213, KP_MEMDIVIDE = 214, KP_PLUSMINUS = 215, KP_CLEAR = 216, KP_CLEARENTRY = 217, KP_BINARY = 218, KP_OCTAL = 219, KP_DECIMAL = 220, KP_HEXADECIMAL = 221, LCTRL = 224, LSHIFT = 225, LALT = 226, LGUI = 227, RCTRL = 228, RSHIFT = 229, RALT = 230, RGUI = 231, MODE = 257, AUDIONEXT = 258, AUDIOPREV = 259, AUDIOSTOP = 260, AUDIOPLAY = 261, AUDIOMUTE = 262, MEDIASELECT = 263, WWW = 264, MAIL = 265, CALCULATOR = 266, COMPUTER = 267, AC_SEARCH = 268, AC_HOME = 269, AC_BACK = 270, AC_FORWARD = 271, AC_STOP = 272, AC_REFRESH = 273, AC_BOOKMARKS = 274, BRIGHTNESSDOWN = 275, BRIGHTNESSUP = 276, DISPLAYSWITCH = 277, KBDILLUMTOGGLE = 278, KBDILLUMDOWN = 279, KBDILLUMUP = 280, EJECT = 281, SLEEP = 282, APP1 = 283, APP2 = 284, AUDIOREWIND = 285, AUDIOFASTFORWARD = 286, SDL_NUM_SCANCODES = 512 } #[repr(C)] #[derive(Clone,Copy)] pub struct SDL_Keysym { pub scancode: SDL_Scancode, pub sym: SDL_Keycode, pub mode: Uint16, pub unused: Uint32, } #[repr(C)] #[derive(Clone,Copy)] pub struct SDL_KeyboardEvent { pub ty: Uint32, pub timestamp: Uint32, pub window_id: Uint32, pub state: Uint8, pub repeat: Uint8, pub padding2: Uint8, pub padding3: Uint8, pub keysym: SDL_Keysym } #[repr(C)] pub union SDL_Event { pub event_type: Uint32, pub key: SDL_KeyboardEvent, padding: [u8;56], paranoid_padding: [u8;128] } pub const SDL_WINDOWPOS_CENTERED_MASK: c_uint = 0x2FFF0000; pub const SDL_WINDOWPOS_CENTERED: c_uint = SDL_WINDOWPOS_CENTERED_MASK; pub const SDL_WINDOW_SHOWN: c_uint = 0x00000004; pub const SDL_RENDERER_SOFTWARE: c_uint = 0x00000001; pub const SDL_RENDERER_ACCELERATED: c_uint = 0x00000002; pub const SDL_KEYDOWN: u32 = 0x300; pub const SDL_KEYUP: u32 = 0x301; pub const SDL_PIXELFORMAT_RGB24: u32 = 0x17101803; pub const SDL_PIXELFORMAT_RGBA8888: u32 = 0x16462004; pub const SDL_TEXTUREACCESS_TARGET: c_int = 2; #[repr(C)] pub struct SDL_Window { _mem: [u8; 0] } #[repr(C)] pub struct SDL_Renderer { _mem: [u8; 0] } #[repr(C)] pub struct SDL_Texture { _mem: [u8; 0] } #[repr(C)] pub struct SDL_Rect { pub x: c_int, pub y: c_int, pub w: c_int, pub h: c_int } #[link(name = "SDL2")] extern "C" { // SDL_video.h pub fn SDL_CreateWindow( title: *const c_char, x: c_int, y: c_int, w: c_int, h: c_int, flags: Uint32 ) -> *mut SDL_Window; // SDL_render.h pub fn SDL_CreateRenderer( window: *mut SDL_Window, index: c_int, flags: Uint32 ) -> *mut SDL_Renderer; pub fn SDL_SetRenderDrawColor(rdr: *mut SDL_Renderer, r: Uint8, g: Uint8, b: Uint8, a: Uint8 ); pub fn SDL_RenderClear(rdr: *mut SDL_Renderer) -> c_int; pub fn SDL_RenderPresent(rdr: *mut SDL_Renderer); pub fn SDL_RenderDrawPoint(rdr: *mut SDL_Renderer, x: c_int, y: c_int) -> c_int; pub fn SDL_RenderFillRect(rdr: *mut SDL_Renderer, rect: *const SDL_Rect) -> c_int; pub fn SDL_Delay(ms: Uint32); pub fn SDL_PollEvent(event: *mut SDL_Event) -> c_int; pub fn SDL_Quit(); pub fn SDL_DestroyWindow(window: *mut SDL_Window); pub fn SDL_SetRenderDrawBlendMode( rdr: *mut SDL_Renderer, blend_mode: SDL_BlendMode ) -> c_int; pub fn SDL_RenderReadPixels(rdr: *mut SDL_Renderer, rect: *const SDL_Rect, format: Uint32, pixels: *mut c_void, picth: c_int ) -> c_int; pub fn SDL_CreateTexture(rdr: *mut SDL_Renderer, format: Uint32, access: c_int, w: c_int, h: c_int ) -> *mut SDL_Texture; pub fn SDL_SetRenderTarget(rdr: *mut SDL_Renderer, texture: *mut SDL_Texture ) -> c_int; pub fn SDL_RenderCopy(rdr: *mut SDL_Renderer, texture: *mut SDL_Texture, srcrect: *const SDL_Rect, dstrect: *const SDL_Rect ) -> c_int; }
BACKSLASH = 49, NONUSHASH = 50, SEMICOLON = 51, APOSTROPHE = 52, GRAVE = 53,
random_line_split
sdl.rs
#![allow(non_camel_case_types)] #![allow(dead_code)] use std::os::raw::{c_int, c_uint, c_char, c_void}; pub type Uint8 = u8; pub type Uint32 = u32; pub type Sint32 = i32; pub type Uint16 = i16; pub type SDL_Keycode = Sint32; #[repr(u32)] #[derive(Copy,Clone)] pub enum SDL_BlendMode{ NONE = 0x00000000, BLEND = 0x00000001, ADD = 0x00000002, MOD = 0x00000004 } #[repr(u32)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum SDL_Scancode { UNKNOWN = 0, A = 4, B = 5, C = 6, D = 7, E = 8, F = 9, G = 10, H = 11, I = 12, J = 13, K = 14, L = 15, M = 16, N = 17, O = 18, P = 19, Q = 20, R = 21, S = 22, T = 23, U = 24, V = 25, W = 26, X = 27, Y = 28, Z = 29, N1 = 30, N2 = 31, N3 = 32, N4 = 33, N5 = 34, N6 = 35, N7 = 36, N8 = 37, N9 = 38, N0 = 39, RETURN = 40, ESCAPE = 41, BACKSPACE = 42, TAB = 43, SPACE = 44, MINUS = 45, EQUALS = 46, LEFTBRACKET = 47, RIGHTBRACKET = 48, BACKSLASH = 49, NONUSHASH = 50, SEMICOLON = 51, APOSTROPHE = 52, GRAVE = 53, COMMA = 54, PERIOD = 55, SLASH = 56, CAPSLOCK = 57, F1 = 58, F2 = 59, F3 = 60, F4 = 61, F5 = 62, F6 = 63, F7 = 64, F8 = 65, F9 = 66, F10 = 67, F11 = 68, F12 = 69, PRINTSCREEN = 70, SCROLLLOCK = 71, PAUSE = 72, INSERT = 73, HOME = 74, PAGEUP = 75, DELETE = 76, END = 77, PAGEDOWN = 78, RIGHT = 79, LEFT = 80, DOWN = 81, UP = 82, NUMLOCKCLEAR = 83, KP_DIVIDE = 84, KP_MULTIPLY = 85, KP_MINUS = 86, KP_PLUS = 87, KP_ENTER = 88, KP_1 = 89, KP_2 = 90, KP_3 = 91, KP_4 = 92, KP_5 = 93, KP_6 = 94, KP_7 = 95, KP_8 = 96, KP_9 = 97, KP_0 = 98, KP_PERIOD = 99, NONUSBACKSLASH = 100, APPLICATION = 101, POWER = 102, KP_EQUALS = 103, F13 = 104, F14 = 105, F15 = 106, F16 = 107, F17 = 108, F18 = 109, F19 = 110, F20 = 111, F21 = 112, F22 = 113, F23 = 114, F24 = 115, EXECUTE = 116, HELP = 117, MENU = 118, SELECT = 119, STOP = 120, AGAIN = 121, UNDO = 122, CUT = 123, COPY = 124, PASTE = 125, FIND = 126, MUTE = 127, VOLUMEUP = 128, VOLUMEDOWN = 129, KP_COMMA = 133, KP_EQUALSAS400 = 134, INTERNATIONAL1 = 135, INTERNATIONAL2 = 136, INTERNATIONAL3 = 137, INTERNATIONAL4 = 138, INTERNATIONAL5 = 139, INTERNATIONAL6 = 140, INTERNATIONAL7 = 141, INTERNATIONAL8 = 142, INTERNATIONAL9 = 143, LANG1 = 144, LANG2 = 145, LANG3 = 146, LANG4 = 147, LANG5 = 148, LANG6 = 149, LANG7 = 150, LANG8 = 151, LANG9 = 152, ALTERASE = 153, SYSREQ = 154, CANCEL = 155, CLEAR = 156, PRIOR = 157, RETURN2 = 158, SEPARATOR = 159, OUT = 160, OPER = 161, CLEARAGAIN = 162, CRSEL = 163, EXSEL = 164, KP_00 = 176, KP_000 = 177, THOUSANDSSEPARATOR = 178, DECIMALSEPARATOR = 179, CURRENCYUNIT = 180, CURRENCYSUBUNIT = 181, KP_LEFTPAREN = 182, KP_RIGHTPAREN = 183, KP_LEFTBRACE = 184, KP_RIGHTBRACE = 185, KP_TAB = 186, KP_BACKSPACE = 187, KP_A = 188, KP_B = 189, KP_C = 190, KP_D = 191, KP_E = 192, KP_F = 193, KP_XOR = 194, KP_POWER = 195, KP_PERCENT = 196, KP_LESS = 197, KP_GREATER = 198, KP_AMPERSAND = 199, KP_DBLAMPERSAND = 200, KP_VERTICALBAR = 201, KP_DBLVERTICALBAR = 202, KP_COLON = 203, KP_HASH = 204, KP_SPACE = 205, KP_AT = 206, KP_EXCLAM = 207, KP_MEMSTORE = 208, KP_MEMRECALL = 209, KP_MEMCLEAR = 210, KP_MEMADD = 211, KP_MEMSUBTRACT = 212, KP_MEMMULTIPLY = 213, KP_MEMDIVIDE = 214, KP_PLUSMINUS = 215, KP_CLEAR = 216, KP_CLEARENTRY = 217, KP_BINARY = 218, KP_OCTAL = 219, KP_DECIMAL = 220, KP_HEXADECIMAL = 221, LCTRL = 224, LSHIFT = 225, LALT = 226, LGUI = 227, RCTRL = 228, RSHIFT = 229, RALT = 230, RGUI = 231, MODE = 257, AUDIONEXT = 258, AUDIOPREV = 259, AUDIOSTOP = 260, AUDIOPLAY = 261, AUDIOMUTE = 262, MEDIASELECT = 263, WWW = 264, MAIL = 265, CALCULATOR = 266, COMPUTER = 267, AC_SEARCH = 268, AC_HOME = 269, AC_BACK = 270, AC_FORWARD = 271, AC_STOP = 272, AC_REFRESH = 273, AC_BOOKMARKS = 274, BRIGHTNESSDOWN = 275, BRIGHTNESSUP = 276, DISPLAYSWITCH = 277, KBDILLUMTOGGLE = 278, KBDILLUMDOWN = 279, KBDILLUMUP = 280, EJECT = 281, SLEEP = 282, APP1 = 283, APP2 = 284, AUDIOREWIND = 285, AUDIOFASTFORWARD = 286, SDL_NUM_SCANCODES = 512 } #[repr(C)] #[derive(Clone,Copy)] pub struct SDL_Keysym { pub scancode: SDL_Scancode, pub sym: SDL_Keycode, pub mode: Uint16, pub unused: Uint32, } #[repr(C)] #[derive(Clone,Copy)] pub struct SDL_KeyboardEvent { pub ty: Uint32, pub timestamp: Uint32, pub window_id: Uint32, pub state: Uint8, pub repeat: Uint8, pub padding2: Uint8, pub padding3: Uint8, pub keysym: SDL_Keysym } #[repr(C)] pub union SDL_Event { pub event_type: Uint32, pub key: SDL_KeyboardEvent, padding: [u8;56], paranoid_padding: [u8;128] } pub const SDL_WINDOWPOS_CENTERED_MASK: c_uint = 0x2FFF0000; pub const SDL_WINDOWPOS_CENTERED: c_uint = SDL_WINDOWPOS_CENTERED_MASK; pub const SDL_WINDOW_SHOWN: c_uint = 0x00000004; pub const SDL_RENDERER_SOFTWARE: c_uint = 0x00000001; pub const SDL_RENDERER_ACCELERATED: c_uint = 0x00000002; pub const SDL_KEYDOWN: u32 = 0x300; pub const SDL_KEYUP: u32 = 0x301; pub const SDL_PIXELFORMAT_RGB24: u32 = 0x17101803; pub const SDL_PIXELFORMAT_RGBA8888: u32 = 0x16462004; pub const SDL_TEXTUREACCESS_TARGET: c_int = 2; #[repr(C)] pub struct SDL_Window { _mem: [u8; 0] } #[repr(C)] pub struct
{ _mem: [u8; 0] } #[repr(C)] pub struct SDL_Texture { _mem: [u8; 0] } #[repr(C)] pub struct SDL_Rect { pub x: c_int, pub y: c_int, pub w: c_int, pub h: c_int } #[link(name = "SDL2")] extern "C" { // SDL_video.h pub fn SDL_CreateWindow( title: *const c_char, x: c_int, y: c_int, w: c_int, h: c_int, flags: Uint32 ) -> *mut SDL_Window; // SDL_render.h pub fn SDL_CreateRenderer( window: *mut SDL_Window, index: c_int, flags: Uint32 ) -> *mut SDL_Renderer; pub fn SDL_SetRenderDrawColor(rdr: *mut SDL_Renderer, r: Uint8, g: Uint8, b: Uint8, a: Uint8 ); pub fn SDL_RenderClear(rdr: *mut SDL_Renderer) -> c_int; pub fn SDL_RenderPresent(rdr: *mut SDL_Renderer); pub fn SDL_RenderDrawPoint(rdr: *mut SDL_Renderer, x: c_int, y: c_int) -> c_int; pub fn SDL_RenderFillRect(rdr: *mut SDL_Renderer, rect: *const SDL_Rect) -> c_int; pub fn SDL_Delay(ms: Uint32); pub fn SDL_PollEvent(event: *mut SDL_Event) -> c_int; pub fn SDL_Quit(); pub fn SDL_DestroyWindow(window: *mut SDL_Window); pub fn SDL_SetRenderDrawBlendMode( rdr: *mut SDL_Renderer, blend_mode: SDL_BlendMode ) -> c_int; pub fn SDL_RenderReadPixels(rdr: *mut SDL_Renderer, rect: *const SDL_Rect, format: Uint32, pixels: *mut c_void, picth: c_int ) -> c_int; pub fn SDL_CreateTexture(rdr: *mut SDL_Renderer, format: Uint32, access: c_int, w: c_int, h: c_int ) -> *mut SDL_Texture; pub fn SDL_SetRenderTarget(rdr: *mut SDL_Renderer, texture: *mut SDL_Texture ) -> c_int; pub fn SDL_RenderCopy(rdr: *mut SDL_Renderer, texture: *mut SDL_Texture, srcrect: *const SDL_Rect, dstrect: *const SDL_Rect ) -> c_int; }
SDL_Renderer
identifier_name
build.rs
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::env; use std::io::Write; use std::path::Path; use std::process::Command; use std::str::{self, FromStr}; fn main() { println!("cargo:rustc-cfg=build_script_ran"); let minor = match rustc_minor_version() { Some(minor) => minor, None => return, }; let target = env::var("TARGET").unwrap(); if minor >= 34 { println!("cargo:rustc-cfg=is_new_rustc"); } else { println!("cargo:rustc-cfg=is_old_rustc"); } if target.contains("android") { println!("cargo:rustc-cfg=is_android"); } if target.contains("darwin") { println!("cargo:rustc-cfg=is_mac"); } let feature_a_enabled = env::var_os("CARGO_FEATURE_MY_FEATURE_A").is_some(); if feature_a_enabled { println!("cargo:rustc-cfg=has_feature_a"); } let feature_b_enabled = env::var_os("CARGO_FEATURE_MY_FEATURE_B").is_some(); if feature_b_enabled { println!("cargo:rustc-cfg=has_feature_b"); } // Some tests as to whether we're properly emulating various cargo features. assert!(Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("build.rs").exists()); assert!(Path::new("build.rs").exists()); assert!(Path::new(&env::var_os("OUT_DIR").unwrap()).exists()); generate_some_code().unwrap(); } fn generate_some_code() -> std::io::Result<()> { let output_dir = Path::new(&env::var_os("OUT_DIR").unwrap()).join("generated"); let _ = std::fs::create_dir_all(&output_dir);
Ok(()) } fn rustc_minor_version() -> Option<u32> { let rustc = match env::var_os("RUSTC") { Some(rustc) => rustc, None => return None, }; let output = match Command::new(rustc).arg("--version").output() { Ok(output) => output, Err(_) => return None, }; let version = match str::from_utf8(&output.stdout) { Ok(version) => version, Err(_) => return None, }; let mut pieces = version.split('.'); if pieces.next()!= Some("rustc 1") { return None; } let next = match pieces.next() { Some(next) => next, None => return None, }; u32::from_str(next).ok() }
let mut file = std::fs::File::create(output_dir.join("generated.rs"))?; file.write_all(b"fn run_some_generated_code() -> u32 { 42 }")?;
random_line_split
build.rs
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::env; use std::io::Write; use std::path::Path; use std::process::Command; use std::str::{self, FromStr}; fn main() { println!("cargo:rustc-cfg=build_script_ran"); let minor = match rustc_minor_version() { Some(minor) => minor, None => return, }; let target = env::var("TARGET").unwrap(); if minor >= 34 { println!("cargo:rustc-cfg=is_new_rustc"); } else { println!("cargo:rustc-cfg=is_old_rustc"); } if target.contains("android") { println!("cargo:rustc-cfg=is_android"); } if target.contains("darwin") { println!("cargo:rustc-cfg=is_mac"); } let feature_a_enabled = env::var_os("CARGO_FEATURE_MY_FEATURE_A").is_some(); if feature_a_enabled { println!("cargo:rustc-cfg=has_feature_a"); } let feature_b_enabled = env::var_os("CARGO_FEATURE_MY_FEATURE_B").is_some(); if feature_b_enabled { println!("cargo:rustc-cfg=has_feature_b"); } // Some tests as to whether we're properly emulating various cargo features. assert!(Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("build.rs").exists()); assert!(Path::new("build.rs").exists()); assert!(Path::new(&env::var_os("OUT_DIR").unwrap()).exists()); generate_some_code().unwrap(); } fn generate_some_code() -> std::io::Result<()> { let output_dir = Path::new(&env::var_os("OUT_DIR").unwrap()).join("generated"); let _ = std::fs::create_dir_all(&output_dir); let mut file = std::fs::File::create(output_dir.join("generated.rs"))?; file.write_all(b"fn run_some_generated_code() -> u32 { 42 }")?; Ok(()) } fn rustc_minor_version() -> Option<u32>
let next = match pieces.next() { Some(next) => next, None => return None, }; u32::from_str(next).ok() }
{ let rustc = match env::var_os("RUSTC") { Some(rustc) => rustc, None => return None, }; let output = match Command::new(rustc).arg("--version").output() { Ok(output) => output, Err(_) => return None, }; let version = match str::from_utf8(&output.stdout) { Ok(version) => version, Err(_) => return None, }; let mut pieces = version.split('.'); if pieces.next() != Some("rustc 1") { return None; }
identifier_body
build.rs
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::env; use std::io::Write; use std::path::Path; use std::process::Command; use std::str::{self, FromStr}; fn
() { println!("cargo:rustc-cfg=build_script_ran"); let minor = match rustc_minor_version() { Some(minor) => minor, None => return, }; let target = env::var("TARGET").unwrap(); if minor >= 34 { println!("cargo:rustc-cfg=is_new_rustc"); } else { println!("cargo:rustc-cfg=is_old_rustc"); } if target.contains("android") { println!("cargo:rustc-cfg=is_android"); } if target.contains("darwin") { println!("cargo:rustc-cfg=is_mac"); } let feature_a_enabled = env::var_os("CARGO_FEATURE_MY_FEATURE_A").is_some(); if feature_a_enabled { println!("cargo:rustc-cfg=has_feature_a"); } let feature_b_enabled = env::var_os("CARGO_FEATURE_MY_FEATURE_B").is_some(); if feature_b_enabled { println!("cargo:rustc-cfg=has_feature_b"); } // Some tests as to whether we're properly emulating various cargo features. assert!(Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("build.rs").exists()); assert!(Path::new("build.rs").exists()); assert!(Path::new(&env::var_os("OUT_DIR").unwrap()).exists()); generate_some_code().unwrap(); } fn generate_some_code() -> std::io::Result<()> { let output_dir = Path::new(&env::var_os("OUT_DIR").unwrap()).join("generated"); let _ = std::fs::create_dir_all(&output_dir); let mut file = std::fs::File::create(output_dir.join("generated.rs"))?; file.write_all(b"fn run_some_generated_code() -> u32 { 42 }")?; Ok(()) } fn rustc_minor_version() -> Option<u32> { let rustc = match env::var_os("RUSTC") { Some(rustc) => rustc, None => return None, }; let output = match Command::new(rustc).arg("--version").output() { Ok(output) => output, Err(_) => return None, }; let version = match str::from_utf8(&output.stdout) { Ok(version) => version, Err(_) => return None, }; let mut pieces = version.split('.'); if pieces.next()!= Some("rustc 1") { return None; } let next = match pieces.next() { Some(next) => next, None => return None, }; u32::from_str(next).ok() }
main
identifier_name
update.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, CliError, Config}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_package: Option<String>, flag_aggressive: bool, flag_precise: Option<String>, flag_manifest_path: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Update dependencies as recorded in the local lock file. Usage: cargo update [options] Options: -h, --help Print this message -p SPEC, --package SPEC Package to update --aggressive Force updating all dependencies of <name> as well --precise PRECISE Update a single dependency to exactly PRECISE --manifest-path PATH Path to the manifest to compile -v, --verbose Use verbose output This command requires that a `Cargo.lock` already exists as generated by `cargo build` or related commands. If SPEC is given, then a conservative update of the lockfile will be performed. This means that only the dependency specified by SPEC will be updated. Its transitive dependencies will be updated only if SPEC cannot be updated without updating dependencies. All other dependencies will remain locked at their currently recorded versions. If PRECISE is specified, then --aggressive must not also be specified. The argument PRECISE is a string representing a precise revision that the package being updated should be updated to. For example, if the package comes from a git repository, then PRECISE would be the exact revision that the repository should be updated to. If SPEC is not given, then all dependencies will be re-resolved and updated. For more information about package id specifications, see `cargo help pkgid`. "; pub fn
(options: Options, config: &Config) -> CliResult<Option<()>> { debug!("executing; cmd=cargo-update; args={:?}", env::args().collect::<Vec<_>>()); config.shell().set_verbose(options.flag_verbose); let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path)); let spec = options.flag_package.as_ref(); let update_opts = ops::UpdateOptions { aggressive: options.flag_aggressive, precise: options.flag_precise.as_ref().map(|s| &s[..]), to_update: spec.map(|s| &s[..]), config: config, }; ops::update_lockfile(&root, &update_opts) .map(|_| None).map_err(|err| CliError::from_boxed(err, 101)) }
execute
identifier_name
update.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, CliError, Config}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_package: Option<String>, flag_aggressive: bool, flag_precise: Option<String>, flag_manifest_path: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Update dependencies as recorded in the local lock file. Usage: cargo update [options] Options: -h, --help Print this message -p SPEC, --package SPEC Package to update --aggressive Force updating all dependencies of <name> as well --precise PRECISE Update a single dependency to exactly PRECISE
If SPEC is given, then a conservative update of the lockfile will be performed. This means that only the dependency specified by SPEC will be updated. Its transitive dependencies will be updated only if SPEC cannot be updated without updating dependencies. All other dependencies will remain locked at their currently recorded versions. If PRECISE is specified, then --aggressive must not also be specified. The argument PRECISE is a string representing a precise revision that the package being updated should be updated to. For example, if the package comes from a git repository, then PRECISE would be the exact revision that the repository should be updated to. If SPEC is not given, then all dependencies will be re-resolved and updated. For more information about package id specifications, see `cargo help pkgid`. "; pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> { debug!("executing; cmd=cargo-update; args={:?}", env::args().collect::<Vec<_>>()); config.shell().set_verbose(options.flag_verbose); let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path)); let spec = options.flag_package.as_ref(); let update_opts = ops::UpdateOptions { aggressive: options.flag_aggressive, precise: options.flag_precise.as_ref().map(|s| &s[..]), to_update: spec.map(|s| &s[..]), config: config, }; ops::update_lockfile(&root, &update_opts) .map(|_| None).map_err(|err| CliError::from_boxed(err, 101)) }
--manifest-path PATH Path to the manifest to compile -v, --verbose Use verbose output This command requires that a `Cargo.lock` already exists as generated by `cargo build` or related commands.
random_line_split
mod.rs
use super::Path; use super::connector::Connector; use super::resolver::Resolve; use futures::{Async, Future, Poll, unsync}; use ordermap::OrderMap; use std::{cmp, io, net}; use std::collections::VecDeque; use std::time::{Duration, Instant}; use tacho; use tokio_core::reactor::Handle; use tokio_timer::Timer; mod dispatcher; mod endpoint; mod factory; pub use self::endpoint::{Connection as EndpointConnection, Ctx as EndpointCtx}; use self::endpoint::Endpoint; pub use self::factory::BalancerFactory; type Waiter = unsync::oneshot::Sender<endpoint::Connection>; /// A weighted concrete destination address. #[derive(Clone, Debug)] pub struct WeightedAddr { pub addr: ::std::net::SocketAddr, pub weight: f64, } impl WeightedAddr { pub fn new(addr: net::SocketAddr, weight: f64) -> WeightedAddr
} pub fn new( reactor: &Handle, timer: &Timer, dst: &Path, connector: Connector, resolve: Resolve, metrics: &tacho::Scope, ) -> Balancer { let (tx, rx) = unsync::mpsc::unbounded(); let dispatcher = dispatcher::new( reactor.clone(), timer.clone(), dst.clone(), connector, resolve, rx, Endpoints::default(), metrics, ); reactor.spawn(dispatcher.map_err(|_| {})); Balancer(tx) } #[derive(Clone)] pub struct Balancer(unsync::mpsc::UnboundedSender<Waiter>); impl Balancer { /// Obtains a connection to the destination. pub fn connect(&self) -> Connect { let (tx, rx) = unsync::oneshot::channel(); let result = unsync::mpsc::UnboundedSender::unbounded_send(&self.0, tx) .map_err(|_| io::Error::new(io::ErrorKind::Other, "lost dispatcher")) .map(|_| rx); Connect(Some(result)) } } pub struct Connect(Option<io::Result<unsync::oneshot::Receiver<endpoint::Connection>>>); impl Future for Connect { type Item = endpoint::Connection; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { let mut recv = self.0.take().expect( "connect must not be polled after completion", )?; match recv.poll() { Err(_) => Err(io::Error::new(io::ErrorKind::Interrupted, "canceled")), Ok(Async::Ready(conn)) => Ok(Async::Ready(conn)), Ok(Async::NotReady) => { self.0 = Some(Ok(recv)); Ok(Async::NotReady) } } } } pub type EndpointMap = OrderMap<net::SocketAddr, Endpoint>; pub type FailedMap = OrderMap<net::SocketAddr, (Instant, Endpoint)>; #[derive(Default)] pub struct Endpoints { //minimum_connections: usize, /// Endpoints considered available for new connections. available: EndpointMap, /// Endpoints that are still active but considered unavailable for new connections. retired: EndpointMap, failed: FailedMap, } impl Endpoints { pub fn available(&self) -> &EndpointMap { &self.available } pub fn failed(&self) -> &FailedMap { &self.failed } pub fn retired(&self) -> &EndpointMap { &self.retired } pub fn update_failed(&mut self, max_failures: usize, penalty: Duration) { let mut available = VecDeque::with_capacity(self.failed.len()); let mut failed = VecDeque::with_capacity(self.failed.len()); for (_, ep) in self.available.drain(..) { if ep.state().consecutive_failures < max_failures { available.push_back(ep); } else { failed.push_back((Instant::now(), ep)); } } for (_, (start, ep)) in self.failed.drain(..) { if start + penalty <= Instant::now() { available.push_back(ep); } else { failed.push_back((start, ep)); } } if available.is_empty() { while let Some((_, ep)) = failed.pop_front() { self.available.insert(ep.peer_addr(), ep); } } else { while let Some(ep) = available.pop_front() { self.available.insert(ep.peer_addr(), ep); } while let Some((since, ep)) = failed.pop_front() { self.failed.insert(ep.peer_addr(), (since, ep)); } } } // TODO: we need to do some sort of probation deal to manage endpoints that are // retired. pub fn update_resolved(&mut self, resolved: &[WeightedAddr]) { let mut temp = { let sz = cmp::max(self.available.len(), self.retired.len()); VecDeque::with_capacity(sz) }; let dsts = Endpoints::dsts_by_addr(resolved); self.check_retired(&dsts, &mut temp); self.check_available(&dsts, &mut temp); self.check_failed(&dsts); self.update_available_from_new(dsts); } /// Checks active endpoints. fn check_available( &mut self, dsts: &OrderMap<net::SocketAddr, f64>, temp: &mut VecDeque<Endpoint>, ) { for (addr, ep) in self.available.drain(..) { if dsts.contains_key(&addr) { temp.push_back(ep); } else if ep.is_idle() { drop(ep); } else { self.retired.insert(addr, ep); } } for _ in 0..temp.len() { let ep = temp.pop_front().unwrap(); self.available.insert(ep.peer_addr(), ep); } } /// Checks retired endpoints. /// /// Endpoints are either salvaged backed into the active pool, maintained as /// retired if still active, or dropped if inactive. fn check_retired( &mut self, dsts: &OrderMap<net::SocketAddr, f64>, temp: &mut VecDeque<Endpoint>, ) { for (addr, ep) in self.retired.drain(..) { if dsts.contains_key(&addr) { self.available.insert(addr, ep); } else if ep.is_idle() { drop(ep); } else { temp.push_back(ep); } } for _ in 0..temp.len() { let ep = temp.pop_front().unwrap(); self.retired.insert(ep.peer_addr(), ep); } } /// Checks failed endpoints. fn check_failed(&mut self, dsts: &OrderMap<net::SocketAddr, f64>) { let mut temp = VecDeque::with_capacity(self.failed.len()); for (addr, (since, ep)) in self.failed.drain(..) { if dsts.contains_key(&addr) { temp.push_back((since, ep)); } else if ep.is_idle() { drop(ep); } else { self.retired.insert(addr, ep); } } for _ in 0..temp.len() { let (instant, ep) = temp.pop_front().unwrap(); self.failed.insert(ep.peer_addr(), (instant, ep)); } } fn update_available_from_new(&mut self, mut dsts: OrderMap<net::SocketAddr, f64>) { // Add new endpoints or update the base weights of existing endpoints. //let metrics = self.endpoint_metrics.clone(); for (addr, weight) in dsts.drain(..) { if let Some(&mut (_, ref mut ep)) = self.failed.get_mut(&addr) { ep.set_weight(weight); continue; } if let Some(ep) = self.available.get_mut(&addr) { ep.set_weight(weight); continue; } self.available.insert(addr, endpoint::new(addr, weight)); } } fn dsts_by_addr(dsts: &[WeightedAddr]) -> OrderMap<net::SocketAddr, f64> { let mut by_addr = OrderMap::with_capacity(dsts.len()); for &WeightedAddr { addr, weight } in dsts { by_addr.insert(addr, weight); } by_addr } }
{ WeightedAddr { addr, weight } }
identifier_body
mod.rs
use super::Path; use super::connector::Connector; use super::resolver::Resolve; use futures::{Async, Future, Poll, unsync}; use ordermap::OrderMap; use std::{cmp, io, net}; use std::collections::VecDeque; use std::time::{Duration, Instant}; use tacho; use tokio_core::reactor::Handle; use tokio_timer::Timer; mod dispatcher; mod endpoint; mod factory; pub use self::endpoint::{Connection as EndpointConnection, Ctx as EndpointCtx}; use self::endpoint::Endpoint; pub use self::factory::BalancerFactory; type Waiter = unsync::oneshot::Sender<endpoint::Connection>; /// A weighted concrete destination address. #[derive(Clone, Debug)] pub struct WeightedAddr { pub addr: ::std::net::SocketAddr, pub weight: f64, } impl WeightedAddr { pub fn new(addr: net::SocketAddr, weight: f64) -> WeightedAddr { WeightedAddr { addr, weight } } } pub fn new( reactor: &Handle, timer: &Timer, dst: &Path, connector: Connector, resolve: Resolve, metrics: &tacho::Scope, ) -> Balancer { let (tx, rx) = unsync::mpsc::unbounded(); let dispatcher = dispatcher::new( reactor.clone(), timer.clone(), dst.clone(), connector, resolve, rx, Endpoints::default(), metrics, ); reactor.spawn(dispatcher.map_err(|_| {})); Balancer(tx) } #[derive(Clone)] pub struct
(unsync::mpsc::UnboundedSender<Waiter>); impl Balancer { /// Obtains a connection to the destination. pub fn connect(&self) -> Connect { let (tx, rx) = unsync::oneshot::channel(); let result = unsync::mpsc::UnboundedSender::unbounded_send(&self.0, tx) .map_err(|_| io::Error::new(io::ErrorKind::Other, "lost dispatcher")) .map(|_| rx); Connect(Some(result)) } } pub struct Connect(Option<io::Result<unsync::oneshot::Receiver<endpoint::Connection>>>); impl Future for Connect { type Item = endpoint::Connection; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { let mut recv = self.0.take().expect( "connect must not be polled after completion", )?; match recv.poll() { Err(_) => Err(io::Error::new(io::ErrorKind::Interrupted, "canceled")), Ok(Async::Ready(conn)) => Ok(Async::Ready(conn)), Ok(Async::NotReady) => { self.0 = Some(Ok(recv)); Ok(Async::NotReady) } } } } pub type EndpointMap = OrderMap<net::SocketAddr, Endpoint>; pub type FailedMap = OrderMap<net::SocketAddr, (Instant, Endpoint)>; #[derive(Default)] pub struct Endpoints { //minimum_connections: usize, /// Endpoints considered available for new connections. available: EndpointMap, /// Endpoints that are still active but considered unavailable for new connections. retired: EndpointMap, failed: FailedMap, } impl Endpoints { pub fn available(&self) -> &EndpointMap { &self.available } pub fn failed(&self) -> &FailedMap { &self.failed } pub fn retired(&self) -> &EndpointMap { &self.retired } pub fn update_failed(&mut self, max_failures: usize, penalty: Duration) { let mut available = VecDeque::with_capacity(self.failed.len()); let mut failed = VecDeque::with_capacity(self.failed.len()); for (_, ep) in self.available.drain(..) { if ep.state().consecutive_failures < max_failures { available.push_back(ep); } else { failed.push_back((Instant::now(), ep)); } } for (_, (start, ep)) in self.failed.drain(..) { if start + penalty <= Instant::now() { available.push_back(ep); } else { failed.push_back((start, ep)); } } if available.is_empty() { while let Some((_, ep)) = failed.pop_front() { self.available.insert(ep.peer_addr(), ep); } } else { while let Some(ep) = available.pop_front() { self.available.insert(ep.peer_addr(), ep); } while let Some((since, ep)) = failed.pop_front() { self.failed.insert(ep.peer_addr(), (since, ep)); } } } // TODO: we need to do some sort of probation deal to manage endpoints that are // retired. pub fn update_resolved(&mut self, resolved: &[WeightedAddr]) { let mut temp = { let sz = cmp::max(self.available.len(), self.retired.len()); VecDeque::with_capacity(sz) }; let dsts = Endpoints::dsts_by_addr(resolved); self.check_retired(&dsts, &mut temp); self.check_available(&dsts, &mut temp); self.check_failed(&dsts); self.update_available_from_new(dsts); } /// Checks active endpoints. fn check_available( &mut self, dsts: &OrderMap<net::SocketAddr, f64>, temp: &mut VecDeque<Endpoint>, ) { for (addr, ep) in self.available.drain(..) { if dsts.contains_key(&addr) { temp.push_back(ep); } else if ep.is_idle() { drop(ep); } else { self.retired.insert(addr, ep); } } for _ in 0..temp.len() { let ep = temp.pop_front().unwrap(); self.available.insert(ep.peer_addr(), ep); } } /// Checks retired endpoints. /// /// Endpoints are either salvaged backed into the active pool, maintained as /// retired if still active, or dropped if inactive. fn check_retired( &mut self, dsts: &OrderMap<net::SocketAddr, f64>, temp: &mut VecDeque<Endpoint>, ) { for (addr, ep) in self.retired.drain(..) { if dsts.contains_key(&addr) { self.available.insert(addr, ep); } else if ep.is_idle() { drop(ep); } else { temp.push_back(ep); } } for _ in 0..temp.len() { let ep = temp.pop_front().unwrap(); self.retired.insert(ep.peer_addr(), ep); } } /// Checks failed endpoints. fn check_failed(&mut self, dsts: &OrderMap<net::SocketAddr, f64>) { let mut temp = VecDeque::with_capacity(self.failed.len()); for (addr, (since, ep)) in self.failed.drain(..) { if dsts.contains_key(&addr) { temp.push_back((since, ep)); } else if ep.is_idle() { drop(ep); } else { self.retired.insert(addr, ep); } } for _ in 0..temp.len() { let (instant, ep) = temp.pop_front().unwrap(); self.failed.insert(ep.peer_addr(), (instant, ep)); } } fn update_available_from_new(&mut self, mut dsts: OrderMap<net::SocketAddr, f64>) { // Add new endpoints or update the base weights of existing endpoints. //let metrics = self.endpoint_metrics.clone(); for (addr, weight) in dsts.drain(..) { if let Some(&mut (_, ref mut ep)) = self.failed.get_mut(&addr) { ep.set_weight(weight); continue; } if let Some(ep) = self.available.get_mut(&addr) { ep.set_weight(weight); continue; } self.available.insert(addr, endpoint::new(addr, weight)); } } fn dsts_by_addr(dsts: &[WeightedAddr]) -> OrderMap<net::SocketAddr, f64> { let mut by_addr = OrderMap::with_capacity(dsts.len()); for &WeightedAddr { addr, weight } in dsts { by_addr.insert(addr, weight); } by_addr } }
Balancer
identifier_name
mod.rs
use super::Path; use super::connector::Connector; use super::resolver::Resolve; use futures::{Async, Future, Poll, unsync}; use ordermap::OrderMap; use std::{cmp, io, net}; use std::collections::VecDeque; use std::time::{Duration, Instant}; use tacho; use tokio_core::reactor::Handle; use tokio_timer::Timer; mod dispatcher; mod endpoint; mod factory; pub use self::endpoint::{Connection as EndpointConnection, Ctx as EndpointCtx}; use self::endpoint::Endpoint; pub use self::factory::BalancerFactory; type Waiter = unsync::oneshot::Sender<endpoint::Connection>; /// A weighted concrete destination address. #[derive(Clone, Debug)] pub struct WeightedAddr { pub addr: ::std::net::SocketAddr, pub weight: f64, } impl WeightedAddr { pub fn new(addr: net::SocketAddr, weight: f64) -> WeightedAddr { WeightedAddr { addr, weight } } } pub fn new( reactor: &Handle, timer: &Timer, dst: &Path, connector: Connector, resolve: Resolve, metrics: &tacho::Scope, ) -> Balancer { let (tx, rx) = unsync::mpsc::unbounded(); let dispatcher = dispatcher::new( reactor.clone(), timer.clone(), dst.clone(), connector, resolve, rx,
} #[derive(Clone)] pub struct Balancer(unsync::mpsc::UnboundedSender<Waiter>); impl Balancer { /// Obtains a connection to the destination. pub fn connect(&self) -> Connect { let (tx, rx) = unsync::oneshot::channel(); let result = unsync::mpsc::UnboundedSender::unbounded_send(&self.0, tx) .map_err(|_| io::Error::new(io::ErrorKind::Other, "lost dispatcher")) .map(|_| rx); Connect(Some(result)) } } pub struct Connect(Option<io::Result<unsync::oneshot::Receiver<endpoint::Connection>>>); impl Future for Connect { type Item = endpoint::Connection; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { let mut recv = self.0.take().expect( "connect must not be polled after completion", )?; match recv.poll() { Err(_) => Err(io::Error::new(io::ErrorKind::Interrupted, "canceled")), Ok(Async::Ready(conn)) => Ok(Async::Ready(conn)), Ok(Async::NotReady) => { self.0 = Some(Ok(recv)); Ok(Async::NotReady) } } } } pub type EndpointMap = OrderMap<net::SocketAddr, Endpoint>; pub type FailedMap = OrderMap<net::SocketAddr, (Instant, Endpoint)>; #[derive(Default)] pub struct Endpoints { //minimum_connections: usize, /// Endpoints considered available for new connections. available: EndpointMap, /// Endpoints that are still active but considered unavailable for new connections. retired: EndpointMap, failed: FailedMap, } impl Endpoints { pub fn available(&self) -> &EndpointMap { &self.available } pub fn failed(&self) -> &FailedMap { &self.failed } pub fn retired(&self) -> &EndpointMap { &self.retired } pub fn update_failed(&mut self, max_failures: usize, penalty: Duration) { let mut available = VecDeque::with_capacity(self.failed.len()); let mut failed = VecDeque::with_capacity(self.failed.len()); for (_, ep) in self.available.drain(..) { if ep.state().consecutive_failures < max_failures { available.push_back(ep); } else { failed.push_back((Instant::now(), ep)); } } for (_, (start, ep)) in self.failed.drain(..) { if start + penalty <= Instant::now() { available.push_back(ep); } else { failed.push_back((start, ep)); } } if available.is_empty() { while let Some((_, ep)) = failed.pop_front() { self.available.insert(ep.peer_addr(), ep); } } else { while let Some(ep) = available.pop_front() { self.available.insert(ep.peer_addr(), ep); } while let Some((since, ep)) = failed.pop_front() { self.failed.insert(ep.peer_addr(), (since, ep)); } } } // TODO: we need to do some sort of probation deal to manage endpoints that are // retired. pub fn update_resolved(&mut self, resolved: &[WeightedAddr]) { let mut temp = { let sz = cmp::max(self.available.len(), self.retired.len()); VecDeque::with_capacity(sz) }; let dsts = Endpoints::dsts_by_addr(resolved); self.check_retired(&dsts, &mut temp); self.check_available(&dsts, &mut temp); self.check_failed(&dsts); self.update_available_from_new(dsts); } /// Checks active endpoints. fn check_available( &mut self, dsts: &OrderMap<net::SocketAddr, f64>, temp: &mut VecDeque<Endpoint>, ) { for (addr, ep) in self.available.drain(..) { if dsts.contains_key(&addr) { temp.push_back(ep); } else if ep.is_idle() { drop(ep); } else { self.retired.insert(addr, ep); } } for _ in 0..temp.len() { let ep = temp.pop_front().unwrap(); self.available.insert(ep.peer_addr(), ep); } } /// Checks retired endpoints. /// /// Endpoints are either salvaged backed into the active pool, maintained as /// retired if still active, or dropped if inactive. fn check_retired( &mut self, dsts: &OrderMap<net::SocketAddr, f64>, temp: &mut VecDeque<Endpoint>, ) { for (addr, ep) in self.retired.drain(..) { if dsts.contains_key(&addr) { self.available.insert(addr, ep); } else if ep.is_idle() { drop(ep); } else { temp.push_back(ep); } } for _ in 0..temp.len() { let ep = temp.pop_front().unwrap(); self.retired.insert(ep.peer_addr(), ep); } } /// Checks failed endpoints. fn check_failed(&mut self, dsts: &OrderMap<net::SocketAddr, f64>) { let mut temp = VecDeque::with_capacity(self.failed.len()); for (addr, (since, ep)) in self.failed.drain(..) { if dsts.contains_key(&addr) { temp.push_back((since, ep)); } else if ep.is_idle() { drop(ep); } else { self.retired.insert(addr, ep); } } for _ in 0..temp.len() { let (instant, ep) = temp.pop_front().unwrap(); self.failed.insert(ep.peer_addr(), (instant, ep)); } } fn update_available_from_new(&mut self, mut dsts: OrderMap<net::SocketAddr, f64>) { // Add new endpoints or update the base weights of existing endpoints. //let metrics = self.endpoint_metrics.clone(); for (addr, weight) in dsts.drain(..) { if let Some(&mut (_, ref mut ep)) = self.failed.get_mut(&addr) { ep.set_weight(weight); continue; } if let Some(ep) = self.available.get_mut(&addr) { ep.set_weight(weight); continue; } self.available.insert(addr, endpoint::new(addr, weight)); } } fn dsts_by_addr(dsts: &[WeightedAddr]) -> OrderMap<net::SocketAddr, f64> { let mut by_addr = OrderMap::with_capacity(dsts.len()); for &WeightedAddr { addr, weight } in dsts { by_addr.insert(addr, weight); } by_addr } }
Endpoints::default(), metrics, ); reactor.spawn(dispatcher.map_err(|_| {})); Balancer(tx)
random_line_split
callee.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. //! Handles codegen of callees as well as other call-related //! things. Callees are a superset of normal rust values and sometimes //! have different representations. In particular, top-level fn items //! and methods are represented as just a fn ptr and not a full //! closure. use attributes; use llvm; use monomorphize::Instance; use context::CodegenCx; use value::Value; use rustc_codegen_ssa::traits::*; use rustc::ty::TypeFoldable; use rustc::ty::layout::{LayoutOf, HasTyCtxt}; /// Codegens a reference to a fn/method item, monomorphizing and /// inlining as it goes. /// /// # Parameters /// /// - `cx`: the crate context /// - `instance`: the instance to be instantiated pub fn get_fn( cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>, ) -> &'ll Value
let llfn = if let Some(llfn) = cx.get_declared_value(&sym) { // This is subtle and surprising, but sometimes we have to bitcast // the resulting fn pointer. The reason has to do with external // functions. If you have two crates that both bind the same C // library, they may not use precisely the same types: for // example, they will probably each declare their own structs, // which are distinct types from LLVM's point of view (nominal // types). // // Now, if those two crates are linked into an application, and // they contain inlined code, you can wind up with a situation // where both of those functions wind up being loaded into this // application simultaneously. In that case, the same function // (from LLVM's point of view) requires two types. But of course // LLVM won't allow one function to have two types. // // What we currently do, therefore, is declare the function with // one of the two types (whichever happens to come first) and then // bitcast as needed when the function is referenced to make sure // it has the type we expect. // // This can occur on either a crate-local or crate-external // reference. It also occurs when testing libcore and in some // other weird situations. Annoying. if cx.val_ty(llfn)!= llptrty { debug!("get_fn: casting {:?} to {:?}", llfn, llptrty); cx.const_ptrcast(llfn, llptrty) } else { debug!("get_fn: not casting pointer!"); llfn } } else { let llfn = cx.declare_fn(&sym, sig); assert_eq!(cx.val_ty(llfn), llptrty); debug!("get_fn: not casting pointer!"); if instance.def.is_inline(tcx) { attributes::inline(cx, llfn, attributes::InlineAttr::Hint); } attributes::from_fn_attrs(cx, llfn, Some(instance.def.def_id()), sig); let instance_def_id = instance.def_id(); // Apply an appropriate linkage/visibility value to our item that we // just declared. // // This is sort of subtle. Inside our codegen unit we started off // compilation by predefining all our own `MonoItem` instances. That // is, everything we're codegenning ourselves is already defined. That // means that anything we're actually codegenning in this codegen unit // will have hit the above branch in `get_declared_value`. As a result, // we're guaranteed here that we're declaring a symbol that won't get // defined, or in other words we're referencing a value from another // codegen unit or even another crate. // // So because this is a foreign value we blanket apply an external // linkage directive because it's coming from a different object file. // The visibility here is where it gets tricky. This symbol could be // referencing some foreign crate or foreign library (an `extern` // block) in which case we want to leave the default visibility. We may // also, though, have multiple codegen units. It could be a // monomorphization, in which case its expected visibility depends on // whether we are sharing generics or not. The important thing here is // that the visibility we apply to the declaration is the same one that // has been applied to the definition (wherever that definition may be). unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::ExternalLinkage); let is_generic = instance.substs.types().next().is_some(); if is_generic { // This is a monomorphization. Its expected visibility depends // on whether we are in share-generics mode. if cx.tcx.sess.opts.share_generics() { // We are in share_generics mode. if instance_def_id.is_local() { // This is a definition from the current crate. If the // definition is unreachable for downstream crates or // the current crate does not re-export generics, the // definition of the instance will have been declared // as `hidden`. if cx.tcx.is_unreachable_local_definition(instance_def_id) || !cx.tcx.local_crate_exports_generics() { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } else { // This is a monomorphization of a generic function // defined in an upstream crate. if cx.tcx.upstream_monomorphizations_for(instance_def_id) .map(|set| set.contains_key(instance.substs)) .unwrap_or(false) { // This is instantiated in another crate. It cannot // be `hidden`. } else { // This is a local instantiation of an upstream definition. // If the current crate does not re-export it // (because it is a C library or an executable), it // will have been declared `hidden`. if!cx.tcx.local_crate_exports_generics() { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } } } else { // When not sharing generics, all instances are in the same // crate and have hidden visibility llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } else { // This is a non-generic function if cx.tcx.is_codegened_item(instance_def_id) { // This is a function that is instantiated in the local crate if instance_def_id.is_local() { // This is function that is defined in the local crate. // If it is not reachable, it is hidden. if!cx.tcx.is_reachable_non_generic(instance_def_id) { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } else { // This is a function from an upstream crate that has // been instantiated here. These are always hidden. llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } } } if cx.use_dll_storage_attrs && tcx.is_dllimport_foreign_item(instance_def_id) { unsafe { llvm::LLVMSetDLLStorageClass(llfn, llvm::DLLStorageClass::DllImport); } } llfn }; cx.instances.borrow_mut().insert(instance, llfn); llfn }
{ let tcx = cx.tcx(); debug!("get_fn(instance={:?})", instance); assert!(!instance.substs.needs_infer()); assert!(!instance.substs.has_escaping_bound_vars()); assert!(!instance.substs.has_param_types()); let sig = instance.fn_sig(cx.tcx()); if let Some(&llfn) = cx.instances().borrow().get(&instance) { return llfn; } let sym = tcx.symbol_name(instance).as_str(); debug!("get_fn({:?}: {:?}) => {}", instance, sig, sym); // Create a fn pointer with the substituted signature. let fn_ptr_ty = tcx.mk_fn_ptr(sig); let llptrty = cx.backend_type(cx.layout_of(fn_ptr_ty));
identifier_body
callee.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. //! Handles codegen of callees as well as other call-related //! things. Callees are a superset of normal rust values and sometimes //! have different representations. In particular, top-level fn items //! and methods are represented as just a fn ptr and not a full //! closure. use attributes; use llvm; use monomorphize::Instance; use context::CodegenCx; use value::Value; use rustc_codegen_ssa::traits::*; use rustc::ty::TypeFoldable; use rustc::ty::layout::{LayoutOf, HasTyCtxt}; /// Codegens a reference to a fn/method item, monomorphizing and /// inlining as it goes. /// /// # Parameters /// /// - `cx`: the crate context /// - `instance`: the instance to be instantiated pub fn get_fn( cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>, ) -> &'ll Value { let tcx = cx.tcx(); debug!("get_fn(instance={:?})", instance); assert!(!instance.substs.needs_infer()); assert!(!instance.substs.has_escaping_bound_vars()); assert!(!instance.substs.has_param_types()); let sig = instance.fn_sig(cx.tcx()); if let Some(&llfn) = cx.instances().borrow().get(&instance) { return llfn; } let sym = tcx.symbol_name(instance).as_str(); debug!("get_fn({:?}: {:?}) => {}", instance, sig, sym); // Create a fn pointer with the substituted signature. let fn_ptr_ty = tcx.mk_fn_ptr(sig); let llptrty = cx.backend_type(cx.layout_of(fn_ptr_ty)); let llfn = if let Some(llfn) = cx.get_declared_value(&sym) { // This is subtle and surprising, but sometimes we have to bitcast // the resulting fn pointer. The reason has to do with external // functions. If you have two crates that both bind the same C // library, they may not use precisely the same types: for // example, they will probably each declare their own structs, // which are distinct types from LLVM's point of view (nominal // types). // // Now, if those two crates are linked into an application, and // they contain inlined code, you can wind up with a situation // where both of those functions wind up being loaded into this // application simultaneously. In that case, the same function // (from LLVM's point of view) requires two types. But of course // LLVM won't allow one function to have two types. // // What we currently do, therefore, is declare the function with // one of the two types (whichever happens to come first) and then // bitcast as needed when the function is referenced to make sure // it has the type we expect. // // This can occur on either a crate-local or crate-external
} else { debug!("get_fn: not casting pointer!"); llfn } } else { let llfn = cx.declare_fn(&sym, sig); assert_eq!(cx.val_ty(llfn), llptrty); debug!("get_fn: not casting pointer!"); if instance.def.is_inline(tcx) { attributes::inline(cx, llfn, attributes::InlineAttr::Hint); } attributes::from_fn_attrs(cx, llfn, Some(instance.def.def_id()), sig); let instance_def_id = instance.def_id(); // Apply an appropriate linkage/visibility value to our item that we // just declared. // // This is sort of subtle. Inside our codegen unit we started off // compilation by predefining all our own `MonoItem` instances. That // is, everything we're codegenning ourselves is already defined. That // means that anything we're actually codegenning in this codegen unit // will have hit the above branch in `get_declared_value`. As a result, // we're guaranteed here that we're declaring a symbol that won't get // defined, or in other words we're referencing a value from another // codegen unit or even another crate. // // So because this is a foreign value we blanket apply an external // linkage directive because it's coming from a different object file. // The visibility here is where it gets tricky. This symbol could be // referencing some foreign crate or foreign library (an `extern` // block) in which case we want to leave the default visibility. We may // also, though, have multiple codegen units. It could be a // monomorphization, in which case its expected visibility depends on // whether we are sharing generics or not. The important thing here is // that the visibility we apply to the declaration is the same one that // has been applied to the definition (wherever that definition may be). unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::ExternalLinkage); let is_generic = instance.substs.types().next().is_some(); if is_generic { // This is a monomorphization. Its expected visibility depends // on whether we are in share-generics mode. if cx.tcx.sess.opts.share_generics() { // We are in share_generics mode. if instance_def_id.is_local() { // This is a definition from the current crate. If the // definition is unreachable for downstream crates or // the current crate does not re-export generics, the // definition of the instance will have been declared // as `hidden`. if cx.tcx.is_unreachable_local_definition(instance_def_id) || !cx.tcx.local_crate_exports_generics() { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } else { // This is a monomorphization of a generic function // defined in an upstream crate. if cx.tcx.upstream_monomorphizations_for(instance_def_id) .map(|set| set.contains_key(instance.substs)) .unwrap_or(false) { // This is instantiated in another crate. It cannot // be `hidden`. } else { // This is a local instantiation of an upstream definition. // If the current crate does not re-export it // (because it is a C library or an executable), it // will have been declared `hidden`. if!cx.tcx.local_crate_exports_generics() { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } } } else { // When not sharing generics, all instances are in the same // crate and have hidden visibility llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } else { // This is a non-generic function if cx.tcx.is_codegened_item(instance_def_id) { // This is a function that is instantiated in the local crate if instance_def_id.is_local() { // This is function that is defined in the local crate. // If it is not reachable, it is hidden. if!cx.tcx.is_reachable_non_generic(instance_def_id) { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } else { // This is a function from an upstream crate that has // been instantiated here. These are always hidden. llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } } } if cx.use_dll_storage_attrs && tcx.is_dllimport_foreign_item(instance_def_id) { unsafe { llvm::LLVMSetDLLStorageClass(llfn, llvm::DLLStorageClass::DllImport); } } llfn }; cx.instances.borrow_mut().insert(instance, llfn); llfn }
// reference. It also occurs when testing libcore and in some // other weird situations. Annoying. if cx.val_ty(llfn) != llptrty { debug!("get_fn: casting {:?} to {:?}", llfn, llptrty); cx.const_ptrcast(llfn, llptrty)
random_line_split
callee.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. //! Handles codegen of callees as well as other call-related //! things. Callees are a superset of normal rust values and sometimes //! have different representations. In particular, top-level fn items //! and methods are represented as just a fn ptr and not a full //! closure. use attributes; use llvm; use monomorphize::Instance; use context::CodegenCx; use value::Value; use rustc_codegen_ssa::traits::*; use rustc::ty::TypeFoldable; use rustc::ty::layout::{LayoutOf, HasTyCtxt}; /// Codegens a reference to a fn/method item, monomorphizing and /// inlining as it goes. /// /// # Parameters /// /// - `cx`: the crate context /// - `instance`: the instance to be instantiated pub fn get_fn( cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>, ) -> &'ll Value { let tcx = cx.tcx(); debug!("get_fn(instance={:?})", instance); assert!(!instance.substs.needs_infer()); assert!(!instance.substs.has_escaping_bound_vars()); assert!(!instance.substs.has_param_types()); let sig = instance.fn_sig(cx.tcx()); if let Some(&llfn) = cx.instances().borrow().get(&instance) { return llfn; } let sym = tcx.symbol_name(instance).as_str(); debug!("get_fn({:?}: {:?}) => {}", instance, sig, sym); // Create a fn pointer with the substituted signature. let fn_ptr_ty = tcx.mk_fn_ptr(sig); let llptrty = cx.backend_type(cx.layout_of(fn_ptr_ty)); let llfn = if let Some(llfn) = cx.get_declared_value(&sym) { // This is subtle and surprising, but sometimes we have to bitcast // the resulting fn pointer. The reason has to do with external // functions. If you have two crates that both bind the same C // library, they may not use precisely the same types: for // example, they will probably each declare their own structs, // which are distinct types from LLVM's point of view (nominal // types). // // Now, if those two crates are linked into an application, and // they contain inlined code, you can wind up with a situation // where both of those functions wind up being loaded into this // application simultaneously. In that case, the same function // (from LLVM's point of view) requires two types. But of course // LLVM won't allow one function to have two types. // // What we currently do, therefore, is declare the function with // one of the two types (whichever happens to come first) and then // bitcast as needed when the function is referenced to make sure // it has the type we expect. // // This can occur on either a crate-local or crate-external // reference. It also occurs when testing libcore and in some // other weird situations. Annoying. if cx.val_ty(llfn)!= llptrty { debug!("get_fn: casting {:?} to {:?}", llfn, llptrty); cx.const_ptrcast(llfn, llptrty) } else { debug!("get_fn: not casting pointer!"); llfn } } else { let llfn = cx.declare_fn(&sym, sig); assert_eq!(cx.val_ty(llfn), llptrty); debug!("get_fn: not casting pointer!"); if instance.def.is_inline(tcx) { attributes::inline(cx, llfn, attributes::InlineAttr::Hint); } attributes::from_fn_attrs(cx, llfn, Some(instance.def.def_id()), sig); let instance_def_id = instance.def_id(); // Apply an appropriate linkage/visibility value to our item that we // just declared. // // This is sort of subtle. Inside our codegen unit we started off // compilation by predefining all our own `MonoItem` instances. That // is, everything we're codegenning ourselves is already defined. That // means that anything we're actually codegenning in this codegen unit // will have hit the above branch in `get_declared_value`. As a result, // we're guaranteed here that we're declaring a symbol that won't get // defined, or in other words we're referencing a value from another // codegen unit or even another crate. // // So because this is a foreign value we blanket apply an external // linkage directive because it's coming from a different object file. // The visibility here is where it gets tricky. This symbol could be // referencing some foreign crate or foreign library (an `extern` // block) in which case we want to leave the default visibility. We may // also, though, have multiple codegen units. It could be a // monomorphization, in which case its expected visibility depends on // whether we are sharing generics or not. The important thing here is // that the visibility we apply to the declaration is the same one that // has been applied to the definition (wherever that definition may be). unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::ExternalLinkage); let is_generic = instance.substs.types().next().is_some(); if is_generic { // This is a monomorphization. Its expected visibility depends // on whether we are in share-generics mode. if cx.tcx.sess.opts.share_generics() { // We are in share_generics mode. if instance_def_id.is_local() { // This is a definition from the current crate. If the // definition is unreachable for downstream crates or // the current crate does not re-export generics, the // definition of the instance will have been declared // as `hidden`. if cx.tcx.is_unreachable_local_definition(instance_def_id) || !cx.tcx.local_crate_exports_generics() { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } else { // This is a monomorphization of a generic function // defined in an upstream crate. if cx.tcx.upstream_monomorphizations_for(instance_def_id) .map(|set| set.contains_key(instance.substs)) .unwrap_or(false) { // This is instantiated in another crate. It cannot // be `hidden`. } else { // This is a local instantiation of an upstream definition. // If the current crate does not re-export it // (because it is a C library or an executable), it // will have been declared `hidden`. if!cx.tcx.local_crate_exports_generics() { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } } } else { // When not sharing generics, all instances are in the same // crate and have hidden visibility llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } else { // This is a non-generic function if cx.tcx.is_codegened_item(instance_def_id) { // This is a function that is instantiated in the local crate if instance_def_id.is_local() { // This is function that is defined in the local crate. // If it is not reachable, it is hidden. if!cx.tcx.is_reachable_non_generic(instance_def_id) { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } else
} } } if cx.use_dll_storage_attrs && tcx.is_dllimport_foreign_item(instance_def_id) { unsafe { llvm::LLVMSetDLLStorageClass(llfn, llvm::DLLStorageClass::DllImport); } } llfn }; cx.instances.borrow_mut().insert(instance, llfn); llfn }
{ // This is a function from an upstream crate that has // been instantiated here. These are always hidden. llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); }
conditional_block
callee.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. //! Handles codegen of callees as well as other call-related //! things. Callees are a superset of normal rust values and sometimes //! have different representations. In particular, top-level fn items //! and methods are represented as just a fn ptr and not a full //! closure. use attributes; use llvm; use monomorphize::Instance; use context::CodegenCx; use value::Value; use rustc_codegen_ssa::traits::*; use rustc::ty::TypeFoldable; use rustc::ty::layout::{LayoutOf, HasTyCtxt}; /// Codegens a reference to a fn/method item, monomorphizing and /// inlining as it goes. /// /// # Parameters /// /// - `cx`: the crate context /// - `instance`: the instance to be instantiated pub fn
( cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>, ) -> &'ll Value { let tcx = cx.tcx(); debug!("get_fn(instance={:?})", instance); assert!(!instance.substs.needs_infer()); assert!(!instance.substs.has_escaping_bound_vars()); assert!(!instance.substs.has_param_types()); let sig = instance.fn_sig(cx.tcx()); if let Some(&llfn) = cx.instances().borrow().get(&instance) { return llfn; } let sym = tcx.symbol_name(instance).as_str(); debug!("get_fn({:?}: {:?}) => {}", instance, sig, sym); // Create a fn pointer with the substituted signature. let fn_ptr_ty = tcx.mk_fn_ptr(sig); let llptrty = cx.backend_type(cx.layout_of(fn_ptr_ty)); let llfn = if let Some(llfn) = cx.get_declared_value(&sym) { // This is subtle and surprising, but sometimes we have to bitcast // the resulting fn pointer. The reason has to do with external // functions. If you have two crates that both bind the same C // library, they may not use precisely the same types: for // example, they will probably each declare their own structs, // which are distinct types from LLVM's point of view (nominal // types). // // Now, if those two crates are linked into an application, and // they contain inlined code, you can wind up with a situation // where both of those functions wind up being loaded into this // application simultaneously. In that case, the same function // (from LLVM's point of view) requires two types. But of course // LLVM won't allow one function to have two types. // // What we currently do, therefore, is declare the function with // one of the two types (whichever happens to come first) and then // bitcast as needed when the function is referenced to make sure // it has the type we expect. // // This can occur on either a crate-local or crate-external // reference. It also occurs when testing libcore and in some // other weird situations. Annoying. if cx.val_ty(llfn)!= llptrty { debug!("get_fn: casting {:?} to {:?}", llfn, llptrty); cx.const_ptrcast(llfn, llptrty) } else { debug!("get_fn: not casting pointer!"); llfn } } else { let llfn = cx.declare_fn(&sym, sig); assert_eq!(cx.val_ty(llfn), llptrty); debug!("get_fn: not casting pointer!"); if instance.def.is_inline(tcx) { attributes::inline(cx, llfn, attributes::InlineAttr::Hint); } attributes::from_fn_attrs(cx, llfn, Some(instance.def.def_id()), sig); let instance_def_id = instance.def_id(); // Apply an appropriate linkage/visibility value to our item that we // just declared. // // This is sort of subtle. Inside our codegen unit we started off // compilation by predefining all our own `MonoItem` instances. That // is, everything we're codegenning ourselves is already defined. That // means that anything we're actually codegenning in this codegen unit // will have hit the above branch in `get_declared_value`. As a result, // we're guaranteed here that we're declaring a symbol that won't get // defined, or in other words we're referencing a value from another // codegen unit or even another crate. // // So because this is a foreign value we blanket apply an external // linkage directive because it's coming from a different object file. // The visibility here is where it gets tricky. This symbol could be // referencing some foreign crate or foreign library (an `extern` // block) in which case we want to leave the default visibility. We may // also, though, have multiple codegen units. It could be a // monomorphization, in which case its expected visibility depends on // whether we are sharing generics or not. The important thing here is // that the visibility we apply to the declaration is the same one that // has been applied to the definition (wherever that definition may be). unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::ExternalLinkage); let is_generic = instance.substs.types().next().is_some(); if is_generic { // This is a monomorphization. Its expected visibility depends // on whether we are in share-generics mode. if cx.tcx.sess.opts.share_generics() { // We are in share_generics mode. if instance_def_id.is_local() { // This is a definition from the current crate. If the // definition is unreachable for downstream crates or // the current crate does not re-export generics, the // definition of the instance will have been declared // as `hidden`. if cx.tcx.is_unreachable_local_definition(instance_def_id) || !cx.tcx.local_crate_exports_generics() { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } else { // This is a monomorphization of a generic function // defined in an upstream crate. if cx.tcx.upstream_monomorphizations_for(instance_def_id) .map(|set| set.contains_key(instance.substs)) .unwrap_or(false) { // This is instantiated in another crate. It cannot // be `hidden`. } else { // This is a local instantiation of an upstream definition. // If the current crate does not re-export it // (because it is a C library or an executable), it // will have been declared `hidden`. if!cx.tcx.local_crate_exports_generics() { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } } } else { // When not sharing generics, all instances are in the same // crate and have hidden visibility llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } else { // This is a non-generic function if cx.tcx.is_codegened_item(instance_def_id) { // This is a function that is instantiated in the local crate if instance_def_id.is_local() { // This is function that is defined in the local crate. // If it is not reachable, it is hidden. if!cx.tcx.is_reachable_non_generic(instance_def_id) { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } else { // This is a function from an upstream crate that has // been instantiated here. These are always hidden. llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } } } } if cx.use_dll_storage_attrs && tcx.is_dllimport_foreign_item(instance_def_id) { unsafe { llvm::LLVMSetDLLStorageClass(llfn, llvm::DLLStorageClass::DllImport); } } llfn }; cx.instances.borrow_mut().insert(instance, llfn); llfn }
get_fn
identifier_name
macro-comma-behavior.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Companion test to the similarly-named file in run-pass. // compile-flags: -C debug_assertions=yes // revisions: std core #![cfg_attr(core, no_std)] #[cfg(std)] use std::fmt; #[cfg(core)] use core::fmt; // (see documentation of the similarly-named test in run-pass) fn to_format_or_not_to_format() { let falsum = || false; // assert!(true, "{}",); // see run-pass assert_eq!(1, 1, "{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments assert_ne!(1, 2, "{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments // debug_assert!(true, "{}",); // see run-pass debug_assert_eq!(1, 1, "{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments debug_assert_ne!(1, 2, "{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments #[cfg(std)] { eprint!("{}",); //[std]~^ ERROR no arguments } #[cfg(std)] { // FIXME: compile-fail says "expected error not found" even though // rustc does emit an error // eprintln!("{}",); // <DISABLED> [std]~^ ERROR no arguments } #[cfg(std)] { format!("{}",); //[std]~^ ERROR no arguments } format_args!("{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments // if falsum() { panic!("{}",); } // see run-pass #[cfg(std)] { print!("{}",); //[std]~^ ERROR no arguments } #[cfg(std)] {
} unimplemented!("{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments // if falsum() { unreachable!("{}",); } // see run-pass struct S; impl fmt::Display for S { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}",)?; //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments // FIXME: compile-fail says "expected error not found" even though // rustc does emit an error // writeln!(f, "{}",)?; // <DISABLED> [core]~^ ERROR no arguments // <DISABLED> [std]~^^ ERROR no arguments Ok(()) } } } fn main() {}
// FIXME: compile-fail says "expected error not found" even though // rustc does emit an error // println!("{}",); // <DISABLED> [std]~^ ERROR no arguments
random_line_split
macro-comma-behavior.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Companion test to the similarly-named file in run-pass. // compile-flags: -C debug_assertions=yes // revisions: std core #![cfg_attr(core, no_std)] #[cfg(std)] use std::fmt; #[cfg(core)] use core::fmt; // (see documentation of the similarly-named test in run-pass) fn to_format_or_not_to_format() { let falsum = || false; // assert!(true, "{}",); // see run-pass assert_eq!(1, 1, "{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments assert_ne!(1, 2, "{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments // debug_assert!(true, "{}",); // see run-pass debug_assert_eq!(1, 1, "{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments debug_assert_ne!(1, 2, "{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments #[cfg(std)] { eprint!("{}",); //[std]~^ ERROR no arguments } #[cfg(std)] { // FIXME: compile-fail says "expected error not found" even though // rustc does emit an error // eprintln!("{}",); // <DISABLED> [std]~^ ERROR no arguments } #[cfg(std)] { format!("{}",); //[std]~^ ERROR no arguments } format_args!("{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments // if falsum() { panic!("{}",); } // see run-pass #[cfg(std)] { print!("{}",); //[std]~^ ERROR no arguments } #[cfg(std)] { // FIXME: compile-fail says "expected error not found" even though // rustc does emit an error // println!("{}",); // <DISABLED> [std]~^ ERROR no arguments } unimplemented!("{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments // if falsum() { unreachable!("{}",); } // see run-pass struct S; impl fmt::Display for S { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}",)?; //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments // FIXME: compile-fail says "expected error not found" even though // rustc does emit an error // writeln!(f, "{}",)?; // <DISABLED> [core]~^ ERROR no arguments // <DISABLED> [std]~^^ ERROR no arguments Ok(()) } } } fn main()
{}
identifier_body
macro-comma-behavior.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Companion test to the similarly-named file in run-pass. // compile-flags: -C debug_assertions=yes // revisions: std core #![cfg_attr(core, no_std)] #[cfg(std)] use std::fmt; #[cfg(core)] use core::fmt; // (see documentation of the similarly-named test in run-pass) fn to_format_or_not_to_format() { let falsum = || false; // assert!(true, "{}",); // see run-pass assert_eq!(1, 1, "{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments assert_ne!(1, 2, "{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments // debug_assert!(true, "{}",); // see run-pass debug_assert_eq!(1, 1, "{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments debug_assert_ne!(1, 2, "{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments #[cfg(std)] { eprint!("{}",); //[std]~^ ERROR no arguments } #[cfg(std)] { // FIXME: compile-fail says "expected error not found" even though // rustc does emit an error // eprintln!("{}",); // <DISABLED> [std]~^ ERROR no arguments } #[cfg(std)] { format!("{}",); //[std]~^ ERROR no arguments } format_args!("{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments // if falsum() { panic!("{}",); } // see run-pass #[cfg(std)] { print!("{}",); //[std]~^ ERROR no arguments } #[cfg(std)] { // FIXME: compile-fail says "expected error not found" even though // rustc does emit an error // println!("{}",); // <DISABLED> [std]~^ ERROR no arguments } unimplemented!("{}",); //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments // if falsum() { unreachable!("{}",); } // see run-pass struct
; impl fmt::Display for S { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}",)?; //[core]~^ ERROR no arguments //[std]~^^ ERROR no arguments // FIXME: compile-fail says "expected error not found" even though // rustc does emit an error // writeln!(f, "{}",)?; // <DISABLED> [core]~^ ERROR no arguments // <DISABLED> [std]~^^ ERROR no arguments Ok(()) } } } fn main() {}
S
identifier_name
main.rs
/* Rust - Std Misc Path Licence : GNU GPL v3 or later Author : AurΓ©lien DESBRIÈRES Mail : aurelien(at)hackers(dot)camp Created on : June 2017 Write with Emacs-nox ───────────────┐ Rust β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ */ use std::path::Path; fn main() { // Create a `Path` from a `&'static str` let path = Path::new("."); // The `display` method returns a `Show`able structure //let display = path.display(); println!("{}", path.display()); // `join` merges a path with a byte container using the OS specific // separator, and returns the new path let new_path = path.join("a").join("b"); // Convert the path into a string slice match new_path.to_str() { None => panic!("new path is not a valid UTF-8 sequence"), Some(s) => println!("new path is {}", s), } } // Other methos:
// windows::Path
// posix::Path
random_line_split
main.rs
/* Rust - Std Misc Path Licence : GNU GPL v3 or later Author : AurΓ©lien DESBRIÈRES Mail : aurelien(at)hackers(dot)camp Created on : June 2017 Write with Emacs-nox ───────────────┐ Rust β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ */ use std::path::Path; fn main() { // Create a `Path` from a `&'static str` let path = Path::new("."); // The `display
` method returns a `Show`able structure //let display = path.display(); println!("{}", path.display()); // `join` merges a path with a byte container using the OS specific // separator, and returns the new path let new_path = path.join("a").join("b"); // Convert the path into a string slice match new_path.to_str() { None => panic!("new path is not a valid UTF-8 sequence"), Some(s) => println!("new path is {}", s), } } // Other methos: // posix::Path // windows::Path
identifier_body
main.rs
/* Rust - Std Misc Path Licence : GNU GPL v3 or later Author : AurΓ©lien DESBRIÈRES Mail : aurelien(at)hackers(dot)camp Created on : June 2017 Write with Emacs-nox ───────────────┐ Rust β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ */ use std::path::Path; fn main() { // Create a `Path` from a `&'static str` let path = Path::new("."); // The `
lay` method returns a `Show`able structure //let display = path.display(); println!("{}", path.display()); // `join` merges a path with a byte container using the OS specific // separator, and returns the new path let new_path = path.join("a").join("b"); // Convert the path into a string slice match new_path.to_str() { None => panic!("new path is not a valid UTF-8 sequence"), Some(s) => println!("new path is {}", s), } } // Other methos: // posix::Path // windows::Path
disp
identifier_name
build.rs
// build.rs use std::process::Command; use std::env; macro_rules! t { ($e:expr) => (match $e { Ok(t) => t, Err(e) => panic!("{} return the error {}", stringify!($e), e), }) } fn run(cmd: &mut Command) { println!("running: {:?}", cmd); assert!(t!(cmd.status()).success()); } fn make() -> &'static str { if cfg!(target_os = "freebsd") {"gmake"} else {"make"} } fn
() { let proj_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let out_dir = env::var("OUT_DIR").unwrap(); run(Command::new(make()) .arg("-j4") .current_dir("3rdparty/FreeImage")); run(Command::new("cp") .arg("3rdparty/FreeImage/Dist/libfreeimage.a") .arg(format!("{}/", out_dir))); println!("cargo:rustc-link-search=native={}", out_dir); println!("cargo:rustc-flags=-l dylib=stdc++"); }
main
identifier_name
build.rs
// build.rs use std::process::Command; use std::env; macro_rules! t { ($e:expr) => (match $e { Ok(t) => t, Err(e) => panic!("{} return the error {}", stringify!($e), e), }) } fn run(cmd: &mut Command) { println!("running: {:?}", cmd); assert!(t!(cmd.status()).success()); } fn make() -> &'static str
fn main() { let proj_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let out_dir = env::var("OUT_DIR").unwrap(); run(Command::new(make()) .arg("-j4") .current_dir("3rdparty/FreeImage")); run(Command::new("cp") .arg("3rdparty/FreeImage/Dist/libfreeimage.a") .arg(format!("{}/", out_dir))); println!("cargo:rustc-link-search=native={}", out_dir); println!("cargo:rustc-flags=-l dylib=stdc++"); }
{ if cfg!(target_os = "freebsd") {"gmake"} else {"make"} }
identifier_body
build.rs
// build.rs use std::process::Command; use std::env; macro_rules! t { ($e:expr) => (match $e { Ok(t) => t, Err(e) => panic!("{} return the error {}", stringify!($e), e), }) } fn run(cmd: &mut Command) { println!("running: {:?}", cmd); assert!(t!(cmd.status()).success()); } fn make() -> &'static str {
let out_dir = env::var("OUT_DIR").unwrap(); run(Command::new(make()) .arg("-j4") .current_dir("3rdparty/FreeImage")); run(Command::new("cp") .arg("3rdparty/FreeImage/Dist/libfreeimage.a") .arg(format!("{}/", out_dir))); println!("cargo:rustc-link-search=native={}", out_dir); println!("cargo:rustc-flags=-l dylib=stdc++"); }
if cfg!(target_os = "freebsd") {"gmake"} else {"make"} } fn main() { let proj_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
random_line_split
build.rs
// build.rs use std::process::Command; use std::env; macro_rules! t { ($e:expr) => (match $e { Ok(t) => t, Err(e) => panic!("{} return the error {}", stringify!($e), e), }) } fn run(cmd: &mut Command) { println!("running: {:?}", cmd); assert!(t!(cmd.status()).success()); } fn make() -> &'static str { if cfg!(target_os = "freebsd") {"gmake"} else
} fn main() { let proj_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let out_dir = env::var("OUT_DIR").unwrap(); run(Command::new(make()) .arg("-j4") .current_dir("3rdparty/FreeImage")); run(Command::new("cp") .arg("3rdparty/FreeImage/Dist/libfreeimage.a") .arg(format!("{}/", out_dir))); println!("cargo:rustc-link-search=native={}", out_dir); println!("cargo:rustc-flags=-l dylib=stdc++"); }
{"make"}
conditional_block
delete.rs
// Copyright (c) 2016-2018 Chef Software Inc. and/or applicable contributors // // 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 depot_client::Client as DepotClient; use common::ui::{Status, UIWriter, UI}; use {PRODUCT, VERSION}; use error::{Error, Result}; pub fn start(ui: &mut UI, bldr_url: &str, token: &str, origin: &str, key: &str) -> Result<()> { let depot_client = DepotClient::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::DepotClient)?; ui.status(Status::Deleting, format!("secret {}.", key))?;
.map_err(Error::DepotClient)?; ui.status(Status::Deleted, format!("secret {}.", key))?; Ok(()) }
depot_client .delete_origin_secret(origin, token, key)
random_line_split