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
row.rs
use fallible_iterator::FallibleIterator; use fallible_streaming_iterator::FallibleStreamingIterator; use std::convert; use super::{Error, Result, Statement}; use crate::types::{FromSql, FromSqlError, ValueRef}; /// An handle for the resulting rows of a query. #[must_use = "Rows is lazy and will do nothing unless consumed"] pub struct Rows<'stmt> { pub(crate) stmt: Option<&'stmt Statement<'stmt>>, row: Option<Row<'stmt>>, } impl<'stmt> Rows<'stmt> { #[inline] fn reset(&mut self) { if let Some(stmt) = self.stmt.take() { stmt.reset(); } } /// Attempt to get the next row from the query. Returns `Ok(Some(Row))` if /// there is another row, `Err(...)` if there was an error /// getting the next row, and `Ok(None)` if all rows have been retrieved. /// /// ## Note /// /// This interface is not compatible with Rust's `Iterator` trait, because /// the lifetime of the returned row is tied to the lifetime of `self`. /// This is a fallible "streaming iterator". For a more natural interface, /// consider using [`query_map`](crate::Statement::query_map) or [`query_and_then`](crate::Statement::query_and_then) instead, which /// return types that implement `Iterator`. #[allow(clippy::should_implement_trait)] // cannot implement Iterator #[inline] pub fn next(&mut self) -> Result<Option<&Row<'stmt>>> { self.advance()?; Ok((*self).get()) } /// Map over this `Rows`, converting it to a [`Map`], which /// implements `FallibleIterator`. /// ```rust,no_run /// use fallible_iterator::FallibleIterator; /// # use rusqlite::{Result, Statement}; /// fn query(stmt: &mut Statement) -> Result<Vec<i64>> { /// let rows = stmt.query([])?; /// rows.map(|r| r.get(0)).collect() /// } /// ``` // FIXME Hide FallibleStreamingIterator::map #[inline] pub fn map<F, B>(self, f: F) -> Map<'stmt, F> where F: FnMut(&Row<'_>) -> Result<B>, { Map { rows: self, f } } /// Map over this `Rows`, converting it to a [`MappedRows`], which /// implements `Iterator`. #[inline] pub fn mapped<F, B>(self, f: F) -> MappedRows<'stmt, F> where F: FnMut(&Row<'_>) -> Result<B>, { MappedRows { rows: self, map: f } } /// Map over this `Rows` with a fallible function, converting it to a /// [`AndThenRows`], which implements `Iterator` (instead of /// `FallibleStreamingIterator`). #[inline] pub fn and_then<F, T, E>(self, f: F) -> AndThenRows<'stmt, F> where F: FnMut(&Row<'_>) -> Result<T, E>, { AndThenRows { rows: self, map: f } } } impl<'stmt> Rows<'stmt> { #[inline] pub(crate) fn new(stmt: &'stmt Statement<'stmt>) -> Rows<'stmt> { Rows { stmt: Some(stmt), row: None, } } #[inline] pub(crate) fn get_expected_row(&mut self) -> Result<&Row<'stmt>> { match self.next()? { Some(row) => Ok(row), None => Err(Error::QueryReturnedNoRows), } } } impl Drop for Rows<'_> { #[inline] fn drop(&mut self) { self.reset(); } } /// `F` is used to tranform the _streaming_ iterator into a _fallible_ iterator. #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct Map<'stmt, F> { rows: Rows<'stmt>, f: F, } impl<F, B> FallibleIterator for Map<'_, F> where F: FnMut(&Row<'_>) -> Result<B>, { type Error = Error; type Item = B; #[inline] fn next(&mut self) -> Result<Option<B>> { match self.rows.next()? { Some(v) => Ok(Some((self.f)(v)?)), None => Ok(None), } } } /// An iterator over the mapped resulting rows of a query. /// /// `F` is used to tranform the _streaming_ iterator into a _standard_ iterator. #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct MappedRows<'stmt, F> { rows: Rows<'stmt>, map: F, } impl<T, F> Iterator for MappedRows<'_, F> where F: FnMut(&Row<'_>) -> Result<T>, { type Item = Result<T>; #[inline] fn next(&mut self) -> Option<Result<T>> { let map = &mut self.map; self.rows .next() .transpose() .map(|row_result| row_result.and_then(|row| (map)(&row))) } } /// An iterator over the mapped resulting rows of a query, with an Error type /// unifying with Error. #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct AndThenRows<'stmt, F> { rows: Rows<'stmt>, map: F, } impl<T, E, F> Iterator for AndThenRows<'_, F> where E: convert::From<Error>, F: FnMut(&Row<'_>) -> Result<T, E>, { type Item = Result<T, E>; #[inline] fn next(&mut self) -> Option<Self::Item> { let map = &mut self.map; self.rows .next() .transpose() .map(|row_result| row_result.map_err(E::from).and_then(|row| (map)(&row))) } } /// `FallibleStreamingIterator` differs from the standard library's `Iterator` /// in two ways: /// * each call to `next` (sqlite3_step) can fail. /// * returned `Row` is valid until `next` is called again or `Statement` is /// reset or finalized. /// /// While these iterators cannot be used with Rust `for` loops, `while let` /// loops offer a similar level of ergonomics: /// ```rust,no_run /// # use rusqlite::{Result, Statement}; /// fn query(stmt: &mut Statement) -> Result<()> { /// let mut rows = stmt.query([])?; /// while let Some(row) = rows.next()? { /// // scan columns value /// } /// Ok(()) /// } /// ``` impl<'stmt> FallibleStreamingIterator for Rows<'stmt> { type Error = Error; type Item = Row<'stmt>; #[inline] fn advance(&mut self) -> Result<()> { match self.stmt { Some(ref stmt) => match stmt.step() { Ok(true) => { self.row = Some(Row { stmt }); Ok(()) } Ok(false) => { self.reset(); self.row = None; Ok(()) } Err(e) => { self.reset(); self.row = None; Err(e) } }, None => { self.row = None; Ok(()) } } } #[inline] fn get(&self) -> Option<&Row<'stmt>> { self.row.as_ref() } } /// A single result row of a query. pub struct Row<'stmt> { pub(crate) stmt: &'stmt Statement<'stmt>, } impl<'stmt> Row<'stmt> { /// Get the value of a particular column of the result row. /// /// ## Failure /// /// Panics if calling [`row.get(idx)`](Row::get) would return an error, /// including: /// /// * If the underlying SQLite column type is not a valid type as a source /// for `T` /// * If the underlying SQLite integral value is outside the range /// representable by `T` /// * If `idx` is outside the range of columns in the returned query pub fn get_unwrap<I: RowIndex, T: FromSql>(&self, idx: I) -> T { self.get(idx).unwrap() } /// Get the value of a particular column of the result row. /// /// ## Failure /// /// Returns an `Error::InvalidColumnType` if the underlying SQLite column /// type is not a valid type as a source for `T`. /// /// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid /// column range for this row. /// /// Returns an `Error::InvalidColumnName` if `idx` is not a valid column /// name for this row. /// /// If the result type is i128 (which requires the `i128_blob` feature to be /// enabled), and the underlying SQLite column is a blob whose size is not /// 16 bytes, `Error::InvalidColumnType` will also be returned. pub fn get<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> { let idx = idx.idx(self.stmt)?; let value = self.stmt.value_ref(idx); FromSql::column_result(value).map_err(|err| match err { FromSqlError::InvalidType => Error::InvalidColumnType( idx, self.stmt.column_name_unwrap(idx).into(), value.data_type(), ), FromSqlError::OutOfRange(i) => Error::IntegralValueOutOfRange(idx, i), FromSqlError::Other(err) => { Error::FromSqlConversionFailure(idx as usize, value.data_type(), err) } #[cfg(feature = "i128_blob")] FromSqlError::InvalidI128Size(_) => Error::InvalidColumnType( idx, self.stmt.column_name_unwrap(idx).into(), value.data_type(), ), #[cfg(feature = "uuid")] FromSqlError::InvalidUuidSize(_) => Error::InvalidColumnType( idx, self.stmt.column_name_unwrap(idx).into(), value.data_type(), ), }) } /// Get the value of a particular column of the result row as a `ValueRef`, /// allowing data to be read out of a row without copying. /// /// This `ValueRef` is valid only as long as this Row, which is enforced by /// it's lifetime. This means that while this method is completely safe, /// it can be somewhat difficult to use, and most callers will be better /// served by [`get`](Row::get) or [`get_unwrap`](Row::get_unwrap). /// /// ## Failure /// /// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid /// column range for this row. /// /// Returns an `Error::InvalidColumnName` if `idx` is not a valid column /// name for this row. pub fn get_ref<I: RowIndex>(&self, idx: I) -> Result<ValueRef<'_>> { let idx = idx.idx(self.stmt)?; // Narrowing from `ValueRef<'stmt>` (which `self.stmt.value_ref(idx)` // returns) to `ValueRef<'a>` is needed because it's only valid until // the next call to sqlite3_step. let val_ref = self.stmt.value_ref(idx); Ok(val_ref) } /// Get the value of a particular column of the result row as a `ValueRef`, /// allowing data to be read out of a row without copying. /// /// This `ValueRef` is valid only as long as this Row, which is enforced by /// it's lifetime. This means that while this method is completely safe, /// it can be difficult to use, and most callers will be better served by /// [`get`](Row::get) or [`get_unwrap`](Row::get_unwrap). /// /// ## Failure /// /// Panics if calling [`row.get_ref(idx)`](Row::get_ref) would return an error, /// including: /// /// * If `idx` is outside the range of columns in the returned query. /// * If `idx` is not a valid column name for this row. pub fn get_ref_unwrap<I: RowIndex>(&self, idx: I) -> ValueRef<'_>
/// Renamed to [`get_ref`](Row::get_ref). #[deprecated = "Use [`get_ref`](Row::get_ref) instead."] #[inline] pub fn get_raw_checked<I: RowIndex>(&self, idx: I) -> Result<ValueRef<'_>> { self.get_ref(idx) } /// Renamed to [`get_ref_unwrap`](Row::get_ref_unwrap). #[deprecated = "Use [`get_ref_unwrap`](Row::get_ref_unwrap) instead."] #[inline] pub fn get_raw<I: RowIndex>(&self, idx: I) -> ValueRef<'_> { self.get_ref_unwrap(idx) } } mod sealed { /// This trait exists just to ensure that the only impls of `trait Params` /// that are allowed are ones in this crate. pub trait Sealed {} impl Sealed for usize {} impl Sealed for &str {} } /// A trait implemented by types that can index into columns of a row. /// /// It is only implemented for `usize` and `&str`. pub trait RowIndex: sealed::Sealed { /// Returns the index of the appropriate column, or `None` if no such /// column exists. fn idx(&self, stmt: &Statement<'_>) -> Result<usize>; } impl RowIndex for usize { #[inline] fn idx(&self, stmt: &Statement<'_>) -> Result<usize> { if *self >= stmt.column_count() { Err(Error::InvalidColumnIndex(*self)) } else { Ok(*self) } } } impl RowIndex for &'_ str { #[inline] fn idx(&self, stmt: &Statement<'_>) -> Result<usize> { stmt.column_index(*self) } } macro_rules! tuple_try_from_row { ($($field:ident),*) => { impl<'a, $($field,)*> convert::TryFrom<&'a Row<'a>> for ($($field,)*) where $($field: FromSql,)* { type Error = crate::Error; // we end with index += 1, which rustc warns about // unused_variables and unused_mut are allowed for () #[allow(unused_assignments, unused_variables, unused_mut)] fn try_from(row: &'a Row<'a>) -> Result<Self> { let mut index = 0; $( #[allow(non_snake_case)] let $field = row.get::<_, $field>(index)?; index += 1; )* Ok(($($field,)*)) } } } } macro_rules! tuples_try_from_row { () => { // not very useful, but maybe some other macro users will find this helpful tuple_try_from_row!(); }; ($first:ident $(, $remaining:ident)*) => { tuple_try_from_row!($first $(, $remaining)*); tuples_try_from_row!($($remaining),*); }; } tuples_try_from_row!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P); #[cfg(test)] mod tests { #![allow(clippy::redundant_closure)] // false positives due to lifetime issues; clippy issue #5594 use crate::{Connection, Result}; #[test] fn test_try_from_row_for_tuple_1() -> Result<()> { use crate::ToSql; use std::convert::TryFrom; let conn = Connection::open_in_memory()?; conn.execute( "CREATE TABLE test (a INTEGER)", crate::params_from_iter(std::iter::empty::<&dyn ToSql>()), )?; conn.execute("INSERT INTO test VALUES (42)", [])?; let val = conn.query_row("SELECT a FROM test", [], |row| <(u32,)>::try_from(row))?; assert_eq!(val, (42,)); let fail = conn.query_row("SELECT a FROM test", [], |row| <(u32, u32)>::try_from(row)); assert!(fail.is_err()); Ok(()) } #[test] fn test_try_from_row_for_tuple_2() -> Result<()> { use std::convert::TryFrom; let conn = Connection::open_in_memory()?; conn.execute("CREATE TABLE test (a INTEGER, b INTEGER)", [])?; conn.execute("INSERT INTO test VALUES (42, 47)", [])?; let val = conn.query_row("SELECT a, b FROM test", [], |row| { <(u32, u32)>::try_from(row) })?; assert_eq!(val, (42, 47)); let fail = conn.query_row("SELECT a, b FROM test", [], |row| { <(u32, u32, u32)>::try_from(row) }); assert!(fail.is_err()); Ok(()) } #[test] fn test_try_from_row_for_tuple_16() -> Result<()> { use std::convert::TryFrom; let create_table = "CREATE TABLE test ( a INTEGER, b INTEGER, c INTEGER, d INTEGER, e INTEGER, f INTEGER, g INTEGER, h INTEGER, i INTEGER, j INTEGER, k INTEGER, l INTEGER, m INTEGER, n INTEGER, o INTEGER, p INTEGER )"; let insert_values = "INSERT INTO test VALUES ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 )"; type BigTuple = ( u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, ); let conn = Connection::open_in_memory()?; conn.execute(create_table, [])?; conn.execute(insert_values, [])?; let val = conn.query_row("SELECT * FROM test", [], |row| BigTuple::try_from(row))?; // Debug is not implemented for tuples of 16 assert_eq!(val.0, 0); assert_eq!(val.1, 1); assert_eq!(val.2, 2); assert_eq!(val.3, 3); assert_eq!(val.4, 4); assert_eq!(val.5, 5); assert_eq!(val.6, 6); assert_eq!(val.7, 7); assert_eq!(val.8, 8); assert_eq!(val.9, 9); assert_eq!(val.10, 10); assert_eq!(val.11, 11); assert_eq!(val.12, 12); assert_eq!(val.13, 13); assert_eq!(val.14, 14); assert_eq!(val.15, 15); // We don't test one bigger because it's unimplemented Ok(()) } }
{ self.get_ref(idx).unwrap() }
identifier_body
cast-enum-with-dtor.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. #![allow(dead_code)] #![feature(const_fn)] // check dtor calling order when casting enums. use std::sync::atomic; use std::sync::atomic::Ordering; use std::mem; enum E { A = 0, B = 1, C = 2 } static FLAG: atomic::AtomicUsize = atomic::AtomicUsize::new(0); impl Drop for E { fn drop(&mut self) { // avoid dtor loop unsafe { mem::forget(mem::replace(self, E::B)) }; FLAG.store(FLAG.load(Ordering::SeqCst)+1, Ordering::SeqCst); } } fn main()
{ assert_eq!(FLAG.load(Ordering::SeqCst), 0); { let e = E::C; assert_eq!(e as u32, 2); assert_eq!(FLAG.load(Ordering::SeqCst), 0); } assert_eq!(FLAG.load(Ordering::SeqCst), 1); }
identifier_body
cast-enum-with-dtor.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. #![allow(dead_code)] #![feature(const_fn)] // check dtor calling order when casting enums.
enum E { A = 0, B = 1, C = 2 } static FLAG: atomic::AtomicUsize = atomic::AtomicUsize::new(0); impl Drop for E { fn drop(&mut self) { // avoid dtor loop unsafe { mem::forget(mem::replace(self, E::B)) }; FLAG.store(FLAG.load(Ordering::SeqCst)+1, Ordering::SeqCst); } } fn main() { assert_eq!(FLAG.load(Ordering::SeqCst), 0); { let e = E::C; assert_eq!(e as u32, 2); assert_eq!(FLAG.load(Ordering::SeqCst), 0); } assert_eq!(FLAG.load(Ordering::SeqCst), 1); }
use std::sync::atomic; use std::sync::atomic::Ordering; use std::mem;
random_line_split
cast-enum-with-dtor.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. #![allow(dead_code)] #![feature(const_fn)] // check dtor calling order when casting enums. use std::sync::atomic; use std::sync::atomic::Ordering; use std::mem; enum E { A = 0, B = 1, C = 2 } static FLAG: atomic::AtomicUsize = atomic::AtomicUsize::new(0); impl Drop for E { fn drop(&mut self) { // avoid dtor loop unsafe { mem::forget(mem::replace(self, E::B)) }; FLAG.store(FLAG.load(Ordering::SeqCst)+1, Ordering::SeqCst); } } fn
() { assert_eq!(FLAG.load(Ordering::SeqCst), 0); { let e = E::C; assert_eq!(e as u32, 2); assert_eq!(FLAG.load(Ordering::SeqCst), 0); } assert_eq!(FLAG.load(Ordering::SeqCst), 1); }
main
identifier_name
mod.rs
pub mod spout; pub mod bolt; use rustc_serialize::json; use tokio_core::net::TcpStream; use tokio_io; use futures::Future; use std; use tokio_uds::UnixStream; pub struct ComponentConfig{ pub sock_file: String, pub component_id: String } #[derive(Debug)] #[derive(RustcEncodable, RustcDecodable)] pub enum Message{ Tuple(String, String), //stream, data Local(String), //local instances' ids (sent to SM) Ready, Metrics, HeartBeat } impl Message{ pub fn from_tcp(stream: TcpStream) -> Box<Future<Item = (Self), Error = std::io::Error >> { let buf = [0; 4]; Box::new(tokio_io::io::read(stream, buf).and_then(|x| { let len = usize::from_str_radix(&String::from_utf8(x.1.to_vec()).unwrap(), 16).unwrap(); let buf = vec![0; len]; tokio_io::io::read_exact(x.0, buf).and_then(|x| { Ok(json::decode(&String::from_utf8(x.1.to_vec()).unwrap()).unwrap()) }) })) } pub fn from_half_uds(stream: tokio_io::io::ReadHalf<UnixStream>) -> Box<Future<Item = ((Self, tokio_io::io::ReadHalf<UnixStream>)), Error = std::io::Error > + Send>{ let buf = [0; 4]; Box::new(tokio_io::io::read(stream, buf).and_then(|x| { let len = usize::from_str_radix(&String::from_utf8(x.1.to_vec()).unwrap(), 16).unwrap(); let buf = vec![0; len]; tokio_io::io::read_exact(x.0, buf).and_then(|x| { Ok((json::decode(&String::from_utf8(x.1.to_vec()).unwrap()).unwrap(), x.0)) }) })) } pub fn to_uds(&self, stream: UnixStream) -> Box<Future<Item = (UnixStream), Error = std::io::Error > + Send> { Box::new(tokio_io::io::write_all(stream, self.encoded()).and_then(|c| Ok(c.0))) } pub fn
(&self, stream: tokio_io::io::WriteHalf<UnixStream>) -> Box<Future<Item = (tokio_io::io::WriteHalf<UnixStream>), Error = std::io::Error > + Send> { Box::new(tokio_io::io::write_all(stream, self.encoded()).and_then(|c| Ok(c.0))) } pub fn encoded(&self) -> Vec<u8>{ let message = json::encode(&self).unwrap(); let message = format!("{:04x}{}", message.len(), message); message.as_bytes().to_vec() } pub fn decoded(){ unimplemented!(); } pub fn tuple(stream: &str, value: &str) -> Self{ Message::Tuple(stream.to_string(), value.to_string()) } }
to_half_uds
identifier_name
mod.rs
pub mod spout; pub mod bolt; use rustc_serialize::json; use tokio_core::net::TcpStream; use tokio_io; use futures::Future; use std; use tokio_uds::UnixStream; pub struct ComponentConfig{ pub sock_file: String, pub component_id: String } #[derive(Debug)] #[derive(RustcEncodable, RustcDecodable)] pub enum Message{ Tuple(String, String), //stream, data Local(String), //local instances' ids (sent to SM) Ready, Metrics, HeartBeat } impl Message{ pub fn from_tcp(stream: TcpStream) -> Box<Future<Item = (Self), Error = std::io::Error >> { let buf = [0; 4]; Box::new(tokio_io::io::read(stream, buf).and_then(|x| { let len = usize::from_str_radix(&String::from_utf8(x.1.to_vec()).unwrap(), 16).unwrap(); let buf = vec![0; len]; tokio_io::io::read_exact(x.0, buf).and_then(|x| { Ok(json::decode(&String::from_utf8(x.1.to_vec()).unwrap()).unwrap()) }) })) } pub fn from_half_uds(stream: tokio_io::io::ReadHalf<UnixStream>) -> Box<Future<Item = ((Self, tokio_io::io::ReadHalf<UnixStream>)), Error = std::io::Error > + Send>{ let buf = [0; 4]; Box::new(tokio_io::io::read(stream, buf).and_then(|x| { let len = usize::from_str_radix(&String::from_utf8(x.1.to_vec()).unwrap(), 16).unwrap(); let buf = vec![0; len]; tokio_io::io::read_exact(x.0, buf).and_then(|x| { Ok((json::decode(&String::from_utf8(x.1.to_vec()).unwrap()).unwrap(), x.0)) }) })) } pub fn to_uds(&self, stream: UnixStream) -> Box<Future<Item = (UnixStream), Error = std::io::Error > + Send> { Box::new(tokio_io::io::write_all(stream, self.encoded()).and_then(|c| Ok(c.0))) } pub fn to_half_uds(&self, stream: tokio_io::io::WriteHalf<UnixStream>) -> Box<Future<Item = (tokio_io::io::WriteHalf<UnixStream>), Error = std::io::Error > + Send> { Box::new(tokio_io::io::write_all(stream, self.encoded()).and_then(|c| Ok(c.0))) } pub fn encoded(&self) -> Vec<u8>{ let message = json::encode(&self).unwrap(); let message = format!("{:04x}{}", message.len(), message); message.as_bytes().to_vec() } pub fn decoded(){ unimplemented!(); } pub fn tuple(stream: &str, value: &str) -> Self
}
{ Message::Tuple(stream.to_string(), value.to_string()) }
identifier_body
mod.rs
pub mod spout; pub mod bolt; use rustc_serialize::json; use tokio_core::net::TcpStream; use tokio_io; use futures::Future; use std; use tokio_uds::UnixStream; pub struct ComponentConfig{ pub sock_file: String, pub component_id: String } #[derive(Debug)] #[derive(RustcEncodable, RustcDecodable)] pub enum Message{ Tuple(String, String), //stream, data Local(String), //local instances' ids (sent to SM) Ready, Metrics, HeartBeat } impl Message{ pub fn from_tcp(stream: TcpStream) -> Box<Future<Item = (Self), Error = std::io::Error >> { let buf = [0; 4]; Box::new(tokio_io::io::read(stream, buf).and_then(|x| { let len = usize::from_str_radix(&String::from_utf8(x.1.to_vec()).unwrap(), 16).unwrap(); let buf = vec![0; len]; tokio_io::io::read_exact(x.0, buf).and_then(|x| { Ok(json::decode(&String::from_utf8(x.1.to_vec()).unwrap()).unwrap()) }) })) } pub fn from_half_uds(stream: tokio_io::io::ReadHalf<UnixStream>) -> Box<Future<Item = ((Self, tokio_io::io::ReadHalf<UnixStream>)), Error = std::io::Error > + Send>{ let buf = [0; 4]; Box::new(tokio_io::io::read(stream, buf).and_then(|x| { let len = usize::from_str_radix(&String::from_utf8(x.1.to_vec()).unwrap(), 16).unwrap(); let buf = vec![0; len]; tokio_io::io::read_exact(x.0, buf).and_then(|x| { Ok((json::decode(&String::from_utf8(x.1.to_vec()).unwrap()).unwrap(), x.0)) }) })) } pub fn to_uds(&self, stream: UnixStream) -> Box<Future<Item = (UnixStream), Error = std::io::Error > + Send> { Box::new(tokio_io::io::write_all(stream, self.encoded()).and_then(|c| Ok(c.0))) } pub fn to_half_uds(&self, stream: tokio_io::io::WriteHalf<UnixStream>) -> Box<Future<Item = (tokio_io::io::WriteHalf<UnixStream>), Error = std::io::Error > + Send> { Box::new(tokio_io::io::write_all(stream, self.encoded()).and_then(|c| Ok(c.0))) } pub fn encoded(&self) -> Vec<u8>{ let message = json::encode(&self).unwrap(); let message = format!("{:04x}{}", message.len(), message); message.as_bytes().to_vec() } pub fn decoded(){
unimplemented!(); } pub fn tuple(stream: &str, value: &str) -> Self{ Message::Tuple(stream.to_string(), value.to_string()) } }
random_line_split
trampoline_to_glib.rs
use analysis::conversion_type::ConversionType; use library; pub trait TrampolineToGlib { fn trampoline_to_glib(&self, library: &library::Library) -> String; } impl TrampolineToGlib for library::Parameter { fn trampoline_to_glib(&self, library: &library::Library) -> String
} fn to_glib_xxx(transfer: library::Transfer) -> &'static str { use library::Transfer::*; match transfer { None => "/*Not checked*/.to_glib_none().0", Full => ".to_glib_full()", Container => "/*Not checked*/.to_glib_container().0", } }
{ use analysis::conversion_type::ConversionType::*; match ConversionType::of(library, self.typ) { Direct => String::new(), Scalar => ".to_glib()".to_owned(), Pointer => to_glib_xxx(self.transfer).to_owned(), Unknown => "/*Unknown conversion*/".to_owned(), } }
identifier_body
trampoline_to_glib.rs
use analysis::conversion_type::ConversionType; use library; pub trait TrampolineToGlib { fn trampoline_to_glib(&self, library: &library::Library) -> String; } impl TrampolineToGlib for library::Parameter { fn trampoline_to_glib(&self, library: &library::Library) -> String { use analysis::conversion_type::ConversionType::*; match ConversionType::of(library, self.typ) { Direct => String::new(), Scalar => ".to_glib()".to_owned(), Pointer => to_glib_xxx(self.transfer).to_owned(), Unknown => "/*Unknown conversion*/".to_owned(), } } }
None => "/*Not checked*/.to_glib_none().0", Full => ".to_glib_full()", Container => "/*Not checked*/.to_glib_container().0", } }
fn to_glib_xxx(transfer: library::Transfer) -> &'static str { use library::Transfer::*; match transfer {
random_line_split
trampoline_to_glib.rs
use analysis::conversion_type::ConversionType; use library; pub trait TrampolineToGlib { fn trampoline_to_glib(&self, library: &library::Library) -> String; } impl TrampolineToGlib for library::Parameter { fn trampoline_to_glib(&self, library: &library::Library) -> String { use analysis::conversion_type::ConversionType::*; match ConversionType::of(library, self.typ) { Direct => String::new(), Scalar => ".to_glib()".to_owned(), Pointer => to_glib_xxx(self.transfer).to_owned(), Unknown => "/*Unknown conversion*/".to_owned(), } } } fn
(transfer: library::Transfer) -> &'static str { use library::Transfer::*; match transfer { None => "/*Not checked*/.to_glib_none().0", Full => ".to_glib_full()", Container => "/*Not checked*/.to_glib_container().0", } }
to_glib_xxx
identifier_name
counts.rs
use needletail::bitkmer::{bitmer_to_bytes, reverse_complement}; use needletail::Sequence; use crate::sketch_schemes::{KmerCount, SketchParams, SketchScheme}; use needletail::parser::SequenceRecord; #[derive(Clone)] pub struct AllCountsSketcher { counts: Vec<u32>, total_bases: u64, k: u8, } impl AllCountsSketcher { pub fn new(k: u8) -> Self { // TODO: should we take a size parameter or the like and clip this? AllCountsSketcher { counts: vec![0; 4usize.pow(k.into())], total_bases: 0, k, } } } impl SketchScheme for AllCountsSketcher { fn process(&mut self, seq: SequenceRecord)
fn total_bases_and_kmers(&self) -> (u64, u64) { ( self.total_bases, self.counts.iter().map(|x| u64::from(*x)).sum(), ) } fn to_vec(&self) -> Vec<KmerCount> { let mut counts = self.counts.clone(); let mut results = Vec::with_capacity(self.counts.len()); for ix in 0u64..counts.len() as u64 { let mut count = counts[ix as usize]; if count == 0 { continue; } let extra_count = self.counts[reverse_complement((ix, self.k)).0 as usize]; counts[reverse_complement((ix, self.k)).0 as usize] = 0; count += extra_count; let new_item = KmerCount { hash: ix, kmer: bitmer_to_bytes((ix as u64, self.k)), count, extra_count, label: None, }; results.push(new_item); } results } fn parameters(&self) -> SketchParams { SketchParams::AllCounts { kmer_length: self.k, } } }
{ for (_, kmer, _) in seq.normalize(false).bit_kmers(self.k, false) { self.counts[kmer.0 as usize] = self.counts[kmer.0 as usize].saturating_add(1); } }
identifier_body
counts.rs
use needletail::bitkmer::{bitmer_to_bytes, reverse_complement}; use needletail::Sequence; use crate::sketch_schemes::{KmerCount, SketchParams, SketchScheme}; use needletail::parser::SequenceRecord; #[derive(Clone)] pub struct AllCountsSketcher { counts: Vec<u32>, total_bases: u64, k: u8, } impl AllCountsSketcher { pub fn new(k: u8) -> Self { // TODO: should we take a size parameter or the like and clip this? AllCountsSketcher { counts: vec![0; 4usize.pow(k.into())], total_bases: 0, k, } } } impl SketchScheme for AllCountsSketcher { fn process(&mut self, seq: SequenceRecord) { for (_, kmer, _) in seq.normalize(false).bit_kmers(self.k, false) { self.counts[kmer.0 as usize] = self.counts[kmer.0 as usize].saturating_add(1); } } fn total_bases_and_kmers(&self) -> (u64, u64) { ( self.total_bases, self.counts.iter().map(|x| u64::from(*x)).sum(), ) } fn to_vec(&self) -> Vec<KmerCount> { let mut counts = self.counts.clone(); let mut results = Vec::with_capacity(self.counts.len()); for ix in 0u64..counts.len() as u64 { let mut count = counts[ix as usize]; if count == 0
let extra_count = self.counts[reverse_complement((ix, self.k)).0 as usize]; counts[reverse_complement((ix, self.k)).0 as usize] = 0; count += extra_count; let new_item = KmerCount { hash: ix, kmer: bitmer_to_bytes((ix as u64, self.k)), count, extra_count, label: None, }; results.push(new_item); } results } fn parameters(&self) -> SketchParams { SketchParams::AllCounts { kmer_length: self.k, } } }
{ continue; }
conditional_block
counts.rs
use needletail::bitkmer::{bitmer_to_bytes, reverse_complement}; use needletail::Sequence; use crate::sketch_schemes::{KmerCount, SketchParams, SketchScheme}; use needletail::parser::SequenceRecord; #[derive(Clone)] pub struct
{ counts: Vec<u32>, total_bases: u64, k: u8, } impl AllCountsSketcher { pub fn new(k: u8) -> Self { // TODO: should we take a size parameter or the like and clip this? AllCountsSketcher { counts: vec![0; 4usize.pow(k.into())], total_bases: 0, k, } } } impl SketchScheme for AllCountsSketcher { fn process(&mut self, seq: SequenceRecord) { for (_, kmer, _) in seq.normalize(false).bit_kmers(self.k, false) { self.counts[kmer.0 as usize] = self.counts[kmer.0 as usize].saturating_add(1); } } fn total_bases_and_kmers(&self) -> (u64, u64) { ( self.total_bases, self.counts.iter().map(|x| u64::from(*x)).sum(), ) } fn to_vec(&self) -> Vec<KmerCount> { let mut counts = self.counts.clone(); let mut results = Vec::with_capacity(self.counts.len()); for ix in 0u64..counts.len() as u64 { let mut count = counts[ix as usize]; if count == 0 { continue; } let extra_count = self.counts[reverse_complement((ix, self.k)).0 as usize]; counts[reverse_complement((ix, self.k)).0 as usize] = 0; count += extra_count; let new_item = KmerCount { hash: ix, kmer: bitmer_to_bytes((ix as u64, self.k)), count, extra_count, label: None, }; results.push(new_item); } results } fn parameters(&self) -> SketchParams { SketchParams::AllCounts { kmer_length: self.k, } } }
AllCountsSketcher
identifier_name
counts.rs
use needletail::bitkmer::{bitmer_to_bytes, reverse_complement}; use needletail::Sequence; use crate::sketch_schemes::{KmerCount, SketchParams, SketchScheme}; use needletail::parser::SequenceRecord; #[derive(Clone)] pub struct AllCountsSketcher { counts: Vec<u32>, total_bases: u64, k: u8, } impl AllCountsSketcher { pub fn new(k: u8) -> Self { // TODO: should we take a size parameter or the like and clip this? AllCountsSketcher { counts: vec![0; 4usize.pow(k.into())], total_bases: 0, k, } } } impl SketchScheme for AllCountsSketcher { fn process(&mut self, seq: SequenceRecord) { for (_, kmer, _) in seq.normalize(false).bit_kmers(self.k, false) { self.counts[kmer.0 as usize] = self.counts[kmer.0 as usize].saturating_add(1); } } fn total_bases_and_kmers(&self) -> (u64, u64) { ( self.total_bases, self.counts.iter().map(|x| u64::from(*x)).sum(), ) } fn to_vec(&self) -> Vec<KmerCount> { let mut counts = self.counts.clone(); let mut results = Vec::with_capacity(self.counts.len()); for ix in 0u64..counts.len() as u64 { let mut count = counts[ix as usize]; if count == 0 { continue; } let extra_count = self.counts[reverse_complement((ix, self.k)).0 as usize]; counts[reverse_complement((ix, self.k)).0 as usize] = 0; count += extra_count; let new_item = KmerCount { hash: ix, kmer: bitmer_to_bytes((ix as u64, self.k)), count, extra_count, label: None, }; results.push(new_item); }
fn parameters(&self) -> SketchParams { SketchParams::AllCounts { kmer_length: self.k, } } }
results }
random_line_split
mod.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// option. This file may not be copied, modified, or distributed // except according to those terms. //! Unordered containers, implemented as hash-tables mod table; pub mod map; pub mod set; trait Recover<Q:?Sized> { type Key; fn get(&self, key: &Q) -> Option<&Self::Key>; fn take(&mut self, key: &Q) -> Option<Self::Key>; fn replace(&mut self, key: Self::Key) -> Option<Self::Key>; }
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
bezier.rs
// Copyright (C) 2020 Inderjit Gill <[email protected]> // This file is part of Seni // Seni is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Seni 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 Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. use crate::ease::Easing; use crate::error::{Error, Result}; use crate::interp::parametric; use crate::mathutil::*; use crate::matrix::Matrix; use crate::render_list::RenderList; use crate::rgb::Rgb; use crate::uvmapper::UvMapping; pub fn render( render_list: &mut RenderList, matrix: &Matrix, coords: &[f32; 8], width_start: f32, width_end: f32, width_mapping: Easing, t_start: f32, t_end: f32, colour: &Rgb, tessellation: usize, uvm: &UvMapping, ) -> Result<()>
let x0 = coords[0]; let x1 = coords[2]; let x2 = coords[4]; let x3 = coords[6]; let y0 = coords[1]; let y1 = coords[3]; let y2 = coords[5]; let y3 = coords[7]; let unit = (t_end - t_start) / (tessellation as f32 - 1.0); let tex_t = 1.0 / tessellation as f32; // this chunk of code is just to calc the initial verts for prepare_to_add_triangle_strip // and to get the appropriate render packet // let t_val = t_start; let t_val_next = t_start + (1.0 * unit); let xs = bezier_point(x0, x1, x2, x3, t_val); let ys = bezier_point(y0, y1, y2, y3, t_val); let xs_next = bezier_point(x0, x1, x2, x3, t_val_next); let ys_next = bezier_point(y0, y1, y2, y3, t_val_next); let (n1x, n1y) = normal(xs, ys, xs_next, ys_next); let half_width = parametric(t_val, t_start, t_end, half_width_start, half_width_end, width_mapping, false); let v1x = (n1x * half_width) + xs; let v1y = (n1y * half_width) + ys; render_list.prepare_to_add_triangle_strip(matrix, tessellation * 2, v1x, v1y)?; let rp = render_list .render_packets .last_mut() .ok_or(Error::Geometry)?; let rpg = rp.get_mut_render_packet_geometry()?; for i in 0..(tessellation - 1) { let t_val = t_start + (i as f32 * unit); let t_val_next = t_start + ((i + 1) as f32 * unit); let xs = bezier_point(x0, x1, x2, x3, t_val); let ys = bezier_point(y0, y1, y2, y3, t_val); let xs_next = bezier_point(x0, x1, x2, x3, t_val_next); let ys_next = bezier_point(y0, y1, y2, y3, t_val_next); // addVerticesAsStrip let (n1x, n1y) = normal(xs, ys, xs_next, ys_next); let (n2x, n2y) = opposite_normal(n1x, n1y); let half_width = parametric(t_val, t_start, t_end, half_width_start, half_width_end, width_mapping, false); let v1x = (n1x * half_width) + xs; let v1y = (n1y * half_width) + ys; let v2x = (n2x * half_width) + xs; let v2y = (n2y * half_width) + ys; let uv_t = tex_t * (i as f32); let u = lerp(uv_t, bu, du); let v = lerp(uv_t, bv, dv); rpg.add_vertex(matrix, v1x, v1y, &colour, u, v); let u = lerp(uv_t, au, cu); let v = lerp(uv_t, av, cv); rpg.add_vertex(matrix, v2x, v2y, &colour, u, v); } // final 2 vertices for the end point let i = tessellation - 2; let t_val = t_start + (i as f32 * unit); let t_val_next = t_start + ((i + 1) as f32 * unit); let xs = bezier_point(x0, x1, x2, x3, t_val); let ys = bezier_point(y0, y1, y2, y3, t_val); let xs_next = bezier_point(x0, x1, x2, x3, t_val_next); let ys_next = bezier_point(y0, y1, y2, y3, t_val_next); let (n1x, n1y) = normal(xs, ys, xs_next, ys_next); let (n2x, n2y) = opposite_normal(n1x, n1y); let v1x = (n1x * half_width_end) + xs_next; let v1y = (n1y * half_width_end) + ys_next; let v2x = (n2x * half_width_end) + xs_next; let v2y = (n2y * half_width_end) + ys_next; rpg.add_vertex(matrix, v1x, v1y, &colour, du, dv); rpg.add_vertex(matrix, v2x, v2y, &colour, cu, cv); Ok(()) }
{ let au = uvm.map[0]; let av = uvm.map[1]; let bu = uvm.map[2]; let bv = uvm.map[3]; let cu = uvm.map[4]; let cv = uvm.map[5]; let du = uvm.map[6]; let dv = uvm.map[7]; // modify the width so that the brush textures provide good coverage // let line_width_start = width_start * uvm.width_scale; let line_width_end = width_end * uvm.width_scale; // variables for interpolating the curve's width // let half_width_start = line_width_start / 2.0; let half_width_end = line_width_end / 2.0;
identifier_body
bezier.rs
// Copyright (C) 2020 Inderjit Gill <[email protected]> // This file is part of Seni // Seni is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Seni 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 Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. use crate::ease::Easing; use crate::error::{Error, Result}; use crate::interp::parametric; use crate::mathutil::*; use crate::matrix::Matrix; use crate::render_list::RenderList; use crate::rgb::Rgb; use crate::uvmapper::UvMapping; pub fn render( render_list: &mut RenderList, matrix: &Matrix, coords: &[f32; 8], width_start: f32, width_end: f32, width_mapping: Easing, t_start: f32, t_end: f32, colour: &Rgb, tessellation: usize, uvm: &UvMapping, ) -> Result<()> { let au = uvm.map[0]; let av = uvm.map[1]; let bu = uvm.map[2]; let bv = uvm.map[3]; let cu = uvm.map[4]; let cv = uvm.map[5]; let du = uvm.map[6]; let dv = uvm.map[7]; // modify the width so that the brush textures provide good coverage // let line_width_start = width_start * uvm.width_scale; let line_width_end = width_end * uvm.width_scale; // variables for interpolating the curve's width // let half_width_start = line_width_start / 2.0; let half_width_end = line_width_end / 2.0; let x0 = coords[0]; let x1 = coords[2]; let x2 = coords[4]; let x3 = coords[6]; let y0 = coords[1]; let y1 = coords[3]; let y2 = coords[5]; let y3 = coords[7]; let unit = (t_end - t_start) / (tessellation as f32 - 1.0);
let tex_t = 1.0 / tessellation as f32; // this chunk of code is just to calc the initial verts for prepare_to_add_triangle_strip // and to get the appropriate render packet // let t_val = t_start; let t_val_next = t_start + (1.0 * unit); let xs = bezier_point(x0, x1, x2, x3, t_val); let ys = bezier_point(y0, y1, y2, y3, t_val); let xs_next = bezier_point(x0, x1, x2, x3, t_val_next); let ys_next = bezier_point(y0, y1, y2, y3, t_val_next); let (n1x, n1y) = normal(xs, ys, xs_next, ys_next); let half_width = parametric(t_val, t_start, t_end, half_width_start, half_width_end, width_mapping, false); let v1x = (n1x * half_width) + xs; let v1y = (n1y * half_width) + ys; render_list.prepare_to_add_triangle_strip(matrix, tessellation * 2, v1x, v1y)?; let rp = render_list .render_packets .last_mut() .ok_or(Error::Geometry)?; let rpg = rp.get_mut_render_packet_geometry()?; for i in 0..(tessellation - 1) { let t_val = t_start + (i as f32 * unit); let t_val_next = t_start + ((i + 1) as f32 * unit); let xs = bezier_point(x0, x1, x2, x3, t_val); let ys = bezier_point(y0, y1, y2, y3, t_val); let xs_next = bezier_point(x0, x1, x2, x3, t_val_next); let ys_next = bezier_point(y0, y1, y2, y3, t_val_next); // addVerticesAsStrip let (n1x, n1y) = normal(xs, ys, xs_next, ys_next); let (n2x, n2y) = opposite_normal(n1x, n1y); let half_width = parametric(t_val, t_start, t_end, half_width_start, half_width_end, width_mapping, false); let v1x = (n1x * half_width) + xs; let v1y = (n1y * half_width) + ys; let v2x = (n2x * half_width) + xs; let v2y = (n2y * half_width) + ys; let uv_t = tex_t * (i as f32); let u = lerp(uv_t, bu, du); let v = lerp(uv_t, bv, dv); rpg.add_vertex(matrix, v1x, v1y, &colour, u, v); let u = lerp(uv_t, au, cu); let v = lerp(uv_t, av, cv); rpg.add_vertex(matrix, v2x, v2y, &colour, u, v); } // final 2 vertices for the end point let i = tessellation - 2; let t_val = t_start + (i as f32 * unit); let t_val_next = t_start + ((i + 1) as f32 * unit); let xs = bezier_point(x0, x1, x2, x3, t_val); let ys = bezier_point(y0, y1, y2, y3, t_val); let xs_next = bezier_point(x0, x1, x2, x3, t_val_next); let ys_next = bezier_point(y0, y1, y2, y3, t_val_next); let (n1x, n1y) = normal(xs, ys, xs_next, ys_next); let (n2x, n2y) = opposite_normal(n1x, n1y); let v1x = (n1x * half_width_end) + xs_next; let v1y = (n1y * half_width_end) + ys_next; let v2x = (n2x * half_width_end) + xs_next; let v2y = (n2y * half_width_end) + ys_next; rpg.add_vertex(matrix, v1x, v1y, &colour, du, dv); rpg.add_vertex(matrix, v2x, v2y, &colour, cu, cv); Ok(()) }
random_line_split
bezier.rs
// Copyright (C) 2020 Inderjit Gill <[email protected]> // This file is part of Seni // Seni is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Seni 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 Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. use crate::ease::Easing; use crate::error::{Error, Result}; use crate::interp::parametric; use crate::mathutil::*; use crate::matrix::Matrix; use crate::render_list::RenderList; use crate::rgb::Rgb; use crate::uvmapper::UvMapping; pub fn
( render_list: &mut RenderList, matrix: &Matrix, coords: &[f32; 8], width_start: f32, width_end: f32, width_mapping: Easing, t_start: f32, t_end: f32, colour: &Rgb, tessellation: usize, uvm: &UvMapping, ) -> Result<()> { let au = uvm.map[0]; let av = uvm.map[1]; let bu = uvm.map[2]; let bv = uvm.map[3]; let cu = uvm.map[4]; let cv = uvm.map[5]; let du = uvm.map[6]; let dv = uvm.map[7]; // modify the width so that the brush textures provide good coverage // let line_width_start = width_start * uvm.width_scale; let line_width_end = width_end * uvm.width_scale; // variables for interpolating the curve's width // let half_width_start = line_width_start / 2.0; let half_width_end = line_width_end / 2.0; let x0 = coords[0]; let x1 = coords[2]; let x2 = coords[4]; let x3 = coords[6]; let y0 = coords[1]; let y1 = coords[3]; let y2 = coords[5]; let y3 = coords[7]; let unit = (t_end - t_start) / (tessellation as f32 - 1.0); let tex_t = 1.0 / tessellation as f32; // this chunk of code is just to calc the initial verts for prepare_to_add_triangle_strip // and to get the appropriate render packet // let t_val = t_start; let t_val_next = t_start + (1.0 * unit); let xs = bezier_point(x0, x1, x2, x3, t_val); let ys = bezier_point(y0, y1, y2, y3, t_val); let xs_next = bezier_point(x0, x1, x2, x3, t_val_next); let ys_next = bezier_point(y0, y1, y2, y3, t_val_next); let (n1x, n1y) = normal(xs, ys, xs_next, ys_next); let half_width = parametric(t_val, t_start, t_end, half_width_start, half_width_end, width_mapping, false); let v1x = (n1x * half_width) + xs; let v1y = (n1y * half_width) + ys; render_list.prepare_to_add_triangle_strip(matrix, tessellation * 2, v1x, v1y)?; let rp = render_list .render_packets .last_mut() .ok_or(Error::Geometry)?; let rpg = rp.get_mut_render_packet_geometry()?; for i in 0..(tessellation - 1) { let t_val = t_start + (i as f32 * unit); let t_val_next = t_start + ((i + 1) as f32 * unit); let xs = bezier_point(x0, x1, x2, x3, t_val); let ys = bezier_point(y0, y1, y2, y3, t_val); let xs_next = bezier_point(x0, x1, x2, x3, t_val_next); let ys_next = bezier_point(y0, y1, y2, y3, t_val_next); // addVerticesAsStrip let (n1x, n1y) = normal(xs, ys, xs_next, ys_next); let (n2x, n2y) = opposite_normal(n1x, n1y); let half_width = parametric(t_val, t_start, t_end, half_width_start, half_width_end, width_mapping, false); let v1x = (n1x * half_width) + xs; let v1y = (n1y * half_width) + ys; let v2x = (n2x * half_width) + xs; let v2y = (n2y * half_width) + ys; let uv_t = tex_t * (i as f32); let u = lerp(uv_t, bu, du); let v = lerp(uv_t, bv, dv); rpg.add_vertex(matrix, v1x, v1y, &colour, u, v); let u = lerp(uv_t, au, cu); let v = lerp(uv_t, av, cv); rpg.add_vertex(matrix, v2x, v2y, &colour, u, v); } // final 2 vertices for the end point let i = tessellation - 2; let t_val = t_start + (i as f32 * unit); let t_val_next = t_start + ((i + 1) as f32 * unit); let xs = bezier_point(x0, x1, x2, x3, t_val); let ys = bezier_point(y0, y1, y2, y3, t_val); let xs_next = bezier_point(x0, x1, x2, x3, t_val_next); let ys_next = bezier_point(y0, y1, y2, y3, t_val_next); let (n1x, n1y) = normal(xs, ys, xs_next, ys_next); let (n2x, n2y) = opposite_normal(n1x, n1y); let v1x = (n1x * half_width_end) + xs_next; let v1y = (n1y * half_width_end) + ys_next; let v2x = (n2x * half_width_end) + xs_next; let v2y = (n2y * half_width_end) + ys_next; rpg.add_vertex(matrix, v1x, v1y, &colour, du, dv); rpg.add_vertex(matrix, v2x, v2y, &colour, cu, cv); Ok(()) }
render
identifier_name
error.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::error; use std::fmt::Display; use std::fmt::{self}; use std::io; use std::str; use std::string; use std::{self}; use serde::de; use serde::ser; #[derive(Debug)] pub struct Error { msg: String, } pub type Result<T> = std::result::Result<T, Error>; impl Error { pub fn new<T: Display>(msg: T) -> Self { Error {
impl error::Error for Error { fn description(&self) -> &str { &self.msg } } impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.msg) } } impl ser::Error for Error { fn custom<T: Display>(msg: T) -> Self { Error::new(msg) } } impl de::Error for Error { fn custom<T: Display>(msg: T) -> Self { Error::new(msg) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Error::new(err) } } impl From<str::Utf8Error> for Error { fn from(err: str::Utf8Error) -> Self { Error::new(err) } } impl From<string::FromUtf8Error> for Error { fn from(err: string::FromUtf8Error) -> Self { Error::new(err) } }
msg: msg.to_string(), } } }
random_line_split
error.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::error; use std::fmt::Display; use std::fmt::{self}; use std::io; use std::str; use std::string; use std::{self}; use serde::de; use serde::ser; #[derive(Debug)] pub struct Error { msg: String, } pub type Result<T> = std::result::Result<T, Error>; impl Error { pub fn new<T: Display>(msg: T) -> Self { Error { msg: msg.to_string(), } } } impl error::Error for Error { fn description(&self) -> &str { &self.msg } } impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.msg) } } impl ser::Error for Error { fn custom<T: Display>(msg: T) -> Self { Error::new(msg) } } impl de::Error for Error { fn custom<T: Display>(msg: T) -> Self { Error::new(msg) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Error::new(err) } } impl From<str::Utf8Error> for Error { fn from(err: str::Utf8Error) -> Self
} impl From<string::FromUtf8Error> for Error { fn from(err: string::FromUtf8Error) -> Self { Error::new(err) } }
{ Error::new(err) }
identifier_body
error.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::error; use std::fmt::Display; use std::fmt::{self}; use std::io; use std::str; use std::string; use std::{self}; use serde::de; use serde::ser; #[derive(Debug)] pub struct Error { msg: String, } pub type Result<T> = std::result::Result<T, Error>; impl Error { pub fn new<T: Display>(msg: T) -> Self { Error { msg: msg.to_string(), } } } impl error::Error for Error { fn
(&self) -> &str { &self.msg } } impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.msg) } } impl ser::Error for Error { fn custom<T: Display>(msg: T) -> Self { Error::new(msg) } } impl de::Error for Error { fn custom<T: Display>(msg: T) -> Self { Error::new(msg) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Error::new(err) } } impl From<str::Utf8Error> for Error { fn from(err: str::Utf8Error) -> Self { Error::new(err) } } impl From<string::FromUtf8Error> for Error { fn from(err: string::FromUtf8Error) -> Self { Error::new(err) } }
description
identifier_name
background_datastore.rs
use rand; use rand::distributions::*; use structures; use constants::*; use GameUpdateArgs; pub struct BackgroundDatastore<'a> { buffer_data: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT], instance_data: &'a mut [u32; MAX_BK_COUNT] } impl <'a> BackgroundDatastore<'a> { pub fn new(buffer_data_ref: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT], instance_data_ref: &'a mut [u32; MAX_BK_COUNT]) -> Self { BackgroundDatastore { buffer_data: buffer_data_ref, instance_data: instance_data_ref } } pub fn update(&mut self, update_args: &mut GameUpdateArgs, appear: bool)
else { self.buffer_data[i].offset[1] += update_args.delta_time * 22.0f32; *m = if self.buffer_data[i].offset[1] >= 20.0f32 { 0 } else { 1 }; } } } }
{ let mut require_appear = appear; let mut left_range = rand::distributions::Range::new(-14.0f32, 14.0f32); let mut count_range = rand::distributions::Range::new(2, 10); let mut scale_range = rand::distributions::Range::new(1.0f32, 3.0f32); for (i, m) in self.instance_data.iter_mut().enumerate() { if *m == 0 { // instantiate randomly if require_appear { let scale = scale_range.sample(&mut update_args.randomizer); *m = 1; self.buffer_data[i].offset = [left_range.sample(&mut update_args.randomizer), -20.0f32, -20.0f32, count_range.sample(&mut update_args.randomizer) as f32]; self.buffer_data[i].scale = [scale, scale, 1.0f32, 1.0f32]; require_appear = false; } }
identifier_body
background_datastore.rs
use rand; use rand::distributions::*; use structures; use constants::*; use GameUpdateArgs; pub struct BackgroundDatastore<'a> { buffer_data: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT], instance_data: &'a mut [u32; MAX_BK_COUNT] } impl <'a> BackgroundDatastore<'a> {
{ buffer_data: buffer_data_ref, instance_data: instance_data_ref } } pub fn update(&mut self, update_args: &mut GameUpdateArgs, appear: bool) { let mut require_appear = appear; let mut left_range = rand::distributions::Range::new(-14.0f32, 14.0f32); let mut count_range = rand::distributions::Range::new(2, 10); let mut scale_range = rand::distributions::Range::new(1.0f32, 3.0f32); for (i, m) in self.instance_data.iter_mut().enumerate() { if *m == 0 { // instantiate randomly if require_appear { let scale = scale_range.sample(&mut update_args.randomizer); *m = 1; self.buffer_data[i].offset = [left_range.sample(&mut update_args.randomizer), -20.0f32, -20.0f32, count_range.sample(&mut update_args.randomizer) as f32]; self.buffer_data[i].scale = [scale, scale, 1.0f32, 1.0f32]; require_appear = false; } } else { self.buffer_data[i].offset[1] += update_args.delta_time * 22.0f32; *m = if self.buffer_data[i].offset[1] >= 20.0f32 { 0 } else { 1 }; } } } }
pub fn new(buffer_data_ref: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT], instance_data_ref: &'a mut [u32; MAX_BK_COUNT]) -> Self { BackgroundDatastore
random_line_split
background_datastore.rs
use rand; use rand::distributions::*; use structures; use constants::*; use GameUpdateArgs; pub struct BackgroundDatastore<'a> { buffer_data: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT], instance_data: &'a mut [u32; MAX_BK_COUNT] } impl <'a> BackgroundDatastore<'a> { pub fn new(buffer_data_ref: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT], instance_data_ref: &'a mut [u32; MAX_BK_COUNT]) -> Self { BackgroundDatastore { buffer_data: buffer_data_ref, instance_data: instance_data_ref } } pub fn
(&mut self, update_args: &mut GameUpdateArgs, appear: bool) { let mut require_appear = appear; let mut left_range = rand::distributions::Range::new(-14.0f32, 14.0f32); let mut count_range = rand::distributions::Range::new(2, 10); let mut scale_range = rand::distributions::Range::new(1.0f32, 3.0f32); for (i, m) in self.instance_data.iter_mut().enumerate() { if *m == 0 { // instantiate randomly if require_appear { let scale = scale_range.sample(&mut update_args.randomizer); *m = 1; self.buffer_data[i].offset = [left_range.sample(&mut update_args.randomizer), -20.0f32, -20.0f32, count_range.sample(&mut update_args.randomizer) as f32]; self.buffer_data[i].scale = [scale, scale, 1.0f32, 1.0f32]; require_appear = false; } } else { self.buffer_data[i].offset[1] += update_args.delta_time * 22.0f32; *m = if self.buffer_data[i].offset[1] >= 20.0f32 { 0 } else { 1 }; } } } }
update
identifier_name
background_datastore.rs
use rand; use rand::distributions::*; use structures; use constants::*; use GameUpdateArgs; pub struct BackgroundDatastore<'a> { buffer_data: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT], instance_data: &'a mut [u32; MAX_BK_COUNT] } impl <'a> BackgroundDatastore<'a> { pub fn new(buffer_data_ref: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT], instance_data_ref: &'a mut [u32; MAX_BK_COUNT]) -> Self { BackgroundDatastore { buffer_data: buffer_data_ref, instance_data: instance_data_ref } } pub fn update(&mut self, update_args: &mut GameUpdateArgs, appear: bool) { let mut require_appear = appear; let mut left_range = rand::distributions::Range::new(-14.0f32, 14.0f32); let mut count_range = rand::distributions::Range::new(2, 10); let mut scale_range = rand::distributions::Range::new(1.0f32, 3.0f32); for (i, m) in self.instance_data.iter_mut().enumerate() { if *m == 0
else { self.buffer_data[i].offset[1] += update_args.delta_time * 22.0f32; *m = if self.buffer_data[i].offset[1] >= 20.0f32 { 0 } else { 1 }; } } } }
{ // instantiate randomly if require_appear { let scale = scale_range.sample(&mut update_args.randomizer); *m = 1; self.buffer_data[i].offset = [left_range.sample(&mut update_args.randomizer), -20.0f32, -20.0f32, count_range.sample(&mut update_args.randomizer) as f32]; self.buffer_data[i].scale = [scale, scale, 1.0f32, 1.0f32]; require_appear = false; } }
conditional_block
boxed.rs
rust1", since = "1.0.0")] use core::any::Any; use core::borrow; use core::cmp::Ordering; use core::convert::From; use core::fmt; use core::future::Future; use core::hash::{Hash, Hasher}; use core::iter::{Iterator, FromIterator, FusedIterator}; use core::marker::{Unpin, Unsize}; use core::mem; use core::pin::Pin; use core::ops::{CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Generator, GeneratorState}; use core::ptr::{self, NonNull, Unique}; use core::task::{LocalWaker, Poll}; use vec::Vec; use raw_vec::RawVec; use str::from_boxed_utf8_unchecked; /// A pointer type for heap allocation. /// /// See the [module-level documentation](../../std/boxed/index.html) for more. #[lang = "owned_box"] #[fundamental] #[stable(feature = "rust1", since = "1.0.0")] pub struct Box<T:?Sized>(Unique<T>); impl<T> Box<T> { /// Allocates memory on the heap and then places `x` into it. /// /// This doesn't actually allocate if `T` is zero-sized. /// /// # Examples /// /// ``` /// let five = Box::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline(always)] pub fn new(x: T) -> Box<T> { box x } #[unstable(feature = "pin", issue = "49150")] #[inline(always)] pub fn pinned(x: T) -> Pin<Box<T>> { (box x).into() } } impl<T:?Sized> Box<T> { /// Constructs a box from a raw pointer. /// /// After calling this function, the raw pointer is owned by the /// resulting `Box`. Specifically, the `Box` destructor will call /// the destructor of `T` and free the allocated memory. Since the /// way `Box` allocates and releases memory is unspecified, the /// only valid pointer to pass to this function is the one taken /// from another `Box` via the [`Box::into_raw`] function. /// /// This function is unsafe because improper use may lead to /// memory problems. For example, a double-free may occur if the /// function is called twice on the same raw pointer. /// /// [`Box::into_raw`]: struct.Box.html#method.into_raw /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let ptr = Box::into_raw(x); /// let x = unsafe { Box::from_raw(ptr) }; /// ``` #[stable(feature = "box_raw", since = "1.4.0")] #[inline] pub unsafe fn from_raw(raw: *mut T) -> Self { Box(Unique::new_unchecked(raw)) } /// Consumes the `Box`, returning a wrapped raw pointer. /// /// The pointer will be properly aligned and non-null. /// /// After calling this function, the caller is responsible for the /// memory previously managed by the `Box`. In particular, the /// caller should properly destroy `T` and release the memory. The /// proper way to do so is to convert the raw pointer back into a /// `Box` with the [`Box::from_raw`] function. /// /// Note: this is an associated function, which means that you have /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This /// is so that there is no conflict with a method on the inner type. /// /// [`Box::from_raw`]: struct.Box.html#method.from_raw /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let ptr = Box::into_raw(x); /// ``` #[stable(feature = "box_raw", since = "1.4.0")] #[inline] pub fn into_raw(b: Box<T>) -> *mut T { Box::into_raw_non_null(b).as_ptr() } /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`. /// /// After calling this function, the caller is responsible for the /// memory previously managed by the `Box`. In particular, the /// caller should properly destroy `T` and release the memory. The /// proper way to do so is to convert the `NonNull<T>` pointer /// into a raw pointer and back into a `Box` with the [`Box::from_raw`] /// function. /// /// Note: this is an associated function, which means that you have /// to call it as `Box::into_raw_non_null(b)` /// instead of `b.into_raw_non_null()`. This /// is so that there is no conflict with a method on the inner type. /// /// [`Box::from_raw`]: struct.Box.html#method.from_raw /// /// # Examples /// /// ``` /// #![feature(box_into_raw_non_null)] /// /// fn main() { /// let x = Box::new(5); /// let ptr = Box::into_raw_non_null(x); /// } /// ``` #[unstable(feature = "box_into_raw_non_null", issue = "47336")] #[inline] pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> { Box::into_unique(b).into() } #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")] #[inline] #[doc(hidden)] pub fn into_unique(b: Box<T>) -> Unique<T> { let unique = b.0; mem::forget(b); unique } /// Consumes and leaks the `Box`, returning a mutable reference, /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime /// `'a`. If the type has only static references, or none at all, then this /// may be chosen to be `'static`. /// /// This function is mainly useful for data that lives for the remainder of /// the program's life. Dropping the returned reference will cause a memory /// leak. If this is not acceptable, the reference should first be wrapped /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can /// then be dropped which will properly destroy `T` and release the /// allocated memory. /// /// Note: this is an associated function, which means that you have /// to call it as `Box::leak(b)` instead of `b.leak()`. This /// is so that there is no conflict with a method on the inner type. /// /// [`Box::from_raw`]: struct.Box.html#method.from_raw /// /// # Examples /// /// Simple usage: /// /// ``` /// fn main() { /// let x = Box::new(41); /// let static_ref: &'static mut usize = Box::leak(x); /// *static_ref += 1; /// assert_eq!(*static_ref, 42); /// } /// ``` /// /// Unsized data: /// /// ``` /// fn main() { /// let x = vec![1, 2, 3].into_boxed_slice(); /// let static_ref = Box::leak(x); /// static_ref[0] = 4; /// assert_eq!(*static_ref, [4, 2, 3]); /// } /// ``` #[stable(feature = "box_leak", since = "1.26.0")] #[inline] pub fn leak<'a>(b: Box<T>) -> &'a mut T where T: 'a // Technically not needed, but kept to be explicit. { unsafe { &mut *Box::into_raw(b) } } } #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<#[may_dangle] T:?Sized> Drop for Box<T> { fn drop(&mut self) { // FIXME: Do nothing, drop is currently performed by compiler. } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: Default> Default for Box<T> { /// Creates a `Box<T>`, with the `Default` value for T. fn default() -> Box<T> { box Default::default() } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> Default for Box<[T]> { fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) } } #[stable(feature = "default_box_extra", since = "1.17.0")] impl Default for Box<str> { fn default() -> Box<str> { unsafe { from_boxed_utf8_unchecked(Default::default()) } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: Clone> Clone for Box<T> { /// Returns a new box with a `clone()` of this box's contents. /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let y = x.clone(); /// ``` #[rustfmt_skip] #[inline] fn clone(&self) -> Box<T> { box { (**self).clone() } } /// Copies `source`'s contents into `self` without creating a new allocation. /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let mut y = Box::new(10); /// /// y.clone_from(&x); /// /// assert_eq!(*y, 5); /// ``` #[inline] fn clone_from(&mut self, source: &Box<T>) { (**self).clone_from(&(**source)); } } #[stable(feature = "box_slice_clone", since = "1.3.0")] impl Clone for Box<str> { fn clone(&self) -> Self { let len = self.len(); let buf = RawVec::with_capacity(len); unsafe { ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len); from_boxed_utf8_unchecked(buf.into_box()) } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + PartialEq> PartialEq for Box<T> { #[inline] fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + PartialOrd> PartialOrd for Box<T> { #[inline] fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> { PartialOrd::partial_cmp(&**self, &**other) } #[inline] fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) } #[inline] fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) } #[inline] fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) } #[inline] fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + Ord> Ord for Box<T> { #[inline] fn cmp(&self, other: &Box<T>) -> Ordering { Ord::cmp(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + Eq> Eq for Box<T> {} #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + Hash> Hash for Box<T> { fn hash<H: Hasher>(&self, state: &mut H) { (**self).hash(state); } } #[stable(feature = "indirect_hasher_impl", since = "1.22.0")] impl<T:?Sized + Hasher> Hasher for Box<T> { fn finish(&self) -> u64 { (**self).finish() } fn write(&mut self, bytes: &[u8]) { (**self).write(bytes) } fn write_u8(&mut self, i: u8) { (**self).write_u8(i) } fn write_u16(&mut self, i: u16) { (**self).write_u16(i) } fn write_u32(&mut self, i: u32) { (**self).write_u32(i) } fn write_u64(&mut self, i: u64) { (**self).write_u64(i) } fn write_u128(&mut self, i: u128) { (**self).write_u128(i) } fn write_usize(&mut self, i: usize)
fn write_i8(&mut self, i: i8) { (**self).write_i8(i) } fn write_i16(&mut self, i: i16) { (**self).write_i16(i) } fn write_i32(&mut self, i: i32) { (**self).write_i32(i) } fn write_i64(&mut self, i: i64) { (**self).write_i64(i) } fn write_i128(&mut self, i: i128) { (**self).write_i128(i) } fn write_isize(&mut self, i: isize) { (**self).write_isize(i) } } #[stable(feature = "from_for_ptrs", since = "1.6.0")] impl<T> From<T> for Box<T> { fn from(t: T) -> Self { Box::new(t) } } #[unstable(feature = "pin", issue = "49150")] impl<T> From<Box<T>> for Pin<Box<T>> { fn from(boxed: Box<T>) -> Self { // It's not possible to move or replace the insides of a `Pin<Box<T>>` // when `T:!Unpin`, so it's safe to pin it directly without any // additional requirements. unsafe { Pin::new_unchecked(boxed) } } } #[stable(feature = "box_from_slice", since = "1.17.0")] impl<'a, T: Copy> From<&'a [T]> for Box<[T]> { fn from(slice: &'a [T]) -> Box<[T]> { let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() }; boxed.copy_from_slice(slice); boxed } } #[stable(feature = "box_from_slice", since = "1.17.0")] impl<'a> From<&'a str> for Box<str> { #[inline] fn from(s: &'a str) -> Box<str> { unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) } } } #[stable(feature = "boxed_str_conv", since = "1.19.0")] impl From<Box<str>> for Box<[u8]> { #[inline] fn from(s: Box<str>) -> Self { unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) } } } impl Box<dyn Any> { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type. /// /// # Examples /// /// ``` /// use std::any::Any; /// /// fn print_if_string(value: Box<dyn Any>) { /// if let Ok(string) = value.downcast::<String>() { /// println!("String ({}): {}", string.len(), string); /// } /// } /// /// fn main() { /// let my_string = "Hello World".to_string(); /// print_if_string(Box::new(my_string)); /// print_if_string(Box::new(0i8)); /// } /// ``` pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> { if self.is::<T>() { unsafe { let raw: *mut dyn Any = Box::into_raw(self); Ok(Box::from_raw(raw as *mut T)) } } else { Err(self) } } } impl Box<dyn Any + Send> { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type. /// /// # Examples /// /// ``` /// use std::any::Any; /// /// fn print_if_string(value: Box<dyn Any + Send>) { /// if let Ok(string) = value.downcast::<String>() { /// println!("String ({}): {}", string.len(), string); /// } /// } /// /// fn main() { /// let my_string = "Hello World".to_string(); /// print_if_string(Box::new(my_string)); /// print_if_string(Box::new(0i8)); /// } /// ``` pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> { <Box<dyn Any>>::downcast(self).map_err(|s| unsafe { // reapply the Send marker Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send)) }) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: fmt::Display +?Sized> fmt::Display for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: fmt::Debug +?Sized> fmt::Debug for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized> fmt::Pointer for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // It's not possible to extract the inner Uniq directly from the Box, // instead we cast it to a *const which aliases the Unique let ptr: *const T = &**self; fmt::Pointer::fmt(&ptr, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized> Deref for Box<T> { type Target = T; fn deref(&self) -> &T { &**self } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized> DerefMut for Box<T> { fn deref_mut(&mut self) -> &mut T { &mut **self } } #[stable(feature = "rust1", since = "1.0.0")] impl<I: Iterator +?Sized> Iterator for Box<I> { type Item = I::Item; fn next(&mut self) -> Option<I::Item> { (**self).next() } fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() } fn nth(&mut self, n: usize) -> Option<I::Item> { (**self).nth(n) } } #[stable(feature = "rust1", since = "1.0.0")] impl<I: DoubleEndedIterator +?Sized> DoubleEndedIterator for Box<I> { fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() } } #[stable(feature = "rust1", since = "1.0.0")] impl<I: ExactSizeIterator +?Sized> ExactSizeIterator for Box<I> { fn len(&self) -> usize { (**self).len() } fn is_empty(&self) -> bool { (**self).is_empty() } } #[stable(feature = "fused", since = "1.26.0")] impl<I: FusedIterator +?Sized> FusedIterator for Box<I> {} /// `FnBox` is a version of the `FnOnce` intended for use with boxed /// closure objects. The idea is that where one would normally store a /// `Box<dyn FnOnce()>` in a data structure, you should use /// `Box<dyn FnBox()>`. The two traits behave essentially the same, except /// that a `FnBox` closure can only be called if it is boxed. (Note /// that `FnBox` may be deprecated in the future if `Box<dyn FnOnce()>` /// closures become directly usable.) /// /// # Examples /// /// Here is a snippet of code which creates a hashmap full of boxed /// once closures and then removes them one by one, calling each /// closure as it is removed. Note that the type of the closures /// stored in the map is `Box<dyn FnBox() -> i32>` and not `Box<dyn FnOnce() /// -> i32>`. /// /// ``` /// #![feature(fnbox)] /// /// use std::boxed::FnBox; /// use std::collections::HashMap; /// /// fn make_map() -> HashMap<i32, Box<dyn FnBox() -> i32>> { /// let mut map: HashMap<i32, Box<dyn FnBox() -> i32>> = HashMap::new(); /// map.insert(1, Box::new(|| 22)); /// map.insert(2, Box::new(|| 44)); /// map /// } /// /// fn main() { /// let mut map = make_map(); /// for i in &[1, 2] { /// let f = map.remove(&i).unwrap(); /// assert_eq!(f(), i * 22); /// } /// } /// ``` #[rustc_paren_sugar] #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] pub trait FnBox<A> { type Output; fn call_box(self: Box<Self>, args: A) -> Self::Output; } #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] impl<A, F> FnBox<A> for F where F: FnOnce<A> { type Output = F::Output; fn call_box(self: Box<F>, args: A) -> F::Output { self.call_once(args) } } #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + 'a> { type Output = R; extern "rust-call" fn call_once(self, args: A) -> R { self.call_box(args) } } #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + Send + 'a> { type Output = R; extern "rust-call" fn call_once(self, args: A) -> R { self.call_box(args) } } #[unstable(feature = "coerce_unsized", issue = "27732")] impl<T:?Sized + Unsize<U>, U:?Sized> CoerceUnsized<Box<U>> for Box<T> {} #[unstable(feature = "dispatch_from_dyn", issue = "0")] impl<T:?Sized + Unsize<U>, U:?Sized> DispatchFromDyn<Box<U>> for Box<T> {} #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")] impl<A> FromIterator<A> for Box<[A]> { fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self { iter.into_iter().collect::<Vec<_>>().into_boxed_slice() } } #[stable(feature = "box_slice_clone", since = "1.3.0")] impl<T: Clone> Clone for Box<[T]> { fn clone(&self) -> Self { let mut new = BoxBuilder { data: RawVec::with_capacity(self.len()), len: 0, }; let mut target = new.data.ptr(); for item in self.iter() { unsafe { ptr::write(target, item.clone()); target = target.offset(1);
{ (**self).write_usize(i) }
identifier_body
boxed.rs
rust1", since = "1.0.0")] use core::any::Any; use core::borrow; use core::cmp::Ordering; use core::convert::From; use core::fmt; use core::future::Future; use core::hash::{Hash, Hasher}; use core::iter::{Iterator, FromIterator, FusedIterator}; use core::marker::{Unpin, Unsize}; use core::mem; use core::pin::Pin; use core::ops::{CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Generator, GeneratorState}; use core::ptr::{self, NonNull, Unique}; use core::task::{LocalWaker, Poll}; use vec::Vec; use raw_vec::RawVec; use str::from_boxed_utf8_unchecked; /// A pointer type for heap allocation. /// /// See the [module-level documentation](../../std/boxed/index.html) for more. #[lang = "owned_box"] #[fundamental] #[stable(feature = "rust1", since = "1.0.0")] pub struct Box<T:?Sized>(Unique<T>); impl<T> Box<T> { /// Allocates memory on the heap and then places `x` into it. /// /// This doesn't actually allocate if `T` is zero-sized. /// /// # Examples /// /// ``` /// let five = Box::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline(always)] pub fn new(x: T) -> Box<T> { box x } #[unstable(feature = "pin", issue = "49150")] #[inline(always)] pub fn pinned(x: T) -> Pin<Box<T>> { (box x).into() } } impl<T:?Sized> Box<T> { /// Constructs a box from a raw pointer. /// /// After calling this function, the raw pointer is owned by the /// resulting `Box`. Specifically, the `Box` destructor will call /// the destructor of `T` and free the allocated memory. Since the /// way `Box` allocates and releases memory is unspecified, the /// only valid pointer to pass to this function is the one taken /// from another `Box` via the [`Box::into_raw`] function. /// /// This function is unsafe because improper use may lead to /// memory problems. For example, a double-free may occur if the /// function is called twice on the same raw pointer. /// /// [`Box::into_raw`]: struct.Box.html#method.into_raw /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let ptr = Box::into_raw(x); /// let x = unsafe { Box::from_raw(ptr) }; /// ``` #[stable(feature = "box_raw", since = "1.4.0")] #[inline] pub unsafe fn from_raw(raw: *mut T) -> Self { Box(Unique::new_unchecked(raw)) } /// Consumes the `Box`, returning a wrapped raw pointer. /// /// The pointer will be properly aligned and non-null. /// /// After calling this function, the caller is responsible for the /// memory previously managed by the `Box`. In particular, the /// caller should properly destroy `T` and release the memory. The /// proper way to do so is to convert the raw pointer back into a /// `Box` with the [`Box::from_raw`] function. /// /// Note: this is an associated function, which means that you have /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This /// is so that there is no conflict with a method on the inner type. /// /// [`Box::from_raw`]: struct.Box.html#method.from_raw /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let ptr = Box::into_raw(x); /// ``` #[stable(feature = "box_raw", since = "1.4.0")] #[inline] pub fn into_raw(b: Box<T>) -> *mut T { Box::into_raw_non_null(b).as_ptr() } /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`. /// /// After calling this function, the caller is responsible for the /// memory previously managed by the `Box`. In particular, the /// caller should properly destroy `T` and release the memory. The /// proper way to do so is to convert the `NonNull<T>` pointer /// into a raw pointer and back into a `Box` with the [`Box::from_raw`] /// function. /// /// Note: this is an associated function, which means that you have /// to call it as `Box::into_raw_non_null(b)` /// instead of `b.into_raw_non_null()`. This /// is so that there is no conflict with a method on the inner type. /// /// [`Box::from_raw`]: struct.Box.html#method.from_raw /// /// # Examples /// /// ``` /// #![feature(box_into_raw_non_null)] /// /// fn main() { /// let x = Box::new(5); /// let ptr = Box::into_raw_non_null(x); /// } /// ``` #[unstable(feature = "box_into_raw_non_null", issue = "47336")] #[inline] pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> { Box::into_unique(b).into() } #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")] #[inline] #[doc(hidden)] pub fn into_unique(b: Box<T>) -> Unique<T> { let unique = b.0; mem::forget(b); unique } /// Consumes and leaks the `Box`, returning a mutable reference, /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime /// `'a`. If the type has only static references, or none at all, then this /// may be chosen to be `'static`. /// /// This function is mainly useful for data that lives for the remainder of /// the program's life. Dropping the returned reference will cause a memory /// leak. If this is not acceptable, the reference should first be wrapped /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can /// then be dropped which will properly destroy `T` and release the /// allocated memory. /// /// Note: this is an associated function, which means that you have /// to call it as `Box::leak(b)` instead of `b.leak()`. This /// is so that there is no conflict with a method on the inner type. /// /// [`Box::from_raw`]: struct.Box.html#method.from_raw /// /// # Examples /// /// Simple usage: /// /// ``` /// fn main() { /// let x = Box::new(41); /// let static_ref: &'static mut usize = Box::leak(x); /// *static_ref += 1; /// assert_eq!(*static_ref, 42); /// } /// ``` /// /// Unsized data: /// /// ``` /// fn main() { /// let x = vec![1, 2, 3].into_boxed_slice(); /// let static_ref = Box::leak(x); /// static_ref[0] = 4; /// assert_eq!(*static_ref, [4, 2, 3]); /// } /// ``` #[stable(feature = "box_leak", since = "1.26.0")] #[inline] pub fn leak<'a>(b: Box<T>) -> &'a mut T where T: 'a // Technically not needed, but kept to be explicit. { unsafe { &mut *Box::into_raw(b) } } } #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<#[may_dangle] T:?Sized> Drop for Box<T> { fn drop(&mut self) { // FIXME: Do nothing, drop is currently performed by compiler. } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: Default> Default for Box<T> { /// Creates a `Box<T>`, with the `Default` value for T. fn default() -> Box<T> { box Default::default() } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> Default for Box<[T]> { fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) } } #[stable(feature = "default_box_extra", since = "1.17.0")] impl Default for Box<str> { fn default() -> Box<str> { unsafe { from_boxed_utf8_unchecked(Default::default()) } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: Clone> Clone for Box<T> { /// Returns a new box with a `clone()` of this box's contents. /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let y = x.clone(); /// ``` #[rustfmt_skip] #[inline] fn clone(&self) -> Box<T> { box { (**self).clone() } } /// Copies `source`'s contents into `self` without creating a new allocation. /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let mut y = Box::new(10); /// /// y.clone_from(&x); /// /// assert_eq!(*y, 5); /// ``` #[inline] fn clone_from(&mut self, source: &Box<T>) { (**self).clone_from(&(**source)); } } #[stable(feature = "box_slice_clone", since = "1.3.0")] impl Clone for Box<str> { fn clone(&self) -> Self { let len = self.len(); let buf = RawVec::with_capacity(len); unsafe { ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len); from_boxed_utf8_unchecked(buf.into_box()) } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + PartialEq> PartialEq for Box<T> { #[inline] fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + PartialOrd> PartialOrd for Box<T> { #[inline] fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> { PartialOrd::partial_cmp(&**self, &**other) } #[inline] fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) } #[inline] fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) } #[inline] fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) } #[inline] fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + Ord> Ord for Box<T> { #[inline] fn cmp(&self, other: &Box<T>) -> Ordering { Ord::cmp(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + Eq> Eq for Box<T> {} #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + Hash> Hash for Box<T> { fn hash<H: Hasher>(&self, state: &mut H) { (**self).hash(state); } } #[stable(feature = "indirect_hasher_impl", since = "1.22.0")] impl<T:?Sized + Hasher> Hasher for Box<T> { fn finish(&self) -> u64 { (**self).finish() } fn write(&mut self, bytes: &[u8]) { (**self).write(bytes) } fn write_u8(&mut self, i: u8) { (**self).write_u8(i) } fn write_u16(&mut self, i: u16) { (**self).write_u16(i) } fn write_u32(&mut self, i: u32) { (**self).write_u32(i) } fn write_u64(&mut self, i: u64) { (**self).write_u64(i) } fn write_u128(&mut self, i: u128) { (**self).write_u128(i) } fn write_usize(&mut self, i: usize) { (**self).write_usize(i) } fn write_i8(&mut self, i: i8) { (**self).write_i8(i) } fn write_i16(&mut self, i: i16) { (**self).write_i16(i) } fn write_i32(&mut self, i: i32) { (**self).write_i32(i) } fn write_i64(&mut self, i: i64) { (**self).write_i64(i) } fn write_i128(&mut self, i: i128) { (**self).write_i128(i) } fn write_isize(&mut self, i: isize) { (**self).write_isize(i) } } #[stable(feature = "from_for_ptrs", since = "1.6.0")] impl<T> From<T> for Box<T> { fn from(t: T) -> Self { Box::new(t) } } #[unstable(feature = "pin", issue = "49150")] impl<T> From<Box<T>> for Pin<Box<T>> { fn from(boxed: Box<T>) -> Self { // It's not possible to move or replace the insides of a `Pin<Box<T>>` // when `T:!Unpin`, so it's safe to pin it directly without any // additional requirements. unsafe { Pin::new_unchecked(boxed) } } } #[stable(feature = "box_from_slice", since = "1.17.0")] impl<'a, T: Copy> From<&'a [T]> for Box<[T]> { fn from(slice: &'a [T]) -> Box<[T]> { let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() }; boxed.copy_from_slice(slice); boxed } } #[stable(feature = "box_from_slice", since = "1.17.0")] impl<'a> From<&'a str> for Box<str> { #[inline] fn from(s: &'a str) -> Box<str> { unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) } } } #[stable(feature = "boxed_str_conv", since = "1.19.0")] impl From<Box<str>> for Box<[u8]> { #[inline] fn from(s: Box<str>) -> Self { unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) } } } impl Box<dyn Any> { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type. /// /// # Examples /// /// ``` /// use std::any::Any; /// /// fn print_if_string(value: Box<dyn Any>) { /// if let Ok(string) = value.downcast::<String>() { /// println!("String ({}): {}", string.len(), string); /// } /// } /// /// fn main() { /// let my_string = "Hello World".to_string(); /// print_if_string(Box::new(my_string)); /// print_if_string(Box::new(0i8)); /// } /// ``` pub fn
<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> { if self.is::<T>() { unsafe { let raw: *mut dyn Any = Box::into_raw(self); Ok(Box::from_raw(raw as *mut T)) } } else { Err(self) } } } impl Box<dyn Any + Send> { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type. /// /// # Examples /// /// ``` /// use std::any::Any; /// /// fn print_if_string(value: Box<dyn Any + Send>) { /// if let Ok(string) = value.downcast::<String>() { /// println!("String ({}): {}", string.len(), string); /// } /// } /// /// fn main() { /// let my_string = "Hello World".to_string(); /// print_if_string(Box::new(my_string)); /// print_if_string(Box::new(0i8)); /// } /// ``` pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> { <Box<dyn Any>>::downcast(self).map_err(|s| unsafe { // reapply the Send marker Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send)) }) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: fmt::Display +?Sized> fmt::Display for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: fmt::Debug +?Sized> fmt::Debug for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized> fmt::Pointer for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // It's not possible to extract the inner Uniq directly from the Box, // instead we cast it to a *const which aliases the Unique let ptr: *const T = &**self; fmt::Pointer::fmt(&ptr, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized> Deref for Box<T> { type Target = T; fn deref(&self) -> &T { &**self } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized> DerefMut for Box<T> { fn deref_mut(&mut self) -> &mut T { &mut **self } } #[stable(feature = "rust1", since = "1.0.0")] impl<I: Iterator +?Sized> Iterator for Box<I> { type Item = I::Item; fn next(&mut self) -> Option<I::Item> { (**self).next() } fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() } fn nth(&mut self, n: usize) -> Option<I::Item> { (**self).nth(n) } } #[stable(feature = "rust1", since = "1.0.0")] impl<I: DoubleEndedIterator +?Sized> DoubleEndedIterator for Box<I> { fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() } } #[stable(feature = "rust1", since = "1.0.0")] impl<I: ExactSizeIterator +?Sized> ExactSizeIterator for Box<I> { fn len(&self) -> usize { (**self).len() } fn is_empty(&self) -> bool { (**self).is_empty() } } #[stable(feature = "fused", since = "1.26.0")] impl<I: FusedIterator +?Sized> FusedIterator for Box<I> {} /// `FnBox` is a version of the `FnOnce` intended for use with boxed /// closure objects. The idea is that where one would normally store a /// `Box<dyn FnOnce()>` in a data structure, you should use /// `Box<dyn FnBox()>`. The two traits behave essentially the same, except /// that a `FnBox` closure can only be called if it is boxed. (Note /// that `FnBox` may be deprecated in the future if `Box<dyn FnOnce()>` /// closures become directly usable.) /// /// # Examples /// /// Here is a snippet of code which creates a hashmap full of boxed /// once closures and then removes them one by one, calling each /// closure as it is removed. Note that the type of the closures /// stored in the map is `Box<dyn FnBox() -> i32>` and not `Box<dyn FnOnce() /// -> i32>`. /// /// ``` /// #![feature(fnbox)] /// /// use std::boxed::FnBox; /// use std::collections::HashMap; /// /// fn make_map() -> HashMap<i32, Box<dyn FnBox() -> i32>> { /// let mut map: HashMap<i32, Box<dyn FnBox() -> i32>> = HashMap::new(); /// map.insert(1, Box::new(|| 22)); /// map.insert(2, Box::new(|| 44)); /// map /// } /// /// fn main() { /// let mut map = make_map(); /// for i in &[1, 2] { /// let f = map.remove(&i).unwrap(); /// assert_eq!(f(), i * 22); /// } /// } /// ``` #[rustc_paren_sugar] #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] pub trait FnBox<A> { type Output; fn call_box(self: Box<Self>, args: A) -> Self::Output; } #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] impl<A, F> FnBox<A> for F where F: FnOnce<A> { type Output = F::Output; fn call_box(self: Box<F>, args: A) -> F::Output { self.call_once(args) } } #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + 'a> { type Output = R; extern "rust-call" fn call_once(self, args: A) -> R { self.call_box(args) } } #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + Send + 'a> { type Output = R; extern "rust-call" fn call_once(self, args: A) -> R { self.call_box(args) } } #[unstable(feature = "coerce_unsized", issue = "27732")] impl<T:?Sized + Unsize<U>, U:?Sized> CoerceUnsized<Box<U>> for Box<T> {} #[unstable(feature = "dispatch_from_dyn", issue = "0")] impl<T:?Sized + Unsize<U>, U:?Sized> DispatchFromDyn<Box<U>> for Box<T> {} #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")] impl<A> FromIterator<A> for Box<[A]> { fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self { iter.into_iter().collect::<Vec<_>>().into_boxed_slice() } } #[stable(feature = "box_slice_clone", since = "1.3.0")] impl<T: Clone> Clone for Box<[T]> { fn clone(&self) -> Self { let mut new = BoxBuilder { data: RawVec::with_capacity(self.len()), len: 0, }; let mut target = new.data.ptr(); for item in self.iter() { unsafe { ptr::write(target, item.clone()); target = target.offset(1);
downcast
identifier_name
boxed.rs
"rust1", since = "1.0.0")] use core::any::Any; use core::borrow; use core::cmp::Ordering; use core::convert::From; use core::fmt; use core::future::Future; use core::hash::{Hash, Hasher}; use core::iter::{Iterator, FromIterator, FusedIterator}; use core::marker::{Unpin, Unsize}; use core::mem; use core::pin::Pin; use core::ops::{CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Generator, GeneratorState}; use core::ptr::{self, NonNull, Unique}; use core::task::{LocalWaker, Poll}; use vec::Vec; use raw_vec::RawVec; use str::from_boxed_utf8_unchecked; /// A pointer type for heap allocation. /// /// See the [module-level documentation](../../std/boxed/index.html) for more. #[lang = "owned_box"] #[fundamental] #[stable(feature = "rust1", since = "1.0.0")] pub struct Box<T:?Sized>(Unique<T>); impl<T> Box<T> { /// Allocates memory on the heap and then places `x` into it. /// /// This doesn't actually allocate if `T` is zero-sized. /// /// # Examples /// /// ``` /// let five = Box::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline(always)] pub fn new(x: T) -> Box<T> { box x } #[unstable(feature = "pin", issue = "49150")] #[inline(always)] pub fn pinned(x: T) -> Pin<Box<T>> { (box x).into() } } impl<T:?Sized> Box<T> { /// Constructs a box from a raw pointer. /// /// After calling this function, the raw pointer is owned by the /// resulting `Box`. Specifically, the `Box` destructor will call /// the destructor of `T` and free the allocated memory. Since the /// way `Box` allocates and releases memory is unspecified, the /// only valid pointer to pass to this function is the one taken /// from another `Box` via the [`Box::into_raw`] function. /// /// This function is unsafe because improper use may lead to /// memory problems. For example, a double-free may occur if the /// function is called twice on the same raw pointer. /// /// [`Box::into_raw`]: struct.Box.html#method.into_raw /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let ptr = Box::into_raw(x); /// let x = unsafe { Box::from_raw(ptr) }; /// ``` #[stable(feature = "box_raw", since = "1.4.0")] #[inline] pub unsafe fn from_raw(raw: *mut T) -> Self { Box(Unique::new_unchecked(raw)) } /// Consumes the `Box`, returning a wrapped raw pointer. /// /// The pointer will be properly aligned and non-null. /// /// After calling this function, the caller is responsible for the /// memory previously managed by the `Box`. In particular, the /// caller should properly destroy `T` and release the memory. The /// proper way to do so is to convert the raw pointer back into a /// `Box` with the [`Box::from_raw`] function. /// /// Note: this is an associated function, which means that you have /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This /// is so that there is no conflict with a method on the inner type. /// /// [`Box::from_raw`]: struct.Box.html#method.from_raw /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let ptr = Box::into_raw(x); /// ``` #[stable(feature = "box_raw", since = "1.4.0")] #[inline] pub fn into_raw(b: Box<T>) -> *mut T { Box::into_raw_non_null(b).as_ptr() } /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`. /// /// After calling this function, the caller is responsible for the /// memory previously managed by the `Box`. In particular, the /// caller should properly destroy `T` and release the memory. The /// proper way to do so is to convert the `NonNull<T>` pointer /// into a raw pointer and back into a `Box` with the [`Box::from_raw`] /// function. /// /// Note: this is an associated function, which means that you have /// to call it as `Box::into_raw_non_null(b)` /// instead of `b.into_raw_non_null()`. This /// is so that there is no conflict with a method on the inner type. /// /// [`Box::from_raw`]: struct.Box.html#method.from_raw /// /// # Examples /// /// ``` /// #![feature(box_into_raw_non_null)] /// /// fn main() { /// let x = Box::new(5); /// let ptr = Box::into_raw_non_null(x); /// } /// ``` #[unstable(feature = "box_into_raw_non_null", issue = "47336")] #[inline] pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> { Box::into_unique(b).into() } #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")] #[inline] #[doc(hidden)] pub fn into_unique(b: Box<T>) -> Unique<T> { let unique = b.0; mem::forget(b); unique } /// Consumes and leaks the `Box`, returning a mutable reference, /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime /// `'a`. If the type has only static references, or none at all, then this /// may be chosen to be `'static`. /// /// This function is mainly useful for data that lives for the remainder of /// the program's life. Dropping the returned reference will cause a memory /// leak. If this is not acceptable, the reference should first be wrapped /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can /// then be dropped which will properly destroy `T` and release the /// allocated memory. /// /// Note: this is an associated function, which means that you have /// to call it as `Box::leak(b)` instead of `b.leak()`. This /// is so that there is no conflict with a method on the inner type. /// /// [`Box::from_raw`]: struct.Box.html#method.from_raw /// /// # Examples /// /// Simple usage: /// /// ``` /// fn main() { /// let x = Box::new(41); /// let static_ref: &'static mut usize = Box::leak(x); /// *static_ref += 1; /// assert_eq!(*static_ref, 42); /// } /// ``` /// /// Unsized data: /// /// ``` /// fn main() { /// let x = vec![1, 2, 3].into_boxed_slice(); /// let static_ref = Box::leak(x); /// static_ref[0] = 4; /// assert_eq!(*static_ref, [4, 2, 3]); /// } /// ``` #[stable(feature = "box_leak", since = "1.26.0")] #[inline] pub fn leak<'a>(b: Box<T>) -> &'a mut T where T: 'a // Technically not needed, but kept to be explicit. { unsafe { &mut *Box::into_raw(b) } } } #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<#[may_dangle] T:?Sized> Drop for Box<T> { fn drop(&mut self) { // FIXME: Do nothing, drop is currently performed by compiler. } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: Default> Default for Box<T> { /// Creates a `Box<T>`, with the `Default` value for T. fn default() -> Box<T> { box Default::default() } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> Default for Box<[T]> { fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) } } #[stable(feature = "default_box_extra", since = "1.17.0")] impl Default for Box<str> { fn default() -> Box<str> { unsafe { from_boxed_utf8_unchecked(Default::default()) } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: Clone> Clone for Box<T> { /// Returns a new box with a `clone()` of this box's contents. /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let y = x.clone(); /// ``` #[rustfmt_skip] #[inline] fn clone(&self) -> Box<T> { box { (**self).clone() } } /// Copies `source`'s contents into `self` without creating a new allocation. /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let mut y = Box::new(10); /// /// y.clone_from(&x); /// /// assert_eq!(*y, 5); /// ``` #[inline] fn clone_from(&mut self, source: &Box<T>) { (**self).clone_from(&(**source)); } } #[stable(feature = "box_slice_clone", since = "1.3.0")] impl Clone for Box<str> { fn clone(&self) -> Self { let len = self.len(); let buf = RawVec::with_capacity(len); unsafe { ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len); from_boxed_utf8_unchecked(buf.into_box()) } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + PartialEq> PartialEq for Box<T> { #[inline] fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other)
} } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + PartialOrd> PartialOrd for Box<T> { #[inline] fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> { PartialOrd::partial_cmp(&**self, &**other) } #[inline] fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) } #[inline] fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) } #[inline] fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) } #[inline] fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + Ord> Ord for Box<T> { #[inline] fn cmp(&self, other: &Box<T>) -> Ordering { Ord::cmp(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + Eq> Eq for Box<T> {} #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + Hash> Hash for Box<T> { fn hash<H: Hasher>(&self, state: &mut H) { (**self).hash(state); } } #[stable(feature = "indirect_hasher_impl", since = "1.22.0")] impl<T:?Sized + Hasher> Hasher for Box<T> { fn finish(&self) -> u64 { (**self).finish() } fn write(&mut self, bytes: &[u8]) { (**self).write(bytes) } fn write_u8(&mut self, i: u8) { (**self).write_u8(i) } fn write_u16(&mut self, i: u16) { (**self).write_u16(i) } fn write_u32(&mut self, i: u32) { (**self).write_u32(i) } fn write_u64(&mut self, i: u64) { (**self).write_u64(i) } fn write_u128(&mut self, i: u128) { (**self).write_u128(i) } fn write_usize(&mut self, i: usize) { (**self).write_usize(i) } fn write_i8(&mut self, i: i8) { (**self).write_i8(i) } fn write_i16(&mut self, i: i16) { (**self).write_i16(i) } fn write_i32(&mut self, i: i32) { (**self).write_i32(i) } fn write_i64(&mut self, i: i64) { (**self).write_i64(i) } fn write_i128(&mut self, i: i128) { (**self).write_i128(i) } fn write_isize(&mut self, i: isize) { (**self).write_isize(i) } } #[stable(feature = "from_for_ptrs", since = "1.6.0")] impl<T> From<T> for Box<T> { fn from(t: T) -> Self { Box::new(t) } } #[unstable(feature = "pin", issue = "49150")] impl<T> From<Box<T>> for Pin<Box<T>> { fn from(boxed: Box<T>) -> Self { // It's not possible to move or replace the insides of a `Pin<Box<T>>` // when `T:!Unpin`, so it's safe to pin it directly without any // additional requirements. unsafe { Pin::new_unchecked(boxed) } } } #[stable(feature = "box_from_slice", since = "1.17.0")] impl<'a, T: Copy> From<&'a [T]> for Box<[T]> { fn from(slice: &'a [T]) -> Box<[T]> { let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() }; boxed.copy_from_slice(slice); boxed } } #[stable(feature = "box_from_slice", since = "1.17.0")] impl<'a> From<&'a str> for Box<str> { #[inline] fn from(s: &'a str) -> Box<str> { unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) } } } #[stable(feature = "boxed_str_conv", since = "1.19.0")] impl From<Box<str>> for Box<[u8]> { #[inline] fn from(s: Box<str>) -> Self { unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) } } } impl Box<dyn Any> { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type. /// /// # Examples /// /// ``` /// use std::any::Any; /// /// fn print_if_string(value: Box<dyn Any>) { /// if let Ok(string) = value.downcast::<String>() { /// println!("String ({}): {}", string.len(), string); /// } /// } /// /// fn main() { /// let my_string = "Hello World".to_string(); /// print_if_string(Box::new(my_string)); /// print_if_string(Box::new(0i8)); /// } /// ``` pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> { if self.is::<T>() { unsafe { let raw: *mut dyn Any = Box::into_raw(self); Ok(Box::from_raw(raw as *mut T)) } } else { Err(self) } } } impl Box<dyn Any + Send> { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type. /// /// # Examples /// /// ``` /// use std::any::Any; /// /// fn print_if_string(value: Box<dyn Any + Send>) { /// if let Ok(string) = value.downcast::<String>() { /// println!("String ({}): {}", string.len(), string); /// } /// } /// /// fn main() { /// let my_string = "Hello World".to_string(); /// print_if_string(Box::new(my_string)); /// print_if_string(Box::new(0i8)); /// } /// ``` pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> { <Box<dyn Any>>::downcast(self).map_err(|s| unsafe { // reapply the Send marker Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send)) }) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: fmt::Display +?Sized> fmt::Display for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: fmt::Debug +?Sized> fmt::Debug for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized> fmt::Pointer for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // It's not possible to extract the inner Uniq directly from the Box, // instead we cast it to a *const which aliases the Unique let ptr: *const T = &**self; fmt::Pointer::fmt(&ptr, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized> Deref for Box<T> { type Target = T; fn deref(&self) -> &T { &**self } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized> DerefMut for Box<T> { fn deref_mut(&mut self) -> &mut T { &mut **self } } #[stable(feature = "rust1", since = "1.0.0")] impl<I: Iterator +?Sized> Iterator for Box<I> { type Item = I::Item; fn next(&mut self) -> Option<I::Item> { (**self).next() } fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() } fn nth(&mut self, n: usize) -> Option<I::Item> { (**self).nth(n) } } #[stable(feature = "rust1", since = "1.0.0")] impl<I: DoubleEndedIterator +?Sized> DoubleEndedIterator for Box<I> { fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() } } #[stable(feature = "rust1", since = "1.0.0")] impl<I: ExactSizeIterator +?Sized> ExactSizeIterator for Box<I> { fn len(&self) -> usize { (**self).len() } fn is_empty(&self) -> bool { (**self).is_empty() } } #[stable(feature = "fused", since = "1.26.0")] impl<I: FusedIterator +?Sized> FusedIterator for Box<I> {} /// `FnBox` is a version of the `FnOnce` intended for use with boxed /// closure objects. The idea is that where one would normally store a /// `Box<dyn FnOnce()>` in a data structure, you should use /// `Box<dyn FnBox()>`. The two traits behave essentially the same, except /// that a `FnBox` closure can only be called if it is boxed. (Note /// that `FnBox` may be deprecated in the future if `Box<dyn FnOnce()>` /// closures become directly usable.) /// /// # Examples /// /// Here is a snippet of code which creates a hashmap full of boxed /// once closures and then removes them one by one, calling each /// closure as it is removed. Note that the type of the closures /// stored in the map is `Box<dyn FnBox() -> i32>` and not `Box<dyn FnOnce() /// -> i32>`. /// /// ``` /// #![feature(fnbox)] /// /// use std::boxed::FnBox; /// use std::collections::HashMap; /// /// fn make_map() -> HashMap<i32, Box<dyn FnBox() -> i32>> { /// let mut map: HashMap<i32, Box<dyn FnBox() -> i32>> = HashMap::new(); /// map.insert(1, Box::new(|| 22)); /// map.insert(2, Box::new(|| 44)); /// map /// } /// /// fn main() { /// let mut map = make_map(); /// for i in &[1, 2] { /// let f = map.remove(&i).unwrap(); /// assert_eq!(f(), i * 22); /// } /// } /// ``` #[rustc_paren_sugar] #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] pub trait FnBox<A> { type Output; fn call_box(self: Box<Self>, args: A) -> Self::Output; } #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] impl<A, F> FnBox<A> for F where F: FnOnce<A> { type Output = F::Output; fn call_box(self: Box<F>, args: A) -> F::Output { self.call_once(args) } } #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + 'a> { type Output = R; extern "rust-call" fn call_once(self, args: A) -> R { self.call_box(args) } } #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + Send + 'a> { type Output = R; extern "rust-call" fn call_once(self, args: A) -> R { self.call_box(args) } } #[unstable(feature = "coerce_unsized", issue = "27732")] impl<T:?Sized + Unsize<U>, U:?Sized> CoerceUnsized<Box<U>> for Box<T> {} #[unstable(feature = "dispatch_from_dyn", issue = "0")] impl<T:?Sized + Unsize<U>, U:?Sized> DispatchFromDyn<Box<U>> for Box<T> {} #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")] impl<A> FromIterator<A> for Box<[A]> { fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self { iter.into_iter().collect::<Vec<_>>().into_boxed_slice() } } #[stable(feature = "box_slice_clone", since = "1.3.0")] impl<T: Clone> Clone for Box<[T]> { fn clone(&self) -> Self { let mut new = BoxBuilder { data: RawVec::with_capacity(self.len()), len: 0, }; let mut target = new.data.ptr(); for item in self.iter() { unsafe { ptr::write(target, item.clone()); target = target.offset(1);
random_line_split
boxed.rs
rust1", since = "1.0.0")] use core::any::Any; use core::borrow; use core::cmp::Ordering; use core::convert::From; use core::fmt; use core::future::Future; use core::hash::{Hash, Hasher}; use core::iter::{Iterator, FromIterator, FusedIterator}; use core::marker::{Unpin, Unsize}; use core::mem; use core::pin::Pin; use core::ops::{CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Generator, GeneratorState}; use core::ptr::{self, NonNull, Unique}; use core::task::{LocalWaker, Poll}; use vec::Vec; use raw_vec::RawVec; use str::from_boxed_utf8_unchecked; /// A pointer type for heap allocation. /// /// See the [module-level documentation](../../std/boxed/index.html) for more. #[lang = "owned_box"] #[fundamental] #[stable(feature = "rust1", since = "1.0.0")] pub struct Box<T:?Sized>(Unique<T>); impl<T> Box<T> { /// Allocates memory on the heap and then places `x` into it. /// /// This doesn't actually allocate if `T` is zero-sized. /// /// # Examples /// /// ``` /// let five = Box::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline(always)] pub fn new(x: T) -> Box<T> { box x } #[unstable(feature = "pin", issue = "49150")] #[inline(always)] pub fn pinned(x: T) -> Pin<Box<T>> { (box x).into() } } impl<T:?Sized> Box<T> { /// Constructs a box from a raw pointer. /// /// After calling this function, the raw pointer is owned by the /// resulting `Box`. Specifically, the `Box` destructor will call /// the destructor of `T` and free the allocated memory. Since the /// way `Box` allocates and releases memory is unspecified, the /// only valid pointer to pass to this function is the one taken /// from another `Box` via the [`Box::into_raw`] function. /// /// This function is unsafe because improper use may lead to /// memory problems. For example, a double-free may occur if the /// function is called twice on the same raw pointer. /// /// [`Box::into_raw`]: struct.Box.html#method.into_raw /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let ptr = Box::into_raw(x); /// let x = unsafe { Box::from_raw(ptr) }; /// ``` #[stable(feature = "box_raw", since = "1.4.0")] #[inline] pub unsafe fn from_raw(raw: *mut T) -> Self { Box(Unique::new_unchecked(raw)) } /// Consumes the `Box`, returning a wrapped raw pointer. /// /// The pointer will be properly aligned and non-null. /// /// After calling this function, the caller is responsible for the /// memory previously managed by the `Box`. In particular, the /// caller should properly destroy `T` and release the memory. The /// proper way to do so is to convert the raw pointer back into a /// `Box` with the [`Box::from_raw`] function. /// /// Note: this is an associated function, which means that you have /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This /// is so that there is no conflict with a method on the inner type. /// /// [`Box::from_raw`]: struct.Box.html#method.from_raw /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let ptr = Box::into_raw(x); /// ``` #[stable(feature = "box_raw", since = "1.4.0")] #[inline] pub fn into_raw(b: Box<T>) -> *mut T { Box::into_raw_non_null(b).as_ptr() } /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`. /// /// After calling this function, the caller is responsible for the /// memory previously managed by the `Box`. In particular, the /// caller should properly destroy `T` and release the memory. The /// proper way to do so is to convert the `NonNull<T>` pointer /// into a raw pointer and back into a `Box` with the [`Box::from_raw`] /// function. /// /// Note: this is an associated function, which means that you have /// to call it as `Box::into_raw_non_null(b)` /// instead of `b.into_raw_non_null()`. This /// is so that there is no conflict with a method on the inner type. /// /// [`Box::from_raw`]: struct.Box.html#method.from_raw /// /// # Examples /// /// ``` /// #![feature(box_into_raw_non_null)] /// /// fn main() { /// let x = Box::new(5); /// let ptr = Box::into_raw_non_null(x); /// } /// ``` #[unstable(feature = "box_into_raw_non_null", issue = "47336")] #[inline] pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> { Box::into_unique(b).into() } #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")] #[inline] #[doc(hidden)] pub fn into_unique(b: Box<T>) -> Unique<T> { let unique = b.0; mem::forget(b); unique } /// Consumes and leaks the `Box`, returning a mutable reference, /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime /// `'a`. If the type has only static references, or none at all, then this /// may be chosen to be `'static`. /// /// This function is mainly useful for data that lives for the remainder of /// the program's life. Dropping the returned reference will cause a memory /// leak. If this is not acceptable, the reference should first be wrapped /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can /// then be dropped which will properly destroy `T` and release the /// allocated memory. /// /// Note: this is an associated function, which means that you have /// to call it as `Box::leak(b)` instead of `b.leak()`. This /// is so that there is no conflict with a method on the inner type. /// /// [`Box::from_raw`]: struct.Box.html#method.from_raw /// /// # Examples /// /// Simple usage: /// /// ``` /// fn main() { /// let x = Box::new(41); /// let static_ref: &'static mut usize = Box::leak(x); /// *static_ref += 1; /// assert_eq!(*static_ref, 42); /// } /// ``` /// /// Unsized data: /// /// ``` /// fn main() { /// let x = vec![1, 2, 3].into_boxed_slice(); /// let static_ref = Box::leak(x); /// static_ref[0] = 4; /// assert_eq!(*static_ref, [4, 2, 3]); /// } /// ``` #[stable(feature = "box_leak", since = "1.26.0")] #[inline] pub fn leak<'a>(b: Box<T>) -> &'a mut T where T: 'a // Technically not needed, but kept to be explicit. { unsafe { &mut *Box::into_raw(b) } } } #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<#[may_dangle] T:?Sized> Drop for Box<T> { fn drop(&mut self) { // FIXME: Do nothing, drop is currently performed by compiler. } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: Default> Default for Box<T> { /// Creates a `Box<T>`, with the `Default` value for T. fn default() -> Box<T> { box Default::default() } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> Default for Box<[T]> { fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) } } #[stable(feature = "default_box_extra", since = "1.17.0")] impl Default for Box<str> { fn default() -> Box<str> { unsafe { from_boxed_utf8_unchecked(Default::default()) } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: Clone> Clone for Box<T> { /// Returns a new box with a `clone()` of this box's contents. /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let y = x.clone(); /// ``` #[rustfmt_skip] #[inline] fn clone(&self) -> Box<T> { box { (**self).clone() } } /// Copies `source`'s contents into `self` without creating a new allocation. /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let mut y = Box::new(10); /// /// y.clone_from(&x); /// /// assert_eq!(*y, 5); /// ``` #[inline] fn clone_from(&mut self, source: &Box<T>) { (**self).clone_from(&(**source)); } } #[stable(feature = "box_slice_clone", since = "1.3.0")] impl Clone for Box<str> { fn clone(&self) -> Self { let len = self.len(); let buf = RawVec::with_capacity(len); unsafe { ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len); from_boxed_utf8_unchecked(buf.into_box()) } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + PartialEq> PartialEq for Box<T> { #[inline] fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + PartialOrd> PartialOrd for Box<T> { #[inline] fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> { PartialOrd::partial_cmp(&**self, &**other) } #[inline] fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) } #[inline] fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) } #[inline] fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) } #[inline] fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + Ord> Ord for Box<T> { #[inline] fn cmp(&self, other: &Box<T>) -> Ordering { Ord::cmp(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + Eq> Eq for Box<T> {} #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized + Hash> Hash for Box<T> { fn hash<H: Hasher>(&self, state: &mut H) { (**self).hash(state); } } #[stable(feature = "indirect_hasher_impl", since = "1.22.0")] impl<T:?Sized + Hasher> Hasher for Box<T> { fn finish(&self) -> u64 { (**self).finish() } fn write(&mut self, bytes: &[u8]) { (**self).write(bytes) } fn write_u8(&mut self, i: u8) { (**self).write_u8(i) } fn write_u16(&mut self, i: u16) { (**self).write_u16(i) } fn write_u32(&mut self, i: u32) { (**self).write_u32(i) } fn write_u64(&mut self, i: u64) { (**self).write_u64(i) } fn write_u128(&mut self, i: u128) { (**self).write_u128(i) } fn write_usize(&mut self, i: usize) { (**self).write_usize(i) } fn write_i8(&mut self, i: i8) { (**self).write_i8(i) } fn write_i16(&mut self, i: i16) { (**self).write_i16(i) } fn write_i32(&mut self, i: i32) { (**self).write_i32(i) } fn write_i64(&mut self, i: i64) { (**self).write_i64(i) } fn write_i128(&mut self, i: i128) { (**self).write_i128(i) } fn write_isize(&mut self, i: isize) { (**self).write_isize(i) } } #[stable(feature = "from_for_ptrs", since = "1.6.0")] impl<T> From<T> for Box<T> { fn from(t: T) -> Self { Box::new(t) } } #[unstable(feature = "pin", issue = "49150")] impl<T> From<Box<T>> for Pin<Box<T>> { fn from(boxed: Box<T>) -> Self { // It's not possible to move or replace the insides of a `Pin<Box<T>>` // when `T:!Unpin`, so it's safe to pin it directly without any // additional requirements. unsafe { Pin::new_unchecked(boxed) } } } #[stable(feature = "box_from_slice", since = "1.17.0")] impl<'a, T: Copy> From<&'a [T]> for Box<[T]> { fn from(slice: &'a [T]) -> Box<[T]> { let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() }; boxed.copy_from_slice(slice); boxed } } #[stable(feature = "box_from_slice", since = "1.17.0")] impl<'a> From<&'a str> for Box<str> { #[inline] fn from(s: &'a str) -> Box<str> { unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) } } } #[stable(feature = "boxed_str_conv", since = "1.19.0")] impl From<Box<str>> for Box<[u8]> { #[inline] fn from(s: Box<str>) -> Self { unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) } } } impl Box<dyn Any> { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type. /// /// # Examples /// /// ``` /// use std::any::Any; /// /// fn print_if_string(value: Box<dyn Any>) { /// if let Ok(string) = value.downcast::<String>() { /// println!("String ({}): {}", string.len(), string); /// } /// } /// /// fn main() { /// let my_string = "Hello World".to_string(); /// print_if_string(Box::new(my_string)); /// print_if_string(Box::new(0i8)); /// } /// ``` pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> { if self.is::<T>() { unsafe { let raw: *mut dyn Any = Box::into_raw(self); Ok(Box::from_raw(raw as *mut T)) } } else
} } impl Box<dyn Any + Send> { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type. /// /// # Examples /// /// ``` /// use std::any::Any; /// /// fn print_if_string(value: Box<dyn Any + Send>) { /// if let Ok(string) = value.downcast::<String>() { /// println!("String ({}): {}", string.len(), string); /// } /// } /// /// fn main() { /// let my_string = "Hello World".to_string(); /// print_if_string(Box::new(my_string)); /// print_if_string(Box::new(0i8)); /// } /// ``` pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> { <Box<dyn Any>>::downcast(self).map_err(|s| unsafe { // reapply the Send marker Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send)) }) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: fmt::Display +?Sized> fmt::Display for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: fmt::Debug +?Sized> fmt::Debug for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized> fmt::Pointer for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // It's not possible to extract the inner Uniq directly from the Box, // instead we cast it to a *const which aliases the Unique let ptr: *const T = &**self; fmt::Pointer::fmt(&ptr, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized> Deref for Box<T> { type Target = T; fn deref(&self) -> &T { &**self } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:?Sized> DerefMut for Box<T> { fn deref_mut(&mut self) -> &mut T { &mut **self } } #[stable(feature = "rust1", since = "1.0.0")] impl<I: Iterator +?Sized> Iterator for Box<I> { type Item = I::Item; fn next(&mut self) -> Option<I::Item> { (**self).next() } fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() } fn nth(&mut self, n: usize) -> Option<I::Item> { (**self).nth(n) } } #[stable(feature = "rust1", since = "1.0.0")] impl<I: DoubleEndedIterator +?Sized> DoubleEndedIterator for Box<I> { fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() } } #[stable(feature = "rust1", since = "1.0.0")] impl<I: ExactSizeIterator +?Sized> ExactSizeIterator for Box<I> { fn len(&self) -> usize { (**self).len() } fn is_empty(&self) -> bool { (**self).is_empty() } } #[stable(feature = "fused", since = "1.26.0")] impl<I: FusedIterator +?Sized> FusedIterator for Box<I> {} /// `FnBox` is a version of the `FnOnce` intended for use with boxed /// closure objects. The idea is that where one would normally store a /// `Box<dyn FnOnce()>` in a data structure, you should use /// `Box<dyn FnBox()>`. The two traits behave essentially the same, except /// that a `FnBox` closure can only be called if it is boxed. (Note /// that `FnBox` may be deprecated in the future if `Box<dyn FnOnce()>` /// closures become directly usable.) /// /// # Examples /// /// Here is a snippet of code which creates a hashmap full of boxed /// once closures and then removes them one by one, calling each /// closure as it is removed. Note that the type of the closures /// stored in the map is `Box<dyn FnBox() -> i32>` and not `Box<dyn FnOnce() /// -> i32>`. /// /// ``` /// #![feature(fnbox)] /// /// use std::boxed::FnBox; /// use std::collections::HashMap; /// /// fn make_map() -> HashMap<i32, Box<dyn FnBox() -> i32>> { /// let mut map: HashMap<i32, Box<dyn FnBox() -> i32>> = HashMap::new(); /// map.insert(1, Box::new(|| 22)); /// map.insert(2, Box::new(|| 44)); /// map /// } /// /// fn main() { /// let mut map = make_map(); /// for i in &[1, 2] { /// let f = map.remove(&i).unwrap(); /// assert_eq!(f(), i * 22); /// } /// } /// ``` #[rustc_paren_sugar] #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] pub trait FnBox<A> { type Output; fn call_box(self: Box<Self>, args: A) -> Self::Output; } #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] impl<A, F> FnBox<A> for F where F: FnOnce<A> { type Output = F::Output; fn call_box(self: Box<F>, args: A) -> F::Output { self.call_once(args) } } #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + 'a> { type Output = R; extern "rust-call" fn call_once(self, args: A) -> R { self.call_box(args) } } #[unstable(feature = "fnbox", reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")] impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + Send + 'a> { type Output = R; extern "rust-call" fn call_once(self, args: A) -> R { self.call_box(args) } } #[unstable(feature = "coerce_unsized", issue = "27732")] impl<T:?Sized + Unsize<U>, U:?Sized> CoerceUnsized<Box<U>> for Box<T> {} #[unstable(feature = "dispatch_from_dyn", issue = "0")] impl<T:?Sized + Unsize<U>, U:?Sized> DispatchFromDyn<Box<U>> for Box<T> {} #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")] impl<A> FromIterator<A> for Box<[A]> { fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self { iter.into_iter().collect::<Vec<_>>().into_boxed_slice() } } #[stable(feature = "box_slice_clone", since = "1.3.0")] impl<T: Clone> Clone for Box<[T]> { fn clone(&self) -> Self { let mut new = BoxBuilder { data: RawVec::with_capacity(self.len()), len: 0, }; let mut target = new.data.ptr(); for item in self.iter() { unsafe { ptr::write(target, item.clone()); target = target.offset(1);
{ Err(self) }
conditional_block
exec_commands.rs
use arguments::{VERBOSE_MODE, JOBLOG}; use execute::command::{self, CommandErr}; use input_iterator::InputsLock; use numtoa::NumToA; use time::{self, Timespec}; use tokenizer::Token; use verbose; use super::pipe::disk::State; use super::job_log::JobLog; use super::child::handle_child; use std::io::{self, Read, Write}; use std::sync::mpsc::Sender; use std::time::Duration; /// Contains all the required data needed for executing commands in parallel. /// Commands will be generated based on a template of argument tokens combined /// with the current input argument. pub struct ExecCommands<IO: Read> { pub slot: usize, pub num_inputs: usize, pub flags: u16, pub timeout: Duration, pub inputs: InputsLock<IO>, pub output_tx: Sender<State>, pub arguments: &'static [Token], pub tempdir: String, } impl<IO: Read> ExecCommands<IO> { pub fn run(&mut self) { let stdout = io::stdout(); let stderr = io::stderr(); let slot = &self.slot.to_string(); let mut command_buffer = &mut String::with_capacity(64); let has_timeout = self.timeout!= Duration::from_millis(0); let mut input = String::with_capacity(64); let mut id_buffer = [0u8; 20]; let mut job_buffer = [0u8; 20]; let mut total_buffer = [0u8; 20]; let mut start_indice = self.num_inputs.numtoa(10, &mut total_buffer); let job_total = &total_buffer[start_indice..]; while let Some(job_id) = self.inputs.try_next(&mut input) { if self.flags & VERBOSE_MODE!= 0 { verbose::processing_task(&stdout, job_id+1, self.num_inputs, &input); } start_indice = (job_id+1).numtoa(10, &mut id_buffer); let command = command::ParallelCommand { slot_no: slot, job_no: &id_buffer[start_indice..], job_total: job_total, input: &input, command_template: self.arguments, flags: self.flags }; command_buffer.clear(); let (start_time, end_time, exit_value, signal) = match command.exec(command_buffer) { Ok(child) => { handle_child(child, &self.output_tx, self.flags, job_id, input.clone(), has_timeout, self.timeout, &self.tempdir, &mut job_buffer) }, Err(cmd_err) => { let mut stderr = stderr.lock(); let _ = stderr.write(b"parallel: command error: "); let message = match cmd_err { CommandErr::IO(error) => format!("I/O error: {}\n", error), }; let _ = stderr.write(message.as_bytes()); let message = format!("{}: {}: {}", job_id+1, command.input, message); let _ = self.output_tx.send(State::Error(job_id, message)); (Timespec::new(0, 0), Timespec::new(0, 0), -1, 0) } }; if self.flags & JOBLOG!= 0 { let runtime: time::Duration = end_time - start_time; let _ = self.output_tx.send(State::JobLog(JobLog { job_id: job_id, start_time: start_time, runtime: runtime.num_nanoseconds().unwrap_or(0) as u64, exit_value: exit_value, signal: signal, flags: self.flags, command: command_buffer.clone(), })); } if self.flags & VERBOSE_MODE!= 0
} } }
{ verbose::task_complete(&stdout, job_id, self.num_inputs, &input); }
conditional_block
exec_commands.rs
use arguments::{VERBOSE_MODE, JOBLOG}; use execute::command::{self, CommandErr}; use input_iterator::InputsLock; use numtoa::NumToA; use time::{self, Timespec}; use tokenizer::Token; use verbose; use super::pipe::disk::State; use super::job_log::JobLog; use super::child::handle_child; use std::io::{self, Read, Write}; use std::sync::mpsc::Sender; use std::time::Duration; /// Contains all the required data needed for executing commands in parallel. /// Commands will be generated based on a template of argument tokens combined /// with the current input argument. pub struct
<IO: Read> { pub slot: usize, pub num_inputs: usize, pub flags: u16, pub timeout: Duration, pub inputs: InputsLock<IO>, pub output_tx: Sender<State>, pub arguments: &'static [Token], pub tempdir: String, } impl<IO: Read> ExecCommands<IO> { pub fn run(&mut self) { let stdout = io::stdout(); let stderr = io::stderr(); let slot = &self.slot.to_string(); let mut command_buffer = &mut String::with_capacity(64); let has_timeout = self.timeout!= Duration::from_millis(0); let mut input = String::with_capacity(64); let mut id_buffer = [0u8; 20]; let mut job_buffer = [0u8; 20]; let mut total_buffer = [0u8; 20]; let mut start_indice = self.num_inputs.numtoa(10, &mut total_buffer); let job_total = &total_buffer[start_indice..]; while let Some(job_id) = self.inputs.try_next(&mut input) { if self.flags & VERBOSE_MODE!= 0 { verbose::processing_task(&stdout, job_id+1, self.num_inputs, &input); } start_indice = (job_id+1).numtoa(10, &mut id_buffer); let command = command::ParallelCommand { slot_no: slot, job_no: &id_buffer[start_indice..], job_total: job_total, input: &input, command_template: self.arguments, flags: self.flags }; command_buffer.clear(); let (start_time, end_time, exit_value, signal) = match command.exec(command_buffer) { Ok(child) => { handle_child(child, &self.output_tx, self.flags, job_id, input.clone(), has_timeout, self.timeout, &self.tempdir, &mut job_buffer) }, Err(cmd_err) => { let mut stderr = stderr.lock(); let _ = stderr.write(b"parallel: command error: "); let message = match cmd_err { CommandErr::IO(error) => format!("I/O error: {}\n", error), }; let _ = stderr.write(message.as_bytes()); let message = format!("{}: {}: {}", job_id+1, command.input, message); let _ = self.output_tx.send(State::Error(job_id, message)); (Timespec::new(0, 0), Timespec::new(0, 0), -1, 0) } }; if self.flags & JOBLOG!= 0 { let runtime: time::Duration = end_time - start_time; let _ = self.output_tx.send(State::JobLog(JobLog { job_id: job_id, start_time: start_time, runtime: runtime.num_nanoseconds().unwrap_or(0) as u64, exit_value: exit_value, signal: signal, flags: self.flags, command: command_buffer.clone(), })); } if self.flags & VERBOSE_MODE!= 0 { verbose::task_complete(&stdout, job_id, self.num_inputs, &input); } } } }
ExecCommands
identifier_name
exec_commands.rs
use arguments::{VERBOSE_MODE, JOBLOG}; use execute::command::{self, CommandErr}; use input_iterator::InputsLock; use numtoa::NumToA; use time::{self, Timespec}; use tokenizer::Token; use verbose; use super::pipe::disk::State; use super::job_log::JobLog; use super::child::handle_child; use std::io::{self, Read, Write}; use std::sync::mpsc::Sender; use std::time::Duration; /// Contains all the required data needed for executing commands in parallel. /// Commands will be generated based on a template of argument tokens combined /// with the current input argument. pub struct ExecCommands<IO: Read> { pub slot: usize, pub num_inputs: usize, pub flags: u16, pub timeout: Duration, pub inputs: InputsLock<IO>, pub output_tx: Sender<State>, pub arguments: &'static [Token], pub tempdir: String, } impl<IO: Read> ExecCommands<IO> { pub fn run(&mut self)
start_indice = (job_id+1).numtoa(10, &mut id_buffer); let command = command::ParallelCommand { slot_no: slot, job_no: &id_buffer[start_indice..], job_total: job_total, input: &input, command_template: self.arguments, flags: self.flags }; command_buffer.clear(); let (start_time, end_time, exit_value, signal) = match command.exec(command_buffer) { Ok(child) => { handle_child(child, &self.output_tx, self.flags, job_id, input.clone(), has_timeout, self.timeout, &self.tempdir, &mut job_buffer) }, Err(cmd_err) => { let mut stderr = stderr.lock(); let _ = stderr.write(b"parallel: command error: "); let message = match cmd_err { CommandErr::IO(error) => format!("I/O error: {}\n", error), }; let _ = stderr.write(message.as_bytes()); let message = format!("{}: {}: {}", job_id+1, command.input, message); let _ = self.output_tx.send(State::Error(job_id, message)); (Timespec::new(0, 0), Timespec::new(0, 0), -1, 0) } }; if self.flags & JOBLOG!= 0 { let runtime: time::Duration = end_time - start_time; let _ = self.output_tx.send(State::JobLog(JobLog { job_id: job_id, start_time: start_time, runtime: runtime.num_nanoseconds().unwrap_or(0) as u64, exit_value: exit_value, signal: signal, flags: self.flags, command: command_buffer.clone(), })); } if self.flags & VERBOSE_MODE!= 0 { verbose::task_complete(&stdout, job_id, self.num_inputs, &input); } } } }
{ let stdout = io::stdout(); let stderr = io::stderr(); let slot = &self.slot.to_string(); let mut command_buffer = &mut String::with_capacity(64); let has_timeout = self.timeout != Duration::from_millis(0); let mut input = String::with_capacity(64); let mut id_buffer = [0u8; 20]; let mut job_buffer = [0u8; 20]; let mut total_buffer = [0u8; 20]; let mut start_indice = self.num_inputs.numtoa(10, &mut total_buffer); let job_total = &total_buffer[start_indice..]; while let Some(job_id) = self.inputs.try_next(&mut input) { if self.flags & VERBOSE_MODE != 0 { verbose::processing_task(&stdout, job_id+1, self.num_inputs, &input); }
identifier_body
exec_commands.rs
use arguments::{VERBOSE_MODE, JOBLOG}; use execute::command::{self, CommandErr}; use input_iterator::InputsLock; use numtoa::NumToA; use time::{self, Timespec}; use tokenizer::Token; use verbose; use super::pipe::disk::State; use super::job_log::JobLog; use super::child::handle_child; use std::io::{self, Read, Write}; use std::sync::mpsc::Sender; use std::time::Duration; /// Contains all the required data needed for executing commands in parallel. /// Commands will be generated based on a template of argument tokens combined /// with the current input argument. pub struct ExecCommands<IO: Read> { pub slot: usize, pub num_inputs: usize, pub flags: u16, pub timeout: Duration, pub inputs: InputsLock<IO>, pub output_tx: Sender<State>, pub arguments: &'static [Token], pub tempdir: String, } impl<IO: Read> ExecCommands<IO> {
let mut command_buffer = &mut String::with_capacity(64); let has_timeout = self.timeout!= Duration::from_millis(0); let mut input = String::with_capacity(64); let mut id_buffer = [0u8; 20]; let mut job_buffer = [0u8; 20]; let mut total_buffer = [0u8; 20]; let mut start_indice = self.num_inputs.numtoa(10, &mut total_buffer); let job_total = &total_buffer[start_indice..]; while let Some(job_id) = self.inputs.try_next(&mut input) { if self.flags & VERBOSE_MODE!= 0 { verbose::processing_task(&stdout, job_id+1, self.num_inputs, &input); } start_indice = (job_id+1).numtoa(10, &mut id_buffer); let command = command::ParallelCommand { slot_no: slot, job_no: &id_buffer[start_indice..], job_total: job_total, input: &input, command_template: self.arguments, flags: self.flags }; command_buffer.clear(); let (start_time, end_time, exit_value, signal) = match command.exec(command_buffer) { Ok(child) => { handle_child(child, &self.output_tx, self.flags, job_id, input.clone(), has_timeout, self.timeout, &self.tempdir, &mut job_buffer) }, Err(cmd_err) => { let mut stderr = stderr.lock(); let _ = stderr.write(b"parallel: command error: "); let message = match cmd_err { CommandErr::IO(error) => format!("I/O error: {}\n", error), }; let _ = stderr.write(message.as_bytes()); let message = format!("{}: {}: {}", job_id+1, command.input, message); let _ = self.output_tx.send(State::Error(job_id, message)); (Timespec::new(0, 0), Timespec::new(0, 0), -1, 0) } }; if self.flags & JOBLOG!= 0 { let runtime: time::Duration = end_time - start_time; let _ = self.output_tx.send(State::JobLog(JobLog { job_id: job_id, start_time: start_time, runtime: runtime.num_nanoseconds().unwrap_or(0) as u64, exit_value: exit_value, signal: signal, flags: self.flags, command: command_buffer.clone(), })); } if self.flags & VERBOSE_MODE!= 0 { verbose::task_complete(&stdout, job_id, self.num_inputs, &input); } } } }
pub fn run(&mut self) { let stdout = io::stdout(); let stderr = io::stderr(); let slot = &self.slot.to_string();
random_line_split
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! # The Rust Core Library //! //! The Rust Core Library is the dependency-free foundation of [The //! Rust Standard Library](../std/index.html). It is the portable glue //! between the language and its libraries, defining the intrinsic and //! primitive building blocks of all Rust code. It links to no //! upstream libraries, no system libraries, and no libc. //! //! The core library is *minimal*: it isn't even aware of heap allocation, //! nor does it provide concurrency or I/O. These things require //! platform integration, and this library is platform-agnostic. //! //! *It is not recommended to use the core library*. The stable //! functionality of libcore is reexported from the //! [standard library](../std/index.html). The composition of this library is //! subject to change over time; only the interface exposed through libstd is //! intended to be stable. //! //! # How to use the core library //! // FIXME: Fill me in with more detail when the interface settles //! This library is built on the assumption of a few existing symbols: //! //! * `memcpy`, `memcmp`, `memset` - These are core memory routines which are //! often generated by LLVM. Additionally, this library can make explicit //! calls to these functions. Their signatures are the same as found in C. //! These functions are often provided by the system libc, but can also be //! provided by `librlibc` which is distributed with the standard rust //! distribution. //! //! * `rust_begin_unwind` - This function takes three arguments, a //! `fmt::Arguments`, a `&str`, and a `uint`. These three arguments dictate //! the panic message, the file at which panic was invoked, and the line. //! It is up to consumers of this core library to define this panic //! function; it is only required to never return. // Since libcore defines many fundamental lang items, all tests live in a // separate crate, libcoretest, to avoid bizarre issues. #![crate_name = "core"] #![unstable(feature = "core")] #![staged_api] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![feature(no_std)] #![no_std] #![allow(raw_pointer_derive)] #![deny(missing_docs)] #![feature(int_uint)] #![feature(intrinsics, lang_items)] #![feature(on_unimplemented)] #![feature(simd, unsafe_destructor, slicing_syntax)] #![feature(staged_api)] #![feature(unboxed_closures)] #[macro_use] mod macros; #[path = "num/float_macros.rs"] #[macro_use] mod float_macros; #[path = "num/int_macros.rs"] #[macro_use] mod int_macros; #[path = "num/uint_macros.rs"] #[macro_use] mod uint_macros; #[path = "num/int.rs"] pub mod int; #[path = "num/isize.rs"] pub mod isize; #[path = "num/i8.rs"] pub mod i8; #[path = "num/i16.rs"] pub mod i16; #[path = "num/i32.rs"] pub mod i32; #[path = "num/i64.rs"] pub mod i64; #[path = "num/uint.rs"] pub mod uint; #[path = "num/usize.rs"] pub mod usize; #[path = "num/u8.rs"] pub mod u8; #[path = "num/u16.rs"] pub mod u16; #[path = "num/u32.rs"] pub mod u32; #[path = "num/u64.rs"] pub mod u64; #[path = "num/f32.rs"] pub mod f32; #[path = "num/f64.rs"] pub mod f64;
/* The libcore prelude, not as all-encompassing as the libstd prelude */ pub mod prelude; /* Core modules for ownership management */ pub mod intrinsics; pub mod mem; pub mod nonzero; pub mod ptr; /* Core language traits */ pub mod marker; pub mod ops; pub mod cmp; pub mod clone; pub mod default; /* Core types and methods on primitives */ pub mod any; pub mod atomic; pub mod borrow; pub mod cell; pub mod char; pub mod panicking; pub mod finally; pub mod iter; pub mod option; pub mod raw; pub mod result; pub mod simd; pub mod slice; pub mod str; pub mod hash; pub mod fmt; pub mod error; #[doc(primitive = "bool")] mod bool { } // note: does not need to be public mod tuple; mod array; #[doc(hidden)] mod core { pub use panicking; pub use fmt; #[cfg(not(stage0))] pub use clone; #[cfg(not(stage0))] pub use cmp; #[cfg(not(stage0))] pub use hash; #[cfg(not(stage0))] pub use marker; #[cfg(not(stage0))] pub use option; #[cfg(not(stage0))] pub use iter; } #[doc(hidden)] mod std { // NOTE: remove after next snapshot #[cfg(stage0)] pub use clone; #[cfg(stage0)] pub use cmp; #[cfg(stage0)] pub use hash; #[cfg(stage0)] pub use marker; #[cfg(stage0)] pub use option; #[cfg(stage0)] pub use fmt; #[cfg(stage0)] pub use iter; // range syntax pub use ops; }
pub mod num;
random_line_split
borrowck-borrow-overloaded-deref-mut.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test how overloaded deref interacts with borrows when DerefMut // is implemented. use std::ops::{Deref, DerefMut}; struct
<T> { value: *mut T } impl<T> Deref for Own<T> { type Target = T; fn deref<'a>(&'a self) -> &'a T { unsafe { &*self.value } } } impl<T> DerefMut for Own<T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *self.value } } } fn deref_imm(x: Own<isize>) { let _i = &*x; } fn deref_mut1(x: Own<isize>) { let _i = &mut *x; //~ ERROR cannot borrow } fn deref_mut2(mut x: Own<isize>) { let _i = &mut *x; } fn deref_extend<'a>(x: &'a Own<isize>) -> &'a isize { &**x } fn deref_extend_mut1<'a>(x: &'a Own<isize>) -> &'a mut isize { &mut **x //~ ERROR cannot borrow } fn deref_extend_mut2<'a>(x: &'a mut Own<isize>) -> &'a mut isize { &mut **x } fn assign1<'a>(x: Own<isize>) { *x = 3; //~ ERROR cannot borrow } fn assign2<'a>(x: &'a Own<isize>) { **x = 3; //~ ERROR cannot borrow } fn assign3<'a>(x: &'a mut Own<isize>) { **x = 3; } pub fn main() {}
Own
identifier_name
borrowck-borrow-overloaded-deref-mut.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test how overloaded deref interacts with borrows when DerefMut // is implemented. use std::ops::{Deref, DerefMut}; struct Own<T> { value: *mut T } impl<T> Deref for Own<T> { type Target = T; fn deref<'a>(&'a self) -> &'a T { unsafe { &*self.value } } } impl<T> DerefMut for Own<T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *self.value } } } fn deref_imm(x: Own<isize>) { let _i = &*x; } fn deref_mut1(x: Own<isize>) { let _i = &mut *x; //~ ERROR cannot borrow } fn deref_mut2(mut x: Own<isize>) { let _i = &mut *x; } fn deref_extend<'a>(x: &'a Own<isize>) -> &'a isize { &**x } fn deref_extend_mut1<'a>(x: &'a Own<isize>) -> &'a mut isize { &mut **x //~ ERROR cannot borrow } fn deref_extend_mut2<'a>(x: &'a mut Own<isize>) -> &'a mut isize { &mut **x } fn assign1<'a>(x: Own<isize>) { *x = 3; //~ ERROR cannot borrow } fn assign2<'a>(x: &'a Own<isize>) { **x = 3; //~ ERROR cannot borrow } fn assign3<'a>(x: &'a mut Own<isize>) {
} pub fn main() {}
**x = 3;
random_line_split
borrowck-borrow-overloaded-deref-mut.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test how overloaded deref interacts with borrows when DerefMut // is implemented. use std::ops::{Deref, DerefMut}; struct Own<T> { value: *mut T } impl<T> Deref for Own<T> { type Target = T; fn deref<'a>(&'a self) -> &'a T { unsafe { &*self.value } } } impl<T> DerefMut for Own<T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *self.value } } } fn deref_imm(x: Own<isize>) { let _i = &*x; } fn deref_mut1(x: Own<isize>) { let _i = &mut *x; //~ ERROR cannot borrow } fn deref_mut2(mut x: Own<isize>) { let _i = &mut *x; } fn deref_extend<'a>(x: &'a Own<isize>) -> &'a isize { &**x } fn deref_extend_mut1<'a>(x: &'a Own<isize>) -> &'a mut isize { &mut **x //~ ERROR cannot borrow } fn deref_extend_mut2<'a>(x: &'a mut Own<isize>) -> &'a mut isize { &mut **x } fn assign1<'a>(x: Own<isize>) { *x = 3; //~ ERROR cannot borrow } fn assign2<'a>(x: &'a Own<isize>) { **x = 3; //~ ERROR cannot borrow } fn assign3<'a>(x: &'a mut Own<isize>)
pub fn main() {}
{ **x = 3; }
identifier_body
lib.rs
extern crate ai_behavior; extern crate find_folder; extern crate gfx_device_gl; extern crate graphics; extern crate nalgebra; extern crate ncollide; extern crate piston_window; extern crate rand; extern crate sprite; extern crate uuid; mod mobs; use gfx_device_gl::Resources; use graphics::Image; use graphics::rectangle::square; use piston_window::*; use mobs::{Hero, Star}; use sprite::*; pub struct Game { scene: Scene<Texture<Resources>>, player: Hero, stars: Vec<Star>, diag: bool, pause: bool, victory: bool, loss: bool, } const TILE_SIZE: u32 = 64; impl Game { pub fn new(w: &mut PistonWindow) -> Game { let mut scene = Scene::new(); let mut stars: Vec<Star> = vec![]; for number in 1..7 { let color = match number % 4 { 1 => "yellow", 2 => "green", 3 => "blue", _ => "pink", }; stars.push(Star::new(color, w, &mut scene)); } let player = Hero::new(w, &mut scene); Game { scene: scene, player: player, stars: stars, diag: false, pause: false, victory: false, loss: false, } } pub fn on_update(&mut self, e: &Input, upd: UpdateArgs, w: &PistonWindow) { if self.pause || self.victory || self.loss { return; } self.scene.event(e); let mut grew = false; for mut star in &mut self.stars { if!star.destroyed && self.player.collides(&star) { star.destroy(&mut self.scene, upd.dt); self.player.grow(&mut self.scene, upd.dt); grew = true; } else { star.mov(w, &mut self.scene, upd.dt); } } if self.stars.iter().all(|star| star.destroyed) { self.victory = true; self.loss = false; return; } if!grew { self.player.shrink(&mut self.scene, upd.dt); } if self.player.size > 0.0 { self.player.mov(w, &mut self.scene, upd.dt); } else { self.loss = true; self.victory = false;
let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets") .unwrap(); let ref font = assets.join("Fresca-Regular.ttf"); let factory = w.factory.clone(); let mut glyphs = Glyphs::new(font, factory).unwrap(); let Size { height, width } = w.size(); let image = Image::new().rect(square(0.0, 0.0, width as f64)); let bg = Texture::from_path(&mut w.factory, assets.join("bg.png"), Flip::None, &TextureSettings::new()).unwrap(); w.draw_2d(e, |c, g| { clear([1.0, 1.0, 1.0, 1.0], g); let cols = width / TILE_SIZE; // 4:3 means rows will be fractional so add one to cover completely let tile_count = cols * (height / TILE_SIZE + 1); for number in 0..tile_count { let x: f64 = (number % cols * TILE_SIZE).into(); let y: f64 = (number / cols * TILE_SIZE).into(); image.draw(&bg, &Default::default(), c.transform.trans(x, y).zoom(1.0 / cols as f64), g); } if self.victory { text::Text::new_color([0.0, 1.0, 0.0, 1.0], height / 10).draw( "Hurray! You win!", &mut glyphs, &c.draw_state, c.transform.trans(width as f64 / 2.0 - width as f64 / 4.5, height as f64 / 2.0), g ); return; } else if self.loss { text::Text::new_color([0.0, 1.0, 0.0, 1.0], height / 10).draw( "Aw! You lose!", &mut glyphs, &c.draw_state, c.transform.trans(width as f64 / 2.0 - width as f64 / 4.5, height as f64 / 2.0), g ); return; } if self.diag { text::Text::new_color([0.0, 1.0, 0.0, 1.0], 10).draw( &format!("{}", self.player.diag()), &mut glyphs, &c.draw_state, c.transform.trans(10.0, 10.0), g ); } self.scene.draw(c.transform, g); }); } // TODO use an enum to track requested movement direction pub fn on_input(&mut self, inp: Input) { match inp { Input::Press(but) => { match but { Button::Keyboard(Key::Up) => { self.player.dir = (self.player.dir.0, -1.0); } Button::Keyboard(Key::Down) => { self.player.dir = (self.player.dir.0, 1.0); } Button::Keyboard(Key::Left) => { self.player.dir = (-1.0, self.player.dir.1); } Button::Keyboard(Key::Right) => { self.player.dir = (1.0, self.player.dir.1); } _ => {} } } Input::Release(but) => { match but { Button::Keyboard(Key::Up) => { self.player.dir = (self.player.dir.0, 0.0); } Button::Keyboard(Key::Down) => { self.player.dir = (self.player.dir.0, 0.0); } Button::Keyboard(Key::Left) => { self.player.dir = (0.0, self.player.dir.1); } Button::Keyboard(Key::Right) => { self.player.dir = (0.0, self.player.dir.1); } Button::Keyboard(Key::H) => { self.diag =!self.diag; } Button::Keyboard(Key::P) => { self.pause =!self.pause; } _ => {} } } _ => {} } } }
} } pub fn on_draw(&mut self, e: &Input, _: RenderArgs, w: &mut PistonWindow) {
random_line_split
lib.rs
extern crate ai_behavior; extern crate find_folder; extern crate gfx_device_gl; extern crate graphics; extern crate nalgebra; extern crate ncollide; extern crate piston_window; extern crate rand; extern crate sprite; extern crate uuid; mod mobs; use gfx_device_gl::Resources; use graphics::Image; use graphics::rectangle::square; use piston_window::*; use mobs::{Hero, Star}; use sprite::*; pub struct Game { scene: Scene<Texture<Resources>>, player: Hero, stars: Vec<Star>, diag: bool, pause: bool, victory: bool, loss: bool, } const TILE_SIZE: u32 = 64; impl Game { pub fn new(w: &mut PistonWindow) -> Game { let mut scene = Scene::new(); let mut stars: Vec<Star> = vec![]; for number in 1..7 { let color = match number % 4 { 1 => "yellow", 2 => "green", 3 => "blue", _ => "pink", }; stars.push(Star::new(color, w, &mut scene)); } let player = Hero::new(w, &mut scene); Game { scene: scene, player: player, stars: stars, diag: false, pause: false, victory: false, loss: false, } } pub fn on_update(&mut self, e: &Input, upd: UpdateArgs, w: &PistonWindow)
return; } if!grew { self.player.shrink(&mut self.scene, upd.dt); } if self.player.size > 0.0 { self.player.mov(w, &mut self.scene, upd.dt); } else { self.loss = true; self.victory = false; } } pub fn on_draw(&mut self, e: &Input, _: RenderArgs, w: &mut PistonWindow) { let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets") .unwrap(); let ref font = assets.join("Fresca-Regular.ttf"); let factory = w.factory.clone(); let mut glyphs = Glyphs::new(font, factory).unwrap(); let Size { height, width } = w.size(); let image = Image::new().rect(square(0.0, 0.0, width as f64)); let bg = Texture::from_path(&mut w.factory, assets.join("bg.png"), Flip::None, &TextureSettings::new()).unwrap(); w.draw_2d(e, |c, g| { clear([1.0, 1.0, 1.0, 1.0], g); let cols = width / TILE_SIZE; // 4:3 means rows will be fractional so add one to cover completely let tile_count = cols * (height / TILE_SIZE + 1); for number in 0..tile_count { let x: f64 = (number % cols * TILE_SIZE).into(); let y: f64 = (number / cols * TILE_SIZE).into(); image.draw(&bg, &Default::default(), c.transform.trans(x, y).zoom(1.0 / cols as f64), g); } if self.victory { text::Text::new_color([0.0, 1.0, 0.0, 1.0], height / 10).draw( "Hurray! You win!", &mut glyphs, &c.draw_state, c.transform.trans(width as f64 / 2.0 - width as f64 / 4.5, height as f64 / 2.0), g ); return; } else if self.loss { text::Text::new_color([0.0, 1.0, 0.0, 1.0], height / 10).draw( "Aw! You lose!", &mut glyphs, &c.draw_state, c.transform.trans(width as f64 / 2.0 - width as f64 / 4.5, height as f64 / 2.0), g ); return; } if self.diag { text::Text::new_color([0.0, 1.0, 0.0, 1.0], 10).draw( &format!("{}", self.player.diag()), &mut glyphs, &c.draw_state, c.transform.trans(10.0, 10.0), g ); } self.scene.draw(c.transform, g); }); } // TODO use an enum to track requested movement direction pub fn on_input(&mut self, inp: Input) { match inp { Input::Press(but) => { match but { Button::Keyboard(Key::Up) => { self.player.dir = (self.player.dir.0, -1.0); } Button::Keyboard(Key::Down) => { self.player.dir = (self.player.dir.0, 1.0); } Button::Keyboard(Key::Left) => { self.player.dir = (-1.0, self.player.dir.1); } Button::Keyboard(Key::Right) => { self.player.dir = (1.0, self.player.dir.1); } _ => {} } } Input::Release(but) => { match but { Button::Keyboard(Key::Up) => { self.player.dir = (self.player.dir.0, 0.0); } Button::Keyboard(Key::Down) => { self.player.dir = (self.player.dir.0, 0.0); } Button::Keyboard(Key::Left) => { self.player.dir = (0.0, self.player.dir.1); } Button::Keyboard(Key::Right) => { self.player.dir = (0.0, self.player.dir.1); } Button::Keyboard(Key::H) => { self.diag =!self.diag; } Button::Keyboard(Key::P) => { self.pause =!self.pause; } _ => {} } } _ => {} } } }
{ if self.pause || self.victory || self.loss { return; } self.scene.event(e); let mut grew = false; for mut star in &mut self.stars { if !star.destroyed && self.player.collides(&star) { star.destroy(&mut self.scene, upd.dt); self.player.grow(&mut self.scene, upd.dt); grew = true; } else { star.mov(w, &mut self.scene, upd.dt); } } if self.stars.iter().all(|star| star.destroyed) { self.victory = true; self.loss = false;
identifier_body
lib.rs
extern crate ai_behavior; extern crate find_folder; extern crate gfx_device_gl; extern crate graphics; extern crate nalgebra; extern crate ncollide; extern crate piston_window; extern crate rand; extern crate sprite; extern crate uuid; mod mobs; use gfx_device_gl::Resources; use graphics::Image; use graphics::rectangle::square; use piston_window::*; use mobs::{Hero, Star}; use sprite::*; pub struct Game { scene: Scene<Texture<Resources>>, player: Hero, stars: Vec<Star>, diag: bool, pause: bool, victory: bool, loss: bool, } const TILE_SIZE: u32 = 64; impl Game { pub fn new(w: &mut PistonWindow) -> Game { let mut scene = Scene::new(); let mut stars: Vec<Star> = vec![]; for number in 1..7 { let color = match number % 4 { 1 => "yellow", 2 => "green", 3 => "blue", _ => "pink", }; stars.push(Star::new(color, w, &mut scene)); } let player = Hero::new(w, &mut scene); Game { scene: scene, player: player, stars: stars, diag: false, pause: false, victory: false, loss: false, } } pub fn on_update(&mut self, e: &Input, upd: UpdateArgs, w: &PistonWindow) { if self.pause || self.victory || self.loss { return; } self.scene.event(e); let mut grew = false; for mut star in &mut self.stars { if!star.destroyed && self.player.collides(&star) { star.destroy(&mut self.scene, upd.dt); self.player.grow(&mut self.scene, upd.dt); grew = true; } else { star.mov(w, &mut self.scene, upd.dt); } } if self.stars.iter().all(|star| star.destroyed) { self.victory = true; self.loss = false; return; } if!grew { self.player.shrink(&mut self.scene, upd.dt); } if self.player.size > 0.0 { self.player.mov(w, &mut self.scene, upd.dt); } else { self.loss = true; self.victory = false; } } pub fn
(&mut self, e: &Input, _: RenderArgs, w: &mut PistonWindow) { let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets") .unwrap(); let ref font = assets.join("Fresca-Regular.ttf"); let factory = w.factory.clone(); let mut glyphs = Glyphs::new(font, factory).unwrap(); let Size { height, width } = w.size(); let image = Image::new().rect(square(0.0, 0.0, width as f64)); let bg = Texture::from_path(&mut w.factory, assets.join("bg.png"), Flip::None, &TextureSettings::new()).unwrap(); w.draw_2d(e, |c, g| { clear([1.0, 1.0, 1.0, 1.0], g); let cols = width / TILE_SIZE; // 4:3 means rows will be fractional so add one to cover completely let tile_count = cols * (height / TILE_SIZE + 1); for number in 0..tile_count { let x: f64 = (number % cols * TILE_SIZE).into(); let y: f64 = (number / cols * TILE_SIZE).into(); image.draw(&bg, &Default::default(), c.transform.trans(x, y).zoom(1.0 / cols as f64), g); } if self.victory { text::Text::new_color([0.0, 1.0, 0.0, 1.0], height / 10).draw( "Hurray! You win!", &mut glyphs, &c.draw_state, c.transform.trans(width as f64 / 2.0 - width as f64 / 4.5, height as f64 / 2.0), g ); return; } else if self.loss { text::Text::new_color([0.0, 1.0, 0.0, 1.0], height / 10).draw( "Aw! You lose!", &mut glyphs, &c.draw_state, c.transform.trans(width as f64 / 2.0 - width as f64 / 4.5, height as f64 / 2.0), g ); return; } if self.diag { text::Text::new_color([0.0, 1.0, 0.0, 1.0], 10).draw( &format!("{}", self.player.diag()), &mut glyphs, &c.draw_state, c.transform.trans(10.0, 10.0), g ); } self.scene.draw(c.transform, g); }); } // TODO use an enum to track requested movement direction pub fn on_input(&mut self, inp: Input) { match inp { Input::Press(but) => { match but { Button::Keyboard(Key::Up) => { self.player.dir = (self.player.dir.0, -1.0); } Button::Keyboard(Key::Down) => { self.player.dir = (self.player.dir.0, 1.0); } Button::Keyboard(Key::Left) => { self.player.dir = (-1.0, self.player.dir.1); } Button::Keyboard(Key::Right) => { self.player.dir = (1.0, self.player.dir.1); } _ => {} } } Input::Release(but) => { match but { Button::Keyboard(Key::Up) => { self.player.dir = (self.player.dir.0, 0.0); } Button::Keyboard(Key::Down) => { self.player.dir = (self.player.dir.0, 0.0); } Button::Keyboard(Key::Left) => { self.player.dir = (0.0, self.player.dir.1); } Button::Keyboard(Key::Right) => { self.player.dir = (0.0, self.player.dir.1); } Button::Keyboard(Key::H) => { self.diag =!self.diag; } Button::Keyboard(Key::P) => { self.pause =!self.pause; } _ => {} } } _ => {} } } }
on_draw
identifier_name
lib.rs
extern crate ai_behavior; extern crate find_folder; extern crate gfx_device_gl; extern crate graphics; extern crate nalgebra; extern crate ncollide; extern crate piston_window; extern crate rand; extern crate sprite; extern crate uuid; mod mobs; use gfx_device_gl::Resources; use graphics::Image; use graphics::rectangle::square; use piston_window::*; use mobs::{Hero, Star}; use sprite::*; pub struct Game { scene: Scene<Texture<Resources>>, player: Hero, stars: Vec<Star>, diag: bool, pause: bool, victory: bool, loss: bool, } const TILE_SIZE: u32 = 64; impl Game { pub fn new(w: &mut PistonWindow) -> Game { let mut scene = Scene::new(); let mut stars: Vec<Star> = vec![]; for number in 1..7 { let color = match number % 4 { 1 => "yellow", 2 => "green", 3 => "blue", _ => "pink", }; stars.push(Star::new(color, w, &mut scene)); } let player = Hero::new(w, &mut scene); Game { scene: scene, player: player, stars: stars, diag: false, pause: false, victory: false, loss: false, } } pub fn on_update(&mut self, e: &Input, upd: UpdateArgs, w: &PistonWindow) { if self.pause || self.victory || self.loss { return; } self.scene.event(e); let mut grew = false; for mut star in &mut self.stars { if!star.destroyed && self.player.collides(&star) { star.destroy(&mut self.scene, upd.dt); self.player.grow(&mut self.scene, upd.dt); grew = true; } else { star.mov(w, &mut self.scene, upd.dt); } } if self.stars.iter().all(|star| star.destroyed) { self.victory = true; self.loss = false; return; } if!grew { self.player.shrink(&mut self.scene, upd.dt); } if self.player.size > 0.0 { self.player.mov(w, &mut self.scene, upd.dt); } else { self.loss = true; self.victory = false; } } pub fn on_draw(&mut self, e: &Input, _: RenderArgs, w: &mut PistonWindow) { let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets") .unwrap(); let ref font = assets.join("Fresca-Regular.ttf"); let factory = w.factory.clone(); let mut glyphs = Glyphs::new(font, factory).unwrap(); let Size { height, width } = w.size(); let image = Image::new().rect(square(0.0, 0.0, width as f64)); let bg = Texture::from_path(&mut w.factory, assets.join("bg.png"), Flip::None, &TextureSettings::new()).unwrap(); w.draw_2d(e, |c, g| { clear([1.0, 1.0, 1.0, 1.0], g); let cols = width / TILE_SIZE; // 4:3 means rows will be fractional so add one to cover completely let tile_count = cols * (height / TILE_SIZE + 1); for number in 0..tile_count { let x: f64 = (number % cols * TILE_SIZE).into(); let y: f64 = (number / cols * TILE_SIZE).into(); image.draw(&bg, &Default::default(), c.transform.trans(x, y).zoom(1.0 / cols as f64), g); } if self.victory { text::Text::new_color([0.0, 1.0, 0.0, 1.0], height / 10).draw( "Hurray! You win!", &mut glyphs, &c.draw_state, c.transform.trans(width as f64 / 2.0 - width as f64 / 4.5, height as f64 / 2.0), g ); return; } else if self.loss { text::Text::new_color([0.0, 1.0, 0.0, 1.0], height / 10).draw( "Aw! You lose!", &mut glyphs, &c.draw_state, c.transform.trans(width as f64 / 2.0 - width as f64 / 4.5, height as f64 / 2.0), g ); return; } if self.diag { text::Text::new_color([0.0, 1.0, 0.0, 1.0], 10).draw( &format!("{}", self.player.diag()), &mut glyphs, &c.draw_state, c.transform.trans(10.0, 10.0), g ); } self.scene.draw(c.transform, g); }); } // TODO use an enum to track requested movement direction pub fn on_input(&mut self, inp: Input) { match inp { Input::Press(but) => { match but { Button::Keyboard(Key::Up) => { self.player.dir = (self.player.dir.0, -1.0); } Button::Keyboard(Key::Down) => { self.player.dir = (self.player.dir.0, 1.0); } Button::Keyboard(Key::Left) => { self.player.dir = (-1.0, self.player.dir.1); } Button::Keyboard(Key::Right) => { self.player.dir = (1.0, self.player.dir.1); } _ => {} } } Input::Release(but) => { match but { Button::Keyboard(Key::Up) =>
Button::Keyboard(Key::Down) => { self.player.dir = (self.player.dir.0, 0.0); } Button::Keyboard(Key::Left) => { self.player.dir = (0.0, self.player.dir.1); } Button::Keyboard(Key::Right) => { self.player.dir = (0.0, self.player.dir.1); } Button::Keyboard(Key::H) => { self.diag =!self.diag; } Button::Keyboard(Key::P) => { self.pause =!self.pause; } _ => {} } } _ => {} } } }
{ self.player.dir = (self.player.dir.0, 0.0); }
conditional_block
paste_data.rs
use rocket::Outcome; use rocket::Request; use rocket::data::{self, FromData, Data}; use rocket::http::{Status, ContentType}; use std::io::{Read}; #[derive(Serialize, Deserialize)] pub struct
{ content: String, } impl PasteData { pub fn get_content_cloned(&self) -> String { self.content.clone() } } impl FromData for PasteData { type Error = String; fn from_data(req: &Request, data: Data) -> data::Outcome<Self, String> { let corr_content_type = ContentType::new("text", "plain"); if req.content_type().expect("Could not extract content type")!= corr_content_type { return Outcome::Forward(data); } // Check size //TODO which size? let max_size = 4 * 1024 * 1024 + 6; // +6 because we have "paste=" in it let req_headers = req.headers(); let content_len_it = req_headers.get("Content-Length"); for c in content_len_it { let content_len = c.parse::<u64>().unwrap(); if content_len > max_size { return Outcome::Failure((Status::PayloadTooLarge, "Content too big!".into())); } } // Read data let mut data_string = String::new(); if let Err(e) = data.open().read_to_string(&mut data_string) { return Outcome::Failure((Status::InternalServerError, format!("{:?}", e))); } // remove the "paste=" from the raw data //TODO Problem: paste= must be at end of request let real_data = match data_string.find("paste=") { Some(i) => &data_string[(i + 6)..], None => return Outcome::Failure((Status::BadRequest, "Missing paste parameter.".into())), }; Outcome::Success(PasteData { content: real_data.to_string() }) } }
PasteData
identifier_name
paste_data.rs
use rocket::Outcome; use rocket::Request; use rocket::data::{self, FromData, Data}; use rocket::http::{Status, ContentType}; use std::io::{Read}; #[derive(Serialize, Deserialize)] pub struct PasteData { content: String, } impl PasteData { pub fn get_content_cloned(&self) -> String
} impl FromData for PasteData { type Error = String; fn from_data(req: &Request, data: Data) -> data::Outcome<Self, String> { let corr_content_type = ContentType::new("text", "plain"); if req.content_type().expect("Could not extract content type")!= corr_content_type { return Outcome::Forward(data); } // Check size //TODO which size? let max_size = 4 * 1024 * 1024 + 6; // +6 because we have "paste=" in it let req_headers = req.headers(); let content_len_it = req_headers.get("Content-Length"); for c in content_len_it { let content_len = c.parse::<u64>().unwrap(); if content_len > max_size { return Outcome::Failure((Status::PayloadTooLarge, "Content too big!".into())); } } // Read data let mut data_string = String::new(); if let Err(e) = data.open().read_to_string(&mut data_string) { return Outcome::Failure((Status::InternalServerError, format!("{:?}", e))); } // remove the "paste=" from the raw data //TODO Problem: paste= must be at end of request let real_data = match data_string.find("paste=") { Some(i) => &data_string[(i + 6)..], None => return Outcome::Failure((Status::BadRequest, "Missing paste parameter.".into())), }; Outcome::Success(PasteData { content: real_data.to_string() }) } }
{ self.content.clone() }
identifier_body
paste_data.rs
use rocket::Outcome; use rocket::Request; use rocket::data::{self, FromData, Data}; use rocket::http::{Status, ContentType}; use std::io::{Read}; #[derive(Serialize, Deserialize)] pub struct PasteData { content: String, } impl PasteData { pub fn get_content_cloned(&self) -> String { self.content.clone() } } impl FromData for PasteData { type Error = String; fn from_data(req: &Request, data: Data) -> data::Outcome<Self, String> { let corr_content_type = ContentType::new("text", "plain"); if req.content_type().expect("Could not extract content type")!= corr_content_type { return Outcome::Forward(data); } // Check size //TODO which size? let max_size = 4 * 1024 * 1024 + 6; // +6 because we have "paste=" in it let req_headers = req.headers(); let content_len_it = req_headers.get("Content-Length"); for c in content_len_it { let content_len = c.parse::<u64>().unwrap(); if content_len > max_size { return Outcome::Failure((Status::PayloadTooLarge, "Content too big!".into())); } } // Read data
let mut data_string = String::new(); if let Err(e) = data.open().read_to_string(&mut data_string) { return Outcome::Failure((Status::InternalServerError, format!("{:?}", e))); } // remove the "paste=" from the raw data //TODO Problem: paste= must be at end of request let real_data = match data_string.find("paste=") { Some(i) => &data_string[(i + 6)..], None => return Outcome::Failure((Status::BadRequest, "Missing paste parameter.".into())), }; Outcome::Success(PasteData { content: real_data.to_string() }) } }
random_line_split
onboarding.rs
use std::io; struct Enemy { name: String, dist: i32, } macro_rules! parse_input { ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap()) } fn debugScanInformation(enemys: &Vec<&Enemy>) { eprintln!("Debug Scan Data"); let mut i: i16; i = 0; for e in enemys.iter() { eprintln!("- enemy_{}: {}", i, e.name); eprintln!("- dist_{} : {}", i, e.dist); i = i + 1; } } /** * CodinGame planet is being attacked by slimy insectoid aliens. * <--- * Hint:To protect the planet, you can implement the pseudo-code provided in the statement, below the player. **/ fn
() { // game loop loop { // Vec (list) of enemys let mut enemys: Vec<&Enemy> = Vec::new(); // Enemy 1 let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let enemy_1 = input_line.trim().to_string(); // name of enemy 1 let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let dist_1 = parse_input!(input_line, i32); // distance to enemy 1 let enemy_a = Enemy { name: enemy_1, dist: dist_1}; enemys.push(&enemy_a); // Enemy 2 let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let enemy_2 = input_line.trim().to_string(); // name of enemy 2 let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let dist_2 = parse_input!(input_line, i32); // distance to enemy 2 let enemy_b = Enemy { name: enemy_2, dist: dist_2}; enemys.push(&enemy_b); debugScanInformation(&enemys); // Sort the Vec on the property.dist enemys.sort_by_key(|a| a.dist); println!("{}", enemys[0].name); } }
main
identifier_name
onboarding.rs
use std::io; struct Enemy { name: String, dist: i32, } macro_rules! parse_input { ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap()) } fn debugScanInformation(enemys: &Vec<&Enemy>)
/** * CodinGame planet is being attacked by slimy insectoid aliens. * <--- * Hint:To protect the planet, you can implement the pseudo-code provided in the statement, below the player. **/ fn main() { // game loop loop { // Vec (list) of enemys let mut enemys: Vec<&Enemy> = Vec::new(); // Enemy 1 let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let enemy_1 = input_line.trim().to_string(); // name of enemy 1 let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let dist_1 = parse_input!(input_line, i32); // distance to enemy 1 let enemy_a = Enemy { name: enemy_1, dist: dist_1}; enemys.push(&enemy_a); // Enemy 2 let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let enemy_2 = input_line.trim().to_string(); // name of enemy 2 let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let dist_2 = parse_input!(input_line, i32); // distance to enemy 2 let enemy_b = Enemy { name: enemy_2, dist: dist_2}; enemys.push(&enemy_b); debugScanInformation(&enemys); // Sort the Vec on the property.dist enemys.sort_by_key(|a| a.dist); println!("{}", enemys[0].name); } }
{ eprintln!("Debug Scan Data"); let mut i: i16; i = 0; for e in enemys.iter() { eprintln!("- enemy_{}: {}", i, e.name); eprintln!("- dist_{} : {}", i, e.dist); i = i + 1; } }
identifier_body
onboarding.rs
use std::io; struct Enemy { name: String, dist: i32, } macro_rules! parse_input { ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap()) } fn debugScanInformation(enemys: &Vec<&Enemy>) { eprintln!("Debug Scan Data"); let mut i: i16; i = 0; for e in enemys.iter() { eprintln!("- enemy_{}: {}", i, e.name); eprintln!("- dist_{} : {}", i, e.dist);
} /** * CodinGame planet is being attacked by slimy insectoid aliens. * <--- * Hint:To protect the planet, you can implement the pseudo-code provided in the statement, below the player. **/ fn main() { // game loop loop { // Vec (list) of enemys let mut enemys: Vec<&Enemy> = Vec::new(); // Enemy 1 let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let enemy_1 = input_line.trim().to_string(); // name of enemy 1 let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let dist_1 = parse_input!(input_line, i32); // distance to enemy 1 let enemy_a = Enemy { name: enemy_1, dist: dist_1}; enemys.push(&enemy_a); // Enemy 2 let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let enemy_2 = input_line.trim().to_string(); // name of enemy 2 let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let dist_2 = parse_input!(input_line, i32); // distance to enemy 2 let enemy_b = Enemy { name: enemy_2, dist: dist_2}; enemys.push(&enemy_b); debugScanInformation(&enemys); // Sort the Vec on the property.dist enemys.sort_by_key(|a| a.dist); println!("{}", enemys[0].name); } }
i = i + 1; }
random_line_split
unwind-rec2.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. // error-pattern:fail fn
() -> ~[int] { ~[0,0,0,0,0,0,0] } fn build2() -> ~[int] { fail!(); } struct Blk { node: ~[int], span: ~[int] } fn main() { let _blk = Blk { node: build1(), span: build2() }; }
build1
identifier_name
unwind-rec2.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
// error-pattern:fail fn build1() -> ~[int] { ~[0,0,0,0,0,0,0] } fn build2() -> ~[int] { fail!(); } struct Blk { node: ~[int], span: ~[int] } fn main() { let _blk = Blk { node: build1(), span: build2() }; }
// 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.
random_line_split
unwind-rec2.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. // error-pattern:fail fn build1() -> ~[int] { ~[0,0,0,0,0,0,0] } fn build2() -> ~[int]
struct Blk { node: ~[int], span: ~[int] } fn main() { let _blk = Blk { node: build1(), span: build2() }; }
{ fail!(); }
identifier_body
cssnamespacerule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding; use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding::CSSNamespaceRuleMethods; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylesheets::NamespaceRule; #[dom_struct] pub struct CSSNamespaceRule { cssrule: CSSRule, #[ignore_heap_size_of = "Arc"] namespacerule: Arc<Locked<NamespaceRule>>, } impl CSSNamespaceRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, namespacerule: Arc<Locked<NamespaceRule>>) -> CSSNamespaceRule { CSSNamespaceRule { cssrule: CSSRule::new_inherited(parent_stylesheet), namespacerule: namespacerule, } }
namespacerule: Arc<Locked<NamespaceRule>>) -> DomRoot<CSSNamespaceRule> { reflect_dom_object(box CSSNamespaceRule::new_inherited(parent_stylesheet, namespacerule), window, CSSNamespaceRuleBinding::Wrap) } } impl CSSNamespaceRuleMethods for CSSNamespaceRule { // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-prefix fn Prefix(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); self.namespacerule.read_with(&guard).prefix .as_ref().map(|s| s.to_string().into()) .unwrap_or(DOMString::new()) } // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-namespaceuri fn NamespaceURI(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); (*self.namespacerule.read_with(&guard).url).into() } } impl SpecificCSSRule for CSSNamespaceRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::NAMESPACE_RULE } fn get_css(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); self.namespacerule.read_with(&guard).to_css_string(&guard).into() } }
#[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
random_line_split
cssnamespacerule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding; use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding::CSSNamespaceRuleMethods; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylesheets::NamespaceRule; #[dom_struct] pub struct CSSNamespaceRule { cssrule: CSSRule, #[ignore_heap_size_of = "Arc"] namespacerule: Arc<Locked<NamespaceRule>>, } impl CSSNamespaceRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, namespacerule: Arc<Locked<NamespaceRule>>) -> CSSNamespaceRule { CSSNamespaceRule { cssrule: CSSRule::new_inherited(parent_stylesheet), namespacerule: namespacerule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, namespacerule: Arc<Locked<NamespaceRule>>) -> DomRoot<CSSNamespaceRule> { reflect_dom_object(box CSSNamespaceRule::new_inherited(parent_stylesheet, namespacerule), window, CSSNamespaceRuleBinding::Wrap) } } impl CSSNamespaceRuleMethods for CSSNamespaceRule { // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-prefix fn Prefix(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); self.namespacerule.read_with(&guard).prefix .as_ref().map(|s| s.to_string().into()) .unwrap_or(DOMString::new()) } // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-namespaceuri fn NamespaceURI(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); (*self.namespacerule.read_with(&guard).url).into() } } impl SpecificCSSRule for CSSNamespaceRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::NAMESPACE_RULE } fn
(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); self.namespacerule.read_with(&guard).to_css_string(&guard).into() } }
get_css
identifier_name
cssnamespacerule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding; use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding::CSSNamespaceRuleMethods; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylesheets::NamespaceRule; #[dom_struct] pub struct CSSNamespaceRule { cssrule: CSSRule, #[ignore_heap_size_of = "Arc"] namespacerule: Arc<Locked<NamespaceRule>>, } impl CSSNamespaceRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, namespacerule: Arc<Locked<NamespaceRule>>) -> CSSNamespaceRule { CSSNamespaceRule { cssrule: CSSRule::new_inherited(parent_stylesheet), namespacerule: namespacerule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, namespacerule: Arc<Locked<NamespaceRule>>) -> DomRoot<CSSNamespaceRule> { reflect_dom_object(box CSSNamespaceRule::new_inherited(parent_stylesheet, namespacerule), window, CSSNamespaceRuleBinding::Wrap) } } impl CSSNamespaceRuleMethods for CSSNamespaceRule { // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-prefix fn Prefix(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); self.namespacerule.read_with(&guard).prefix .as_ref().map(|s| s.to_string().into()) .unwrap_or(DOMString::new()) } // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-namespaceuri fn NamespaceURI(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); (*self.namespacerule.read_with(&guard).url).into() } } impl SpecificCSSRule for CSSNamespaceRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::NAMESPACE_RULE } fn get_css(&self) -> DOMString
}
{ let guard = self.cssrule.shared_lock().read(); self.namespacerule.read_with(&guard).to_css_string(&guard).into() }
identifier_body
mod.rs
type FontSize = u32; /// A context for building some **Text**. pub struct Builder<'a> { text: Cow<'a, str>, layout_builder: layout::Builder, } /// An instance of some multi-line text and its layout. #[derive(Clone)] pub struct Text<'a> { text: Cow<'a, str>, font: Font, layout: Layout, line_infos: Vec<line::Info>, rect: geom::Rect, } /// An iterator yielding each line within the given `text` as a new `&str`, where the start and end /// indices into each line are provided by the given iterator. #[derive(Clone)] pub struct Lines<'a, I> { text: &'a str, ranges: I, } /// An alias for the line info iterator yielded by `Text::line_infos`. pub type TextLineInfos<'a> = line::Infos<'a, line::NextBreakFnPtr>; /// An alias for the line iterator yielded by `Text::lines`. pub type TextLines<'a> = Lines< 'a, std::iter::Map<std::slice::Iter<'a, line::Info>, fn(&line::Info) -> std::ops::Range<usize>>, >; /// An alias for the line rect iterator used internally within the `Text::line_rects` iterator. type LineRects<'a> = line::Rects<std::iter::Cloned<std::slice::Iter<'a, line::Info>>>; /// An alias for the line rect iterator yielded by `Text::line_rects`. #[derive(Clone)] pub struct TextLineRects<'a> { line_rects: LineRects<'a>, offset: geom::Vector2, } /// An alias for the iterator yielded by `Text::lines_with_rects`. pub type TextLinesWithRects<'a> = std::iter::Zip<TextLines<'a>, TextLineRects<'a>>; /// An alias for the iterator yielded by `Text::glyphs_per_line`. pub type TextGlyphsPerLine<'a> = glyph::RectsPerLine<'a, TextLinesWithRects<'a>>; /// An alias for the iterator yielded by `Text::glyphs`. pub type TextGlyphs<'a> = std::iter::FlatMap< TextGlyphsPerLine<'a>, glyph::Rects<'a, 'a>, fn(glyph::Rects<'a, 'a>) -> glyph::Rects<'a, 'a>, >; /// Alignment along an axis. #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)] pub enum Align { Start, Middle, End, } /// A type used for referring to typographic alignment of `Text`. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Justify { /// Align text to the start of the bounding `Rect`'s *x* axis. Left, /// Symmetrically align text along the *y* axis. Center, /// Align text to the end of the bounding `Rect`'s *x* axis. Right, // /// Align wrapped text to both the start and end of the bounding `Rect`s *x* axis. // /// // /// Extra space is added between words in order to achieve this alignment. // TODO: Full, } /// The way in which text should wrap around the width. #[derive(Copy, Clone, Debug, PartialEq)] pub enum Wrap { /// Wrap at the first character that exceeds the width. Character, /// Wrap at the first word that exceeds the width. Whitespace, } impl<'a> From<Cow<'a, str>> for Builder<'a> { fn from(text: Cow<'a, str>) -> Self { let layout_builder = Default::default(); Builder { text, layout_builder, } } } impl<'a> From<&'a str> for Builder<'a> { fn from(s: &'a str) -> Self { let text = Cow::Borrowed(s); Self::from(text) } } impl From<String> for Builder<'static> { fn from(s: String) -> Self { let text = Cow::Owned(s); Self::from(text) } } impl<'a> Builder<'a> { /// Apply the given function to the inner text layout. fn map_layout<F>(mut self, map: F) -> Self where F: FnOnce(layout::Builder) -> layout::Builder, { self.layout_builder = map(self.layout_builder); self } /// The font size to use for the text. pub fn font_size(self, size: FontSize) -> Self { self.map_layout(|l| l.font_size(size)) } /// Specify whether or not text should be wrapped around some width and how to do so. /// /// The default value is `DEFAULT_LINE_WRAP`. pub fn line_wrap(self, line_wrap: Option<Wrap>) -> Self { self.map_layout(|l| l.line_wrap(line_wrap)) } /// Specify that the **Text** should not wrap lines around the width. /// /// Shorthand for `builder.line_wrap(None)`. pub fn no_line_wrap(self) -> Self { self.map_layout(|l| l.no_line_wrap()) } /// Line wrap the **Text** at the beginning of the first word that exceeds the width. /// /// Shorthand for `builder.line_wrap(Some(Wrap::Whitespace))`. pub fn wrap_by_word(self) -> Self { self.map_layout(|l| l.wrap_by_word()) } /// Line wrap the **Text** at the beginning of the first character that exceeds the width. /// /// Shorthand for `builder.line_wrap(Some(Wrap::Character))`. pub fn wrap_by_character(self) -> Self { self.map_layout(|l| l.wrap_by_character()) } /// A method for specifying the `Font` used for displaying the `Text`. pub fn font(self, font: Font) -> Self { self.map_layout(|l| l.font(font)) } /// Describe the end along the *x* axis to which the text should be aligned. pub fn justify(self, justify: Justify) -> Self { self.map_layout(|l| l.justify(justify)) } /// Align the text to the left of its bounding **Rect**'s *x* axis range. pub fn left_justify(self) -> Self { self.map_layout(|l| l.left_justify()) } /// Align the text to the middle of its bounding **Rect**'s *x* axis range. pub fn center_justify(self) -> Self { self.map_layout(|l| l.center_justify()) } /// Align the text to the right of its bounding **Rect**'s *x* axis range. pub fn right_justify(self) -> Self { self.map_layout(|l| l.right_justify()) } /// Specify how much vertical space should separate each line of text. pub fn line_spacing(self, spacing: Scalar) -> Self { self.map_layout(|l| l.line_spacing(spacing)) }
} /// Align the top edge of the text with the top edge of its bounding rectangle. pub fn align_top(self) -> Self { self.map_layout(|l| l.align_top()) } /// Align the middle of the text with the middle of the bounding rect along the y axis.. /// /// This is the default behaviour. pub fn align_middle_y(self) -> Self { self.map_layout(|l| l.align_middle_y()) } /// Align the bottom edge of the text with the bottom edge of its bounding rectangle. pub fn align_bottom(self) -> Self { self.map_layout(|l| l.align_bottom()) } /// Set all the parameters via an existing `Layout` pub fn layout(self, layout: &Layout) -> Self { self.map_layout(|l| l.layout(layout)) } /// Build the text. /// /// This iterates over the text in order to pre-calculates the text's multi-line information /// using the `line::infos` function. /// /// The given `rect` will be used for applying the layout including text alignment, positioning /// of text, multi-line wrapping, etc, pub fn build(self, rect: geom::Rect) -> Text<'a> { let text = self.text; let layout = self.layout_builder.build(); #[allow(unreachable_code)] let font = layout.font.clone().unwrap_or_else(|| { #[cfg(feature = "notosans")] { return font::default_notosans(); } let assets = crate::app::find_assets_path() .expect("failed to detect the assets directory when searching for a default font"); font::default(&assets).expect("failed to detect a default font") }); let max_width = rect.w(); let line_infos = line::infos_maybe_wrapped(&text, &font, layout.font_size, layout.line_wrap, max_width) .collect(); Text { text, font, layout, line_infos, rect, } } } impl<'a> Text<'a> { /// Produce an iterator yielding information about each line. pub fn line_infos(&self) -> &[line::Info] { &self.line_infos } /// The full string of text as a slice. pub fn text(&self) -> &str { &self.text } /// The layout parameters for this text instance. pub fn layout(&self) -> &Layout { &self.layout } /// The font used for this text instance. pub fn font(&self) -> &Font { &self.font } /// The number of lines in the text. pub fn num_lines(&self) -> usize { self.line_infos.len() } /// The rectangle used to layout and build the text instance. /// /// This is the same `Rect` that was passed to the `text::Builder::build` method. pub fn layout_rect(&self) -> geom::Rect { self.rect } /// The rectangle that describes the min and max bounds along each axis reached by the text. pub fn bounding_rect(&self) -> geom::Rect { let mut r = self.bounding_rect_by_lines(); let info = match self.line_infos.first() { None => return geom::Rect::from_w_h(0.0, 0.0), Some(info) => info, }; let line_h = self.layout.font_size as Scalar; r.y.end -= line_h - info.height; r } /// The rectangle that describes the min and max bounds along each axis reached by the text. /// /// This is similar to `bounding_rect` but assumes that all lines have a height equal to /// `font_size`, rather than using the exact height. pub fn bounding_rect_by_lines(&self) -> geom::Rect { let mut lrs = self.line_rects(); let lr = match lrs.next() { None => return geom::Rect::from_w_h(0.0, 0.0), Some(lr) => lr, }; lrs.fold(lr, |acc, lr| { let x = geom::Range::new(acc.x.start.min(lr.x.start), acc.x.end.max(lr.x.end)); let y = geom::Range::new(acc.y.start.min(lr.y.start), acc.y.end.max(lr.y.end)); geom::Rect { x, y } }) } /// The width of the widest line of text. pub fn width(&self) -> Scalar { self.line_infos .iter() .fold(0.0, |max, info| max.max(info.width)) } /// The exact height of the full text accounting for font size and line spacing.. pub fn height(&self) -> Scalar { let info = match self.line_infos.first() { None => return 0.0, Some(info) => info, }; exact_height( info.height, self.num_lines(), self.layout.font_size, self.layout.line_spacing, ) } /// Determine the total height of a block of text with the given number of lines, font size and /// `line_spacing` (the space that separates each line of text). /// /// The height of all lines of text are assumed to match the `font_size`. If looking for the exact /// height, see the `exact_height` function. pub fn height_by_lines(&self) -> Scalar { height_by_lines( self.num_lines(), self.layout.font_size, self.layout.line_spacing, ) } /// Produce an iterator yielding each wrapped line within the **Text**. pub fn lines(&self) -> TextLines { fn info_byte_range(info: &line::Info) -> std::ops::Range<usize> { info.byte_range() } lines(&self.text, self.line_infos.iter().map(info_byte_range)) } /// The bounding rectangle for each line. pub fn line_rects(&self) -> TextLineRects { let offset = self.position_offset(); let line_rects = line::rects( self.line_infos.iter().cloned(), self.layout.font_size, self.rect.w(), self.layout.justify, self.layout.line_spacing, ); TextLineRects { line_rects, offset } } /// Produce an iterator yielding all lines of text alongside their bounding rects. pub fn lines_with_rects(&self) -> TextLinesWithRects { self.lines().zip(self.line_rects()) } /// Produce an iterator yielding iterators yielding every glyph alongside its bounding rect for /// each line. pub fn glyphs_per_line(&self) -> TextGlyphsPerLine { glyph::rects_per_line(self.lines_with_rects(), &self.font, self.layout.font_size) } /// Produce an iterator yielding every glyph alongside its bounding rect. /// /// This is the "flattened" version of the `glyphs_per_line` method. pub fn glyphs(&self) -> TextGlyphs { self.glyphs_per_line().flat_map(std::convert::identity) } /// Produce an iterator yielding the path events for every glyph in every line. pub fn path_events<'b>(&'b self) -> impl 'b + Iterator<Item = lyon::path::PathEvent> { use lyon::path::PathEvent; // Translate the given lyon point by the given vector. fn trans_lyon_point(p: &lyon::math::Point, v: geom::Vector2) -> lyon::math::Point { lyon::math::point(p.x + v.x, p.y + v.y) } // Translate the given path event in 2D space. fn trans_path_event(e: &PathEvent, v: geom::Vector2) -> PathEvent { match *e { PathEvent::Begin { ref at } => PathEvent::Begin { at: trans_lyon_point(at, v), }, PathEvent::Line { ref from, ref to } => PathEvent::Line { from: trans_lyon_point(from, v), to: trans_lyon_point(to, v), }, PathEvent::Quadratic { ref from, ref ctrl, ref to, } => PathEvent::Quadratic { from: trans_lyon_point(from, v), ctrl: trans_lyon_point(ctrl, v), to: trans_lyon_point(to, v), }, PathEvent::Cubic { ref from, ref ctrl1, ref ctrl2, ref to, } => PathEvent::Cubic { from: trans_lyon_point(from, v), ctrl1: trans_lyon_point(ctrl1, v), ctrl2: trans_lyon_point(ctrl2, v), to: trans_lyon_point(to, v), }, PathEvent::End { ref last, ref first, ref close, } => PathEvent::End { last: trans_lyon_point(last, v), first: trans_lyon_point(first, v), close: *close, }, } } self.glyphs().flat_map(|(g, r)| { glyph::path_events(g) .into_iter() .flat_map(|es| es) .map(move |e| trans_path_event(&e, r.bottom_left())) }) } /// Produce an iterator yielding positioned rusttype glyphs ready for caching. /// /// The window dimensions (in logical space) and scale_factor are required to transform glyph /// positions into rusttype's pixel-space, ready for caching into the rusttype glyph cache /// pixel buffer. pub fn rt_glyphs<'b: 'a>( &'b self, window_size: geom::Vector2, scale_factor: Scalar, ) -> impl 'a + 'b + Iterator<Item = PositionedGlyph> { rt_positioned_glyphs( self.lines_with_rects(), &self.font, self.layout.font_size, window_size, scale_factor, ) } /// Converts this `Text` instance into an instance that owns the inner text string. pub fn into_owned(self) -> Text<'static> { let Text { text, font, layout, line_infos, rect, } = self; let text = Cow::Owned(text.into_owned()); Text { text, font, layout, line_infos, rect, } } fn position_offset(&self) -> geom::Vector2 { position_offset( self.num_lines(), self.layout.font_size, self.layout.line_spacing, self.rect, self.layout.y_align, ) } } impl<'a, I> Iterator for Lines<'a, I> where I: Iterator<Item = std::ops::Range<usize>>, { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { let Lines { text, ref mut ranges, } = *self; ranges.next().map(|range| &text[range]) } } impl<'a> Iterator for TextLineRects<'a> { type Item = geom::Rect; fn next(&mut self) -> Option<Self::Item> { self.line_rects.next().map(|r| r.shift(self.offset)) } } /// Determine the total height of a block of text with the given number of lines, font size and /// `line_spacing` (the space that separates each line of text). /// /// The height of all lines of text are assumed to match the `font_size`. If looking for the exact /// height, see the `exact_height` function. pub fn height_by_lines(num_lines: usize, font_size: FontSize, line_spacing: Scalar) -> Scalar { if num_lines > 0 { num_lines as Scalar * font_size as Scalar + (num_lines - 1) as Scalar * line_spacing } else { 0.0 } } /// Determine the exact height of a block of text. /// /// The `first_line_height` can be retrieved via its `line::Info` which can be retrieved via the /// first element of a `line_infos` iterator. pub fn exact_height( first_line_height: Scalar, num_lines: usize, font_size: FontSize, line_spacing: Scalar, ) -> Scalar { if num_lines > 0 { let lt_num_lines = num_lines - 1; let other_lines_height = lt_num_lines as Scalar * font_size as Scalar; let space_height = lt_num_lines as Scalar * line_spacing; first_line_height + other_lines_height + space_height } else { 0.0 } } /// Produce an iterator yielding each line within the given `text` as a new `&str`, where the /// start and end indices into each line are provided by the given iterator. pub fn lines<I>(text: &str, ranges: I) -> Lines<I> where I: Iterator<Item = std::ops::Range<usize>>, { Lines { text: text, ranges: ranges, } } /// The position offset required to shift the associated text into the given bounding rectangle. /// /// This function assumes the `max_width` used to produce the `line_infos` is equal to the given /// `bounding_rect` max width. pub fn position_offset( num_lines: usize, font_size: FontSize, line_spacing: f32, bounding_rect: geom::Rect, y_align: Align, ) -> geom::Vector2 { let x_offset = bounding_rect.x.start; let y_offset = { // Calculate the `y` `Range` of the first line `Rect`. let total_text_height = height_by_lines(num_lines, font_size, line_spacing); let total_text_y_range = geom::Range::new(0.0, total_text_height); let total_text_y = match y_align { Align::Start => total_text_y_range.align_start_of(bounding_rect.y), Align::Middle => total_text_y_range.align_middle_of(bounding_rect.y), Align::End => total_text_y_range.align_end_of(bounding_rect.y), }; total_text_y.end }; geom::vec2(x_offset, y_offset) } /// Produce the position of each glyph ready for the rusttype glyph cache. /// /// Window dimensions are expected in logical coordinates. pub fn rt_positioned
/// Specify how the whole text should be aligned along the y axis of its bounding rectangle pub fn y_align(self, align: Align) -> Self { self.map_layout(|l| l.y_align(align))
random_line_split
mod.rs
FontSize = u32; /// A context for building some **Text**. pub struct
<'a> { text: Cow<'a, str>, layout_builder: layout::Builder, } /// An instance of some multi-line text and its layout. #[derive(Clone)] pub struct Text<'a> { text: Cow<'a, str>, font: Font, layout: Layout, line_infos: Vec<line::Info>, rect: geom::Rect, } /// An iterator yielding each line within the given `text` as a new `&str`, where the start and end /// indices into each line are provided by the given iterator. #[derive(Clone)] pub struct Lines<'a, I> { text: &'a str, ranges: I, } /// An alias for the line info iterator yielded by `Text::line_infos`. pub type TextLineInfos<'a> = line::Infos<'a, line::NextBreakFnPtr>; /// An alias for the line iterator yielded by `Text::lines`. pub type TextLines<'a> = Lines< 'a, std::iter::Map<std::slice::Iter<'a, line::Info>, fn(&line::Info) -> std::ops::Range<usize>>, >; /// An alias for the line rect iterator used internally within the `Text::line_rects` iterator. type LineRects<'a> = line::Rects<std::iter::Cloned<std::slice::Iter<'a, line::Info>>>; /// An alias for the line rect iterator yielded by `Text::line_rects`. #[derive(Clone)] pub struct TextLineRects<'a> { line_rects: LineRects<'a>, offset: geom::Vector2, } /// An alias for the iterator yielded by `Text::lines_with_rects`. pub type TextLinesWithRects<'a> = std::iter::Zip<TextLines<'a>, TextLineRects<'a>>; /// An alias for the iterator yielded by `Text::glyphs_per_line`. pub type TextGlyphsPerLine<'a> = glyph::RectsPerLine<'a, TextLinesWithRects<'a>>; /// An alias for the iterator yielded by `Text::glyphs`. pub type TextGlyphs<'a> = std::iter::FlatMap< TextGlyphsPerLine<'a>, glyph::Rects<'a, 'a>, fn(glyph::Rects<'a, 'a>) -> glyph::Rects<'a, 'a>, >; /// Alignment along an axis. #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)] pub enum Align { Start, Middle, End, } /// A type used for referring to typographic alignment of `Text`. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Justify { /// Align text to the start of the bounding `Rect`'s *x* axis. Left, /// Symmetrically align text along the *y* axis. Center, /// Align text to the end of the bounding `Rect`'s *x* axis. Right, // /// Align wrapped text to both the start and end of the bounding `Rect`s *x* axis. // /// // /// Extra space is added between words in order to achieve this alignment. // TODO: Full, } /// The way in which text should wrap around the width. #[derive(Copy, Clone, Debug, PartialEq)] pub enum Wrap { /// Wrap at the first character that exceeds the width. Character, /// Wrap at the first word that exceeds the width. Whitespace, } impl<'a> From<Cow<'a, str>> for Builder<'a> { fn from(text: Cow<'a, str>) -> Self { let layout_builder = Default::default(); Builder { text, layout_builder, } } } impl<'a> From<&'a str> for Builder<'a> { fn from(s: &'a str) -> Self { let text = Cow::Borrowed(s); Self::from(text) } } impl From<String> for Builder<'static> { fn from(s: String) -> Self { let text = Cow::Owned(s); Self::from(text) } } impl<'a> Builder<'a> { /// Apply the given function to the inner text layout. fn map_layout<F>(mut self, map: F) -> Self where F: FnOnce(layout::Builder) -> layout::Builder, { self.layout_builder = map(self.layout_builder); self } /// The font size to use for the text. pub fn font_size(self, size: FontSize) -> Self { self.map_layout(|l| l.font_size(size)) } /// Specify whether or not text should be wrapped around some width and how to do so. /// /// The default value is `DEFAULT_LINE_WRAP`. pub fn line_wrap(self, line_wrap: Option<Wrap>) -> Self { self.map_layout(|l| l.line_wrap(line_wrap)) } /// Specify that the **Text** should not wrap lines around the width. /// /// Shorthand for `builder.line_wrap(None)`. pub fn no_line_wrap(self) -> Self { self.map_layout(|l| l.no_line_wrap()) } /// Line wrap the **Text** at the beginning of the first word that exceeds the width. /// /// Shorthand for `builder.line_wrap(Some(Wrap::Whitespace))`. pub fn wrap_by_word(self) -> Self { self.map_layout(|l| l.wrap_by_word()) } /// Line wrap the **Text** at the beginning of the first character that exceeds the width. /// /// Shorthand for `builder.line_wrap(Some(Wrap::Character))`. pub fn wrap_by_character(self) -> Self { self.map_layout(|l| l.wrap_by_character()) } /// A method for specifying the `Font` used for displaying the `Text`. pub fn font(self, font: Font) -> Self { self.map_layout(|l| l.font(font)) } /// Describe the end along the *x* axis to which the text should be aligned. pub fn justify(self, justify: Justify) -> Self { self.map_layout(|l| l.justify(justify)) } /// Align the text to the left of its bounding **Rect**'s *x* axis range. pub fn left_justify(self) -> Self { self.map_layout(|l| l.left_justify()) } /// Align the text to the middle of its bounding **Rect**'s *x* axis range. pub fn center_justify(self) -> Self { self.map_layout(|l| l.center_justify()) } /// Align the text to the right of its bounding **Rect**'s *x* axis range. pub fn right_justify(self) -> Self { self.map_layout(|l| l.right_justify()) } /// Specify how much vertical space should separate each line of text. pub fn line_spacing(self, spacing: Scalar) -> Self { self.map_layout(|l| l.line_spacing(spacing)) } /// Specify how the whole text should be aligned along the y axis of its bounding rectangle pub fn y_align(self, align: Align) -> Self { self.map_layout(|l| l.y_align(align)) } /// Align the top edge of the text with the top edge of its bounding rectangle. pub fn align_top(self) -> Self { self.map_layout(|l| l.align_top()) } /// Align the middle of the text with the middle of the bounding rect along the y axis.. /// /// This is the default behaviour. pub fn align_middle_y(self) -> Self { self.map_layout(|l| l.align_middle_y()) } /// Align the bottom edge of the text with the bottom edge of its bounding rectangle. pub fn align_bottom(self) -> Self { self.map_layout(|l| l.align_bottom()) } /// Set all the parameters via an existing `Layout` pub fn layout(self, layout: &Layout) -> Self { self.map_layout(|l| l.layout(layout)) } /// Build the text. /// /// This iterates over the text in order to pre-calculates the text's multi-line information /// using the `line::infos` function. /// /// The given `rect` will be used for applying the layout including text alignment, positioning /// of text, multi-line wrapping, etc, pub fn build(self, rect: geom::Rect) -> Text<'a> { let text = self.text; let layout = self.layout_builder.build(); #[allow(unreachable_code)] let font = layout.font.clone().unwrap_or_else(|| { #[cfg(feature = "notosans")] { return font::default_notosans(); } let assets = crate::app::find_assets_path() .expect("failed to detect the assets directory when searching for a default font"); font::default(&assets).expect("failed to detect a default font") }); let max_width = rect.w(); let line_infos = line::infos_maybe_wrapped(&text, &font, layout.font_size, layout.line_wrap, max_width) .collect(); Text { text, font, layout, line_infos, rect, } } } impl<'a> Text<'a> { /// Produce an iterator yielding information about each line. pub fn line_infos(&self) -> &[line::Info] { &self.line_infos } /// The full string of text as a slice. pub fn text(&self) -> &str { &self.text } /// The layout parameters for this text instance. pub fn layout(&self) -> &Layout { &self.layout } /// The font used for this text instance. pub fn font(&self) -> &Font { &self.font } /// The number of lines in the text. pub fn num_lines(&self) -> usize { self.line_infos.len() } /// The rectangle used to layout and build the text instance. /// /// This is the same `Rect` that was passed to the `text::Builder::build` method. pub fn layout_rect(&self) -> geom::Rect { self.rect } /// The rectangle that describes the min and max bounds along each axis reached by the text. pub fn bounding_rect(&self) -> geom::Rect { let mut r = self.bounding_rect_by_lines(); let info = match self.line_infos.first() { None => return geom::Rect::from_w_h(0.0, 0.0), Some(info) => info, }; let line_h = self.layout.font_size as Scalar; r.y.end -= line_h - info.height; r } /// The rectangle that describes the min and max bounds along each axis reached by the text. /// /// This is similar to `bounding_rect` but assumes that all lines have a height equal to /// `font_size`, rather than using the exact height. pub fn bounding_rect_by_lines(&self) -> geom::Rect { let mut lrs = self.line_rects(); let lr = match lrs.next() { None => return geom::Rect::from_w_h(0.0, 0.0), Some(lr) => lr, }; lrs.fold(lr, |acc, lr| { let x = geom::Range::new(acc.x.start.min(lr.x.start), acc.x.end.max(lr.x.end)); let y = geom::Range::new(acc.y.start.min(lr.y.start), acc.y.end.max(lr.y.end)); geom::Rect { x, y } }) } /// The width of the widest line of text. pub fn width(&self) -> Scalar { self.line_infos .iter() .fold(0.0, |max, info| max.max(info.width)) } /// The exact height of the full text accounting for font size and line spacing.. pub fn height(&self) -> Scalar { let info = match self.line_infos.first() { None => return 0.0, Some(info) => info, }; exact_height( info.height, self.num_lines(), self.layout.font_size, self.layout.line_spacing, ) } /// Determine the total height of a block of text with the given number of lines, font size and /// `line_spacing` (the space that separates each line of text). /// /// The height of all lines of text are assumed to match the `font_size`. If looking for the exact /// height, see the `exact_height` function. pub fn height_by_lines(&self) -> Scalar { height_by_lines( self.num_lines(), self.layout.font_size, self.layout.line_spacing, ) } /// Produce an iterator yielding each wrapped line within the **Text**. pub fn lines(&self) -> TextLines { fn info_byte_range(info: &line::Info) -> std::ops::Range<usize> { info.byte_range() } lines(&self.text, self.line_infos.iter().map(info_byte_range)) } /// The bounding rectangle for each line. pub fn line_rects(&self) -> TextLineRects { let offset = self.position_offset(); let line_rects = line::rects( self.line_infos.iter().cloned(), self.layout.font_size, self.rect.w(), self.layout.justify, self.layout.line_spacing, ); TextLineRects { line_rects, offset } } /// Produce an iterator yielding all lines of text alongside their bounding rects. pub fn lines_with_rects(&self) -> TextLinesWithRects { self.lines().zip(self.line_rects()) } /// Produce an iterator yielding iterators yielding every glyph alongside its bounding rect for /// each line. pub fn glyphs_per_line(&self) -> TextGlyphsPerLine { glyph::rects_per_line(self.lines_with_rects(), &self.font, self.layout.font_size) } /// Produce an iterator yielding every glyph alongside its bounding rect. /// /// This is the "flattened" version of the `glyphs_per_line` method. pub fn glyphs(&self) -> TextGlyphs { self.glyphs_per_line().flat_map(std::convert::identity) } /// Produce an iterator yielding the path events for every glyph in every line. pub fn path_events<'b>(&'b self) -> impl 'b + Iterator<Item = lyon::path::PathEvent> { use lyon::path::PathEvent; // Translate the given lyon point by the given vector. fn trans_lyon_point(p: &lyon::math::Point, v: geom::Vector2) -> lyon::math::Point { lyon::math::point(p.x + v.x, p.y + v.y) } // Translate the given path event in 2D space. fn trans_path_event(e: &PathEvent, v: geom::Vector2) -> PathEvent { match *e { PathEvent::Begin { ref at } => PathEvent::Begin { at: trans_lyon_point(at, v), }, PathEvent::Line { ref from, ref to } => PathEvent::Line { from: trans_lyon_point(from, v), to: trans_lyon_point(to, v), }, PathEvent::Quadratic { ref from, ref ctrl, ref to, } => PathEvent::Quadratic { from: trans_lyon_point(from, v), ctrl: trans_lyon_point(ctrl, v), to: trans_lyon_point(to, v), }, PathEvent::Cubic { ref from, ref ctrl1, ref ctrl2, ref to, } => PathEvent::Cubic { from: trans_lyon_point(from, v), ctrl1: trans_lyon_point(ctrl1, v), ctrl2: trans_lyon_point(ctrl2, v), to: trans_lyon_point(to, v), }, PathEvent::End { ref last, ref first, ref close, } => PathEvent::End { last: trans_lyon_point(last, v), first: trans_lyon_point(first, v), close: *close, }, } } self.glyphs().flat_map(|(g, r)| { glyph::path_events(g) .into_iter() .flat_map(|es| es) .map(move |e| trans_path_event(&e, r.bottom_left())) }) } /// Produce an iterator yielding positioned rusttype glyphs ready for caching. /// /// The window dimensions (in logical space) and scale_factor are required to transform glyph /// positions into rusttype's pixel-space, ready for caching into the rusttype glyph cache /// pixel buffer. pub fn rt_glyphs<'b: 'a>( &'b self, window_size: geom::Vector2, scale_factor: Scalar, ) -> impl 'a + 'b + Iterator<Item = PositionedGlyph> { rt_positioned_glyphs( self.lines_with_rects(), &self.font, self.layout.font_size, window_size, scale_factor, ) } /// Converts this `Text` instance into an instance that owns the inner text string. pub fn into_owned(self) -> Text<'static> { let Text { text, font, layout, line_infos, rect, } = self; let text = Cow::Owned(text.into_owned()); Text { text, font, layout, line_infos, rect, } } fn position_offset(&self) -> geom::Vector2 { position_offset( self.num_lines(), self.layout.font_size, self.layout.line_spacing, self.rect, self.layout.y_align, ) } } impl<'a, I> Iterator for Lines<'a, I> where I: Iterator<Item = std::ops::Range<usize>>, { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { let Lines { text, ref mut ranges, } = *self; ranges.next().map(|range| &text[range]) } } impl<'a> Iterator for TextLineRects<'a> { type Item = geom::Rect; fn next(&mut self) -> Option<Self::Item> { self.line_rects.next().map(|r| r.shift(self.offset)) } } /// Determine the total height of a block of text with the given number of lines, font size and /// `line_spacing` (the space that separates each line of text). /// /// The height of all lines of text are assumed to match the `font_size`. If looking for the exact /// height, see the `exact_height` function. pub fn height_by_lines(num_lines: usize, font_size: FontSize, line_spacing: Scalar) -> Scalar { if num_lines > 0 { num_lines as Scalar * font_size as Scalar + (num_lines - 1) as Scalar * line_spacing } else { 0.0 } } /// Determine the exact height of a block of text. /// /// The `first_line_height` can be retrieved via its `line::Info` which can be retrieved via the /// first element of a `line_infos` iterator. pub fn exact_height( first_line_height: Scalar, num_lines: usize, font_size: FontSize, line_spacing: Scalar, ) -> Scalar { if num_lines > 0 { let lt_num_lines = num_lines - 1; let other_lines_height = lt_num_lines as Scalar * font_size as Scalar; let space_height = lt_num_lines as Scalar * line_spacing; first_line_height + other_lines_height + space_height } else { 0.0 } } /// Produce an iterator yielding each line within the given `text` as a new `&str`, where the /// start and end indices into each line are provided by the given iterator. pub fn lines<I>(text: &str, ranges: I) -> Lines<I> where I: Iterator<Item = std::ops::Range<usize>>, { Lines { text: text, ranges: ranges, } } /// The position offset required to shift the associated text into the given bounding rectangle. /// /// This function assumes the `max_width` used to produce the `line_infos` is equal to the given /// `bounding_rect` max width. pub fn position_offset( num_lines: usize, font_size: FontSize, line_spacing: f32, bounding_rect: geom::Rect, y_align: Align, ) -> geom::Vector2 { let x_offset = bounding_rect.x.start; let y_offset = { // Calculate the `y` `Range` of the first line `Rect`. let total_text_height = height_by_lines(num_lines, font_size, line_spacing); let total_text_y_range = geom::Range::new(0.0, total_text_height); let total_text_y = match y_align { Align::Start => total_text_y_range.align_start_of(bounding_rect.y), Align::Middle => total_text_y_range.align_middle_of(bounding_rect.y), Align::End => total_text_y_range.align_end_of(bounding_rect.y), }; total_text_y.end }; geom::vec2(x_offset, y_offset) } /// Produce the position of each glyph ready for the rusttype glyph cache. /// /// Window dimensions are expected in logical coordinates. pub fn rt_
Builder
identifier_name
mod.rs
FontSize = u32; /// A context for building some **Text**. pub struct Builder<'a> { text: Cow<'a, str>, layout_builder: layout::Builder, } /// An instance of some multi-line text and its layout. #[derive(Clone)] pub struct Text<'a> { text: Cow<'a, str>, font: Font, layout: Layout, line_infos: Vec<line::Info>, rect: geom::Rect, } /// An iterator yielding each line within the given `text` as a new `&str`, where the start and end /// indices into each line are provided by the given iterator. #[derive(Clone)] pub struct Lines<'a, I> { text: &'a str, ranges: I, } /// An alias for the line info iterator yielded by `Text::line_infos`. pub type TextLineInfos<'a> = line::Infos<'a, line::NextBreakFnPtr>; /// An alias for the line iterator yielded by `Text::lines`. pub type TextLines<'a> = Lines< 'a, std::iter::Map<std::slice::Iter<'a, line::Info>, fn(&line::Info) -> std::ops::Range<usize>>, >; /// An alias for the line rect iterator used internally within the `Text::line_rects` iterator. type LineRects<'a> = line::Rects<std::iter::Cloned<std::slice::Iter<'a, line::Info>>>; /// An alias for the line rect iterator yielded by `Text::line_rects`. #[derive(Clone)] pub struct TextLineRects<'a> { line_rects: LineRects<'a>, offset: geom::Vector2, } /// An alias for the iterator yielded by `Text::lines_with_rects`. pub type TextLinesWithRects<'a> = std::iter::Zip<TextLines<'a>, TextLineRects<'a>>; /// An alias for the iterator yielded by `Text::glyphs_per_line`. pub type TextGlyphsPerLine<'a> = glyph::RectsPerLine<'a, TextLinesWithRects<'a>>; /// An alias for the iterator yielded by `Text::glyphs`. pub type TextGlyphs<'a> = std::iter::FlatMap< TextGlyphsPerLine<'a>, glyph::Rects<'a, 'a>, fn(glyph::Rects<'a, 'a>) -> glyph::Rects<'a, 'a>, >; /// Alignment along an axis. #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)] pub enum Align { Start, Middle, End, } /// A type used for referring to typographic alignment of `Text`. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Justify { /// Align text to the start of the bounding `Rect`'s *x* axis. Left, /// Symmetrically align text along the *y* axis. Center, /// Align text to the end of the bounding `Rect`'s *x* axis. Right, // /// Align wrapped text to both the start and end of the bounding `Rect`s *x* axis. // /// // /// Extra space is added between words in order to achieve this alignment. // TODO: Full, } /// The way in which text should wrap around the width. #[derive(Copy, Clone, Debug, PartialEq)] pub enum Wrap { /// Wrap at the first character that exceeds the width. Character, /// Wrap at the first word that exceeds the width. Whitespace, } impl<'a> From<Cow<'a, str>> for Builder<'a> { fn from(text: Cow<'a, str>) -> Self { let layout_builder = Default::default(); Builder { text, layout_builder, } } } impl<'a> From<&'a str> for Builder<'a> { fn from(s: &'a str) -> Self { let text = Cow::Borrowed(s); Self::from(text) } } impl From<String> for Builder<'static> { fn from(s: String) -> Self { let text = Cow::Owned(s); Self::from(text) } } impl<'a> Builder<'a> { /// Apply the given function to the inner text layout. fn map_layout<F>(mut self, map: F) -> Self where F: FnOnce(layout::Builder) -> layout::Builder, { self.layout_builder = map(self.layout_builder); self } /// The font size to use for the text. pub fn font_size(self, size: FontSize) -> Self { self.map_layout(|l| l.font_size(size)) } /// Specify whether or not text should be wrapped around some width and how to do so. /// /// The default value is `DEFAULT_LINE_WRAP`. pub fn line_wrap(self, line_wrap: Option<Wrap>) -> Self { self.map_layout(|l| l.line_wrap(line_wrap)) } /// Specify that the **Text** should not wrap lines around the width. /// /// Shorthand for `builder.line_wrap(None)`. pub fn no_line_wrap(self) -> Self { self.map_layout(|l| l.no_line_wrap()) } /// Line wrap the **Text** at the beginning of the first word that exceeds the width. /// /// Shorthand for `builder.line_wrap(Some(Wrap::Whitespace))`. pub fn wrap_by_word(self) -> Self { self.map_layout(|l| l.wrap_by_word()) } /// Line wrap the **Text** at the beginning of the first character that exceeds the width. /// /// Shorthand for `builder.line_wrap(Some(Wrap::Character))`. pub fn wrap_by_character(self) -> Self { self.map_layout(|l| l.wrap_by_character()) } /// A method for specifying the `Font` used for displaying the `Text`. pub fn font(self, font: Font) -> Self { self.map_layout(|l| l.font(font)) } /// Describe the end along the *x* axis to which the text should be aligned. pub fn justify(self, justify: Justify) -> Self { self.map_layout(|l| l.justify(justify)) } /// Align the text to the left of its bounding **Rect**'s *x* axis range. pub fn left_justify(self) -> Self { self.map_layout(|l| l.left_justify()) } /// Align the text to the middle of its bounding **Rect**'s *x* axis range. pub fn center_justify(self) -> Self { self.map_layout(|l| l.center_justify()) } /// Align the text to the right of its bounding **Rect**'s *x* axis range. pub fn right_justify(self) -> Self { self.map_layout(|l| l.right_justify()) } /// Specify how much vertical space should separate each line of text. pub fn line_spacing(self, spacing: Scalar) -> Self { self.map_layout(|l| l.line_spacing(spacing)) } /// Specify how the whole text should be aligned along the y axis of its bounding rectangle pub fn y_align(self, align: Align) -> Self { self.map_layout(|l| l.y_align(align)) } /// Align the top edge of the text with the top edge of its bounding rectangle. pub fn align_top(self) -> Self { self.map_layout(|l| l.align_top()) } /// Align the middle of the text with the middle of the bounding rect along the y axis.. /// /// This is the default behaviour. pub fn align_middle_y(self) -> Self { self.map_layout(|l| l.align_middle_y()) } /// Align the bottom edge of the text with the bottom edge of its bounding rectangle. pub fn align_bottom(self) -> Self { self.map_layout(|l| l.align_bottom()) } /// Set all the parameters via an existing `Layout` pub fn layout(self, layout: &Layout) -> Self { self.map_layout(|l| l.layout(layout)) } /// Build the text. /// /// This iterates over the text in order to pre-calculates the text's multi-line information /// using the `line::infos` function. /// /// The given `rect` will be used for applying the layout including text alignment, positioning /// of text, multi-line wrapping, etc, pub fn build(self, rect: geom::Rect) -> Text<'a>
layout, line_infos, rect, } } } impl<'a> Text<'a> { /// Produce an iterator yielding information about each line. pub fn line_infos(&self) -> &[line::Info] { &self.line_infos } /// The full string of text as a slice. pub fn text(&self) -> &str { &self.text } /// The layout parameters for this text instance. pub fn layout(&self) -> &Layout { &self.layout } /// The font used for this text instance. pub fn font(&self) -> &Font { &self.font } /// The number of lines in the text. pub fn num_lines(&self) -> usize { self.line_infos.len() } /// The rectangle used to layout and build the text instance. /// /// This is the same `Rect` that was passed to the `text::Builder::build` method. pub fn layout_rect(&self) -> geom::Rect { self.rect } /// The rectangle that describes the min and max bounds along each axis reached by the text. pub fn bounding_rect(&self) -> geom::Rect { let mut r = self.bounding_rect_by_lines(); let info = match self.line_infos.first() { None => return geom::Rect::from_w_h(0.0, 0.0), Some(info) => info, }; let line_h = self.layout.font_size as Scalar; r.y.end -= line_h - info.height; r } /// The rectangle that describes the min and max bounds along each axis reached by the text. /// /// This is similar to `bounding_rect` but assumes that all lines have a height equal to /// `font_size`, rather than using the exact height. pub fn bounding_rect_by_lines(&self) -> geom::Rect { let mut lrs = self.line_rects(); let lr = match lrs.next() { None => return geom::Rect::from_w_h(0.0, 0.0), Some(lr) => lr, }; lrs.fold(lr, |acc, lr| { let x = geom::Range::new(acc.x.start.min(lr.x.start), acc.x.end.max(lr.x.end)); let y = geom::Range::new(acc.y.start.min(lr.y.start), acc.y.end.max(lr.y.end)); geom::Rect { x, y } }) } /// The width of the widest line of text. pub fn width(&self) -> Scalar { self.line_infos .iter() .fold(0.0, |max, info| max.max(info.width)) } /// The exact height of the full text accounting for font size and line spacing.. pub fn height(&self) -> Scalar { let info = match self.line_infos.first() { None => return 0.0, Some(info) => info, }; exact_height( info.height, self.num_lines(), self.layout.font_size, self.layout.line_spacing, ) } /// Determine the total height of a block of text with the given number of lines, font size and /// `line_spacing` (the space that separates each line of text). /// /// The height of all lines of text are assumed to match the `font_size`. If looking for the exact /// height, see the `exact_height` function. pub fn height_by_lines(&self) -> Scalar { height_by_lines( self.num_lines(), self.layout.font_size, self.layout.line_spacing, ) } /// Produce an iterator yielding each wrapped line within the **Text**. pub fn lines(&self) -> TextLines { fn info_byte_range(info: &line::Info) -> std::ops::Range<usize> { info.byte_range() } lines(&self.text, self.line_infos.iter().map(info_byte_range)) } /// The bounding rectangle for each line. pub fn line_rects(&self) -> TextLineRects { let offset = self.position_offset(); let line_rects = line::rects( self.line_infos.iter().cloned(), self.layout.font_size, self.rect.w(), self.layout.justify, self.layout.line_spacing, ); TextLineRects { line_rects, offset } } /// Produce an iterator yielding all lines of text alongside their bounding rects. pub fn lines_with_rects(&self) -> TextLinesWithRects { self.lines().zip(self.line_rects()) } /// Produce an iterator yielding iterators yielding every glyph alongside its bounding rect for /// each line. pub fn glyphs_per_line(&self) -> TextGlyphsPerLine { glyph::rects_per_line(self.lines_with_rects(), &self.font, self.layout.font_size) } /// Produce an iterator yielding every glyph alongside its bounding rect. /// /// This is the "flattened" version of the `glyphs_per_line` method. pub fn glyphs(&self) -> TextGlyphs { self.glyphs_per_line().flat_map(std::convert::identity) } /// Produce an iterator yielding the path events for every glyph in every line. pub fn path_events<'b>(&'b self) -> impl 'b + Iterator<Item = lyon::path::PathEvent> { use lyon::path::PathEvent; // Translate the given lyon point by the given vector. fn trans_lyon_point(p: &lyon::math::Point, v: geom::Vector2) -> lyon::math::Point { lyon::math::point(p.x + v.x, p.y + v.y) } // Translate the given path event in 2D space. fn trans_path_event(e: &PathEvent, v: geom::Vector2) -> PathEvent { match *e { PathEvent::Begin { ref at } => PathEvent::Begin { at: trans_lyon_point(at, v), }, PathEvent::Line { ref from, ref to } => PathEvent::Line { from: trans_lyon_point(from, v), to: trans_lyon_point(to, v), }, PathEvent::Quadratic { ref from, ref ctrl, ref to, } => PathEvent::Quadratic { from: trans_lyon_point(from, v), ctrl: trans_lyon_point(ctrl, v), to: trans_lyon_point(to, v), }, PathEvent::Cubic { ref from, ref ctrl1, ref ctrl2, ref to, } => PathEvent::Cubic { from: trans_lyon_point(from, v), ctrl1: trans_lyon_point(ctrl1, v), ctrl2: trans_lyon_point(ctrl2, v), to: trans_lyon_point(to, v), }, PathEvent::End { ref last, ref first, ref close, } => PathEvent::End { last: trans_lyon_point(last, v), first: trans_lyon_point(first, v), close: *close, }, } } self.glyphs().flat_map(|(g, r)| { glyph::path_events(g) .into_iter() .flat_map(|es| es) .map(move |e| trans_path_event(&e, r.bottom_left())) }) } /// Produce an iterator yielding positioned rusttype glyphs ready for caching. /// /// The window dimensions (in logical space) and scale_factor are required to transform glyph /// positions into rusttype's pixel-space, ready for caching into the rusttype glyph cache /// pixel buffer. pub fn rt_glyphs<'b: 'a>( &'b self, window_size: geom::Vector2, scale_factor: Scalar, ) -> impl 'a + 'b + Iterator<Item = PositionedGlyph> { rt_positioned_glyphs( self.lines_with_rects(), &self.font, self.layout.font_size, window_size, scale_factor, ) } /// Converts this `Text` instance into an instance that owns the inner text string. pub fn into_owned(self) -> Text<'static> { let Text { text, font, layout, line_infos, rect, } = self; let text = Cow::Owned(text.into_owned()); Text { text, font, layout, line_infos, rect, } } fn position_offset(&self) -> geom::Vector2 { position_offset( self.num_lines(), self.layout.font_size, self.layout.line_spacing, self.rect, self.layout.y_align, ) } } impl<'a, I> Iterator for Lines<'a, I> where I: Iterator<Item = std::ops::Range<usize>>, { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { let Lines { text, ref mut ranges, } = *self; ranges.next().map(|range| &text[range]) } } impl<'a> Iterator for TextLineRects<'a> { type Item = geom::Rect; fn next(&mut self) -> Option<Self::Item> { self.line_rects.next().map(|r| r.shift(self.offset)) } } /// Determine the total height of a block of text with the given number of lines, font size and /// `line_spacing` (the space that separates each line of text). /// /// The height of all lines of text are assumed to match the `font_size`. If looking for the exact /// height, see the `exact_height` function. pub fn height_by_lines(num_lines: usize, font_size: FontSize, line_spacing: Scalar) -> Scalar { if num_lines > 0 { num_lines as Scalar * font_size as Scalar + (num_lines - 1) as Scalar * line_spacing } else { 0.0 } } /// Determine the exact height of a block of text. /// /// The `first_line_height` can be retrieved via its `line::Info` which can be retrieved via the /// first element of a `line_infos` iterator. pub fn exact_height( first_line_height: Scalar, num_lines: usize, font_size: FontSize, line_spacing: Scalar, ) -> Scalar { if num_lines > 0 { let lt_num_lines = num_lines - 1; let other_lines_height = lt_num_lines as Scalar * font_size as Scalar; let space_height = lt_num_lines as Scalar * line_spacing; first_line_height + other_lines_height + space_height } else { 0.0 } } /// Produce an iterator yielding each line within the given `text` as a new `&str`, where the /// start and end indices into each line are provided by the given iterator. pub fn lines<I>(text: &str, ranges: I) -> Lines<I> where I: Iterator<Item = std::ops::Range<usize>>, { Lines { text: text, ranges: ranges, } } /// The position offset required to shift the associated text into the given bounding rectangle. /// /// This function assumes the `max_width` used to produce the `line_infos` is equal to the given /// `bounding_rect` max width. pub fn position_offset( num_lines: usize, font_size: FontSize, line_spacing: f32, bounding_rect: geom::Rect, y_align: Align, ) -> geom::Vector2 { let x_offset = bounding_rect.x.start; let y_offset = { // Calculate the `y` `Range` of the first line `Rect`. let total_text_height = height_by_lines(num_lines, font_size, line_spacing); let total_text_y_range = geom::Range::new(0.0, total_text_height); let total_text_y = match y_align { Align::Start => total_text_y_range.align_start_of(bounding_rect.y), Align::Middle => total_text_y_range.align_middle_of(bounding_rect.y), Align::End => total_text_y_range.align_end_of(bounding_rect.y), }; total_text_y.end }; geom::vec2(x_offset, y_offset) } /// Produce the position of each glyph ready for the rusttype glyph cache. /// /// Window dimensions are expected in logical coordinates. pub fn rt_
{ let text = self.text; let layout = self.layout_builder.build(); #[allow(unreachable_code)] let font = layout.font.clone().unwrap_or_else(|| { #[cfg(feature = "notosans")] { return font::default_notosans(); } let assets = crate::app::find_assets_path() .expect("failed to detect the assets directory when searching for a default font"); font::default(&assets).expect("failed to detect a default font") }); let max_width = rect.w(); let line_infos = line::infos_maybe_wrapped(&text, &font, layout.font_size, layout.line_wrap, max_width) .collect(); Text { text, font,
identifier_body
dht22_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::rc::Rc; use syntax::ext::base::ExtCtxt; use builder::{Builder, TokenString, add_node_dependency}; use node; pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(build_dht22 as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); node.mutator.set(Some(mutate_pin as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); let pin_node_name = node.get_ref_attr("pin").unwrap(); let pin_node = builder.pt().get_by_name(pin_node_name.as_slice()).unwrap(); add_node_dependency(&node, &pin_node); let timer_node_name = node.get_ref_attr("timer").unwrap(); let timer_node = builder.pt().get_by_name(timer_node_name.as_slice()).unwrap(); add_node_dependency(&node, &timer_node); } fn mutate_pin(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { let pin_node_name = node.get_ref_attr("pin").unwrap(); let pin_node = builder.pt().get_by_name(pin_node_name.as_slice()).unwrap(); pin_node.attributes.borrow_mut().insert("direction".to_string(), Rc::new(node::Attribute::new_nosp(node::StrValue("out".to_string())))); } fn build_dht22(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { if!node.expect_no_subnodes(cx) {return} if!node.expect_attributes(cx, &[("pin", node::RefAttribute), ("timer", node::RefAttribute)]) { return } let pin_node_name = node.get_ref_attr("pin").unwrap(); let timer_node_name = node.get_ref_attr("timer").unwrap(); let pin = TokenString(pin_node_name); let timer = TokenString(timer_node_name); let name = TokenString(node.name.clone().unwrap()); let typename = format!("zinc::drivers::dht22::DHT22"); node.set_type_name(typename); let ty_params = vec!( "'a".to_string(), "zinc::hal::timer::Timer".to_string(), "zinc::hal::pin::Gpio".to_string()); node.set_type_params(ty_params); let st = quote_stmt!(&*cx, let $name = zinc::drivers::dht22::DHT22::new(&$timer, &$pin); ); builder.add_main_statement(st); } #[cfg(test)] mod test { use std::ops::Deref; use builder::Builder; use test_helpers::{assert_equal_source, with_parsed}; use hamcrest::{assert_that, is, equal_to}; #[test] fn builds_lpc17xx_pt() { with_parsed(" timer@timer; pin@pin;
pin = &pin; timer = &timer; }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone()); pt.get_by_name("timer").unwrap().set_type_name("T".to_string()); pt.get_by_name("pin").unwrap().set_type_name("P".to_string()); super::mutate_pin(&mut builder, cx, pt.get_by_name("dht").unwrap()); super::build_dht22(&mut builder, cx, pt.get_by_name("dht").unwrap()); assert_that(unsafe{*failed}, is(equal_to(false))); assert_that(builder.main_stmts().len(), is(equal_to(1u))); assert_equal_source(builder.main_stmts()[0].deref(), "let dht = zinc::drivers::dht22::DHT22::new(&timer, &pin);"); let pin_node = pt.get_by_name("pin").unwrap(); assert_that(pin_node.get_string_attr("direction").unwrap(), is(equal_to("out".to_string()))); }); } }
dht@dht22 {
random_line_split
dht22_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::rc::Rc; use syntax::ext::base::ExtCtxt; use builder::{Builder, TokenString, add_node_dependency}; use node; pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(build_dht22 as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); node.mutator.set(Some(mutate_pin as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); let pin_node_name = node.get_ref_attr("pin").unwrap(); let pin_node = builder.pt().get_by_name(pin_node_name.as_slice()).unwrap(); add_node_dependency(&node, &pin_node); let timer_node_name = node.get_ref_attr("timer").unwrap(); let timer_node = builder.pt().get_by_name(timer_node_name.as_slice()).unwrap(); add_node_dependency(&node, &timer_node); } fn mutate_pin(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { let pin_node_name = node.get_ref_attr("pin").unwrap(); let pin_node = builder.pt().get_by_name(pin_node_name.as_slice()).unwrap(); pin_node.attributes.borrow_mut().insert("direction".to_string(), Rc::new(node::Attribute::new_nosp(node::StrValue("out".to_string())))); } fn build_dht22(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>)
"zinc::hal::pin::Gpio".to_string()); node.set_type_params(ty_params); let st = quote_stmt!(&*cx, let $name = zinc::drivers::dht22::DHT22::new(&$timer, &$pin); ); builder.add_main_statement(st); } #[cfg(test)] mod test { use std::ops::Deref; use builder::Builder; use test_helpers::{assert_equal_source, with_parsed}; use hamcrest::{assert_that, is, equal_to}; #[test] fn builds_lpc17xx_pt() { with_parsed(" timer@timer; pin@pin; dht@dht22 { pin = &pin; timer = &timer; }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone()); pt.get_by_name("timer").unwrap().set_type_name("T".to_string()); pt.get_by_name("pin").unwrap().set_type_name("P".to_string()); super::mutate_pin(&mut builder, cx, pt.get_by_name("dht").unwrap()); super::build_dht22(&mut builder, cx, pt.get_by_name("dht").unwrap()); assert_that(unsafe{*failed}, is(equal_to(false))); assert_that(builder.main_stmts().len(), is(equal_to(1u))); assert_equal_source(builder.main_stmts()[0].deref(), "let dht = zinc::drivers::dht22::DHT22::new(&timer, &pin);"); let pin_node = pt.get_by_name("pin").unwrap(); assert_that(pin_node.get_string_attr("direction").unwrap(), is(equal_to("out".to_string()))); }); } }
{ if !node.expect_no_subnodes(cx) {return} if !node.expect_attributes(cx, &[("pin", node::RefAttribute), ("timer", node::RefAttribute)]) { return } let pin_node_name = node.get_ref_attr("pin").unwrap(); let timer_node_name = node.get_ref_attr("timer").unwrap(); let pin = TokenString(pin_node_name); let timer = TokenString(timer_node_name); let name = TokenString(node.name.clone().unwrap()); let typename = format!("zinc::drivers::dht22::DHT22"); node.set_type_name(typename); let ty_params = vec!( "'a".to_string(), "zinc::hal::timer::Timer".to_string(),
identifier_body
dht22_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::rc::Rc; use syntax::ext::base::ExtCtxt; use builder::{Builder, TokenString, add_node_dependency}; use node; pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(build_dht22 as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); node.mutator.set(Some(mutate_pin as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); let pin_node_name = node.get_ref_attr("pin").unwrap(); let pin_node = builder.pt().get_by_name(pin_node_name.as_slice()).unwrap(); add_node_dependency(&node, &pin_node); let timer_node_name = node.get_ref_attr("timer").unwrap(); let timer_node = builder.pt().get_by_name(timer_node_name.as_slice()).unwrap(); add_node_dependency(&node, &timer_node); } fn mutate_pin(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { let pin_node_name = node.get_ref_attr("pin").unwrap(); let pin_node = builder.pt().get_by_name(pin_node_name.as_slice()).unwrap(); pin_node.attributes.borrow_mut().insert("direction".to_string(), Rc::new(node::Attribute::new_nosp(node::StrValue("out".to_string())))); } fn build_dht22(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { if!node.expect_no_subnodes(cx)
if!node.expect_attributes(cx, &[("pin", node::RefAttribute), ("timer", node::RefAttribute)]) { return } let pin_node_name = node.get_ref_attr("pin").unwrap(); let timer_node_name = node.get_ref_attr("timer").unwrap(); let pin = TokenString(pin_node_name); let timer = TokenString(timer_node_name); let name = TokenString(node.name.clone().unwrap()); let typename = format!("zinc::drivers::dht22::DHT22"); node.set_type_name(typename); let ty_params = vec!( "'a".to_string(), "zinc::hal::timer::Timer".to_string(), "zinc::hal::pin::Gpio".to_string()); node.set_type_params(ty_params); let st = quote_stmt!(&*cx, let $name = zinc::drivers::dht22::DHT22::new(&$timer, &$pin); ); builder.add_main_statement(st); } #[cfg(test)] mod test { use std::ops::Deref; use builder::Builder; use test_helpers::{assert_equal_source, with_parsed}; use hamcrest::{assert_that, is, equal_to}; #[test] fn builds_lpc17xx_pt() { with_parsed(" timer@timer; pin@pin; dht@dht22 { pin = &pin; timer = &timer; }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone()); pt.get_by_name("timer").unwrap().set_type_name("T".to_string()); pt.get_by_name("pin").unwrap().set_type_name("P".to_string()); super::mutate_pin(&mut builder, cx, pt.get_by_name("dht").unwrap()); super::build_dht22(&mut builder, cx, pt.get_by_name("dht").unwrap()); assert_that(unsafe{*failed}, is(equal_to(false))); assert_that(builder.main_stmts().len(), is(equal_to(1u))); assert_equal_source(builder.main_stmts()[0].deref(), "let dht = zinc::drivers::dht22::DHT22::new(&timer, &pin);"); let pin_node = pt.get_by_name("pin").unwrap(); assert_that(pin_node.get_string_attr("direction").unwrap(), is(equal_to("out".to_string()))); }); } }
{return}
conditional_block
dht22_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::rc::Rc; use syntax::ext::base::ExtCtxt; use builder::{Builder, TokenString, add_node_dependency}; use node; pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(build_dht22 as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); node.mutator.set(Some(mutate_pin as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); let pin_node_name = node.get_ref_attr("pin").unwrap(); let pin_node = builder.pt().get_by_name(pin_node_name.as_slice()).unwrap(); add_node_dependency(&node, &pin_node); let timer_node_name = node.get_ref_attr("timer").unwrap(); let timer_node = builder.pt().get_by_name(timer_node_name.as_slice()).unwrap(); add_node_dependency(&node, &timer_node); } fn mutate_pin(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { let pin_node_name = node.get_ref_attr("pin").unwrap(); let pin_node = builder.pt().get_by_name(pin_node_name.as_slice()).unwrap(); pin_node.attributes.borrow_mut().insert("direction".to_string(), Rc::new(node::Attribute::new_nosp(node::StrValue("out".to_string())))); } fn
(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { if!node.expect_no_subnodes(cx) {return} if!node.expect_attributes(cx, &[("pin", node::RefAttribute), ("timer", node::RefAttribute)]) { return } let pin_node_name = node.get_ref_attr("pin").unwrap(); let timer_node_name = node.get_ref_attr("timer").unwrap(); let pin = TokenString(pin_node_name); let timer = TokenString(timer_node_name); let name = TokenString(node.name.clone().unwrap()); let typename = format!("zinc::drivers::dht22::DHT22"); node.set_type_name(typename); let ty_params = vec!( "'a".to_string(), "zinc::hal::timer::Timer".to_string(), "zinc::hal::pin::Gpio".to_string()); node.set_type_params(ty_params); let st = quote_stmt!(&*cx, let $name = zinc::drivers::dht22::DHT22::new(&$timer, &$pin); ); builder.add_main_statement(st); } #[cfg(test)] mod test { use std::ops::Deref; use builder::Builder; use test_helpers::{assert_equal_source, with_parsed}; use hamcrest::{assert_that, is, equal_to}; #[test] fn builds_lpc17xx_pt() { with_parsed(" timer@timer; pin@pin; dht@dht22 { pin = &pin; timer = &timer; }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone()); pt.get_by_name("timer").unwrap().set_type_name("T".to_string()); pt.get_by_name("pin").unwrap().set_type_name("P".to_string()); super::mutate_pin(&mut builder, cx, pt.get_by_name("dht").unwrap()); super::build_dht22(&mut builder, cx, pt.get_by_name("dht").unwrap()); assert_that(unsafe{*failed}, is(equal_to(false))); assert_that(builder.main_stmts().len(), is(equal_to(1u))); assert_equal_source(builder.main_stmts()[0].deref(), "let dht = zinc::drivers::dht22::DHT22::new(&timer, &pin);"); let pin_node = pt.get_by_name("pin").unwrap(); assert_that(pin_node.get_string_attr("direction").unwrap(), is(equal_to("out".to_string()))); }); } }
build_dht22
identifier_name
messageport.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 crate::dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use crate::dom::bindings::codegen::Bindings::MessagePortBinding::{ MessagePortMethods, PostMessageOptions, Wrap, }; use crate::dom::bindings::conversions::root_from_object; use crate::dom::bindings::error::{Error, ErrorResult}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::structuredclone::{self, StructuredDataHolder}; use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::bindings::transferable::Transferable; use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::script_runtime::JSContext as SafeJSContext; use dom_struct::dom_struct; use js::jsapi::Heap; use js::jsapi::{JSObject, MutableHandleObject}; use js::rust::{CustomAutoRooter, CustomAutoRooterGuard, HandleValue}; use msg::constellation_msg::{MessagePortId, MessagePortIndex, PipelineNamespaceId}; use script_traits::PortMessageTask; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::convert::TryInto; use std::num::NonZeroU32; use std::rc::Rc; #[dom_struct] /// The MessagePort used in the DOM. pub struct MessagePort { eventtarget: EventTarget, message_port_id: MessagePortId, entangled_port: RefCell<Option<MessagePortId>>, detached: Cell<bool>, } impl MessagePort { fn new_inherited(message_port_id: MessagePortId) -> MessagePort { MessagePort { eventtarget: EventTarget::new_inherited(), entangled_port: RefCell::new(None), detached: Cell::new(false), message_port_id, } } /// <https://html.spec.whatwg.org/multipage/#create-a-new-messageport-object> pub fn new(owner: &GlobalScope) -> DomRoot<MessagePort> { let port_id = MessagePortId::new(); reflect_dom_object(Box::new(MessagePort::new_inherited(port_id)), owner, Wrap) } /// Create a new port for an incoming transfer-received one. fn new_transferred( owner: &GlobalScope, transferred_port: MessagePortId, entangled_port: Option<MessagePortId>, ) -> DomRoot<MessagePort> { reflect_dom_object( Box::new(MessagePort { message_port_id: transferred_port, eventtarget: EventTarget::new_inherited(), detached: Cell::new(false), entangled_port: RefCell::new(entangled_port), }), owner, Wrap, ) } /// <https://html.spec.whatwg.org/multipage/#entangle> pub fn entangle(&self, other_id: MessagePortId) { *self.entangled_port.borrow_mut() = Some(other_id); } pub fn message_port_id(&self) -> &MessagePortId { &self.message_port_id } pub fn detached(&self) -> bool { self.detached.get() } /// <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessage> fn set_onmessage(&self, listener: Option<Rc<EventHandlerNonNull>>) { let eventtarget = self.upcast::<EventTarget>(); eventtarget.set_event_handler_common("message", listener); } /// <https://html.spec.whatwg.org/multipage/#message-port-post-message-steps> fn post_message_impl( &self, cx: SafeJSContext, message: HandleValue, transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>, ) -> ErrorResult { if self.detached.get() { return Ok(()); } // Step 1 is the transfer argument. let target_port = self.entangled_port.borrow(); // Step 3 let mut doomed = false; let ports = transfer .iter() .filter_map(|&obj| root_from_object::<MessagePort>(obj, *cx).ok()); for port in ports { // Step 2 if port.message_port_id() == self.message_port_id() { return Err(Error::DataClone); } // Step 4 if let Some(target_id) = target_port.as_ref() { if port.message_port_id() == target_id { doomed = true; } } } // Step 5 let data = structuredclone::write(cx, message, Some(transfer))?; if doomed { // TODO: The spec says to optionally report such a case to a dev console. return Ok(()); } // Step 6, done in MessagePortImpl. let incumbent = match GlobalScope::incumbent() { None => unreachable!("postMessage called with no incumbent global"), Some(incumbent) => incumbent, }; // Step 7 let task = PortMessageTask { origin: incumbent.origin().immutable().clone(), data, }; // Have the global proxy this call to the corresponding MessagePortImpl. self.global() .post_messageport_msg(self.message_port_id().clone(), task); Ok(()) } } impl Transferable for MessagePort { /// <https://html.spec.whatwg.org/multipage/#message-ports:transfer-steps> fn transfer(&self, sc_holder: &mut StructuredDataHolder) -> Result<u64, ()> { if self.detached.get() { return Err(()); } let port_impls = match sc_holder { StructuredDataHolder::Write { ports,.. } => ports, _ => panic!("Unexpected variant of StructuredDataHolder"), }; self.detached.set(true); let id = self.message_port_id(); // 1. Run local transfer logic, and return the object to be transferred. let transferred_port = self.global().mark_port_as_transferred(id); // 2. Store the transferred object at a given key. if let Some(ports) = port_impls.as_mut() { ports.insert(id.clone(), transferred_port); } else { let mut ports = HashMap::new(); ports.insert(id.clone(), transferred_port); *port_impls = Some(ports); } let PipelineNamespaceId(name_space) = id.clone().namespace_id; let MessagePortIndex(index) = id.clone().index; let index = index.get(); let mut big: [u8; 8] = [0; 8]; let name_space = name_space.to_ne_bytes(); let index = index.to_ne_bytes(); let (left, right) = big.split_at_mut(4); left.copy_from_slice(&name_space); right.copy_from_slice(&index); // 3. Return a u64 representation of the key where the object is stored. Ok(u64::from_ne_bytes(big)) } /// https://html.spec.whatwg.org/multipage/#message-ports:transfer-receiving-steps fn transfer_receive( owner: &GlobalScope, sc_holder: &mut StructuredDataHolder, extra_data: u64, return_object: MutableHandleObject, ) -> Result<(), ()> { let (message_ports, port_impls) = match sc_holder { StructuredDataHolder::Read { message_ports, port_impls, .. } => (message_ports, port_impls), _ => panic!("Unexpected variant of StructuredDataHolder"), }; // 1. Re-build the key for the storage location // of the transferred object. let big: [u8; 8] = extra_data.to_ne_bytes(); let (name_space, index) = big.split_at(4); let namespace_id = PipelineNamespaceId(u32::from_ne_bytes( name_space .try_into() .expect("name_space to be a slice of four."), )); let index = MessagePortIndex( NonZeroU32::new(u32::from_ne_bytes( index.try_into().expect("index to be a slice of four."), )) .expect("Index to be non-zero"), ); let id = MessagePortId { namespace_id, index, }; // 2. Get the transferred object from its storage, using the key. // Assign the transfer-received port-impl, and total number of transferred ports. let (ports_len, port_impl) = if let Some(ports) = port_impls.as_mut() { let ports_len = ports.len(); let port_impl = ports.remove(&id).expect("Transferred port to be stored"); if ports.is_empty() { *port_impls = None; } (ports_len, port_impl) } else { panic!("A messageport was transfer-received, yet the SC holder does not have any port impls"); }; let transferred_port = MessagePort::new_transferred(&*owner, id.clone(), port_impl.entangled_port_id()); owner.track_message_port(&transferred_port, Some(port_impl)); return_object.set(transferred_port.reflector().rootable().get()); // Store the DOM port where it will be passed along to script in the message-event. if let Some(ports) = message_ports.as_mut() { ports.push(transferred_port); } else { let mut ports = Vec::with_capacity(ports_len); ports.push(transferred_port); *message_ports = Some(ports); } Ok(()) } } impl MessagePortMethods for MessagePort { /// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage> fn PostMessage( &self, cx: SafeJSContext, message: HandleValue, transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>, ) -> ErrorResult { if self.detached.get() { return Ok(()); } self.post_message_impl(cx, message, transfer) } /// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage> fn PostMessage_( &self, cx: SafeJSContext, message: HandleValue, options: RootedTraceableBox<PostMessageOptions>, ) -> ErrorResult { if self.detached.get() { return Ok(()); } let mut rooted = CustomAutoRooter::new( options .transfer .iter() .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get()) .collect(), ); let guard = CustomAutoRooterGuard::new(*cx, &mut rooted); self.post_message_impl(cx, message, guard) } /// <https://html.spec.whatwg.org/multipage/#dom-messageport-start> fn Start(&self)
/// <https://html.spec.whatwg.org/multipage/#dom-messageport-close> fn Close(&self) { if self.detached.get() { return; } self.detached.set(true); self.global().close_message_port(self.message_port_id()); } /// <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessage> fn GetOnmessage(&self) -> Option<Rc<EventHandlerNonNull>> { if self.detached.get() { return None; } let eventtarget = self.upcast::<EventTarget>(); eventtarget.get_event_handler_common("message") } /// <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessage> fn SetOnmessage(&self, listener: Option<Rc<EventHandlerNonNull>>) { if self.detached.get() { return; } self.set_onmessage(listener); // Note: we cannot use the event_handler macro, due to the need to start the port. self.global().start_message_port(self.message_port_id()); } // <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessageerror> event_handler!(messageerror, GetOnmessageerror, SetOnmessageerror); }
{ if self.detached.get() { return; } self.global().start_message_port(self.message_port_id()); }
identifier_body
messageport.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 crate::dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use crate::dom::bindings::codegen::Bindings::MessagePortBinding::{ MessagePortMethods, PostMessageOptions, Wrap, }; use crate::dom::bindings::conversions::root_from_object; use crate::dom::bindings::error::{Error, ErrorResult}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::structuredclone::{self, StructuredDataHolder}; use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::bindings::transferable::Transferable; use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::script_runtime::JSContext as SafeJSContext; use dom_struct::dom_struct; use js::jsapi::Heap; use js::jsapi::{JSObject, MutableHandleObject}; use js::rust::{CustomAutoRooter, CustomAutoRooterGuard, HandleValue}; use msg::constellation_msg::{MessagePortId, MessagePortIndex, PipelineNamespaceId}; use script_traits::PortMessageTask; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::convert::TryInto; use std::num::NonZeroU32; use std::rc::Rc; #[dom_struct] /// The MessagePort used in the DOM. pub struct MessagePort { eventtarget: EventTarget, message_port_id: MessagePortId, entangled_port: RefCell<Option<MessagePortId>>, detached: Cell<bool>, } impl MessagePort { fn new_inherited(message_port_id: MessagePortId) -> MessagePort { MessagePort { eventtarget: EventTarget::new_inherited(), entangled_port: RefCell::new(None), detached: Cell::new(false), message_port_id, } } /// <https://html.spec.whatwg.org/multipage/#create-a-new-messageport-object> pub fn
(owner: &GlobalScope) -> DomRoot<MessagePort> { let port_id = MessagePortId::new(); reflect_dom_object(Box::new(MessagePort::new_inherited(port_id)), owner, Wrap) } /// Create a new port for an incoming transfer-received one. fn new_transferred( owner: &GlobalScope, transferred_port: MessagePortId, entangled_port: Option<MessagePortId>, ) -> DomRoot<MessagePort> { reflect_dom_object( Box::new(MessagePort { message_port_id: transferred_port, eventtarget: EventTarget::new_inherited(), detached: Cell::new(false), entangled_port: RefCell::new(entangled_port), }), owner, Wrap, ) } /// <https://html.spec.whatwg.org/multipage/#entangle> pub fn entangle(&self, other_id: MessagePortId) { *self.entangled_port.borrow_mut() = Some(other_id); } pub fn message_port_id(&self) -> &MessagePortId { &self.message_port_id } pub fn detached(&self) -> bool { self.detached.get() } /// <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessage> fn set_onmessage(&self, listener: Option<Rc<EventHandlerNonNull>>) { let eventtarget = self.upcast::<EventTarget>(); eventtarget.set_event_handler_common("message", listener); } /// <https://html.spec.whatwg.org/multipage/#message-port-post-message-steps> fn post_message_impl( &self, cx: SafeJSContext, message: HandleValue, transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>, ) -> ErrorResult { if self.detached.get() { return Ok(()); } // Step 1 is the transfer argument. let target_port = self.entangled_port.borrow(); // Step 3 let mut doomed = false; let ports = transfer .iter() .filter_map(|&obj| root_from_object::<MessagePort>(obj, *cx).ok()); for port in ports { // Step 2 if port.message_port_id() == self.message_port_id() { return Err(Error::DataClone); } // Step 4 if let Some(target_id) = target_port.as_ref() { if port.message_port_id() == target_id { doomed = true; } } } // Step 5 let data = structuredclone::write(cx, message, Some(transfer))?; if doomed { // TODO: The spec says to optionally report such a case to a dev console. return Ok(()); } // Step 6, done in MessagePortImpl. let incumbent = match GlobalScope::incumbent() { None => unreachable!("postMessage called with no incumbent global"), Some(incumbent) => incumbent, }; // Step 7 let task = PortMessageTask { origin: incumbent.origin().immutable().clone(), data, }; // Have the global proxy this call to the corresponding MessagePortImpl. self.global() .post_messageport_msg(self.message_port_id().clone(), task); Ok(()) } } impl Transferable for MessagePort { /// <https://html.spec.whatwg.org/multipage/#message-ports:transfer-steps> fn transfer(&self, sc_holder: &mut StructuredDataHolder) -> Result<u64, ()> { if self.detached.get() { return Err(()); } let port_impls = match sc_holder { StructuredDataHolder::Write { ports,.. } => ports, _ => panic!("Unexpected variant of StructuredDataHolder"), }; self.detached.set(true); let id = self.message_port_id(); // 1. Run local transfer logic, and return the object to be transferred. let transferred_port = self.global().mark_port_as_transferred(id); // 2. Store the transferred object at a given key. if let Some(ports) = port_impls.as_mut() { ports.insert(id.clone(), transferred_port); } else { let mut ports = HashMap::new(); ports.insert(id.clone(), transferred_port); *port_impls = Some(ports); } let PipelineNamespaceId(name_space) = id.clone().namespace_id; let MessagePortIndex(index) = id.clone().index; let index = index.get(); let mut big: [u8; 8] = [0; 8]; let name_space = name_space.to_ne_bytes(); let index = index.to_ne_bytes(); let (left, right) = big.split_at_mut(4); left.copy_from_slice(&name_space); right.copy_from_slice(&index); // 3. Return a u64 representation of the key where the object is stored. Ok(u64::from_ne_bytes(big)) } /// https://html.spec.whatwg.org/multipage/#message-ports:transfer-receiving-steps fn transfer_receive( owner: &GlobalScope, sc_holder: &mut StructuredDataHolder, extra_data: u64, return_object: MutableHandleObject, ) -> Result<(), ()> { let (message_ports, port_impls) = match sc_holder { StructuredDataHolder::Read { message_ports, port_impls, .. } => (message_ports, port_impls), _ => panic!("Unexpected variant of StructuredDataHolder"), }; // 1. Re-build the key for the storage location // of the transferred object. let big: [u8; 8] = extra_data.to_ne_bytes(); let (name_space, index) = big.split_at(4); let namespace_id = PipelineNamespaceId(u32::from_ne_bytes( name_space .try_into() .expect("name_space to be a slice of four."), )); let index = MessagePortIndex( NonZeroU32::new(u32::from_ne_bytes( index.try_into().expect("index to be a slice of four."), )) .expect("Index to be non-zero"), ); let id = MessagePortId { namespace_id, index, }; // 2. Get the transferred object from its storage, using the key. // Assign the transfer-received port-impl, and total number of transferred ports. let (ports_len, port_impl) = if let Some(ports) = port_impls.as_mut() { let ports_len = ports.len(); let port_impl = ports.remove(&id).expect("Transferred port to be stored"); if ports.is_empty() { *port_impls = None; } (ports_len, port_impl) } else { panic!("A messageport was transfer-received, yet the SC holder does not have any port impls"); }; let transferred_port = MessagePort::new_transferred(&*owner, id.clone(), port_impl.entangled_port_id()); owner.track_message_port(&transferred_port, Some(port_impl)); return_object.set(transferred_port.reflector().rootable().get()); // Store the DOM port where it will be passed along to script in the message-event. if let Some(ports) = message_ports.as_mut() { ports.push(transferred_port); } else { let mut ports = Vec::with_capacity(ports_len); ports.push(transferred_port); *message_ports = Some(ports); } Ok(()) } } impl MessagePortMethods for MessagePort { /// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage> fn PostMessage( &self, cx: SafeJSContext, message: HandleValue, transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>, ) -> ErrorResult { if self.detached.get() { return Ok(()); } self.post_message_impl(cx, message, transfer) } /// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage> fn PostMessage_( &self, cx: SafeJSContext, message: HandleValue, options: RootedTraceableBox<PostMessageOptions>, ) -> ErrorResult { if self.detached.get() { return Ok(()); } let mut rooted = CustomAutoRooter::new( options .transfer .iter() .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get()) .collect(), ); let guard = CustomAutoRooterGuard::new(*cx, &mut rooted); self.post_message_impl(cx, message, guard) } /// <https://html.spec.whatwg.org/multipage/#dom-messageport-start> fn Start(&self) { if self.detached.get() { return; } self.global().start_message_port(self.message_port_id()); } /// <https://html.spec.whatwg.org/multipage/#dom-messageport-close> fn Close(&self) { if self.detached.get() { return; } self.detached.set(true); self.global().close_message_port(self.message_port_id()); } /// <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessage> fn GetOnmessage(&self) -> Option<Rc<EventHandlerNonNull>> { if self.detached.get() { return None; } let eventtarget = self.upcast::<EventTarget>(); eventtarget.get_event_handler_common("message") } /// <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessage> fn SetOnmessage(&self, listener: Option<Rc<EventHandlerNonNull>>) { if self.detached.get() { return; } self.set_onmessage(listener); // Note: we cannot use the event_handler macro, due to the need to start the port. self.global().start_message_port(self.message_port_id()); } // <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessageerror> event_handler!(messageerror, GetOnmessageerror, SetOnmessageerror); }
new
identifier_name
messageport.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 crate::dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use crate::dom::bindings::codegen::Bindings::MessagePortBinding::{ MessagePortMethods, PostMessageOptions, Wrap, }; use crate::dom::bindings::conversions::root_from_object; use crate::dom::bindings::error::{Error, ErrorResult}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::structuredclone::{self, StructuredDataHolder}; use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::bindings::transferable::Transferable; use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::script_runtime::JSContext as SafeJSContext; use dom_struct::dom_struct; use js::jsapi::Heap; use js::jsapi::{JSObject, MutableHandleObject}; use js::rust::{CustomAutoRooter, CustomAutoRooterGuard, HandleValue}; use msg::constellation_msg::{MessagePortId, MessagePortIndex, PipelineNamespaceId}; use script_traits::PortMessageTask; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::convert::TryInto; use std::num::NonZeroU32; use std::rc::Rc; #[dom_struct] /// The MessagePort used in the DOM. pub struct MessagePort { eventtarget: EventTarget, message_port_id: MessagePortId, entangled_port: RefCell<Option<MessagePortId>>, detached: Cell<bool>, } impl MessagePort { fn new_inherited(message_port_id: MessagePortId) -> MessagePort { MessagePort { eventtarget: EventTarget::new_inherited(), entangled_port: RefCell::new(None), detached: Cell::new(false), message_port_id, } } /// <https://html.spec.whatwg.org/multipage/#create-a-new-messageport-object> pub fn new(owner: &GlobalScope) -> DomRoot<MessagePort> { let port_id = MessagePortId::new(); reflect_dom_object(Box::new(MessagePort::new_inherited(port_id)), owner, Wrap) } /// Create a new port for an incoming transfer-received one. fn new_transferred( owner: &GlobalScope, transferred_port: MessagePortId, entangled_port: Option<MessagePortId>, ) -> DomRoot<MessagePort> { reflect_dom_object( Box::new(MessagePort { message_port_id: transferred_port, eventtarget: EventTarget::new_inherited(), detached: Cell::new(false), entangled_port: RefCell::new(entangled_port), }), owner, Wrap, ) } /// <https://html.spec.whatwg.org/multipage/#entangle> pub fn entangle(&self, other_id: MessagePortId) { *self.entangled_port.borrow_mut() = Some(other_id); } pub fn message_port_id(&self) -> &MessagePortId { &self.message_port_id } pub fn detached(&self) -> bool { self.detached.get() } /// <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessage> fn set_onmessage(&self, listener: Option<Rc<EventHandlerNonNull>>) { let eventtarget = self.upcast::<EventTarget>(); eventtarget.set_event_handler_common("message", listener); } /// <https://html.spec.whatwg.org/multipage/#message-port-post-message-steps> fn post_message_impl( &self, cx: SafeJSContext, message: HandleValue, transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>, ) -> ErrorResult { if self.detached.get() { return Ok(()); } // Step 1 is the transfer argument. let target_port = self.entangled_port.borrow(); // Step 3 let mut doomed = false; let ports = transfer .iter() .filter_map(|&obj| root_from_object::<MessagePort>(obj, *cx).ok()); for port in ports { // Step 2 if port.message_port_id() == self.message_port_id() { return Err(Error::DataClone); } // Step 4 if let Some(target_id) = target_port.as_ref() { if port.message_port_id() == target_id { doomed = true; } } } // Step 5 let data = structuredclone::write(cx, message, Some(transfer))?; if doomed { // TODO: The spec says to optionally report such a case to a dev console. return Ok(()); } // Step 6, done in MessagePortImpl. let incumbent = match GlobalScope::incumbent() { None => unreachable!("postMessage called with no incumbent global"), Some(incumbent) => incumbent, }; // Step 7 let task = PortMessageTask { origin: incumbent.origin().immutable().clone(), data, }; // Have the global proxy this call to the corresponding MessagePortImpl. self.global() .post_messageport_msg(self.message_port_id().clone(), task); Ok(()) } } impl Transferable for MessagePort { /// <https://html.spec.whatwg.org/multipage/#message-ports:transfer-steps> fn transfer(&self, sc_holder: &mut StructuredDataHolder) -> Result<u64, ()> { if self.detached.get() { return Err(()); } let port_impls = match sc_holder { StructuredDataHolder::Write { ports,.. } => ports, _ => panic!("Unexpected variant of StructuredDataHolder"), }; self.detached.set(true); let id = self.message_port_id(); // 1. Run local transfer logic, and return the object to be transferred. let transferred_port = self.global().mark_port_as_transferred(id); // 2. Store the transferred object at a given key. if let Some(ports) = port_impls.as_mut() { ports.insert(id.clone(), transferred_port); } else { let mut ports = HashMap::new(); ports.insert(id.clone(), transferred_port); *port_impls = Some(ports); } let PipelineNamespaceId(name_space) = id.clone().namespace_id; let MessagePortIndex(index) = id.clone().index; let index = index.get(); let mut big: [u8; 8] = [0; 8]; let name_space = name_space.to_ne_bytes(); let index = index.to_ne_bytes(); let (left, right) = big.split_at_mut(4); left.copy_from_slice(&name_space); right.copy_from_slice(&index); // 3. Return a u64 representation of the key where the object is stored. Ok(u64::from_ne_bytes(big)) } /// https://html.spec.whatwg.org/multipage/#message-ports:transfer-receiving-steps fn transfer_receive( owner: &GlobalScope, sc_holder: &mut StructuredDataHolder, extra_data: u64, return_object: MutableHandleObject, ) -> Result<(), ()> { let (message_ports, port_impls) = match sc_holder { StructuredDataHolder::Read { message_ports, port_impls, .. } => (message_ports, port_impls), _ => panic!("Unexpected variant of StructuredDataHolder"), }; // 1. Re-build the key for the storage location // of the transferred object. let big: [u8; 8] = extra_data.to_ne_bytes(); let (name_space, index) = big.split_at(4); let namespace_id = PipelineNamespaceId(u32::from_ne_bytes( name_space .try_into() .expect("name_space to be a slice of four."), )); let index = MessagePortIndex( NonZeroU32::new(u32::from_ne_bytes( index.try_into().expect("index to be a slice of four."), )) .expect("Index to be non-zero"), ); let id = MessagePortId { namespace_id, index, }; // 2. Get the transferred object from its storage, using the key. // Assign the transfer-received port-impl, and total number of transferred ports. let (ports_len, port_impl) = if let Some(ports) = port_impls.as_mut() { let ports_len = ports.len(); let port_impl = ports.remove(&id).expect("Transferred port to be stored"); if ports.is_empty() { *port_impls = None; } (ports_len, port_impl) } else { panic!("A messageport was transfer-received, yet the SC holder does not have any port impls"); }; let transferred_port = MessagePort::new_transferred(&*owner, id.clone(), port_impl.entangled_port_id()); owner.track_message_port(&transferred_port, Some(port_impl)); return_object.set(transferred_port.reflector().rootable().get()); // Store the DOM port where it will be passed along to script in the message-event. if let Some(ports) = message_ports.as_mut() { ports.push(transferred_port); } else
Ok(()) } } impl MessagePortMethods for MessagePort { /// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage> fn PostMessage( &self, cx: SafeJSContext, message: HandleValue, transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>, ) -> ErrorResult { if self.detached.get() { return Ok(()); } self.post_message_impl(cx, message, transfer) } /// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage> fn PostMessage_( &self, cx: SafeJSContext, message: HandleValue, options: RootedTraceableBox<PostMessageOptions>, ) -> ErrorResult { if self.detached.get() { return Ok(()); } let mut rooted = CustomAutoRooter::new( options .transfer .iter() .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get()) .collect(), ); let guard = CustomAutoRooterGuard::new(*cx, &mut rooted); self.post_message_impl(cx, message, guard) } /// <https://html.spec.whatwg.org/multipage/#dom-messageport-start> fn Start(&self) { if self.detached.get() { return; } self.global().start_message_port(self.message_port_id()); } /// <https://html.spec.whatwg.org/multipage/#dom-messageport-close> fn Close(&self) { if self.detached.get() { return; } self.detached.set(true); self.global().close_message_port(self.message_port_id()); } /// <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessage> fn GetOnmessage(&self) -> Option<Rc<EventHandlerNonNull>> { if self.detached.get() { return None; } let eventtarget = self.upcast::<EventTarget>(); eventtarget.get_event_handler_common("message") } /// <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessage> fn SetOnmessage(&self, listener: Option<Rc<EventHandlerNonNull>>) { if self.detached.get() { return; } self.set_onmessage(listener); // Note: we cannot use the event_handler macro, due to the need to start the port. self.global().start_message_port(self.message_port_id()); } // <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessageerror> event_handler!(messageerror, GetOnmessageerror, SetOnmessageerror); }
{ let mut ports = Vec::with_capacity(ports_len); ports.push(transferred_port); *message_ports = Some(ports); }
conditional_block
messageport.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 crate::dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use crate::dom::bindings::codegen::Bindings::MessagePortBinding::{ MessagePortMethods, PostMessageOptions, Wrap, }; use crate::dom::bindings::conversions::root_from_object; use crate::dom::bindings::error::{Error, ErrorResult}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::structuredclone::{self, StructuredDataHolder}; use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::bindings::transferable::Transferable; use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::script_runtime::JSContext as SafeJSContext; use dom_struct::dom_struct; use js::jsapi::Heap; use js::jsapi::{JSObject, MutableHandleObject}; use js::rust::{CustomAutoRooter, CustomAutoRooterGuard, HandleValue}; use msg::constellation_msg::{MessagePortId, MessagePortIndex, PipelineNamespaceId}; use script_traits::PortMessageTask; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::convert::TryInto; use std::num::NonZeroU32; use std::rc::Rc; #[dom_struct] /// The MessagePort used in the DOM. pub struct MessagePort { eventtarget: EventTarget, message_port_id: MessagePortId, entangled_port: RefCell<Option<MessagePortId>>, detached: Cell<bool>, } impl MessagePort { fn new_inherited(message_port_id: MessagePortId) -> MessagePort { MessagePort { eventtarget: EventTarget::new_inherited(), entangled_port: RefCell::new(None), detached: Cell::new(false), message_port_id, } } /// <https://html.spec.whatwg.org/multipage/#create-a-new-messageport-object> pub fn new(owner: &GlobalScope) -> DomRoot<MessagePort> { let port_id = MessagePortId::new(); reflect_dom_object(Box::new(MessagePort::new_inherited(port_id)), owner, Wrap) } /// Create a new port for an incoming transfer-received one. fn new_transferred( owner: &GlobalScope, transferred_port: MessagePortId, entangled_port: Option<MessagePortId>, ) -> DomRoot<MessagePort> { reflect_dom_object( Box::new(MessagePort { message_port_id: transferred_port, eventtarget: EventTarget::new_inherited(), detached: Cell::new(false), entangled_port: RefCell::new(entangled_port), }), owner, Wrap, ) } /// <https://html.spec.whatwg.org/multipage/#entangle> pub fn entangle(&self, other_id: MessagePortId) { *self.entangled_port.borrow_mut() = Some(other_id); } pub fn message_port_id(&self) -> &MessagePortId { &self.message_port_id } pub fn detached(&self) -> bool { self.detached.get() } /// <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessage> fn set_onmessage(&self, listener: Option<Rc<EventHandlerNonNull>>) { let eventtarget = self.upcast::<EventTarget>(); eventtarget.set_event_handler_common("message", listener); } /// <https://html.spec.whatwg.org/multipage/#message-port-post-message-steps> fn post_message_impl( &self, cx: SafeJSContext, message: HandleValue, transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>, ) -> ErrorResult { if self.detached.get() { return Ok(()); } // Step 1 is the transfer argument. let target_port = self.entangled_port.borrow(); // Step 3 let mut doomed = false; let ports = transfer .iter() .filter_map(|&obj| root_from_object::<MessagePort>(obj, *cx).ok()); for port in ports { // Step 2 if port.message_port_id() == self.message_port_id() { return Err(Error::DataClone); } // Step 4 if let Some(target_id) = target_port.as_ref() { if port.message_port_id() == target_id { doomed = true; } } } // Step 5 let data = structuredclone::write(cx, message, Some(transfer))?; if doomed { // TODO: The spec says to optionally report such a case to a dev console. return Ok(()); } // Step 6, done in MessagePortImpl. let incumbent = match GlobalScope::incumbent() { None => unreachable!("postMessage called with no incumbent global"), Some(incumbent) => incumbent, }; // Step 7 let task = PortMessageTask { origin: incumbent.origin().immutable().clone(), data, }; // Have the global proxy this call to the corresponding MessagePortImpl. self.global() .post_messageport_msg(self.message_port_id().clone(), task); Ok(()) } } impl Transferable for MessagePort { /// <https://html.spec.whatwg.org/multipage/#message-ports:transfer-steps> fn transfer(&self, sc_holder: &mut StructuredDataHolder) -> Result<u64, ()> { if self.detached.get() { return Err(()); } let port_impls = match sc_holder { StructuredDataHolder::Write { ports,.. } => ports, _ => panic!("Unexpected variant of StructuredDataHolder"), }; self.detached.set(true); let id = self.message_port_id(); // 1. Run local transfer logic, and return the object to be transferred. let transferred_port = self.global().mark_port_as_transferred(id); // 2. Store the transferred object at a given key. if let Some(ports) = port_impls.as_mut() { ports.insert(id.clone(), transferred_port); } else { let mut ports = HashMap::new(); ports.insert(id.clone(), transferred_port); *port_impls = Some(ports); } let PipelineNamespaceId(name_space) = id.clone().namespace_id; let MessagePortIndex(index) = id.clone().index; let index = index.get(); let mut big: [u8; 8] = [0; 8]; let name_space = name_space.to_ne_bytes(); let index = index.to_ne_bytes(); let (left, right) = big.split_at_mut(4); left.copy_from_slice(&name_space); right.copy_from_slice(&index); // 3. Return a u64 representation of the key where the object is stored. Ok(u64::from_ne_bytes(big)) } /// https://html.spec.whatwg.org/multipage/#message-ports:transfer-receiving-steps fn transfer_receive( owner: &GlobalScope, sc_holder: &mut StructuredDataHolder, extra_data: u64, return_object: MutableHandleObject, ) -> Result<(), ()> { let (message_ports, port_impls) = match sc_holder { StructuredDataHolder::Read { message_ports, port_impls, .. } => (message_ports, port_impls), _ => panic!("Unexpected variant of StructuredDataHolder"), }; // 1. Re-build the key for the storage location // of the transferred object. let big: [u8; 8] = extra_data.to_ne_bytes(); let (name_space, index) = big.split_at(4); let namespace_id = PipelineNamespaceId(u32::from_ne_bytes( name_space .try_into() .expect("name_space to be a slice of four."), )); let index = MessagePortIndex( NonZeroU32::new(u32::from_ne_bytes( index.try_into().expect("index to be a slice of four."), )) .expect("Index to be non-zero"), ); let id = MessagePortId { namespace_id, index, }; // 2. Get the transferred object from its storage, using the key. // Assign the transfer-received port-impl, and total number of transferred ports. let (ports_len, port_impl) = if let Some(ports) = port_impls.as_mut() { let ports_len = ports.len(); let port_impl = ports.remove(&id).expect("Transferred port to be stored"); if ports.is_empty() { *port_impls = None; } (ports_len, port_impl) } else { panic!("A messageport was transfer-received, yet the SC holder does not have any port impls"); }; let transferred_port = MessagePort::new_transferred(&*owner, id.clone(), port_impl.entangled_port_id()); owner.track_message_port(&transferred_port, Some(port_impl)); return_object.set(transferred_port.reflector().rootable().get());
ports.push(transferred_port); } else { let mut ports = Vec::with_capacity(ports_len); ports.push(transferred_port); *message_ports = Some(ports); } Ok(()) } } impl MessagePortMethods for MessagePort { /// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage> fn PostMessage( &self, cx: SafeJSContext, message: HandleValue, transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>, ) -> ErrorResult { if self.detached.get() { return Ok(()); } self.post_message_impl(cx, message, transfer) } /// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage> fn PostMessage_( &self, cx: SafeJSContext, message: HandleValue, options: RootedTraceableBox<PostMessageOptions>, ) -> ErrorResult { if self.detached.get() { return Ok(()); } let mut rooted = CustomAutoRooter::new( options .transfer .iter() .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get()) .collect(), ); let guard = CustomAutoRooterGuard::new(*cx, &mut rooted); self.post_message_impl(cx, message, guard) } /// <https://html.spec.whatwg.org/multipage/#dom-messageport-start> fn Start(&self) { if self.detached.get() { return; } self.global().start_message_port(self.message_port_id()); } /// <https://html.spec.whatwg.org/multipage/#dom-messageport-close> fn Close(&self) { if self.detached.get() { return; } self.detached.set(true); self.global().close_message_port(self.message_port_id()); } /// <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessage> fn GetOnmessage(&self) -> Option<Rc<EventHandlerNonNull>> { if self.detached.get() { return None; } let eventtarget = self.upcast::<EventTarget>(); eventtarget.get_event_handler_common("message") } /// <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessage> fn SetOnmessage(&self, listener: Option<Rc<EventHandlerNonNull>>) { if self.detached.get() { return; } self.set_onmessage(listener); // Note: we cannot use the event_handler macro, due to the need to start the port. self.global().start_message_port(self.message_port_id()); } // <https://html.spec.whatwg.org/multipage/#handler-messageport-onmessageerror> event_handler!(messageerror, GetOnmessageerror, SetOnmessageerror); }
// Store the DOM port where it will be passed along to script in the message-event. if let Some(ports) = message_ports.as_mut() {
random_line_split
text.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> <% data.new_style_struct("Text", inherited=False, gecko_name="TextReset", additional_methods=[Method("has_underline", "bool"), Method("has_overline", "bool"), Method("has_line_through", "bool")]) %>
"computed::TextOverflow::get_initial_value()", animation_value_type="discrete", boxed=True, flags="APPLIES_TO_PLACEHOLDER", spec="https://drafts.csswg.org/css-ui/#propdef-text-overflow")} ${helpers.single_keyword("unicode-bidi", "normal embed isolate bidi-override isolate-override plaintext", animation_value_type="discrete", spec="https://drafts.csswg.org/css-writing-modes/#propdef-unicode-bidi")} ${helpers.predefined_type("text-decoration-line", "TextDecorationLine", "specified::TextDecorationLine::none()", initial_specified_value="specified::TextDecorationLine::none()", custom_cascade= product =='servo', custom_cascade_function="specified::TextDecorationLine::cascade_property_custom", animation_value_type="discrete", flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER", spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-line")} ${helpers.single_keyword("text-decoration-style", "solid double dotted dashed wavy -moz-none", products="gecko", animation_value_type="discrete", flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER", spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-style")} ${helpers.predefined_type( "text-decoration-color", "Color", "computed_value::T::currentcolor()", initial_specified_value="specified::Color::currentcolor()", products="gecko", animation_value_type="AnimatedColor", ignored_when_colors_disabled=True, flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER", spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-color", )} ${helpers.predefined_type( "initial-letter", "InitialLetter", "computed::InitialLetter::normal()", initial_specified_value="specified::InitialLetter::normal()", animation_value_type="discrete", products="gecko", flags="APPLIES_TO_FIRST_LETTER", spec="https://drafts.csswg.org/css-inline/#sizing-drop-initials")}
${helpers.predefined_type("text-overflow", "TextOverflow",
random_line_split
round_trip.rs
// Copyright 2017 GFX Developers // // 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 obj::{Obj, ObjData}; #[test] fn
() { let sponza: Obj = Obj::load("test_assets/sponza.obj").unwrap(); let mut obj = Vec::new(); sponza.data.write_to_buf(&mut obj).unwrap(); let sponza_round_trip = ObjData::load_buf(obj.as_slice()).unwrap(); assert_eq!(sponza_round_trip, sponza.data); } #[test] fn round_trip_sponza_with_mtl() { let mut sponza: Obj = Obj::load("test_assets/sponza.obj").unwrap(); sponza.load_mtls().unwrap(); // Write obj to string, and then load it from that string to create a round trip Obj instance. let mut obj = Vec::new(); sponza.data.write_to_buf(&mut obj).unwrap(); let mut sponza_round_trip: Obj = Obj { data: ObjData::load_buf(obj.as_slice()).unwrap(), path: sponza.path, }; // Write each mtl lib to a string and load it back using load_mtls_fn into sponza_round_trip. let mut round_trip_mtl_libs = std::collections::HashMap::new(); for mtl in sponza.data.material_libs.iter() { let mut out = Vec::new(); mtl.write_to_buf(&mut out).unwrap(); round_trip_mtl_libs.insert(mtl.filename.as_str(), out); } sponza_round_trip .load_mtls_fn(|_, mtllib| Ok(round_trip_mtl_libs.get(mtllib).unwrap().as_slice())) .unwrap(); assert_eq!(sponza_round_trip.data, sponza.data); }
round_trip_sponza_no_mtls
identifier_name
round_trip.rs
// Copyright 2017 GFX Developers // // 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 obj::{Obj, ObjData};
let mut obj = Vec::new(); sponza.data.write_to_buf(&mut obj).unwrap(); let sponza_round_trip = ObjData::load_buf(obj.as_slice()).unwrap(); assert_eq!(sponza_round_trip, sponza.data); } #[test] fn round_trip_sponza_with_mtl() { let mut sponza: Obj = Obj::load("test_assets/sponza.obj").unwrap(); sponza.load_mtls().unwrap(); // Write obj to string, and then load it from that string to create a round trip Obj instance. let mut obj = Vec::new(); sponza.data.write_to_buf(&mut obj).unwrap(); let mut sponza_round_trip: Obj = Obj { data: ObjData::load_buf(obj.as_slice()).unwrap(), path: sponza.path, }; // Write each mtl lib to a string and load it back using load_mtls_fn into sponza_round_trip. let mut round_trip_mtl_libs = std::collections::HashMap::new(); for mtl in sponza.data.material_libs.iter() { let mut out = Vec::new(); mtl.write_to_buf(&mut out).unwrap(); round_trip_mtl_libs.insert(mtl.filename.as_str(), out); } sponza_round_trip .load_mtls_fn(|_, mtllib| Ok(round_trip_mtl_libs.get(mtllib).unwrap().as_slice())) .unwrap(); assert_eq!(sponza_round_trip.data, sponza.data); }
#[test] fn round_trip_sponza_no_mtls() { let sponza: Obj = Obj::load("test_assets/sponza.obj").unwrap();
random_line_split
round_trip.rs
// Copyright 2017 GFX Developers // // 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 obj::{Obj, ObjData}; #[test] fn round_trip_sponza_no_mtls() { let sponza: Obj = Obj::load("test_assets/sponza.obj").unwrap(); let mut obj = Vec::new(); sponza.data.write_to_buf(&mut obj).unwrap(); let sponza_round_trip = ObjData::load_buf(obj.as_slice()).unwrap(); assert_eq!(sponza_round_trip, sponza.data); } #[test] fn round_trip_sponza_with_mtl()
.load_mtls_fn(|_, mtllib| Ok(round_trip_mtl_libs.get(mtllib).unwrap().as_slice())) .unwrap(); assert_eq!(sponza_round_trip.data, sponza.data); }
{ let mut sponza: Obj = Obj::load("test_assets/sponza.obj").unwrap(); sponza.load_mtls().unwrap(); // Write obj to string, and then load it from that string to create a round trip Obj instance. let mut obj = Vec::new(); sponza.data.write_to_buf(&mut obj).unwrap(); let mut sponza_round_trip: Obj = Obj { data: ObjData::load_buf(obj.as_slice()).unwrap(), path: sponza.path, }; // Write each mtl lib to a string and load it back using load_mtls_fn into sponza_round_trip. let mut round_trip_mtl_libs = std::collections::HashMap::new(); for mtl in sponza.data.material_libs.iter() { let mut out = Vec::new(); mtl.write_to_buf(&mut out).unwrap(); round_trip_mtl_libs.insert(mtl.filename.as_str(), out); } sponza_round_trip
identifier_body
workletglobalscope.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 crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use crate::dom::paintworkletglobalscope::PaintWorkletGlobalScope; use crate::dom::paintworkletglobalscope::PaintWorkletTask; use crate::dom::testworkletglobalscope::TestWorkletGlobalScope; use crate::dom::testworkletglobalscope::TestWorkletTask; use crate::dom::worklet::WorkletExecutor; use crate::script_thread::MainThreadScriptMsg; use devtools_traits::ScriptToDevtoolsControlMsg; use dom_struct::dom_struct; use ipc_channel::ipc; use ipc_channel::ipc::IpcSender; use js::jsapi::JSContext; use js::jsval::UndefinedValue; use js::rust::Runtime; use msg::constellation_msg::PipelineId; use net_traits::image_cache::ImageCache; use net_traits::ResourceThreads; use profile_traits::mem; use profile_traits::time; use script_traits::{Painter, ScriptMsg}; use script_traits::{ScriptToConstellationChan, TimerSchedulerMsg}; use servo_atoms::Atom; use servo_channel::Sender; use servo_url::ImmutableOrigin; use servo_url::MutableOrigin; use servo_url::ServoUrl; use std::sync::Arc; #[dom_struct] /// <https://drafts.css-houdini.org/worklets/#workletglobalscope> pub struct WorkletGlobalScope { /// The global for this worklet. globalscope: GlobalScope, /// The base URL for this worklet. base_url: ServoUrl, /// Sender back to the script thread #[ignore_malloc_size_of = "channels are hard"] to_script_thread_sender: Sender<MainThreadScriptMsg>, /// Worklet task executor executor: WorkletExecutor, } impl WorkletGlobalScope { /// Create a new stack-allocated `WorkletGlobalScope`. pub fn new_inherited( pipeline_id: PipelineId, base_url: ServoUrl, executor: WorkletExecutor, init: &WorkletGlobalScopeInit, ) -> Self { // Any timer events fired on this global are ignored. let (timer_event_chan, _) = ipc::channel().unwrap(); let script_to_constellation_chan = ScriptToConstellationChan { sender: init.to_constellation_sender.clone(), pipeline_id, }; Self { globalscope: GlobalScope::new_inherited( pipeline_id, init.devtools_chan.clone(), init.mem_profiler_chan.clone(), init.time_profiler_chan.clone(), script_to_constellation_chan, init.scheduler_chan.clone(), init.resource_threads.clone(), timer_event_chan, MutableOrigin::new(ImmutableOrigin::new_opaque()), Default::default(), ), base_url, to_script_thread_sender: init.to_script_thread_sender.clone(), executor, } } /// Get the JS context. pub fn get_cx(&self) -> *mut JSContext { self.globalscope.get_cx() } /// Evaluate a JS script in this global. pub fn evaluate_js(&self, script: &str) -> bool { debug!("Evaluating Dom."); rooted!(in (self.globalscope.get_cx()) let mut rval = UndefinedValue()); self.globalscope .evaluate_js_on_global_with_result(&*script, rval.handle_mut()) } /// Register a paint worklet to the script thread. pub fn register_paint_worklet( &self, name: Atom, properties: Vec<Atom>, painter: Box<dyn Painter>, ) { self.to_script_thread_sender .send(MainThreadScriptMsg::RegisterPaintWorklet { pipeline_id: self.globalscope.pipeline_id(), name, properties, painter, }) .expect("Worklet thread outlived script thread."); } /// The base URL of this global. pub fn base_url(&self) -> ServoUrl { self.base_url.clone() } /// The worklet executor. pub fn executor(&self) -> WorkletExecutor { self.executor.clone() } /// Perform a worklet task pub fn perform_a_worklet_task(&self, task: WorkletTask) { match task { WorkletTask::Test(task) => match self.downcast::<TestWorkletGlobalScope>() { Some(global) => global.perform_a_worklet_task(task), None => warn!("This is not a test worklet."), }, WorkletTask::Paint(task) => match self.downcast::<PaintWorkletGlobalScope>() { Some(global) => global.perform_a_worklet_task(task), None => warn!("This is not a paint worklet."), }, } } } /// Resources required by workletglobalscopes #[derive(Clone)] pub struct WorkletGlobalScopeInit { /// Channel to the main script thread pub to_script_thread_sender: Sender<MainThreadScriptMsg>, /// Channel to a resource thread pub resource_threads: ResourceThreads, /// Channel to the memory profiler pub mem_profiler_chan: mem::ProfilerChan, /// Channel to the time profiler pub time_profiler_chan: time::ProfilerChan, /// Channel to devtools pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>, /// Messages to send to constellation pub to_constellation_sender: IpcSender<(PipelineId, ScriptMsg)>, /// Message to send to the scheduler pub scheduler_chan: IpcSender<TimerSchedulerMsg>, /// The image cache pub image_cache: Arc<dyn ImageCache>, } /// <https://drafts.css-houdini.org/worklets/#worklet-global-scope-type> #[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)] pub enum WorkletGlobalScopeType { /// A servo-specific testing worklet Test, /// A paint worklet Paint, } impl WorkletGlobalScopeType { /// Create a new heap-allocated `WorkletGlobalScope`. pub fn new(
executor: WorkletExecutor, init: &WorkletGlobalScopeInit, ) -> DomRoot<WorkletGlobalScope> { match *self { WorkletGlobalScopeType::Test => DomRoot::upcast(TestWorkletGlobalScope::new( runtime, pipeline_id, base_url, executor, init, )), WorkletGlobalScopeType::Paint => DomRoot::upcast(PaintWorkletGlobalScope::new( runtime, pipeline_id, base_url, executor, init, )), } } } /// A task which can be performed in the context of a worklet global. pub enum WorkletTask { Test(TestWorkletTask), Paint(PaintWorkletTask), }
&self, runtime: &Runtime, pipeline_id: PipelineId, base_url: ServoUrl,
random_line_split
workletglobalscope.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 crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use crate::dom::paintworkletglobalscope::PaintWorkletGlobalScope; use crate::dom::paintworkletglobalscope::PaintWorkletTask; use crate::dom::testworkletglobalscope::TestWorkletGlobalScope; use crate::dom::testworkletglobalscope::TestWorkletTask; use crate::dom::worklet::WorkletExecutor; use crate::script_thread::MainThreadScriptMsg; use devtools_traits::ScriptToDevtoolsControlMsg; use dom_struct::dom_struct; use ipc_channel::ipc; use ipc_channel::ipc::IpcSender; use js::jsapi::JSContext; use js::jsval::UndefinedValue; use js::rust::Runtime; use msg::constellation_msg::PipelineId; use net_traits::image_cache::ImageCache; use net_traits::ResourceThreads; use profile_traits::mem; use profile_traits::time; use script_traits::{Painter, ScriptMsg}; use script_traits::{ScriptToConstellationChan, TimerSchedulerMsg}; use servo_atoms::Atom; use servo_channel::Sender; use servo_url::ImmutableOrigin; use servo_url::MutableOrigin; use servo_url::ServoUrl; use std::sync::Arc; #[dom_struct] /// <https://drafts.css-houdini.org/worklets/#workletglobalscope> pub struct WorkletGlobalScope { /// The global for this worklet. globalscope: GlobalScope, /// The base URL for this worklet. base_url: ServoUrl, /// Sender back to the script thread #[ignore_malloc_size_of = "channels are hard"] to_script_thread_sender: Sender<MainThreadScriptMsg>, /// Worklet task executor executor: WorkletExecutor, } impl WorkletGlobalScope { /// Create a new stack-allocated `WorkletGlobalScope`. pub fn new_inherited( pipeline_id: PipelineId, base_url: ServoUrl, executor: WorkletExecutor, init: &WorkletGlobalScopeInit, ) -> Self { // Any timer events fired on this global are ignored. let (timer_event_chan, _) = ipc::channel().unwrap(); let script_to_constellation_chan = ScriptToConstellationChan { sender: init.to_constellation_sender.clone(), pipeline_id, }; Self { globalscope: GlobalScope::new_inherited( pipeline_id, init.devtools_chan.clone(), init.mem_profiler_chan.clone(), init.time_profiler_chan.clone(), script_to_constellation_chan, init.scheduler_chan.clone(), init.resource_threads.clone(), timer_event_chan, MutableOrigin::new(ImmutableOrigin::new_opaque()), Default::default(), ), base_url, to_script_thread_sender: init.to_script_thread_sender.clone(), executor, } } /// Get the JS context. pub fn get_cx(&self) -> *mut JSContext { self.globalscope.get_cx() } /// Evaluate a JS script in this global. pub fn evaluate_js(&self, script: &str) -> bool { debug!("Evaluating Dom."); rooted!(in (self.globalscope.get_cx()) let mut rval = UndefinedValue()); self.globalscope .evaluate_js_on_global_with_result(&*script, rval.handle_mut()) } /// Register a paint worklet to the script thread. pub fn register_paint_worklet( &self, name: Atom, properties: Vec<Atom>, painter: Box<dyn Painter>, ) { self.to_script_thread_sender .send(MainThreadScriptMsg::RegisterPaintWorklet { pipeline_id: self.globalscope.pipeline_id(), name, properties, painter, }) .expect("Worklet thread outlived script thread."); } /// The base URL of this global. pub fn base_url(&self) -> ServoUrl { self.base_url.clone() } /// The worklet executor. pub fn executor(&self) -> WorkletExecutor { self.executor.clone() } /// Perform a worklet task pub fn perform_a_worklet_task(&self, task: WorkletTask) { match task { WorkletTask::Test(task) => match self.downcast::<TestWorkletGlobalScope>() { Some(global) => global.perform_a_worklet_task(task), None => warn!("This is not a test worklet."), }, WorkletTask::Paint(task) => match self.downcast::<PaintWorkletGlobalScope>() { Some(global) => global.perform_a_worklet_task(task), None => warn!("This is not a paint worklet."), }, } } } /// Resources required by workletglobalscopes #[derive(Clone)] pub struct WorkletGlobalScopeInit { /// Channel to the main script thread pub to_script_thread_sender: Sender<MainThreadScriptMsg>, /// Channel to a resource thread pub resource_threads: ResourceThreads, /// Channel to the memory profiler pub mem_profiler_chan: mem::ProfilerChan, /// Channel to the time profiler pub time_profiler_chan: time::ProfilerChan, /// Channel to devtools pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>, /// Messages to send to constellation pub to_constellation_sender: IpcSender<(PipelineId, ScriptMsg)>, /// Message to send to the scheduler pub scheduler_chan: IpcSender<TimerSchedulerMsg>, /// The image cache pub image_cache: Arc<dyn ImageCache>, } /// <https://drafts.css-houdini.org/worklets/#worklet-global-scope-type> #[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)] pub enum
{ /// A servo-specific testing worklet Test, /// A paint worklet Paint, } impl WorkletGlobalScopeType { /// Create a new heap-allocated `WorkletGlobalScope`. pub fn new( &self, runtime: &Runtime, pipeline_id: PipelineId, base_url: ServoUrl, executor: WorkletExecutor, init: &WorkletGlobalScopeInit, ) -> DomRoot<WorkletGlobalScope> { match *self { WorkletGlobalScopeType::Test => DomRoot::upcast(TestWorkletGlobalScope::new( runtime, pipeline_id, base_url, executor, init, )), WorkletGlobalScopeType::Paint => DomRoot::upcast(PaintWorkletGlobalScope::new( runtime, pipeline_id, base_url, executor, init, )), } } } /// A task which can be performed in the context of a worklet global. pub enum WorkletTask { Test(TestWorkletTask), Paint(PaintWorkletTask), }
WorkletGlobalScopeType
identifier_name
workletglobalscope.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 crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use crate::dom::paintworkletglobalscope::PaintWorkletGlobalScope; use crate::dom::paintworkletglobalscope::PaintWorkletTask; use crate::dom::testworkletglobalscope::TestWorkletGlobalScope; use crate::dom::testworkletglobalscope::TestWorkletTask; use crate::dom::worklet::WorkletExecutor; use crate::script_thread::MainThreadScriptMsg; use devtools_traits::ScriptToDevtoolsControlMsg; use dom_struct::dom_struct; use ipc_channel::ipc; use ipc_channel::ipc::IpcSender; use js::jsapi::JSContext; use js::jsval::UndefinedValue; use js::rust::Runtime; use msg::constellation_msg::PipelineId; use net_traits::image_cache::ImageCache; use net_traits::ResourceThreads; use profile_traits::mem; use profile_traits::time; use script_traits::{Painter, ScriptMsg}; use script_traits::{ScriptToConstellationChan, TimerSchedulerMsg}; use servo_atoms::Atom; use servo_channel::Sender; use servo_url::ImmutableOrigin; use servo_url::MutableOrigin; use servo_url::ServoUrl; use std::sync::Arc; #[dom_struct] /// <https://drafts.css-houdini.org/worklets/#workletglobalscope> pub struct WorkletGlobalScope { /// The global for this worklet. globalscope: GlobalScope, /// The base URL for this worklet. base_url: ServoUrl, /// Sender back to the script thread #[ignore_malloc_size_of = "channels are hard"] to_script_thread_sender: Sender<MainThreadScriptMsg>, /// Worklet task executor executor: WorkletExecutor, } impl WorkletGlobalScope { /// Create a new stack-allocated `WorkletGlobalScope`. pub fn new_inherited( pipeline_id: PipelineId, base_url: ServoUrl, executor: WorkletExecutor, init: &WorkletGlobalScopeInit, ) -> Self { // Any timer events fired on this global are ignored. let (timer_event_chan, _) = ipc::channel().unwrap(); let script_to_constellation_chan = ScriptToConstellationChan { sender: init.to_constellation_sender.clone(), pipeline_id, }; Self { globalscope: GlobalScope::new_inherited( pipeline_id, init.devtools_chan.clone(), init.mem_profiler_chan.clone(), init.time_profiler_chan.clone(), script_to_constellation_chan, init.scheduler_chan.clone(), init.resource_threads.clone(), timer_event_chan, MutableOrigin::new(ImmutableOrigin::new_opaque()), Default::default(), ), base_url, to_script_thread_sender: init.to_script_thread_sender.clone(), executor, } } /// Get the JS context. pub fn get_cx(&self) -> *mut JSContext { self.globalscope.get_cx() } /// Evaluate a JS script in this global. pub fn evaluate_js(&self, script: &str) -> bool { debug!("Evaluating Dom."); rooted!(in (self.globalscope.get_cx()) let mut rval = UndefinedValue()); self.globalscope .evaluate_js_on_global_with_result(&*script, rval.handle_mut()) } /// Register a paint worklet to the script thread. pub fn register_paint_worklet( &self, name: Atom, properties: Vec<Atom>, painter: Box<dyn Painter>, ) { self.to_script_thread_sender .send(MainThreadScriptMsg::RegisterPaintWorklet { pipeline_id: self.globalscope.pipeline_id(), name, properties, painter, }) .expect("Worklet thread outlived script thread."); } /// The base URL of this global. pub fn base_url(&self) -> ServoUrl { self.base_url.clone() } /// The worklet executor. pub fn executor(&self) -> WorkletExecutor { self.executor.clone() } /// Perform a worklet task pub fn perform_a_worklet_task(&self, task: WorkletTask) { match task { WorkletTask::Test(task) => match self.downcast::<TestWorkletGlobalScope>() { Some(global) => global.perform_a_worklet_task(task), None => warn!("This is not a test worklet."), }, WorkletTask::Paint(task) => match self.downcast::<PaintWorkletGlobalScope>() { Some(global) => global.perform_a_worklet_task(task), None => warn!("This is not a paint worklet."), }, } } } /// Resources required by workletglobalscopes #[derive(Clone)] pub struct WorkletGlobalScopeInit { /// Channel to the main script thread pub to_script_thread_sender: Sender<MainThreadScriptMsg>, /// Channel to a resource thread pub resource_threads: ResourceThreads, /// Channel to the memory profiler pub mem_profiler_chan: mem::ProfilerChan, /// Channel to the time profiler pub time_profiler_chan: time::ProfilerChan, /// Channel to devtools pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>, /// Messages to send to constellation pub to_constellation_sender: IpcSender<(PipelineId, ScriptMsg)>, /// Message to send to the scheduler pub scheduler_chan: IpcSender<TimerSchedulerMsg>, /// The image cache pub image_cache: Arc<dyn ImageCache>, } /// <https://drafts.css-houdini.org/worklets/#worklet-global-scope-type> #[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)] pub enum WorkletGlobalScopeType { /// A servo-specific testing worklet Test, /// A paint worklet Paint, } impl WorkletGlobalScopeType { /// Create a new heap-allocated `WorkletGlobalScope`. pub fn new( &self, runtime: &Runtime, pipeline_id: PipelineId, base_url: ServoUrl, executor: WorkletExecutor, init: &WorkletGlobalScopeInit, ) -> DomRoot<WorkletGlobalScope>
} /// A task which can be performed in the context of a worklet global. pub enum WorkletTask { Test(TestWorkletTask), Paint(PaintWorkletTask), }
{ match *self { WorkletGlobalScopeType::Test => DomRoot::upcast(TestWorkletGlobalScope::new( runtime, pipeline_id, base_url, executor, init, )), WorkletGlobalScopeType::Paint => DomRoot::upcast(PaintWorkletGlobalScope::new( runtime, pipeline_id, base_url, executor, init, )), } }
identifier_body
event.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ use ui::input::*; use ui::readline; use ui::navigation::State as NavigationState; pub enum Direction { Left, Right, } #[derive(Clone, Hash, PartialEq, Eq)] pub enum SearchAction { ReadInput(Vec<i32>), ToggleFilterMode, FindNextMatch, FindPreviousMatch, } pub enum Offset { Line(i32), Viewport(i32), Top, Bottom, } pub enum Event { ScrollContents(Offset), SelectMenuItem(Direction), Navigation(NavigationState), Search(SearchAction), Resize, Quit, Other, } #[derive(Clone, Hash, PartialEq, Eq)] pub enum QueuedEvent { Unhighlight(SearchAction), PerformSearch, } pub struct EventBuilder { input: Input, key: i32, } impl EventBuilder { pub fn new(input: Input, key: i32) -> EventBuilder
pub fn construct(&self, current_navigation_state: &NavigationState) -> Event { let mut result = self.create_global_event(); if result.is_none() { result = match *current_navigation_state { NavigationState::Menu => self.create_menu_event(), NavigationState::Search => self.create_search_event(), }; } result.unwrap_or(Event::Other) } fn create_menu_event(&self) -> Option<Event> { match self.input { Input::Kb(Key::Left, None) => Some(Event::SelectMenuItem(Direction::Left)), Input::Kb(Key::Right, None) => Some(Event::SelectMenuItem(Direction::Right)), Input::Kb(Key::Char('/'), None) | Input::Kb(Key::Char('F'), Some(Modifier::Ctrl)) => { Some(Event::Navigation(NavigationState::Search)) } Input::Kb(Key::Char('q'), None) => Some(Event::Quit), _ => None, } } fn create_search_event(&self) -> Option<Event> { match self.input { Input::Kb(Key::Char('n'), Some(Modifier::Alt(_))) => { Some(Event::Search(SearchAction::FindNextMatch)) } Input::Kb(Key::Char('p'), Some(Modifier::Alt(_))) => { Some(Event::Search(SearchAction::FindPreviousMatch)) } Input::Kb(Key::Char('m'), Some(Modifier::Alt(_))) => { Some(Event::Search(SearchAction::ToggleFilterMode)) } Input::Kb(Key::Escape, None) if!readline::is_history() => { Some(Event::Navigation(NavigationState::Menu)) } _ => self.create_input_event(), } } fn create_global_event(&self) -> Option<Event> { match self.input { Input::Kb(Key::Up, None) => Some(Event::ScrollContents(Offset::Line(1))), Input::Kb(Key::Down, None) => Some(Event::ScrollContents(Offset::Line(-1))), Input::Kb(Key::PageUp, None) => Some(Event::ScrollContents(Offset::Viewport(1))), Input::Kb(Key::PageDown, None) => Some(Event::ScrollContents(Offset::Viewport(-1))), Input::Kb(Key::Home, None) => Some(Event::ScrollContents(Offset::Top)), Input::Kb(Key::End, None) => Some(Event::ScrollContents(Offset::Bottom)), Input::Resize => Some(Event::Resize), _ => None, } } fn create_input_event(&self) -> Option<Event> { match self.input { Input::Kb(Key::Left, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_LEFT_SEQ.to_vec()))) } Input::Kb(Key::Right, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_RIGHT_SEQ.to_vec()))) } Input::Kb(Key::Home, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_HOME_SEQ.to_vec()))) } Input::Kb(Key::End, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_END_SEQ.to_vec()))) } Input::Kb(Key::Delete, None) => { let mut keys = KEY_RIGHT_SEQ.to_vec(); keys.extend(KEY_BACKSPACE_SEQ.to_vec()); Some(Event::Search(SearchAction::ReadInput(keys))) } Input::Kb(Key::Backspace, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_BACKSPACE_SEQ.to_vec()))) } Input::Kb(_, ref modifier) => { let mut keys = vec![self.key]; if let Some(Modifier::Alt(value)) = *modifier { keys.push(value) }; Some(Event::Search(SearchAction::ReadInput(keys))) } _ => None, } } }
{ EventBuilder { input: input, key: key, } }
identifier_body
event.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ use ui::input::*; use ui::readline; use ui::navigation::State as NavigationState; pub enum Direction { Left, Right, } #[derive(Clone, Hash, PartialEq, Eq)] pub enum SearchAction { ReadInput(Vec<i32>), ToggleFilterMode, FindNextMatch, FindPreviousMatch, } pub enum Offset { Line(i32), Viewport(i32), Top, Bottom, } pub enum Event { ScrollContents(Offset), SelectMenuItem(Direction), Navigation(NavigationState), Search(SearchAction), Resize, Quit, Other, } #[derive(Clone, Hash, PartialEq, Eq)] pub enum QueuedEvent { Unhighlight(SearchAction), PerformSearch, } pub struct EventBuilder { input: Input, key: i32, } impl EventBuilder { pub fn new(input: Input, key: i32) -> EventBuilder { EventBuilder { input: input, key: key, } } pub fn construct(&self, current_navigation_state: &NavigationState) -> Event { let mut result = self.create_global_event(); if result.is_none() { result = match *current_navigation_state { NavigationState::Menu => self.create_menu_event(), NavigationState::Search => self.create_search_event(), }; } result.unwrap_or(Event::Other) } fn create_menu_event(&self) -> Option<Event> { match self.input { Input::Kb(Key::Left, None) => Some(Event::SelectMenuItem(Direction::Left)), Input::Kb(Key::Right, None) => Some(Event::SelectMenuItem(Direction::Right)), Input::Kb(Key::Char('/'), None) | Input::Kb(Key::Char('F'), Some(Modifier::Ctrl)) => { Some(Event::Navigation(NavigationState::Search)) } Input::Kb(Key::Char('q'), None) => Some(Event::Quit), _ => None, } } fn create_search_event(&self) -> Option<Event> { match self.input { Input::Kb(Key::Char('n'), Some(Modifier::Alt(_))) => { Some(Event::Search(SearchAction::FindNextMatch)) } Input::Kb(Key::Char('p'), Some(Modifier::Alt(_))) => { Some(Event::Search(SearchAction::FindPreviousMatch)) } Input::Kb(Key::Char('m'), Some(Modifier::Alt(_))) => { Some(Event::Search(SearchAction::ToggleFilterMode)) } Input::Kb(Key::Escape, None) if!readline::is_history() => { Some(Event::Navigation(NavigationState::Menu)) } _ => self.create_input_event(), } } fn create_global_event(&self) -> Option<Event> { match self.input { Input::Kb(Key::Up, None) => Some(Event::ScrollContents(Offset::Line(1))), Input::Kb(Key::Down, None) => Some(Event::ScrollContents(Offset::Line(-1))), Input::Kb(Key::PageUp, None) => Some(Event::ScrollContents(Offset::Viewport(1))), Input::Kb(Key::PageDown, None) => Some(Event::ScrollContents(Offset::Viewport(-1))),
} fn create_input_event(&self) -> Option<Event> { match self.input { Input::Kb(Key::Left, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_LEFT_SEQ.to_vec()))) } Input::Kb(Key::Right, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_RIGHT_SEQ.to_vec()))) } Input::Kb(Key::Home, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_HOME_SEQ.to_vec()))) } Input::Kb(Key::End, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_END_SEQ.to_vec()))) } Input::Kb(Key::Delete, None) => { let mut keys = KEY_RIGHT_SEQ.to_vec(); keys.extend(KEY_BACKSPACE_SEQ.to_vec()); Some(Event::Search(SearchAction::ReadInput(keys))) } Input::Kb(Key::Backspace, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_BACKSPACE_SEQ.to_vec()))) } Input::Kb(_, ref modifier) => { let mut keys = vec![self.key]; if let Some(Modifier::Alt(value)) = *modifier { keys.push(value) }; Some(Event::Search(SearchAction::ReadInput(keys))) } _ => None, } } }
Input::Kb(Key::Home, None) => Some(Event::ScrollContents(Offset::Top)), Input::Kb(Key::End, None) => Some(Event::ScrollContents(Offset::Bottom)), Input::Resize => Some(Event::Resize), _ => None, }
random_line_split
event.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ use ui::input::*; use ui::readline; use ui::navigation::State as NavigationState; pub enum Direction { Left, Right, } #[derive(Clone, Hash, PartialEq, Eq)] pub enum SearchAction { ReadInput(Vec<i32>), ToggleFilterMode, FindNextMatch, FindPreviousMatch, } pub enum Offset { Line(i32), Viewport(i32), Top, Bottom, } pub enum Event { ScrollContents(Offset), SelectMenuItem(Direction), Navigation(NavigationState), Search(SearchAction), Resize, Quit, Other, } #[derive(Clone, Hash, PartialEq, Eq)] pub enum QueuedEvent { Unhighlight(SearchAction), PerformSearch, } pub struct EventBuilder { input: Input, key: i32, } impl EventBuilder { pub fn new(input: Input, key: i32) -> EventBuilder { EventBuilder { input: input, key: key, } } pub fn construct(&self, current_navigation_state: &NavigationState) -> Event { let mut result = self.create_global_event(); if result.is_none() { result = match *current_navigation_state { NavigationState::Menu => self.create_menu_event(), NavigationState::Search => self.create_search_event(), }; } result.unwrap_or(Event::Other) } fn create_menu_event(&self) -> Option<Event> { match self.input { Input::Kb(Key::Left, None) => Some(Event::SelectMenuItem(Direction::Left)), Input::Kb(Key::Right, None) => Some(Event::SelectMenuItem(Direction::Right)), Input::Kb(Key::Char('/'), None) | Input::Kb(Key::Char('F'), Some(Modifier::Ctrl)) => { Some(Event::Navigation(NavigationState::Search)) } Input::Kb(Key::Char('q'), None) => Some(Event::Quit), _ => None, } } fn
(&self) -> Option<Event> { match self.input { Input::Kb(Key::Char('n'), Some(Modifier::Alt(_))) => { Some(Event::Search(SearchAction::FindNextMatch)) } Input::Kb(Key::Char('p'), Some(Modifier::Alt(_))) => { Some(Event::Search(SearchAction::FindPreviousMatch)) } Input::Kb(Key::Char('m'), Some(Modifier::Alt(_))) => { Some(Event::Search(SearchAction::ToggleFilterMode)) } Input::Kb(Key::Escape, None) if!readline::is_history() => { Some(Event::Navigation(NavigationState::Menu)) } _ => self.create_input_event(), } } fn create_global_event(&self) -> Option<Event> { match self.input { Input::Kb(Key::Up, None) => Some(Event::ScrollContents(Offset::Line(1))), Input::Kb(Key::Down, None) => Some(Event::ScrollContents(Offset::Line(-1))), Input::Kb(Key::PageUp, None) => Some(Event::ScrollContents(Offset::Viewport(1))), Input::Kb(Key::PageDown, None) => Some(Event::ScrollContents(Offset::Viewport(-1))), Input::Kb(Key::Home, None) => Some(Event::ScrollContents(Offset::Top)), Input::Kb(Key::End, None) => Some(Event::ScrollContents(Offset::Bottom)), Input::Resize => Some(Event::Resize), _ => None, } } fn create_input_event(&self) -> Option<Event> { match self.input { Input::Kb(Key::Left, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_LEFT_SEQ.to_vec()))) } Input::Kb(Key::Right, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_RIGHT_SEQ.to_vec()))) } Input::Kb(Key::Home, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_HOME_SEQ.to_vec()))) } Input::Kb(Key::End, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_END_SEQ.to_vec()))) } Input::Kb(Key::Delete, None) => { let mut keys = KEY_RIGHT_SEQ.to_vec(); keys.extend(KEY_BACKSPACE_SEQ.to_vec()); Some(Event::Search(SearchAction::ReadInput(keys))) } Input::Kb(Key::Backspace, None) => { Some(Event::Search(SearchAction::ReadInput(KEY_BACKSPACE_SEQ.to_vec()))) } Input::Kb(_, ref modifier) => { let mut keys = vec![self.key]; if let Some(Modifier::Alt(value)) = *modifier { keys.push(value) }; Some(Event::Search(SearchAction::ReadInput(keys))) } _ => None, } } }
create_search_event
identifier_name
allocator.rs
use crate::attributes; use libc::c_uint; use rustc_ast::expand::allocator::{AllocatorKind, AllocatorTy, ALLOCATOR_METHODS}; use rustc_middle::bug; use rustc_middle::ty::TyCtxt; use rustc_session::config::DebugInfo; use rustc_span::symbol::sym; use crate::debuginfo; use crate::llvm::{self, False, True}; use crate::ModuleLlvm; pub(crate) unsafe fn codegen( tcx: TyCtxt<'_>, module_llvm: &mut ModuleLlvm, module_name: &str, kind: AllocatorKind, has_alloc_error_handler: bool, )
} AllocatorTy::Ptr => args.push(i8p), AllocatorTy::Usize => args.push(usize), AllocatorTy::ResultPtr | AllocatorTy::Unit => panic!("invalid allocator arg"), } } let output = match method.output { AllocatorTy::ResultPtr => Some(i8p), AllocatorTy::Unit => None, AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => { panic!("invalid allocator output") } }; let ty = llvm::LLVMFunctionType( output.unwrap_or(void), args.as_ptr(), args.len() as c_uint, False, ); let name = format!("__rust_{}", method.name); let llfn = llvm::LLVMRustGetOrInsertFunction(llmod, name.as_ptr().cast(), name.len(), ty); if tcx.sess.target.default_hidden_visibility { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } if tcx.sess.must_emit_unwind_tables() { attributes::emit_uwtable(llfn, true); } let callee = kind.fn_name(method.name); let callee = llvm::LLVMRustGetOrInsertFunction(llmod, callee.as_ptr().cast(), callee.len(), ty); llvm::LLVMRustSetVisibility(callee, llvm::Visibility::Hidden); let llbb = llvm::LLVMAppendBasicBlockInContext(llcx, llfn, "entry\0".as_ptr().cast()); let llbuilder = llvm::LLVMCreateBuilderInContext(llcx); llvm::LLVMPositionBuilderAtEnd(llbuilder, llbb); let args = args .iter() .enumerate() .map(|(i, _)| llvm::LLVMGetParam(llfn, i as c_uint)) .collect::<Vec<_>>(); let ret = llvm::LLVMRustBuildCall( llbuilder, ty, callee, args.as_ptr(), args.len() as c_uint, None, ); llvm::LLVMSetTailCall(ret, True); if output.is_some() { llvm::LLVMBuildRet(llbuilder, ret); } else { llvm::LLVMBuildRetVoid(llbuilder); } llvm::LLVMDisposeBuilder(llbuilder); } // rust alloc error handler let args = [usize, usize]; // size, align let ty = llvm::LLVMFunctionType(void, args.as_ptr(), args.len() as c_uint, False); let name = "__rust_alloc_error_handler"; let llfn = llvm::LLVMRustGetOrInsertFunction(llmod, name.as_ptr().cast(), name.len(), ty); // ->! DIFlagNoReturn llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, llfn); if tcx.sess.target.default_hidden_visibility { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } if tcx.sess.must_emit_unwind_tables() { attributes::emit_uwtable(llfn, true); } let kind = if has_alloc_error_handler { AllocatorKind::Global } else { AllocatorKind::Default }; let callee = kind.fn_name(sym::oom); let callee = llvm::LLVMRustGetOrInsertFunction(llmod, callee.as_ptr().cast(), callee.len(), ty); // ->! DIFlagNoReturn llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, callee); llvm::LLVMRustSetVisibility(callee, llvm::Visibility::Hidden); let llbb = llvm::LLVMAppendBasicBlockInContext(llcx, llfn, "entry\0".as_ptr().cast()); let llbuilder = llvm::LLVMCreateBuilderInContext(llcx); llvm::LLVMPositionBuilderAtEnd(llbuilder, llbb); let args = args .iter() .enumerate() .map(|(i, _)| llvm::LLVMGetParam(llfn, i as c_uint)) .collect::<Vec<_>>(); let ret = llvm::LLVMRustBuildCall(llbuilder, ty, callee, args.as_ptr(), args.len() as c_uint, None); llvm::LLVMSetTailCall(ret, True); llvm::LLVMBuildRetVoid(llbuilder); llvm::LLVMDisposeBuilder(llbuilder); if tcx.sess.opts.debuginfo!= DebugInfo::None { let dbg_cx = debuginfo::CrateDebugContext::new(llmod); debuginfo::metadata::compile_unit_metadata(tcx, module_name, &dbg_cx); dbg_cx.finalize(tcx.sess); } }
{ let llcx = &*module_llvm.llcx; let llmod = module_llvm.llmod(); let usize = match tcx.sess.target.pointer_width { 16 => llvm::LLVMInt16TypeInContext(llcx), 32 => llvm::LLVMInt32TypeInContext(llcx), 64 => llvm::LLVMInt64TypeInContext(llcx), tws => bug!("Unsupported target word size for int: {}", tws), }; let i8 = llvm::LLVMInt8TypeInContext(llcx); let i8p = llvm::LLVMPointerType(i8, 0); let void = llvm::LLVMVoidTypeInContext(llcx); for method in ALLOCATOR_METHODS { let mut args = Vec::with_capacity(method.inputs.len()); for ty in method.inputs.iter() { match *ty { AllocatorTy::Layout => { args.push(usize); // size args.push(usize); // align
identifier_body
allocator.rs
use crate::attributes; use libc::c_uint; use rustc_ast::expand::allocator::{AllocatorKind, AllocatorTy, ALLOCATOR_METHODS}; use rustc_middle::bug; use rustc_middle::ty::TyCtxt; use rustc_session::config::DebugInfo; use rustc_span::symbol::sym; use crate::debuginfo; use crate::llvm::{self, False, True}; use crate::ModuleLlvm; pub(crate) unsafe fn codegen( tcx: TyCtxt<'_>, module_llvm: &mut ModuleLlvm, module_name: &str, kind: AllocatorKind, has_alloc_error_handler: bool, ) { let llcx = &*module_llvm.llcx; let llmod = module_llvm.llmod(); let usize = match tcx.sess.target.pointer_width { 16 => llvm::LLVMInt16TypeInContext(llcx), 32 => llvm::LLVMInt32TypeInContext(llcx), 64 => llvm::LLVMInt64TypeInContext(llcx), tws => bug!("Unsupported target word size for int: {}", tws), }; let i8 = llvm::LLVMInt8TypeInContext(llcx); let i8p = llvm::LLVMPointerType(i8, 0); let void = llvm::LLVMVoidTypeInContext(llcx); for method in ALLOCATOR_METHODS { let mut args = Vec::with_capacity(method.inputs.len()); for ty in method.inputs.iter() { match *ty { AllocatorTy::Layout => { args.push(usize); // size args.push(usize); // align } AllocatorTy::Ptr => args.push(i8p), AllocatorTy::Usize => args.push(usize), AllocatorTy::ResultPtr | AllocatorTy::Unit => panic!("invalid allocator arg"), } } let output = match method.output { AllocatorTy::ResultPtr => Some(i8p), AllocatorTy::Unit => None, AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => { panic!("invalid allocator output") } }; let ty = llvm::LLVMFunctionType( output.unwrap_or(void), args.as_ptr(), args.len() as c_uint, False, ); let name = format!("__rust_{}", method.name); let llfn = llvm::LLVMRustGetOrInsertFunction(llmod, name.as_ptr().cast(), name.len(), ty); if tcx.sess.target.default_hidden_visibility { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } if tcx.sess.must_emit_unwind_tables() { attributes::emit_uwtable(llfn, true); } let callee = kind.fn_name(method.name); let callee = llvm::LLVMRustGetOrInsertFunction(llmod, callee.as_ptr().cast(), callee.len(), ty); llvm::LLVMRustSetVisibility(callee, llvm::Visibility::Hidden); let llbb = llvm::LLVMAppendBasicBlockInContext(llcx, llfn, "entry\0".as_ptr().cast()); let llbuilder = llvm::LLVMCreateBuilderInContext(llcx); llvm::LLVMPositionBuilderAtEnd(llbuilder, llbb); let args = args .iter() .enumerate() .map(|(i, _)| llvm::LLVMGetParam(llfn, i as c_uint)) .collect::<Vec<_>>(); let ret = llvm::LLVMRustBuildCall( llbuilder, ty, callee, args.as_ptr(), args.len() as c_uint, None, ); llvm::LLVMSetTailCall(ret, True); if output.is_some() { llvm::LLVMBuildRet(llbuilder, ret); } else { llvm::LLVMBuildRetVoid(llbuilder); } llvm::LLVMDisposeBuilder(llbuilder); }
let ty = llvm::LLVMFunctionType(void, args.as_ptr(), args.len() as c_uint, False); let name = "__rust_alloc_error_handler"; let llfn = llvm::LLVMRustGetOrInsertFunction(llmod, name.as_ptr().cast(), name.len(), ty); // ->! DIFlagNoReturn llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, llfn); if tcx.sess.target.default_hidden_visibility { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } if tcx.sess.must_emit_unwind_tables() { attributes::emit_uwtable(llfn, true); } let kind = if has_alloc_error_handler { AllocatorKind::Global } else { AllocatorKind::Default }; let callee = kind.fn_name(sym::oom); let callee = llvm::LLVMRustGetOrInsertFunction(llmod, callee.as_ptr().cast(), callee.len(), ty); // ->! DIFlagNoReturn llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, callee); llvm::LLVMRustSetVisibility(callee, llvm::Visibility::Hidden); let llbb = llvm::LLVMAppendBasicBlockInContext(llcx, llfn, "entry\0".as_ptr().cast()); let llbuilder = llvm::LLVMCreateBuilderInContext(llcx); llvm::LLVMPositionBuilderAtEnd(llbuilder, llbb); let args = args .iter() .enumerate() .map(|(i, _)| llvm::LLVMGetParam(llfn, i as c_uint)) .collect::<Vec<_>>(); let ret = llvm::LLVMRustBuildCall(llbuilder, ty, callee, args.as_ptr(), args.len() as c_uint, None); llvm::LLVMSetTailCall(ret, True); llvm::LLVMBuildRetVoid(llbuilder); llvm::LLVMDisposeBuilder(llbuilder); if tcx.sess.opts.debuginfo!= DebugInfo::None { let dbg_cx = debuginfo::CrateDebugContext::new(llmod); debuginfo::metadata::compile_unit_metadata(tcx, module_name, &dbg_cx); dbg_cx.finalize(tcx.sess); } }
// rust alloc error handler let args = [usize, usize]; // size, align
random_line_split
allocator.rs
use crate::attributes; use libc::c_uint; use rustc_ast::expand::allocator::{AllocatorKind, AllocatorTy, ALLOCATOR_METHODS}; use rustc_middle::bug; use rustc_middle::ty::TyCtxt; use rustc_session::config::DebugInfo; use rustc_span::symbol::sym; use crate::debuginfo; use crate::llvm::{self, False, True}; use crate::ModuleLlvm; pub(crate) unsafe fn
( tcx: TyCtxt<'_>, module_llvm: &mut ModuleLlvm, module_name: &str, kind: AllocatorKind, has_alloc_error_handler: bool, ) { let llcx = &*module_llvm.llcx; let llmod = module_llvm.llmod(); let usize = match tcx.sess.target.pointer_width { 16 => llvm::LLVMInt16TypeInContext(llcx), 32 => llvm::LLVMInt32TypeInContext(llcx), 64 => llvm::LLVMInt64TypeInContext(llcx), tws => bug!("Unsupported target word size for int: {}", tws), }; let i8 = llvm::LLVMInt8TypeInContext(llcx); let i8p = llvm::LLVMPointerType(i8, 0); let void = llvm::LLVMVoidTypeInContext(llcx); for method in ALLOCATOR_METHODS { let mut args = Vec::with_capacity(method.inputs.len()); for ty in method.inputs.iter() { match *ty { AllocatorTy::Layout => { args.push(usize); // size args.push(usize); // align } AllocatorTy::Ptr => args.push(i8p), AllocatorTy::Usize => args.push(usize), AllocatorTy::ResultPtr | AllocatorTy::Unit => panic!("invalid allocator arg"), } } let output = match method.output { AllocatorTy::ResultPtr => Some(i8p), AllocatorTy::Unit => None, AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => { panic!("invalid allocator output") } }; let ty = llvm::LLVMFunctionType( output.unwrap_or(void), args.as_ptr(), args.len() as c_uint, False, ); let name = format!("__rust_{}", method.name); let llfn = llvm::LLVMRustGetOrInsertFunction(llmod, name.as_ptr().cast(), name.len(), ty); if tcx.sess.target.default_hidden_visibility { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } if tcx.sess.must_emit_unwind_tables() { attributes::emit_uwtable(llfn, true); } let callee = kind.fn_name(method.name); let callee = llvm::LLVMRustGetOrInsertFunction(llmod, callee.as_ptr().cast(), callee.len(), ty); llvm::LLVMRustSetVisibility(callee, llvm::Visibility::Hidden); let llbb = llvm::LLVMAppendBasicBlockInContext(llcx, llfn, "entry\0".as_ptr().cast()); let llbuilder = llvm::LLVMCreateBuilderInContext(llcx); llvm::LLVMPositionBuilderAtEnd(llbuilder, llbb); let args = args .iter() .enumerate() .map(|(i, _)| llvm::LLVMGetParam(llfn, i as c_uint)) .collect::<Vec<_>>(); let ret = llvm::LLVMRustBuildCall( llbuilder, ty, callee, args.as_ptr(), args.len() as c_uint, None, ); llvm::LLVMSetTailCall(ret, True); if output.is_some() { llvm::LLVMBuildRet(llbuilder, ret); } else { llvm::LLVMBuildRetVoid(llbuilder); } llvm::LLVMDisposeBuilder(llbuilder); } // rust alloc error handler let args = [usize, usize]; // size, align let ty = llvm::LLVMFunctionType(void, args.as_ptr(), args.len() as c_uint, False); let name = "__rust_alloc_error_handler"; let llfn = llvm::LLVMRustGetOrInsertFunction(llmod, name.as_ptr().cast(), name.len(), ty); // ->! DIFlagNoReturn llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, llfn); if tcx.sess.target.default_hidden_visibility { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } if tcx.sess.must_emit_unwind_tables() { attributes::emit_uwtable(llfn, true); } let kind = if has_alloc_error_handler { AllocatorKind::Global } else { AllocatorKind::Default }; let callee = kind.fn_name(sym::oom); let callee = llvm::LLVMRustGetOrInsertFunction(llmod, callee.as_ptr().cast(), callee.len(), ty); // ->! DIFlagNoReturn llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, callee); llvm::LLVMRustSetVisibility(callee, llvm::Visibility::Hidden); let llbb = llvm::LLVMAppendBasicBlockInContext(llcx, llfn, "entry\0".as_ptr().cast()); let llbuilder = llvm::LLVMCreateBuilderInContext(llcx); llvm::LLVMPositionBuilderAtEnd(llbuilder, llbb); let args = args .iter() .enumerate() .map(|(i, _)| llvm::LLVMGetParam(llfn, i as c_uint)) .collect::<Vec<_>>(); let ret = llvm::LLVMRustBuildCall(llbuilder, ty, callee, args.as_ptr(), args.len() as c_uint, None); llvm::LLVMSetTailCall(ret, True); llvm::LLVMBuildRetVoid(llbuilder); llvm::LLVMDisposeBuilder(llbuilder); if tcx.sess.opts.debuginfo!= DebugInfo::None { let dbg_cx = debuginfo::CrateDebugContext::new(llmod); debuginfo::metadata::compile_unit_metadata(tcx, module_name, &dbg_cx); dbg_cx.finalize(tcx.sess); } }
codegen
identifier_name
allocator.rs
use crate::attributes; use libc::c_uint; use rustc_ast::expand::allocator::{AllocatorKind, AllocatorTy, ALLOCATOR_METHODS}; use rustc_middle::bug; use rustc_middle::ty::TyCtxt; use rustc_session::config::DebugInfo; use rustc_span::symbol::sym; use crate::debuginfo; use crate::llvm::{self, False, True}; use crate::ModuleLlvm; pub(crate) unsafe fn codegen( tcx: TyCtxt<'_>, module_llvm: &mut ModuleLlvm, module_name: &str, kind: AllocatorKind, has_alloc_error_handler: bool, ) { let llcx = &*module_llvm.llcx; let llmod = module_llvm.llmod(); let usize = match tcx.sess.target.pointer_width { 16 => llvm::LLVMInt16TypeInContext(llcx), 32 => llvm::LLVMInt32TypeInContext(llcx), 64 => llvm::LLVMInt64TypeInContext(llcx), tws => bug!("Unsupported target word size for int: {}", tws), }; let i8 = llvm::LLVMInt8TypeInContext(llcx); let i8p = llvm::LLVMPointerType(i8, 0); let void = llvm::LLVMVoidTypeInContext(llcx); for method in ALLOCATOR_METHODS { let mut args = Vec::with_capacity(method.inputs.len()); for ty in method.inputs.iter() { match *ty { AllocatorTy::Layout => { args.push(usize); // size args.push(usize); // align } AllocatorTy::Ptr => args.push(i8p), AllocatorTy::Usize => args.push(usize), AllocatorTy::ResultPtr | AllocatorTy::Unit => panic!("invalid allocator arg"), } } let output = match method.output { AllocatorTy::ResultPtr => Some(i8p), AllocatorTy::Unit => None, AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => { panic!("invalid allocator output") } }; let ty = llvm::LLVMFunctionType( output.unwrap_or(void), args.as_ptr(), args.len() as c_uint, False, ); let name = format!("__rust_{}", method.name); let llfn = llvm::LLVMRustGetOrInsertFunction(llmod, name.as_ptr().cast(), name.len(), ty); if tcx.sess.target.default_hidden_visibility { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } if tcx.sess.must_emit_unwind_tables() { attributes::emit_uwtable(llfn, true); } let callee = kind.fn_name(method.name); let callee = llvm::LLVMRustGetOrInsertFunction(llmod, callee.as_ptr().cast(), callee.len(), ty); llvm::LLVMRustSetVisibility(callee, llvm::Visibility::Hidden); let llbb = llvm::LLVMAppendBasicBlockInContext(llcx, llfn, "entry\0".as_ptr().cast()); let llbuilder = llvm::LLVMCreateBuilderInContext(llcx); llvm::LLVMPositionBuilderAtEnd(llbuilder, llbb); let args = args .iter() .enumerate() .map(|(i, _)| llvm::LLVMGetParam(llfn, i as c_uint)) .collect::<Vec<_>>(); let ret = llvm::LLVMRustBuildCall( llbuilder, ty, callee, args.as_ptr(), args.len() as c_uint, None, ); llvm::LLVMSetTailCall(ret, True); if output.is_some()
else { llvm::LLVMBuildRetVoid(llbuilder); } llvm::LLVMDisposeBuilder(llbuilder); } // rust alloc error handler let args = [usize, usize]; // size, align let ty = llvm::LLVMFunctionType(void, args.as_ptr(), args.len() as c_uint, False); let name = "__rust_alloc_error_handler"; let llfn = llvm::LLVMRustGetOrInsertFunction(llmod, name.as_ptr().cast(), name.len(), ty); // ->! DIFlagNoReturn llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, llfn); if tcx.sess.target.default_hidden_visibility { llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); } if tcx.sess.must_emit_unwind_tables() { attributes::emit_uwtable(llfn, true); } let kind = if has_alloc_error_handler { AllocatorKind::Global } else { AllocatorKind::Default }; let callee = kind.fn_name(sym::oom); let callee = llvm::LLVMRustGetOrInsertFunction(llmod, callee.as_ptr().cast(), callee.len(), ty); // ->! DIFlagNoReturn llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, callee); llvm::LLVMRustSetVisibility(callee, llvm::Visibility::Hidden); let llbb = llvm::LLVMAppendBasicBlockInContext(llcx, llfn, "entry\0".as_ptr().cast()); let llbuilder = llvm::LLVMCreateBuilderInContext(llcx); llvm::LLVMPositionBuilderAtEnd(llbuilder, llbb); let args = args .iter() .enumerate() .map(|(i, _)| llvm::LLVMGetParam(llfn, i as c_uint)) .collect::<Vec<_>>(); let ret = llvm::LLVMRustBuildCall(llbuilder, ty, callee, args.as_ptr(), args.len() as c_uint, None); llvm::LLVMSetTailCall(ret, True); llvm::LLVMBuildRetVoid(llbuilder); llvm::LLVMDisposeBuilder(llbuilder); if tcx.sess.opts.debuginfo!= DebugInfo::None { let dbg_cx = debuginfo::CrateDebugContext::new(llmod); debuginfo::metadata::compile_unit_metadata(tcx, module_name, &dbg_cx); dbg_cx.finalize(tcx.sess); } }
{ llvm::LLVMBuildRet(llbuilder, ret); }
conditional_block
main.rs
#[macro_use] extern crate glium; extern crate glium_text_rusttype as glium_text; extern crate glutin; extern crate winit; use std::io; use std::io::prelude::*; use std::fs::File; use glium::{Surface, Program}; use glium::backend::Facade; use glium::glutin::{Event, WindowEvent}; #[derive(Copy, Clone, Debug, PartialEq)] pub struct Point { position: (f32, f32) } implement_vertex!(Point, position); /// The four corners of OpenGL screen space. const VERTICES: [Point; 4] = [ Point { position: ( 1.0, 1.0 ) }, Point { position: ( -1.0, 1.0 ) }, Point { position: ( -1.0, -1.0 ) }, Point { position: ( 1.0, -1.0 ) }, ]; /// Two triangles arranged as a rectangle covering OpenGL screen space. /// All the real work happens in the fragment shader, so we just want to /// run the shader on every pixel. const INDICES: [u16; 6] = [ 0, 1, 2, 0, 2, 3 ]; fn main() { let mut event_loop = winit::EventsLoop::new(); let window = winit::WindowBuilder::new() .with_title("Julia"); let context = glutin::ContextBuilder::new(); let display = glium::Display::new(window, context, &event_loop) .expect("failed to build glium window"); /* let system = glium_text::TextSystem::new(&display); let fontfile = File::open("/home/jimb/rust/julia-glium/src/Inconsolata-Regular.ttf") .expect("error opening Inconsolata.otf file"); let font = glium_text::FontTexture::new(&display, fontfile, 24, glium_text::FontTexture::ascii_character_list()) .expect("error creating font texture"); */ let positions = glium::VertexBuffer::new(&display, &VERTICES) .expect("building positions"); let indices = glium::IndexBuffer::new(&display, glium::index::PrimitiveType::TrianglesList, &INDICES) .expect("building indices"); let mut program = Program::from_source(&display, &include_str!("julia.vert"), &include_str!("julia.frag"), None) .expect("building program"); let mut dimensions = display.get_framebuffer_dimensions(); let mut aspect = dimensions.0 as f32 / dimensions.1 as f32; let mut c = [ 0.0, 0.0f32 ]; loop { if let Ok(p) = load_shader_program(&display) { program = p; } let mut target = display.draw(); target.clear_color(0.0, 0.0, 1.0, 1.0); let params = Default::default(); target.draw(&positions, &indices, &program, &uniform! { screen_to_complex: if aspect < 1.0 { [ 2.0, 2.0 / aspect ] } else { [ 2.0 * aspect, 2.0 ] }, c: c }, &params) .expect("draw Julia set"); /* let text = glium_text::TextDisplay::new(&system, &font, &format!("{}+i{}", c[0], c[1])); let text_matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; glium_text::draw(&text, &system, &mut target, text_matrix, (0.0, 0.0, 0.0, 1.0)) .expect("draw c text"); */ target.finish().expect("target.finish"); let mut should_return = false; event_loop.poll_events(|ev| { match ev { Event::WindowEvent { event: WindowEvent::Closed,.. } => { should_return = true; } Event::WindowEvent { event: WindowEvent::Resized(w, h),.. } => { dimensions = (w, h); aspect = dimensions.0 as f32 / dimensions.1 as f32; } Event::WindowEvent { event: WindowEvent::CursorMoved { position: (x,y),.. },.. } => { // Map pixels to complex coordinates, keeping the circle of radius // two centered at the origin in the middle of the image. if dimensions.0 > dimensions.1 { // Window is wider than it is high. c[0] = (x as f32 / dimensions.0 as f32 - 0.5) * 2.0 * aspect; c[1] = (y as f32 / dimensions.1 as f32 - 0.5) * 2.0; } else { // Window is higher than it is wide. c[0] = (x as f32 / dimensions.0 as f32 - 0.5) * 2.0; c[1] = (y as f32 / dimensions.1 as f32 - 0.5) * 2.0 / aspect; } }, _ => () } }); if should_return { return; } } } #[derive(Debug)] struct ShaderError; impl From<std::io::Error> for ShaderError { fn
(_e: io::Error) -> ShaderError { ShaderError } } fn read_file(path: &str) -> io::Result<String> { let mut s = String::new(); let mut f = try!(File::open(path)); try!(f.read_to_string(&mut s)); Ok(s) } fn load_shader_program<F: Facade>(display: &F) -> Result<Program, ShaderError> { let vert_shader = try!(read_file("src/julia.vert")); let frag_shader = try!(read_file("src/julia.frag")); if let Ok(p) = glium::Program::from_source(display, &vert_shader, &frag_shader, None) { Ok(p) } else { Err(ShaderError) } }
from
identifier_name
main.rs
#[macro_use] extern crate glium; extern crate glium_text_rusttype as glium_text; extern crate glutin; extern crate winit; use std::io; use std::io::prelude::*; use std::fs::File; use glium::{Surface, Program}; use glium::backend::Facade; use glium::glutin::{Event, WindowEvent}; #[derive(Copy, Clone, Debug, PartialEq)] pub struct Point { position: (f32, f32) } implement_vertex!(Point, position); /// The four corners of OpenGL screen space.
Point { position: ( -1.0, 1.0 ) }, Point { position: ( -1.0, -1.0 ) }, Point { position: ( 1.0, -1.0 ) }, ]; /// Two triangles arranged as a rectangle covering OpenGL screen space. /// All the real work happens in the fragment shader, so we just want to /// run the shader on every pixel. const INDICES: [u16; 6] = [ 0, 1, 2, 0, 2, 3 ]; fn main() { let mut event_loop = winit::EventsLoop::new(); let window = winit::WindowBuilder::new() .with_title("Julia"); let context = glutin::ContextBuilder::new(); let display = glium::Display::new(window, context, &event_loop) .expect("failed to build glium window"); /* let system = glium_text::TextSystem::new(&display); let fontfile = File::open("/home/jimb/rust/julia-glium/src/Inconsolata-Regular.ttf") .expect("error opening Inconsolata.otf file"); let font = glium_text::FontTexture::new(&display, fontfile, 24, glium_text::FontTexture::ascii_character_list()) .expect("error creating font texture"); */ let positions = glium::VertexBuffer::new(&display, &VERTICES) .expect("building positions"); let indices = glium::IndexBuffer::new(&display, glium::index::PrimitiveType::TrianglesList, &INDICES) .expect("building indices"); let mut program = Program::from_source(&display, &include_str!("julia.vert"), &include_str!("julia.frag"), None) .expect("building program"); let mut dimensions = display.get_framebuffer_dimensions(); let mut aspect = dimensions.0 as f32 / dimensions.1 as f32; let mut c = [ 0.0, 0.0f32 ]; loop { if let Ok(p) = load_shader_program(&display) { program = p; } let mut target = display.draw(); target.clear_color(0.0, 0.0, 1.0, 1.0); let params = Default::default(); target.draw(&positions, &indices, &program, &uniform! { screen_to_complex: if aspect < 1.0 { [ 2.0, 2.0 / aspect ] } else { [ 2.0 * aspect, 2.0 ] }, c: c }, &params) .expect("draw Julia set"); /* let text = glium_text::TextDisplay::new(&system, &font, &format!("{}+i{}", c[0], c[1])); let text_matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; glium_text::draw(&text, &system, &mut target, text_matrix, (0.0, 0.0, 0.0, 1.0)) .expect("draw c text"); */ target.finish().expect("target.finish"); let mut should_return = false; event_loop.poll_events(|ev| { match ev { Event::WindowEvent { event: WindowEvent::Closed,.. } => { should_return = true; } Event::WindowEvent { event: WindowEvent::Resized(w, h),.. } => { dimensions = (w, h); aspect = dimensions.0 as f32 / dimensions.1 as f32; } Event::WindowEvent { event: WindowEvent::CursorMoved { position: (x,y),.. },.. } => { // Map pixels to complex coordinates, keeping the circle of radius // two centered at the origin in the middle of the image. if dimensions.0 > dimensions.1 { // Window is wider than it is high. c[0] = (x as f32 / dimensions.0 as f32 - 0.5) * 2.0 * aspect; c[1] = (y as f32 / dimensions.1 as f32 - 0.5) * 2.0; } else { // Window is higher than it is wide. c[0] = (x as f32 / dimensions.0 as f32 - 0.5) * 2.0; c[1] = (y as f32 / dimensions.1 as f32 - 0.5) * 2.0 / aspect; } }, _ => () } }); if should_return { return; } } } #[derive(Debug)] struct ShaderError; impl From<std::io::Error> for ShaderError { fn from(_e: io::Error) -> ShaderError { ShaderError } } fn read_file(path: &str) -> io::Result<String> { let mut s = String::new(); let mut f = try!(File::open(path)); try!(f.read_to_string(&mut s)); Ok(s) } fn load_shader_program<F: Facade>(display: &F) -> Result<Program, ShaderError> { let vert_shader = try!(read_file("src/julia.vert")); let frag_shader = try!(read_file("src/julia.frag")); if let Ok(p) = glium::Program::from_source(display, &vert_shader, &frag_shader, None) { Ok(p) } else { Err(ShaderError) } }
const VERTICES: [Point; 4] = [ Point { position: ( 1.0, 1.0 ) },
random_line_split
main.rs
#[macro_use] extern crate glium; extern crate glium_text_rusttype as glium_text; extern crate glutin; extern crate winit; use std::io; use std::io::prelude::*; use std::fs::File; use glium::{Surface, Program}; use glium::backend::Facade; use glium::glutin::{Event, WindowEvent}; #[derive(Copy, Clone, Debug, PartialEq)] pub struct Point { position: (f32, f32) } implement_vertex!(Point, position); /// The four corners of OpenGL screen space. const VERTICES: [Point; 4] = [ Point { position: ( 1.0, 1.0 ) }, Point { position: ( -1.0, 1.0 ) }, Point { position: ( -1.0, -1.0 ) }, Point { position: ( 1.0, -1.0 ) }, ]; /// Two triangles arranged as a rectangle covering OpenGL screen space. /// All the real work happens in the fragment shader, so we just want to /// run the shader on every pixel. const INDICES: [u16; 6] = [ 0, 1, 2, 0, 2, 3 ]; fn main() { let mut event_loop = winit::EventsLoop::new(); let window = winit::WindowBuilder::new() .with_title("Julia"); let context = glutin::ContextBuilder::new(); let display = glium::Display::new(window, context, &event_loop) .expect("failed to build glium window"); /* let system = glium_text::TextSystem::new(&display); let fontfile = File::open("/home/jimb/rust/julia-glium/src/Inconsolata-Regular.ttf") .expect("error opening Inconsolata.otf file"); let font = glium_text::FontTexture::new(&display, fontfile, 24, glium_text::FontTexture::ascii_character_list()) .expect("error creating font texture"); */ let positions = glium::VertexBuffer::new(&display, &VERTICES) .expect("building positions"); let indices = glium::IndexBuffer::new(&display, glium::index::PrimitiveType::TrianglesList, &INDICES) .expect("building indices"); let mut program = Program::from_source(&display, &include_str!("julia.vert"), &include_str!("julia.frag"), None) .expect("building program"); let mut dimensions = display.get_framebuffer_dimensions(); let mut aspect = dimensions.0 as f32 / dimensions.1 as f32; let mut c = [ 0.0, 0.0f32 ]; loop { if let Ok(p) = load_shader_program(&display) { program = p; } let mut target = display.draw(); target.clear_color(0.0, 0.0, 1.0, 1.0); let params = Default::default(); target.draw(&positions, &indices, &program, &uniform! { screen_to_complex: if aspect < 1.0 { [ 2.0, 2.0 / aspect ] } else { [ 2.0 * aspect, 2.0 ] }, c: c }, &params) .expect("draw Julia set"); /* let text = glium_text::TextDisplay::new(&system, &font, &format!("{}+i{}", c[0], c[1])); let text_matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; glium_text::draw(&text, &system, &mut target, text_matrix, (0.0, 0.0, 0.0, 1.0)) .expect("draw c text"); */ target.finish().expect("target.finish"); let mut should_return = false; event_loop.poll_events(|ev| { match ev { Event::WindowEvent { event: WindowEvent::Closed,.. } => { should_return = true; } Event::WindowEvent { event: WindowEvent::Resized(w, h),.. } => { dimensions = (w, h); aspect = dimensions.0 as f32 / dimensions.1 as f32; } Event::WindowEvent { event: WindowEvent::CursorMoved { position: (x,y),.. },.. } => { // Map pixels to complex coordinates, keeping the circle of radius // two centered at the origin in the middle of the image. if dimensions.0 > dimensions.1 { // Window is wider than it is high. c[0] = (x as f32 / dimensions.0 as f32 - 0.5) * 2.0 * aspect; c[1] = (y as f32 / dimensions.1 as f32 - 0.5) * 2.0; } else { // Window is higher than it is wide. c[0] = (x as f32 / dimensions.0 as f32 - 0.5) * 2.0; c[1] = (y as f32 / dimensions.1 as f32 - 0.5) * 2.0 / aspect; } }, _ => () } }); if should_return { return; } } } #[derive(Debug)] struct ShaderError; impl From<std::io::Error> for ShaderError { fn from(_e: io::Error) -> ShaderError { ShaderError } } fn read_file(path: &str) -> io::Result<String> { let mut s = String::new(); let mut f = try!(File::open(path)); try!(f.read_to_string(&mut s)); Ok(s) } fn load_shader_program<F: Facade>(display: &F) -> Result<Program, ShaderError> { let vert_shader = try!(read_file("src/julia.vert")); let frag_shader = try!(read_file("src/julia.frag")); if let Ok(p) = glium::Program::from_source(display, &vert_shader, &frag_shader, None) { Ok(p) } else
}
{ Err(ShaderError) }
conditional_block
blockDoc.rs
/*! # Iterator * * The heart and soul of this module is the [`Iterator`] trait. The core of * [`Iterator`] looks like this: * * ``` * trait Iterator { * type Item; * fn next(&mut self) -> Option<Self::Item>; * }
* [`Option`]`<Item>`. [`next()`] will return `Some(Item)` as long as there * are elements, and once they've all been exhausted, will return `None` to * indicate that iteration is finished. Individual iterators may choose to * resume iteration, and so calling [`next()`] again may or may not eventually * start returning `Some(Item)` again at some point. * * [`Iterator`]'s full definition includes a number of other methods as well, * but they are default methods, built on top of [`next()`], and so you get * them for free. * * Iterators are also composable, and it's common to chain them together to do * more complex forms of processing. See the [Adapters](#adapters) section * below for more details. * * [`Iterator`]: trait.Iterator.html * [`next()`]: trait.Iterator.html#tymethod.next * [`Option`]:../../std/option/enum.Option.html */ /**The `Option` type. See [the module level documentation](index.html) for more.*/ /** Lorem ipsum dolor sit amet, consectetur adipiscing elit, * sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. * Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris * nisi ut aliquip ex ea commodo consequat. */ /** missing asterisk */ /** ``` missing asterisk ``` */
* ``` * * An iterator has a method, [`next()`], which when called, returns an
random_line_split
html_writer.rs
extern crate marksman_escape; use self::marksman_escape::Escape; use {DomNode, DomNodes, DomValue}; use processors::DomNodeProcessor; // This module as a whole is "use_std"-only, so these don't need to be cfg'd use std::marker::PhantomData; use std::fmt; use std::io; /// Type to use for processing a `DomNode` tree and writing it to HTML. /// /// This type should not ever need to be instantiated. Instead, simply /// name the type in calls to `DomNodes::process_all::<HtmlWriter<...>>(...)`. #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct HtmlWriter<W: io::Write>(PhantomData<W>); impl<'a, M, W: io::Write> DomNodeProcessor<'a, M> for HtmlWriter<W> { type Acc = W; type Error = io::Error; fn get_processor<T: DomNode<M>>() -> fn(&mut Self::Acc, &T) -> Result<(), Self::Error> { fn add_node<M, W, T>(w: &mut W, node: &T) -> Result<(), io::Error> where W: io::Write, T: DomNode<M> { match node.value() { DomValue::Element { tag: tagname } => { write!(w, "<{}", tagname)?; for attr in node.attributes() { write!(w, " {}=\"{}\"", attr.0, attr.1)?; } write!(w, ">")?; node.children().process_all::<HtmlWriter<W>>(w)?; write!(w, "</{}>", tagname) } DomValue::Text(text) =>
} } add_node } } /// Wrapper struct to allow `DomNode`s to implement `Display` as html #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct HtmlDisplayable<'a, M, T: DomNode<M> + 'a>(pub &'a T, pub PhantomData<M>); impl<'a, M, T: DomNode<M>> fmt::Display for HtmlDisplayable<'a, M, T> { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { // TODO the extra string allocation here is almost certainly avoidable let mut string_buffer = Vec::new(); self.0.write_html(&mut string_buffer) .map_err(|_| fmt::Error)?; let string = String::from_utf8(string_buffer) .map_err(|_| fmt::Error)?; formatter.write_str(&string) } }
{ for escaped_u8 in Escape::new(text.bytes()) { w.write(&[escaped_u8])?; } Ok(()) }
conditional_block
html_writer.rs
extern crate marksman_escape; use self::marksman_escape::Escape; use {DomNode, DomNodes, DomValue}; use processors::DomNodeProcessor; // This module as a whole is "use_std"-only, so these don't need to be cfg'd use std::marker::PhantomData; use std::fmt; use std::io; /// Type to use for processing a `DomNode` tree and writing it to HTML. /// /// This type should not ever need to be instantiated. Instead, simply /// name the type in calls to `DomNodes::process_all::<HtmlWriter<...>>(...)`. #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct HtmlWriter<W: io::Write>(PhantomData<W>); impl<'a, M, W: io::Write> DomNodeProcessor<'a, M> for HtmlWriter<W> { type Acc = W; type Error = io::Error; fn get_processor<T: DomNode<M>>() -> fn(&mut Self::Acc, &T) -> Result<(), Self::Error> { fn add_node<M, W, T>(w: &mut W, node: &T) -> Result<(), io::Error> where W: io::Write, T: DomNode<M> { match node.value() { DomValue::Element { tag: tagname } => { write!(w, "<{}", tagname)?; for attr in node.attributes() { write!(w, " {}=\"{}\"", attr.0, attr.1)?; } write!(w, ">")?; node.children().process_all::<HtmlWriter<W>>(w)?; write!(w, "</{}>", tagname) } DomValue::Text(text) => { for escaped_u8 in Escape::new(text.bytes()) { w.write(&[escaped_u8])?; } Ok(()) } } } add_node } }
impl<'a, M, T: DomNode<M>> fmt::Display for HtmlDisplayable<'a, M, T> { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { // TODO the extra string allocation here is almost certainly avoidable let mut string_buffer = Vec::new(); self.0.write_html(&mut string_buffer) .map_err(|_| fmt::Error)?; let string = String::from_utf8(string_buffer) .map_err(|_| fmt::Error)?; formatter.write_str(&string) } }
/// Wrapper struct to allow `DomNode`s to implement `Display` as html #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct HtmlDisplayable<'a, M, T: DomNode<M> + 'a>(pub &'a T, pub PhantomData<M>);
random_line_split
html_writer.rs
extern crate marksman_escape; use self::marksman_escape::Escape; use {DomNode, DomNodes, DomValue}; use processors::DomNodeProcessor; // This module as a whole is "use_std"-only, so these don't need to be cfg'd use std::marker::PhantomData; use std::fmt; use std::io; /// Type to use for processing a `DomNode` tree and writing it to HTML. /// /// This type should not ever need to be instantiated. Instead, simply /// name the type in calls to `DomNodes::process_all::<HtmlWriter<...>>(...)`. #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct HtmlWriter<W: io::Write>(PhantomData<W>); impl<'a, M, W: io::Write> DomNodeProcessor<'a, M> for HtmlWriter<W> { type Acc = W; type Error = io::Error; fn get_processor<T: DomNode<M>>() -> fn(&mut Self::Acc, &T) -> Result<(), Self::Error> { fn add_node<M, W, T>(w: &mut W, node: &T) -> Result<(), io::Error> where W: io::Write, T: DomNode<M> { match node.value() { DomValue::Element { tag: tagname } => { write!(w, "<{}", tagname)?; for attr in node.attributes() { write!(w, " {}=\"{}\"", attr.0, attr.1)?; } write!(w, ">")?; node.children().process_all::<HtmlWriter<W>>(w)?; write!(w, "</{}>", tagname) } DomValue::Text(text) => { for escaped_u8 in Escape::new(text.bytes()) { w.write(&[escaped_u8])?; } Ok(()) } } } add_node } } /// Wrapper struct to allow `DomNode`s to implement `Display` as html #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct HtmlDisplayable<'a, M, T: DomNode<M> + 'a>(pub &'a T, pub PhantomData<M>); impl<'a, M, T: DomNode<M>> fmt::Display for HtmlDisplayable<'a, M, T> { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error>
}
{ // TODO the extra string allocation here is almost certainly avoidable let mut string_buffer = Vec::new(); self.0.write_html(&mut string_buffer) .map_err(|_| fmt::Error)?; let string = String::from_utf8(string_buffer) .map_err(|_| fmt::Error)?; formatter.write_str(&string) }
identifier_body
html_writer.rs
extern crate marksman_escape; use self::marksman_escape::Escape; use {DomNode, DomNodes, DomValue}; use processors::DomNodeProcessor; // This module as a whole is "use_std"-only, so these don't need to be cfg'd use std::marker::PhantomData; use std::fmt; use std::io; /// Type to use for processing a `DomNode` tree and writing it to HTML. /// /// This type should not ever need to be instantiated. Instead, simply /// name the type in calls to `DomNodes::process_all::<HtmlWriter<...>>(...)`. #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct HtmlWriter<W: io::Write>(PhantomData<W>); impl<'a, M, W: io::Write> DomNodeProcessor<'a, M> for HtmlWriter<W> { type Acc = W; type Error = io::Error; fn get_processor<T: DomNode<M>>() -> fn(&mut Self::Acc, &T) -> Result<(), Self::Error> { fn add_node<M, W, T>(w: &mut W, node: &T) -> Result<(), io::Error> where W: io::Write, T: DomNode<M> { match node.value() { DomValue::Element { tag: tagname } => { write!(w, "<{}", tagname)?; for attr in node.attributes() { write!(w, " {}=\"{}\"", attr.0, attr.1)?; } write!(w, ">")?; node.children().process_all::<HtmlWriter<W>>(w)?; write!(w, "</{}>", tagname) } DomValue::Text(text) => { for escaped_u8 in Escape::new(text.bytes()) { w.write(&[escaped_u8])?; } Ok(()) } } } add_node } } /// Wrapper struct to allow `DomNode`s to implement `Display` as html #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct
<'a, M, T: DomNode<M> + 'a>(pub &'a T, pub PhantomData<M>); impl<'a, M, T: DomNode<M>> fmt::Display for HtmlDisplayable<'a, M, T> { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { // TODO the extra string allocation here is almost certainly avoidable let mut string_buffer = Vec::new(); self.0.write_html(&mut string_buffer) .map_err(|_| fmt::Error)?; let string = String::from_utf8(string_buffer) .map_err(|_| fmt::Error)?; formatter.write_str(&string) } }
HtmlDisplayable
identifier_name
load_instructions.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 extern crate test_generation; use test_generation::abstract_state::{AbstractState, AbstractValue}; use vm::file_format::{Bytecode, ConstantPoolIndex, SignatureToken}; mod common; #[test] fn bytecode_ldu64() { let state1 = AbstractState::new(); let (state2, _) = common::run_instruction(Bytecode::LdU64(0), state1); assert_eq!( state2.stack_peek(0), Some(AbstractValue::new_primitive(SignatureToken::U64)), "stack type postcondition not met" ); } #[test] fn bytecode_ldtrue() { let state1 = AbstractState::new(); let (state2, _) = common::run_instruction(Bytecode::LdTrue, state1); assert_eq!( state2.stack_peek(0), Some(AbstractValue::new_primitive(SignatureToken::Bool)), "stack type postcondition not met" ); } #[test] fn bytecode_ldfalse() { let state1 = AbstractState::new(); let (state2, _) = common::run_instruction(Bytecode::LdFalse, state1); assert_eq!( state2.stack_peek(0), Some(AbstractValue::new_primitive(SignatureToken::Bool)), "stack type postcondition not met" ); } #[test] fn bytecode_ldconst()
{ let state1 = AbstractState::new(); let (state2, _) = common::run_instruction(Bytecode::LdConst(ConstantPoolIndex::new(0)), state1); assert_eq!( state2.stack_peek(0), Some(AbstractValue::new_primitive(SignatureToken::Address)), "stack type postcondition not met" ); }
identifier_body
load_instructions.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 extern crate test_generation; use test_generation::abstract_state::{AbstractState, AbstractValue}; use vm::file_format::{Bytecode, ConstantPoolIndex, SignatureToken}; mod common; #[test] fn bytecode_ldu64() { let state1 = AbstractState::new(); let (state2, _) = common::run_instruction(Bytecode::LdU64(0), state1); assert_eq!( state2.stack_peek(0), Some(AbstractValue::new_primitive(SignatureToken::U64)), "stack type postcondition not met" ); } #[test] fn bytecode_ldtrue() { let state1 = AbstractState::new(); let (state2, _) = common::run_instruction(Bytecode::LdTrue, state1); assert_eq!( state2.stack_peek(0), Some(AbstractValue::new_primitive(SignatureToken::Bool)), "stack type postcondition not met" ); } #[test] fn bytecode_ldfalse() { let state1 = AbstractState::new(); let (state2, _) = common::run_instruction(Bytecode::LdFalse, state1); assert_eq!( state2.stack_peek(0), Some(AbstractValue::new_primitive(SignatureToken::Bool)), "stack type postcondition not met" ); } #[test] fn
() { let state1 = AbstractState::new(); let (state2, _) = common::run_instruction(Bytecode::LdConst(ConstantPoolIndex::new(0)), state1); assert_eq!( state2.stack_peek(0), Some(AbstractValue::new_primitive(SignatureToken::Address)), "stack type postcondition not met" ); }
bytecode_ldconst
identifier_name
load_instructions.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0
#[test] fn bytecode_ldu64() { let state1 = AbstractState::new(); let (state2, _) = common::run_instruction(Bytecode::LdU64(0), state1); assert_eq!( state2.stack_peek(0), Some(AbstractValue::new_primitive(SignatureToken::U64)), "stack type postcondition not met" ); } #[test] fn bytecode_ldtrue() { let state1 = AbstractState::new(); let (state2, _) = common::run_instruction(Bytecode::LdTrue, state1); assert_eq!( state2.stack_peek(0), Some(AbstractValue::new_primitive(SignatureToken::Bool)), "stack type postcondition not met" ); } #[test] fn bytecode_ldfalse() { let state1 = AbstractState::new(); let (state2, _) = common::run_instruction(Bytecode::LdFalse, state1); assert_eq!( state2.stack_peek(0), Some(AbstractValue::new_primitive(SignatureToken::Bool)), "stack type postcondition not met" ); } #[test] fn bytecode_ldconst() { let state1 = AbstractState::new(); let (state2, _) = common::run_instruction(Bytecode::LdConst(ConstantPoolIndex::new(0)), state1); assert_eq!( state2.stack_peek(0), Some(AbstractValue::new_primitive(SignatureToken::Address)), "stack type postcondition not met" ); }
extern crate test_generation; use test_generation::abstract_state::{AbstractState, AbstractValue}; use vm::file_format::{Bytecode, ConstantPoolIndex, SignatureToken}; mod common;
random_line_split
lib.rs
#![cfg(any( target_os = "windows", target_os = "linux", target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ))] #![allow(non_camel_case_types)] pub mod egl { pub type khronos_utime_nanoseconds_t = super::khronos_utime_nanoseconds_t; pub type khronos_uint64_t = super::khronos_uint64_t; pub type khronos_ssize_t = super::khronos_ssize_t; pub type EGLNativeDisplayType = super::EGLNativeDisplayType; pub type EGLNativePixmapType = super::EGLNativePixmapType; pub type EGLNativeWindowType = super::EGLNativeWindowType; pub type EGLint = super::EGLint;
include!(concat!(env!("OUT_DIR"), "/egl_bindings.rs")); } pub use self::egl::types::EGLContext; pub use self::egl::types::EGLDisplay; use std::os::raw; pub type khronos_utime_nanoseconds_t = khronos_uint64_t; pub type khronos_uint64_t = u64; pub type khronos_ssize_t = raw::c_long; pub type EGLint = i32; pub type EGLNativeDisplayType = *const raw::c_void; pub type EGLNativePixmapType = *const raw::c_void; // FIXME: egl_native_pixmap_t instead #[cfg(target_os = "windows")] pub type EGLNativeWindowType = winapi::shared::windef::HWND; #[cfg(target_os = "linux")] pub type EGLNativeWindowType = *const raw::c_void; #[cfg(target_os = "android")] pub type EGLNativeWindowType = *const raw::c_void; #[cfg(any( target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ))] pub type EGLNativeWindowType = *const raw::c_void;
pub type NativeDisplayType = super::EGLNativeDisplayType; pub type NativePixmapType = super::EGLNativePixmapType; pub type NativeWindowType = super::EGLNativeWindowType;
random_line_split
iso_8859_5.rs
pub fn charmap() -> [&'static str,.. 256]
"\x14", // 0x14 "\x15", // 0x15 "\x16", // 0x16 "\x17", // 0x17 "\x18", // 0x18 "\x19", // 0x19 "\x1a", // 0x1a "\x1b", // 0x1b "\x1c", // 0x1c "\x1d", // 0x1d "\x1e", // 0x1e "\x1f", // 0x1f " ", // 0x20 "!", // 0x21 "\"", // 0x22 "#", // 0x23 "$", // 0x24 "%", // 0x25 "&", // 0x26 "'", // 0x27 "(", // 0x28 ")", // 0x29 "*", // 0x2a "+", // 0x2b ",", // 0x2c "-", // 0x2d ".", // 0x2e "/", // 0x2f "0", // 0x30 "1", // 0x31 "2", // 0x32 "3", // 0x33 "4", // 0x34 "5", // 0x35 "6", // 0x36 "7", // 0x37 "8", // 0x38 "9", // 0x39 ":", // 0x3a ";", // 0x3b "<", // 0x3c "=", // 0x3d ">", // 0x3e "?", // 0x3f "@", // 0x40 "A", // 0x41 "B", // 0x42 "C", // 0x43 "D", // 0x44 "E", // 0x45 "F", // 0x46 "G", // 0x47 "H", // 0x48 "I", // 0x49 "J", // 0x4a "K", // 0x4b "L", // 0x4c "M", // 0x4d "N", // 0x4e "O", // 0x4f "P", // 0x50 "Q", // 0x51 "R", // 0x52 "S", // 0x53 "T", // 0x54 "U", // 0x55 "V", // 0x56 "W", // 0x57 "X", // 0x58 "Y", // 0x59 "Z", // 0x5a "[", // 0x5b "\\", // 0x5c "]", // 0x5d "^", // 0x5e "_", // 0x5f "`", // 0x60 "a", // 0x61 "b", // 0x62 "c", // 0x63 "d", // 0x64 "e", // 0x65 "f", // 0x66 "g", // 0x67 "h", // 0x68 "i", // 0x69 "j", // 0x6a "k", // 0x6b "l", // 0x6c "m", // 0x6d "n", // 0x6e "o", // 0x6f "p", // 0x70 "q", // 0x71 "r", // 0x72 "s", // 0x73 "t", // 0x74 "u", // 0x75 "v", // 0x76 "w", // 0x77 "x", // 0x78 "y", // 0x79 "z", // 0x7a "{", // 0x7b "|", // 0x7c "}", // 0x7d "~", // 0x7e "\x7f", // 0x7f "\x80", // 0x80 "\x81", // 0x81 "\x82", // 0x82 "\x83", // 0x83 "\x84", // 0x84 "\x85", // 0x85 "\x86", // 0x86 "\x87", // 0x87 "\x88", // 0x88 "\x89", // 0x89 "\x8a", // 0x8a "\x8b", // 0x8b "\x8c", // 0x8c "\x8d", // 0x8d "\x8e", // 0x8e "\x8f", // 0x8f "\x90", // 0x90 "\x91", // 0x91 "\x92", // 0x92 "\x93", // 0x93 "\x94", // 0x94 "\x95", // 0x95 "\x96", // 0x96 "\x97", // 0x97 "\x98", // 0x98 "\x99", // 0x99 "\x9a", // 0x9a "\x9b", // 0x9b "\x9c", // 0x9c "\x9d", // 0x9d "\x9e", // 0x9e "\x9f", // 0x9f "\xa0", // 0xa0 "\u0401", // 0xa1 "\u0402", // 0xa2 "\u0403", // 0xa3 "\u0404", // 0xa4 "\u0405", // 0xa5 "\u0406", // 0xa6 "\u0407", // 0xa7 "\u0408", // 0xa8 "\u0409", // 0xa9 "\u040a", // 0xaa "\u040b", // 0xab "\u040c", // 0xac "\xad", // 0xad "\u040e", // 0xae "\u040f", // 0xaf "\u0410", // 0xb0 "\u0411", // 0xb1 "\u0412", // 0xb2 "\u0413", // 0xb3 "\u0414", // 0xb4 "\u0415", // 0xb5 "\u0416", // 0xb6 "\u0417", // 0xb7 "\u0418", // 0xb8 "\u0419", // 0xb9 "\u041a", // 0xba "\u041b", // 0xbb "\u041c", // 0xbc "\u041d", // 0xbd "\u041e", // 0xbe "\u041f", // 0xbf "\u0420", // 0xc0 "\u0421", // 0xc1 "\u0422", // 0xc2 "\u0423", // 0xc3 "\u0424", // 0xc4 "\u0425", // 0xc5 "\u0426", // 0xc6 "\u0427", // 0xc7 "\u0428", // 0xc8 "\u0429", // 0xc9 "\u042a", // 0xca "\u042b", // 0xcb "\u042c", // 0xcc "\u042d", // 0xcd "\u042e", // 0xce "\u042f", // 0xcf "\u0430", // 0xd0 "\u0431", // 0xd1 "\u0432", // 0xd2 "\u0433", // 0xd3 "\u0434", // 0xd4 "\u0435", // 0xd5 "\u0436", // 0xd6 "\u0437", // 0xd7 "\u0438", // 0xd8 "\u0439", // 0xd9 "\u043a", // 0xda "\u043b", // 0xdb "\u043c", // 0xdc "\u043d", // 0xdd "\u043e", // 0xde "\u043f", // 0xdf "\u0440", // 0xe0 "\u0441", // 0xe1 "\u0442", // 0xe2 "\u0443", // 0xe3 "\u0444", // 0xe4 "\u0445", // 0xe5 "\u0446", // 0xe6 "\u0447", // 0xe7 "\u0448", // 0xe8 "\u0449", // 0xe9 "\u044a", // 0xea "\u044b", // 0xeb "\u044c", // 0xec "\u044d", // 0xed "\u044e", // 0xee "\u044f", // 0xef "\u2116", // 0xf0 "\u0451", // 0xf1 "\u0452", // 0xf2 "\u0453", // 0xf3 "\u0454", // 0xf4 "\u0455", // 0xf5 "\u0456", // 0xf6 "\u0457", // 0xf7 "\u0458", // 0xf8 "\u0459", // 0xf9 "\u045a", // 0xfa "\u045b", // 0xfb "\u045c", // 0xfc "\xa7", // 0xfd "\u045e", // 0xfe "\u045f", // 0xff ];}
{ return ["\x00", // 0x0 "\x01", // 0x1 "\x02", // 0x2 "\x03", // 0x3 "\x04", // 0x4 "\x05", // 0x5 "\x06", // 0x6 "\x07", // 0x7 "\x08", // 0x8 "\t", // 0x9 "\n", // 0xa "\x0b", // 0xb "\x0c", // 0xc "\r", // 0xd "\x0e", // 0xe "\x0f", // 0xf "\x10", // 0x10 "\x11", // 0x11 "\x12", // 0x12 "\x13", // 0x13
identifier_body
iso_8859_5.rs
pub fn charmap() -> [&'static str,.. 256]{ return ["\x00", // 0x0 "\x01", // 0x1 "\x02", // 0x2 "\x03", // 0x3 "\x04", // 0x4 "\x05", // 0x5 "\x06", // 0x6 "\x07", // 0x7 "\x08", // 0x8 "\t", // 0x9 "\n", // 0xa "\x0b", // 0xb "\x0c", // 0xc "\r", // 0xd "\x0e", // 0xe "\x0f", // 0xf "\x10", // 0x10 "\x11", // 0x11 "\x12", // 0x12 "\x13", // 0x13 "\x14", // 0x14 "\x15", // 0x15 "\x16", // 0x16 "\x17", // 0x17 "\x18", // 0x18 "\x19", // 0x19 "\x1a", // 0x1a "\x1b", // 0x1b "\x1c", // 0x1c "\x1d", // 0x1d "\x1e", // 0x1e "\x1f", // 0x1f " ", // 0x20 "!", // 0x21 "\"", // 0x22 "#", // 0x23 "$", // 0x24 "%", // 0x25 "&", // 0x26 "'", // 0x27 "(", // 0x28 ")", // 0x29 "*", // 0x2a "+", // 0x2b ",", // 0x2c "-", // 0x2d ".", // 0x2e "/", // 0x2f "0", // 0x30 "1", // 0x31 "2", // 0x32 "3", // 0x33 "4", // 0x34 "5", // 0x35 "6", // 0x36 "7", // 0x37 "8", // 0x38 "9", // 0x39 ":", // 0x3a ";", // 0x3b "<", // 0x3c "=", // 0x3d ">", // 0x3e "?", // 0x3f "@", // 0x40 "A", // 0x41 "B", // 0x42 "C", // 0x43 "D", // 0x44 "E", // 0x45 "F", // 0x46 "G", // 0x47 "H", // 0x48 "I", // 0x49
"M", // 0x4d "N", // 0x4e "O", // 0x4f "P", // 0x50 "Q", // 0x51 "R", // 0x52 "S", // 0x53 "T", // 0x54 "U", // 0x55 "V", // 0x56 "W", // 0x57 "X", // 0x58 "Y", // 0x59 "Z", // 0x5a "[", // 0x5b "\\", // 0x5c "]", // 0x5d "^", // 0x5e "_", // 0x5f "`", // 0x60 "a", // 0x61 "b", // 0x62 "c", // 0x63 "d", // 0x64 "e", // 0x65 "f", // 0x66 "g", // 0x67 "h", // 0x68 "i", // 0x69 "j", // 0x6a "k", // 0x6b "l", // 0x6c "m", // 0x6d "n", // 0x6e "o", // 0x6f "p", // 0x70 "q", // 0x71 "r", // 0x72 "s", // 0x73 "t", // 0x74 "u", // 0x75 "v", // 0x76 "w", // 0x77 "x", // 0x78 "y", // 0x79 "z", // 0x7a "{", // 0x7b "|", // 0x7c "}", // 0x7d "~", // 0x7e "\x7f", // 0x7f "\x80", // 0x80 "\x81", // 0x81 "\x82", // 0x82 "\x83", // 0x83 "\x84", // 0x84 "\x85", // 0x85 "\x86", // 0x86 "\x87", // 0x87 "\x88", // 0x88 "\x89", // 0x89 "\x8a", // 0x8a "\x8b", // 0x8b "\x8c", // 0x8c "\x8d", // 0x8d "\x8e", // 0x8e "\x8f", // 0x8f "\x90", // 0x90 "\x91", // 0x91 "\x92", // 0x92 "\x93", // 0x93 "\x94", // 0x94 "\x95", // 0x95 "\x96", // 0x96 "\x97", // 0x97 "\x98", // 0x98 "\x99", // 0x99 "\x9a", // 0x9a "\x9b", // 0x9b "\x9c", // 0x9c "\x9d", // 0x9d "\x9e", // 0x9e "\x9f", // 0x9f "\xa0", // 0xa0 "\u0401", // 0xa1 "\u0402", // 0xa2 "\u0403", // 0xa3 "\u0404", // 0xa4 "\u0405", // 0xa5 "\u0406", // 0xa6 "\u0407", // 0xa7 "\u0408", // 0xa8 "\u0409", // 0xa9 "\u040a", // 0xaa "\u040b", // 0xab "\u040c", // 0xac "\xad", // 0xad "\u040e", // 0xae "\u040f", // 0xaf "\u0410", // 0xb0 "\u0411", // 0xb1 "\u0412", // 0xb2 "\u0413", // 0xb3 "\u0414", // 0xb4 "\u0415", // 0xb5 "\u0416", // 0xb6 "\u0417", // 0xb7 "\u0418", // 0xb8 "\u0419", // 0xb9 "\u041a", // 0xba "\u041b", // 0xbb "\u041c", // 0xbc "\u041d", // 0xbd "\u041e", // 0xbe "\u041f", // 0xbf "\u0420", // 0xc0 "\u0421", // 0xc1 "\u0422", // 0xc2 "\u0423", // 0xc3 "\u0424", // 0xc4 "\u0425", // 0xc5 "\u0426", // 0xc6 "\u0427", // 0xc7 "\u0428", // 0xc8 "\u0429", // 0xc9 "\u042a", // 0xca "\u042b", // 0xcb "\u042c", // 0xcc "\u042d", // 0xcd "\u042e", // 0xce "\u042f", // 0xcf "\u0430", // 0xd0 "\u0431", // 0xd1 "\u0432", // 0xd2 "\u0433", // 0xd3 "\u0434", // 0xd4 "\u0435", // 0xd5 "\u0436", // 0xd6 "\u0437", // 0xd7 "\u0438", // 0xd8 "\u0439", // 0xd9 "\u043a", // 0xda "\u043b", // 0xdb "\u043c", // 0xdc "\u043d", // 0xdd "\u043e", // 0xde "\u043f", // 0xdf "\u0440", // 0xe0 "\u0441", // 0xe1 "\u0442", // 0xe2 "\u0443", // 0xe3 "\u0444", // 0xe4 "\u0445", // 0xe5 "\u0446", // 0xe6 "\u0447", // 0xe7 "\u0448", // 0xe8 "\u0449", // 0xe9 "\u044a", // 0xea "\u044b", // 0xeb "\u044c", // 0xec "\u044d", // 0xed "\u044e", // 0xee "\u044f", // 0xef "\u2116", // 0xf0 "\u0451", // 0xf1 "\u0452", // 0xf2 "\u0453", // 0xf3 "\u0454", // 0xf4 "\u0455", // 0xf5 "\u0456", // 0xf6 "\u0457", // 0xf7 "\u0458", // 0xf8 "\u0459", // 0xf9 "\u045a", // 0xfa "\u045b", // 0xfb "\u045c", // 0xfc "\xa7", // 0xfd "\u045e", // 0xfe "\u045f", // 0xff ];}
"J", // 0x4a "K", // 0x4b "L", // 0x4c
random_line_split
iso_8859_5.rs
pub fn
() -> [&'static str,.. 256]{ return ["\x00", // 0x0 "\x01", // 0x1 "\x02", // 0x2 "\x03", // 0x3 "\x04", // 0x4 "\x05", // 0x5 "\x06", // 0x6 "\x07", // 0x7 "\x08", // 0x8 "\t", // 0x9 "\n", // 0xa "\x0b", // 0xb "\x0c", // 0xc "\r", // 0xd "\x0e", // 0xe "\x0f", // 0xf "\x10", // 0x10 "\x11", // 0x11 "\x12", // 0x12 "\x13", // 0x13 "\x14", // 0x14 "\x15", // 0x15 "\x16", // 0x16 "\x17", // 0x17 "\x18", // 0x18 "\x19", // 0x19 "\x1a", // 0x1a "\x1b", // 0x1b "\x1c", // 0x1c "\x1d", // 0x1d "\x1e", // 0x1e "\x1f", // 0x1f " ", // 0x20 "!", // 0x21 "\"", // 0x22 "#", // 0x23 "$", // 0x24 "%", // 0x25 "&", // 0x26 "'", // 0x27 "(", // 0x28 ")", // 0x29 "*", // 0x2a "+", // 0x2b ",", // 0x2c "-", // 0x2d ".", // 0x2e "/", // 0x2f "0", // 0x30 "1", // 0x31 "2", // 0x32 "3", // 0x33 "4", // 0x34 "5", // 0x35 "6", // 0x36 "7", // 0x37 "8", // 0x38 "9", // 0x39 ":", // 0x3a ";", // 0x3b "<", // 0x3c "=", // 0x3d ">", // 0x3e "?", // 0x3f "@", // 0x40 "A", // 0x41 "B", // 0x42 "C", // 0x43 "D", // 0x44 "E", // 0x45 "F", // 0x46 "G", // 0x47 "H", // 0x48 "I", // 0x49 "J", // 0x4a "K", // 0x4b "L", // 0x4c "M", // 0x4d "N", // 0x4e "O", // 0x4f "P", // 0x50 "Q", // 0x51 "R", // 0x52 "S", // 0x53 "T", // 0x54 "U", // 0x55 "V", // 0x56 "W", // 0x57 "X", // 0x58 "Y", // 0x59 "Z", // 0x5a "[", // 0x5b "\\", // 0x5c "]", // 0x5d "^", // 0x5e "_", // 0x5f "`", // 0x60 "a", // 0x61 "b", // 0x62 "c", // 0x63 "d", // 0x64 "e", // 0x65 "f", // 0x66 "g", // 0x67 "h", // 0x68 "i", // 0x69 "j", // 0x6a "k", // 0x6b "l", // 0x6c "m", // 0x6d "n", // 0x6e "o", // 0x6f "p", // 0x70 "q", // 0x71 "r", // 0x72 "s", // 0x73 "t", // 0x74 "u", // 0x75 "v", // 0x76 "w", // 0x77 "x", // 0x78 "y", // 0x79 "z", // 0x7a "{", // 0x7b "|", // 0x7c "}", // 0x7d "~", // 0x7e "\x7f", // 0x7f "\x80", // 0x80 "\x81", // 0x81 "\x82", // 0x82 "\x83", // 0x83 "\x84", // 0x84 "\x85", // 0x85 "\x86", // 0x86 "\x87", // 0x87 "\x88", // 0x88 "\x89", // 0x89 "\x8a", // 0x8a "\x8b", // 0x8b "\x8c", // 0x8c "\x8d", // 0x8d "\x8e", // 0x8e "\x8f", // 0x8f "\x90", // 0x90 "\x91", // 0x91 "\x92", // 0x92 "\x93", // 0x93 "\x94", // 0x94 "\x95", // 0x95 "\x96", // 0x96 "\x97", // 0x97 "\x98", // 0x98 "\x99", // 0x99 "\x9a", // 0x9a "\x9b", // 0x9b "\x9c", // 0x9c "\x9d", // 0x9d "\x9e", // 0x9e "\x9f", // 0x9f "\xa0", // 0xa0 "\u0401", // 0xa1 "\u0402", // 0xa2 "\u0403", // 0xa3 "\u0404", // 0xa4 "\u0405", // 0xa5 "\u0406", // 0xa6 "\u0407", // 0xa7 "\u0408", // 0xa8 "\u0409", // 0xa9 "\u040a", // 0xaa "\u040b", // 0xab "\u040c", // 0xac "\xad", // 0xad "\u040e", // 0xae "\u040f", // 0xaf "\u0410", // 0xb0 "\u0411", // 0xb1 "\u0412", // 0xb2 "\u0413", // 0xb3 "\u0414", // 0xb4 "\u0415", // 0xb5 "\u0416", // 0xb6 "\u0417", // 0xb7 "\u0418", // 0xb8 "\u0419", // 0xb9 "\u041a", // 0xba "\u041b", // 0xbb "\u041c", // 0xbc "\u041d", // 0xbd "\u041e", // 0xbe "\u041f", // 0xbf "\u0420", // 0xc0 "\u0421", // 0xc1 "\u0422", // 0xc2 "\u0423", // 0xc3 "\u0424", // 0xc4 "\u0425", // 0xc5 "\u0426", // 0xc6 "\u0427", // 0xc7 "\u0428", // 0xc8 "\u0429", // 0xc9 "\u042a", // 0xca "\u042b", // 0xcb "\u042c", // 0xcc "\u042d", // 0xcd "\u042e", // 0xce "\u042f", // 0xcf "\u0430", // 0xd0 "\u0431", // 0xd1 "\u0432", // 0xd2 "\u0433", // 0xd3 "\u0434", // 0xd4 "\u0435", // 0xd5 "\u0436", // 0xd6 "\u0437", // 0xd7 "\u0438", // 0xd8 "\u0439", // 0xd9 "\u043a", // 0xda "\u043b", // 0xdb "\u043c", // 0xdc "\u043d", // 0xdd "\u043e", // 0xde "\u043f", // 0xdf "\u0440", // 0xe0 "\u0441", // 0xe1 "\u0442", // 0xe2 "\u0443", // 0xe3 "\u0444", // 0xe4 "\u0445", // 0xe5 "\u0446", // 0xe6 "\u0447", // 0xe7 "\u0448", // 0xe8 "\u0449", // 0xe9 "\u044a", // 0xea "\u044b", // 0xeb "\u044c", // 0xec "\u044d", // 0xed "\u044e", // 0xee "\u044f", // 0xef "\u2116", // 0xf0 "\u0451", // 0xf1 "\u0452", // 0xf2 "\u0453", // 0xf3 "\u0454", // 0xf4 "\u0455", // 0xf5 "\u0456", // 0xf6 "\u0457", // 0xf7 "\u0458", // 0xf8 "\u0459", // 0xf9 "\u045a", // 0xfa "\u045b", // 0xfb "\u045c", // 0xfc "\xa7", // 0xfd "\u045e", // 0xfe "\u045f", // 0xff ];}
charmap
identifier_name
lib.rs
// Copyright (C) 2016 Cloudlabs, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. extern crate libc; use std::fs::File; use std::io; pub trait FileExt { fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize>; fn write_at(&self, offset: u64, data: &[u8]) -> io::Result<usize>; fn close(self) -> io::Result<()>; } impl FileExt for File { fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> { use libc::pread; use std::os::unix::io::AsRawFd; unsafe { cvt(pread(self.as_raw_fd(), buf.as_mut_ptr() as *mut ::libc::c_void, buf.len(), offset as ::libc::off_t) as ::libc::c_int) } } fn write_at(&self, offset: u64, data: &[u8]) -> io::Result<usize> { use libc::pwrite; use std::os::unix::io::AsRawFd; unsafe { cvt(pwrite(self.as_raw_fd(), data.as_ptr() as *const ::libc::c_void, data.len(), offset as ::libc::off_t) as ::libc::c_int) } } fn close(self) -> io::Result<()> { use libc::close; use std::os::unix::io::IntoRawFd; unsafe { cvt(close(self.into_raw_fd())).map(|_| ()) } } } pub trait SparseFileExt { fn punch(&self, offset: u64, size: usize) -> io::Result<()>; } impl SparseFileExt for File { #[cfg(target_os = "linux")] fn punch(&self, offset: u64, size: usize) -> io::Result<()> { use libc::{fallocate, FALLOC_FL_PUNCH_HOLE, FALLOC_FL_KEEP_SIZE}; use std::os::unix::io::AsRawFd; unsafe { cvt(fallocate(self.as_raw_fd(), FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, offset as ::libc::off_t, size as ::libc::off_t) as ::libc::c_int) }.map(|_| ()) } #[cfg(not(target_os = "linux"))] /// WARNING: Implemented using zeroing on the system this documentation was generated for. fn punch(&self, offset: u64, size: usize) -> io::Result<()> { self.write_at(offset, &vec![0; size]).map(|_| ()) } } // Shim for converting C-style errors to io::Errors. fn cvt(err: ::libc::c_int) -> io::Result<usize> { if err < 0
else { Ok(err as usize) } } #[test] fn test_file_ext() { extern crate tempfile; let file = tempfile::tempfile().unwrap(); file.write_at(50, &[1, 2, 3, 4, 5]).unwrap(); file.write_at(100, &[7, 6, 5, 4, 3, 2, 1]).unwrap(); let mut buf = &mut [0; 5]; file.read_at(50, buf).unwrap(); assert_eq!(buf, &[1, 2, 3, 4, 5]); let mut buf = &mut [0; 7]; file.read_at(100, buf).unwrap(); assert_eq!(buf, &[7, 6, 5, 4, 3, 2, 1]); // Punched data is read as zeroed. let mut buf = &mut [1; 5]; file.punch(50, 5).unwrap(); file.read_at(50, buf).unwrap(); assert_eq!(buf, &[0; 5]); // Data at the later offset still present after punch. let mut buf = &mut [0; 7]; file.read_at(100, buf).unwrap(); assert_eq!(buf, &[7, 6, 5, 4, 3, 2, 1]); file.close().unwrap(); }
{ Err(io::Error::last_os_error()) }
conditional_block
lib.rs
// Copyright (C) 2016 Cloudlabs, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. extern crate libc; use std::fs::File; use std::io; pub trait FileExt { fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize>; fn write_at(&self, offset: u64, data: &[u8]) -> io::Result<usize>; fn close(self) -> io::Result<()>; } impl FileExt for File { fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> { use libc::pread; use std::os::unix::io::AsRawFd; unsafe { cvt(pread(self.as_raw_fd(), buf.as_mut_ptr() as *mut ::libc::c_void, buf.len(), offset as ::libc::off_t) as ::libc::c_int) } } fn write_at(&self, offset: u64, data: &[u8]) -> io::Result<usize> { use libc::pwrite; use std::os::unix::io::AsRawFd;
data.as_ptr() as *const ::libc::c_void, data.len(), offset as ::libc::off_t) as ::libc::c_int) } } fn close(self) -> io::Result<()> { use libc::close; use std::os::unix::io::IntoRawFd; unsafe { cvt(close(self.into_raw_fd())).map(|_| ()) } } } pub trait SparseFileExt { fn punch(&self, offset: u64, size: usize) -> io::Result<()>; } impl SparseFileExt for File { #[cfg(target_os = "linux")] fn punch(&self, offset: u64, size: usize) -> io::Result<()> { use libc::{fallocate, FALLOC_FL_PUNCH_HOLE, FALLOC_FL_KEEP_SIZE}; use std::os::unix::io::AsRawFd; unsafe { cvt(fallocate(self.as_raw_fd(), FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, offset as ::libc::off_t, size as ::libc::off_t) as ::libc::c_int) }.map(|_| ()) } #[cfg(not(target_os = "linux"))] /// WARNING: Implemented using zeroing on the system this documentation was generated for. fn punch(&self, offset: u64, size: usize) -> io::Result<()> { self.write_at(offset, &vec![0; size]).map(|_| ()) } } // Shim for converting C-style errors to io::Errors. fn cvt(err: ::libc::c_int) -> io::Result<usize> { if err < 0 { Err(io::Error::last_os_error()) } else { Ok(err as usize) } } #[test] fn test_file_ext() { extern crate tempfile; let file = tempfile::tempfile().unwrap(); file.write_at(50, &[1, 2, 3, 4, 5]).unwrap(); file.write_at(100, &[7, 6, 5, 4, 3, 2, 1]).unwrap(); let mut buf = &mut [0; 5]; file.read_at(50, buf).unwrap(); assert_eq!(buf, &[1, 2, 3, 4, 5]); let mut buf = &mut [0; 7]; file.read_at(100, buf).unwrap(); assert_eq!(buf, &[7, 6, 5, 4, 3, 2, 1]); // Punched data is read as zeroed. let mut buf = &mut [1; 5]; file.punch(50, 5).unwrap(); file.read_at(50, buf).unwrap(); assert_eq!(buf, &[0; 5]); // Data at the later offset still present after punch. let mut buf = &mut [0; 7]; file.read_at(100, buf).unwrap(); assert_eq!(buf, &[7, 6, 5, 4, 3, 2, 1]); file.close().unwrap(); }
unsafe { cvt(pwrite(self.as_raw_fd(),
random_line_split
lib.rs
// Copyright (C) 2016 Cloudlabs, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. extern crate libc; use std::fs::File; use std::io; pub trait FileExt { fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize>; fn write_at(&self, offset: u64, data: &[u8]) -> io::Result<usize>; fn close(self) -> io::Result<()>; } impl FileExt for File { fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> { use libc::pread; use std::os::unix::io::AsRawFd; unsafe { cvt(pread(self.as_raw_fd(), buf.as_mut_ptr() as *mut ::libc::c_void, buf.len(), offset as ::libc::off_t) as ::libc::c_int) } } fn write_at(&self, offset: u64, data: &[u8]) -> io::Result<usize> { use libc::pwrite; use std::os::unix::io::AsRawFd; unsafe { cvt(pwrite(self.as_raw_fd(), data.as_ptr() as *const ::libc::c_void, data.len(), offset as ::libc::off_t) as ::libc::c_int) } } fn close(self) -> io::Result<()> { use libc::close; use std::os::unix::io::IntoRawFd; unsafe { cvt(close(self.into_raw_fd())).map(|_| ()) } } } pub trait SparseFileExt { fn punch(&self, offset: u64, size: usize) -> io::Result<()>; } impl SparseFileExt for File { #[cfg(target_os = "linux")] fn
(&self, offset: u64, size: usize) -> io::Result<()> { use libc::{fallocate, FALLOC_FL_PUNCH_HOLE, FALLOC_FL_KEEP_SIZE}; use std::os::unix::io::AsRawFd; unsafe { cvt(fallocate(self.as_raw_fd(), FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, offset as ::libc::off_t, size as ::libc::off_t) as ::libc::c_int) }.map(|_| ()) } #[cfg(not(target_os = "linux"))] /// WARNING: Implemented using zeroing on the system this documentation was generated for. fn punch(&self, offset: u64, size: usize) -> io::Result<()> { self.write_at(offset, &vec![0; size]).map(|_| ()) } } // Shim for converting C-style errors to io::Errors. fn cvt(err: ::libc::c_int) -> io::Result<usize> { if err < 0 { Err(io::Error::last_os_error()) } else { Ok(err as usize) } } #[test] fn test_file_ext() { extern crate tempfile; let file = tempfile::tempfile().unwrap(); file.write_at(50, &[1, 2, 3, 4, 5]).unwrap(); file.write_at(100, &[7, 6, 5, 4, 3, 2, 1]).unwrap(); let mut buf = &mut [0; 5]; file.read_at(50, buf).unwrap(); assert_eq!(buf, &[1, 2, 3, 4, 5]); let mut buf = &mut [0; 7]; file.read_at(100, buf).unwrap(); assert_eq!(buf, &[7, 6, 5, 4, 3, 2, 1]); // Punched data is read as zeroed. let mut buf = &mut [1; 5]; file.punch(50, 5).unwrap(); file.read_at(50, buf).unwrap(); assert_eq!(buf, &[0; 5]); // Data at the later offset still present after punch. let mut buf = &mut [0; 7]; file.read_at(100, buf).unwrap(); assert_eq!(buf, &[7, 6, 5, 4, 3, 2, 1]); file.close().unwrap(); }
punch
identifier_name
lib.rs
// Copyright (C) 2016 Cloudlabs, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. extern crate libc; use std::fs::File; use std::io; pub trait FileExt { fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize>; fn write_at(&self, offset: u64, data: &[u8]) -> io::Result<usize>; fn close(self) -> io::Result<()>; } impl FileExt for File { fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> { use libc::pread; use std::os::unix::io::AsRawFd; unsafe { cvt(pread(self.as_raw_fd(), buf.as_mut_ptr() as *mut ::libc::c_void, buf.len(), offset as ::libc::off_t) as ::libc::c_int) } } fn write_at(&self, offset: u64, data: &[u8]) -> io::Result<usize> { use libc::pwrite; use std::os::unix::io::AsRawFd; unsafe { cvt(pwrite(self.as_raw_fd(), data.as_ptr() as *const ::libc::c_void, data.len(), offset as ::libc::off_t) as ::libc::c_int) } } fn close(self) -> io::Result<()> { use libc::close; use std::os::unix::io::IntoRawFd; unsafe { cvt(close(self.into_raw_fd())).map(|_| ()) } } } pub trait SparseFileExt { fn punch(&self, offset: u64, size: usize) -> io::Result<()>; } impl SparseFileExt for File { #[cfg(target_os = "linux")] fn punch(&self, offset: u64, size: usize) -> io::Result<()> { use libc::{fallocate, FALLOC_FL_PUNCH_HOLE, FALLOC_FL_KEEP_SIZE}; use std::os::unix::io::AsRawFd; unsafe { cvt(fallocate(self.as_raw_fd(), FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, offset as ::libc::off_t, size as ::libc::off_t) as ::libc::c_int) }.map(|_| ()) } #[cfg(not(target_os = "linux"))] /// WARNING: Implemented using zeroing on the system this documentation was generated for. fn punch(&self, offset: u64, size: usize) -> io::Result<()>
} // Shim for converting C-style errors to io::Errors. fn cvt(err: ::libc::c_int) -> io::Result<usize> { if err < 0 { Err(io::Error::last_os_error()) } else { Ok(err as usize) } } #[test] fn test_file_ext() { extern crate tempfile; let file = tempfile::tempfile().unwrap(); file.write_at(50, &[1, 2, 3, 4, 5]).unwrap(); file.write_at(100, &[7, 6, 5, 4, 3, 2, 1]).unwrap(); let mut buf = &mut [0; 5]; file.read_at(50, buf).unwrap(); assert_eq!(buf, &[1, 2, 3, 4, 5]); let mut buf = &mut [0; 7]; file.read_at(100, buf).unwrap(); assert_eq!(buf, &[7, 6, 5, 4, 3, 2, 1]); // Punched data is read as zeroed. let mut buf = &mut [1; 5]; file.punch(50, 5).unwrap(); file.read_at(50, buf).unwrap(); assert_eq!(buf, &[0; 5]); // Data at the later offset still present after punch. let mut buf = &mut [0; 7]; file.read_at(100, buf).unwrap(); assert_eq!(buf, &[7, 6, 5, 4, 3, 2, 1]); file.close().unwrap(); }
{ self.write_at(offset, &vec![0; size]).map(|_| ()) }
identifier_body
envelope.rs
//! Envelope function used by sounds 1, 2 and 4 use spu::{Sample, SOUND_MAX}; #[derive(Clone,Copy)] pub struct Envelope { direction: EnvelopeDirection, volume: Volume, step_duration: u32, counter: u32, } impl Envelope { pub fn from_reg(val: u8) -> Envelope { let vol = Volume::from_field(val >> 4); let dir = match val & 8!= 0 { true => EnvelopeDirection::Up, false => EnvelopeDirection::Down, }; let l = (val & 7) as u32; Envelope { direction: dir, volume: vol, step_duration: l * 0x10000, counter: 0, } } pub fn into_reg(&self) -> u8 { let vol = self.volume.into_field(); let dir = self.direction as u8; let l = (self.step_duration / 0x10000) as u8; (vol << 4) | (dir << 3) | l } pub fn step(&mut self) { if self.step_duration == 0 { // If the step duration is 0 the envelope is not active return; } self.counter += 1; self.counter %= self.step_duration; if self.counter == 0 { // Move on to the next step match self.direction { EnvelopeDirection::Up => self.volume.up(), EnvelopeDirection::Down => self.volume.down(), } } } pub fn into_sample(&self) -> Sample { self.volume.into_sample() } /// DAC is disabled when envelope direction goes down and volume is 0 pub fn dac_enabled(&self) -> bool { self.direction!= EnvelopeDirection::Down || self.volume.into_sample()!= 0 } } // Sound envelopes can become louder or quieter #[derive(Clone,Copy,PartialEq,Eq)] pub enum EnvelopeDirection { // Volume increases at each step Up = 1, // Volume decreases at each step Down = 0, } /// The game boy sound uses 4bit DACs and can therefore only output 16 /// sound levels #[derive(Clone,Copy)] struct Volume(u8); impl Volume { fn from_field(vol: u8) -> Volume { if vol > SOUND_MAX { panic!("Volume out of range: {}", vol); } Volume(vol) } fn into_field(self) -> u8 { let Volume(v) = self; v } /// Convert from 4-bit volume value to Sample range fn into_sample(self) -> Sample { let Volume(v) = self; v as Sample } fn up(&mut self) { let Volume(v) = *self; // I'm not sure how to handle overflows, let's saturate for // now if v < SOUND_MAX
} fn down(&mut self) { let Volume(v) = *self; if v > 0 { *self = Volume(v - 1); } } }
{ *self = Volume(v + 1); }
conditional_block
envelope.rs
//! Envelope function used by sounds 1, 2 and 4 use spu::{Sample, SOUND_MAX}; #[derive(Clone,Copy)] pub struct Envelope { direction: EnvelopeDirection, volume: Volume, step_duration: u32, counter: u32, } impl Envelope { pub fn from_reg(val: u8) -> Envelope { let vol = Volume::from_field(val >> 4); let dir = match val & 8!= 0 { true => EnvelopeDirection::Up, false => EnvelopeDirection::Down, }; let l = (val & 7) as u32; Envelope { direction: dir, volume: vol, step_duration: l * 0x10000, counter: 0, } } pub fn into_reg(&self) -> u8 { let vol = self.volume.into_field(); let dir = self.direction as u8; let l = (self.step_duration / 0x10000) as u8; (vol << 4) | (dir << 3) | l } pub fn step(&mut self) { if self.step_duration == 0 { // If the step duration is 0 the envelope is not active return; } self.counter += 1; self.counter %= self.step_duration; if self.counter == 0 { // Move on to the next step match self.direction { EnvelopeDirection::Up => self.volume.up(), EnvelopeDirection::Down => self.volume.down(), } } } pub fn into_sample(&self) -> Sample { self.volume.into_sample() } /// DAC is disabled when envelope direction goes down and volume is 0 pub fn dac_enabled(&self) -> bool { self.direction!= EnvelopeDirection::Down || self.volume.into_sample()!= 0 } } // Sound envelopes can become louder or quieter #[derive(Clone,Copy,PartialEq,Eq)] pub enum EnvelopeDirection { // Volume increases at each step Up = 1, // Volume decreases at each step Down = 0, } /// The game boy sound uses 4bit DACs and can therefore only output 16 /// sound levels #[derive(Clone,Copy)] struct Volume(u8); impl Volume { fn from_field(vol: u8) -> Volume { if vol > SOUND_MAX { panic!("Volume out of range: {}", vol); } Volume(vol) } fn into_field(self) -> u8 { let Volume(v) = self; v } /// Convert from 4-bit volume value to Sample range fn into_sample(self) -> Sample { let Volume(v) = self; v as Sample } fn up(&mut self) { let Volume(v) = *self; // I'm not sure how to handle overflows, let's saturate for // now if v < SOUND_MAX { *self = Volume(v + 1); } }
let Volume(v) = *self; if v > 0 { *self = Volume(v - 1); } } }
fn down(&mut self) {
random_line_split
envelope.rs
//! Envelope function used by sounds 1, 2 and 4 use spu::{Sample, SOUND_MAX}; #[derive(Clone,Copy)] pub struct Envelope { direction: EnvelopeDirection, volume: Volume, step_duration: u32, counter: u32, } impl Envelope { pub fn from_reg(val: u8) -> Envelope { let vol = Volume::from_field(val >> 4); let dir = match val & 8!= 0 { true => EnvelopeDirection::Up, false => EnvelopeDirection::Down, }; let l = (val & 7) as u32; Envelope { direction: dir, volume: vol, step_duration: l * 0x10000, counter: 0, } } pub fn into_reg(&self) -> u8 { let vol = self.volume.into_field(); let dir = self.direction as u8; let l = (self.step_duration / 0x10000) as u8; (vol << 4) | (dir << 3) | l } pub fn step(&mut self) { if self.step_duration == 0 { // If the step duration is 0 the envelope is not active return; } self.counter += 1; self.counter %= self.step_duration; if self.counter == 0 { // Move on to the next step match self.direction { EnvelopeDirection::Up => self.volume.up(), EnvelopeDirection::Down => self.volume.down(), } } } pub fn
(&self) -> Sample { self.volume.into_sample() } /// DAC is disabled when envelope direction goes down and volume is 0 pub fn dac_enabled(&self) -> bool { self.direction!= EnvelopeDirection::Down || self.volume.into_sample()!= 0 } } // Sound envelopes can become louder or quieter #[derive(Clone,Copy,PartialEq,Eq)] pub enum EnvelopeDirection { // Volume increases at each step Up = 1, // Volume decreases at each step Down = 0, } /// The game boy sound uses 4bit DACs and can therefore only output 16 /// sound levels #[derive(Clone,Copy)] struct Volume(u8); impl Volume { fn from_field(vol: u8) -> Volume { if vol > SOUND_MAX { panic!("Volume out of range: {}", vol); } Volume(vol) } fn into_field(self) -> u8 { let Volume(v) = self; v } /// Convert from 4-bit volume value to Sample range fn into_sample(self) -> Sample { let Volume(v) = self; v as Sample } fn up(&mut self) { let Volume(v) = *self; // I'm not sure how to handle overflows, let's saturate for // now if v < SOUND_MAX { *self = Volume(v + 1); } } fn down(&mut self) { let Volume(v) = *self; if v > 0 { *self = Volume(v - 1); } } }
into_sample
identifier_name