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
util.rs
use std::collections::HashSet; use std::fmt; use std::net::IpAddr; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use futures::{Async, Future, Poll}; use ifaces; use url::Url; use pb::HostPortPb; use timestamp::DateTime; use DataType; use Error; use Row; pub fn time_to_us(time: SystemTime) -> i64 { // TODO: do overflow checking match time.duration_since(UNIX_EPOCH) { Ok(duration) => { (duration.as_secs() * 1_000_000 + u64::from(duration.subsec_nanos()) / 1000) as i64 } Err(error) => { let duration = error.duration(); (-((duration.as_secs() * 1_000_000 + u64::from(duration.subsec_nanos()) / 1000) as i64)) } } } pub fn us_to_time(us: i64) -> SystemTime { let abs = us.abs() as u64; let s = abs / 1_000_000; let ns = (abs % 1_000_000) as u32 * 1000; if us.is_negative() { UNIX_EPOCH - Duration::new(s, ns) } else { UNIX_EPOCH + Duration::new(s, ns) } } pub fn fmt_hex<T>(f: &mut fmt::Formatter, bytes: &[T]) -> fmt::Result where T: fmt::LowerHex, { write!(f, "0x")?; for b in bytes { write!(f, "{:02x}", b)?; } Ok(()) } fn fmt_timestamp(timestamp: SystemTime) -> impl fmt::Display { DateTime::from(timestamp) } pub fn fmt_cell(f: &mut fmt::Formatter, row: &Row, idx: usize) -> fmt::Result { debug_assert!(row.is_set(idx).unwrap()); if row.is_null(idx).unwrap() { return write!(f, "NULL"); } match row.schema().columns()[idx].data_type() { DataType::Bool => write!(f, "{}", row.get::<_, bool>(idx).unwrap()), DataType::Int8 => write!(f, "{}", row.get::<_, i8>(idx).unwrap()), DataType::Int16 => write!(f, "{}", row.get::<_, i16>(idx).unwrap()), DataType::Int32 => write!(f, "{}", row.get::<_, i32>(idx).unwrap()), DataType::Int64 => write!(f, "{}", row.get::<_, i64>(idx).unwrap()), DataType::Timestamp => write!( f, "{}", fmt_timestamp(row.get::<_, SystemTime>(idx).unwrap()) ), DataType::Float => write!(f, "{}", row.get::<_, f32>(idx).unwrap()), DataType::Double => write!(f, "{}", row.get::<_, f64>(idx).unwrap()), DataType::Binary => fmt_hex(f, row.get::<_, &[u8]>(idx).unwrap()), DataType::String => write!(f, "{:?}", row.get::<_, &str>(idx).unwrap()), } } lazy_static! { static ref LOCAL_ADDRS: HashSet<IpAddr> = { let mut addrs = HashSet::new(); match ifaces::Interface::get_all() { Ok(ifaces) => { for iface in ifaces { if let Some(addr) = iface.addr { addrs.insert(addr.ip()); } } } Err(error) => warn!("failed to resolve local interface addresses: {}", error), }
addrs }; } /// Returns `true` if socket addr is for a local interface. #[allow(dead_code)] pub fn is_local_addr(addr: &IpAddr) -> bool { LOCAL_ADDRS.contains(addr) || addr.is_loopback() } pub(crate) fn urls_from_pb( hostports: &[HostPortPb], https_enabled: bool, ) -> Result<Vec<Url>, Error> { hostports .iter() .map(|hostport| { Url::parse(&format!( "{}://{}:{}", if https_enabled { "https" } else { "http" }, hostport.host, hostport.port )).map_err(From::from) }).collect() } pub struct ContextFuture<F, C> { future: F, context: Option<C>, } impl<F, C> ContextFuture<F, C> { pub fn new(future: F, context: C) -> ContextFuture<F, C> { ContextFuture { future, context: Some(context), } } } impl<F, C> Future for ContextFuture<F, C> where F: Future, { type Item = (F::Item, C); type Error = (F::Error, C); fn poll(&mut self) -> Poll<(F::Item, C), (F::Error, C)> { match self.future.poll() { Ok(Async::Ready(item)) => Ok(Async::Ready(( item, self.context.take().expect("future already complete"), ))), Ok(Async::NotReady) => Ok(Async::NotReady), Err(error) => Err((error, self.context.take().expect("future already complete"))), } } } #[cfg(test)] mod tests { use std::net::ToSocketAddrs; use env_logger; use proptest::prelude::*; use super::*; #[test] fn test_is_local_addr() { let _ = env_logger::try_init(); let addr = "127.0.1.1:0" .to_socket_addrs() .unwrap() .next() .unwrap() .ip(); assert!(is_local_addr(&addr)); let addr = "127.0.0.1:0" .to_socket_addrs() .unwrap() .next() .unwrap() .ip(); assert!(is_local_addr(&addr)); } proptest! { #[test] fn check_timestamp_micros_roundtrip(us in any::<i64>()) { prop_assert_eq!(us, time_to_us(us_to_time(us))) } #[test] fn check_systemtime_roundtrip(timestamp in any::<SystemTime>()) { prop_assert_eq!(timestamp, us_to_time(time_to_us(timestamp))); } #[test] fn check_format_timestamp(system_time in any::<SystemTime>()) { let _ = env_logger::try_init(); format!("{}", fmt_timestamp(system_time)); } } }
random_line_split
util.rs
use std::collections::HashSet; use std::fmt; use std::net::IpAddr; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use futures::{Async, Future, Poll}; use ifaces; use url::Url; use pb::HostPortPb; use timestamp::DateTime; use DataType; use Error; use Row; pub fn time_to_us(time: SystemTime) -> i64 { // TODO: do overflow checking match time.duration_since(UNIX_EPOCH) { Ok(duration) => { (duration.as_secs() * 1_000_000 + u64::from(duration.subsec_nanos()) / 1000) as i64 } Err(error) => { let duration = error.duration(); (-((duration.as_secs() * 1_000_000 + u64::from(duration.subsec_nanos()) / 1000) as i64)) } } } pub fn us_to_time(us: i64) -> SystemTime { let abs = us.abs() as u64; let s = abs / 1_000_000; let ns = (abs % 1_000_000) as u32 * 1000; if us.is_negative() { UNIX_EPOCH - Duration::new(s, ns) } else { UNIX_EPOCH + Duration::new(s, ns) } } pub fn fmt_hex<T>(f: &mut fmt::Formatter, bytes: &[T]) -> fmt::Result where T: fmt::LowerHex, { write!(f, "0x")?; for b in bytes { write!(f, "{:02x}", b)?; } Ok(()) } fn fmt_timestamp(timestamp: SystemTime) -> impl fmt::Display { DateTime::from(timestamp) } pub fn fmt_cell(f: &mut fmt::Formatter, row: &Row, idx: usize) -> fmt::Result { debug_assert!(row.is_set(idx).unwrap()); if row.is_null(idx).unwrap() { return write!(f, "NULL"); } match row.schema().columns()[idx].data_type() { DataType::Bool => write!(f, "{}", row.get::<_, bool>(idx).unwrap()), DataType::Int8 => write!(f, "{}", row.get::<_, i8>(idx).unwrap()), DataType::Int16 => write!(f, "{}", row.get::<_, i16>(idx).unwrap()), DataType::Int32 => write!(f, "{}", row.get::<_, i32>(idx).unwrap()), DataType::Int64 => write!(f, "{}", row.get::<_, i64>(idx).unwrap()), DataType::Timestamp => write!( f, "{}", fmt_timestamp(row.get::<_, SystemTime>(idx).unwrap()) ), DataType::Float => write!(f, "{}", row.get::<_, f32>(idx).unwrap()), DataType::Double => write!(f, "{}", row.get::<_, f64>(idx).unwrap()), DataType::Binary => fmt_hex(f, row.get::<_, &[u8]>(idx).unwrap()), DataType::String => write!(f, "{:?}", row.get::<_, &str>(idx).unwrap()), } } lazy_static! { static ref LOCAL_ADDRS: HashSet<IpAddr> = { let mut addrs = HashSet::new(); match ifaces::Interface::get_all() { Ok(ifaces) => { for iface in ifaces { if let Some(addr) = iface.addr { addrs.insert(addr.ip()); } } } Err(error) => warn!("failed to resolve local interface addresses: {}", error), } addrs }; } /// Returns `true` if socket addr is for a local interface. #[allow(dead_code)] pub fn is_local_addr(addr: &IpAddr) -> bool { LOCAL_ADDRS.contains(addr) || addr.is_loopback() } pub(crate) fn urls_from_pb( hostports: &[HostPortPb], https_enabled: bool, ) -> Result<Vec<Url>, Error> { hostports .iter() .map(|hostport| { Url::parse(&format!( "{}://{}:{}", if https_enabled { "https" } else { "http" }, hostport.host, hostport.port )).map_err(From::from) }).collect() } pub struct ContextFuture<F, C> { future: F, context: Option<C>, } impl<F, C> ContextFuture<F, C> { pub fn new(future: F, context: C) -> ContextFuture<F, C> { ContextFuture { future, context: Some(context), } } } impl<F, C> Future for ContextFuture<F, C> where F: Future, { type Item = (F::Item, C); type Error = (F::Error, C); fn
(&mut self) -> Poll<(F::Item, C), (F::Error, C)> { match self.future.poll() { Ok(Async::Ready(item)) => Ok(Async::Ready(( item, self.context.take().expect("future already complete"), ))), Ok(Async::NotReady) => Ok(Async::NotReady), Err(error) => Err((error, self.context.take().expect("future already complete"))), } } } #[cfg(test)] mod tests { use std::net::ToSocketAddrs; use env_logger; use proptest::prelude::*; use super::*; #[test] fn test_is_local_addr() { let _ = env_logger::try_init(); let addr = "127.0.1.1:0" .to_socket_addrs() .unwrap() .next() .unwrap() .ip(); assert!(is_local_addr(&addr)); let addr = "127.0.0.1:0" .to_socket_addrs() .unwrap() .next() .unwrap() .ip(); assert!(is_local_addr(&addr)); } proptest! { #[test] fn check_timestamp_micros_roundtrip(us in any::<i64>()) { prop_assert_eq!(us, time_to_us(us_to_time(us))) } #[test] fn check_systemtime_roundtrip(timestamp in any::<SystemTime>()) { prop_assert_eq!(timestamp, us_to_time(time_to_us(timestamp))); } #[test] fn check_format_timestamp(system_time in any::<SystemTime>()) { let _ = env_logger::try_init(); format!("{}", fmt_timestamp(system_time)); } } }
poll
identifier_name
error.rs
use std::convert::TryFrom; use std::error::Error; use super::*; use crate::attributes::{ComInterface, ComInterfaceVariant}; use crate::type_system::{AutomationTypeSystem, ExternOutput, RawTypeSystem, TypeSystem}; /// Error structure containing the available information on a COM error. #[derive(Debug)] pub struct ComError { /// `HRESULT` that triggered the error. pub hresult: raw::HRESULT, /// Possible detailed error info. pub error_info: Option<ErrorInfo>, } impl std::error::Error for ComError { fn description(&self) -> &str { "ComError (Use Display for more information)" } fn cause(&self) -> Option<&dyn Error> { None } fn source(&self) -> Option<&(dyn Error +'static)> { None } } impl std::fmt::Display for ComError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "COM error ({:#x})", self.hresult.hr) } } unsafe impl<TS: TypeSystem> ExternOutput<TS> for ComError { type ForeignType = raw::HRESULT; fn into_foreign_output(self) -> ComResult<Self::ForeignType> { Ok(self.hresult) } unsafe fn from_foreign_output(source: Self::ForeignType) -> ComResult<Self> { Ok(ComError { hresult: source, error_info: None, }) } } unsafe impl<TS: TypeSystem> ExternOutput<TS> for std::io::Error { type ForeignType = raw::HRESULT; fn into_foreign_output(self) -> ComResult<Self::ForeignType> { let com_error: ComError = ComError::from(self); <ComError as ExternOutput<TS>>::into_foreign_output(com_error) } unsafe fn from_foreign_output(source: Self::ForeignType) -> ComResult<Self> { let com_error: ComError = <ComError as ExternOutput<TS>>::from_foreign_output(source)?; Ok(Self::from(com_error)) } } impl ComError { /// Constructs a new `ComError` from a `HRESULT` code. pub fn new_hr(hresult: raw::HRESULT) -> ComError { ComError { hresult, error_info: None, } } /// Construts a new `ComError` with a given message. pub fn new_message(hresult: raw::HRESULT, description: String) -> ComError { ComError { hresult, error_info: Some(ErrorInfo::new(description)), } } pub fn with_message<S: Into<String>>(mut self, msg: S) -> Self { self.error_info = Some(ErrorInfo::new(msg.into())); self } /// Gets the description if it's available. pub fn description(&self) -> Option<&str> { self.error_info.as_ref().map(|e| e.description.as_str()) } pub const E_NOTIMPL: ComError = ComError { hresult: raw::E_NOTIMPL, error_info: None, }; pub const E_NOINTERFACE: ComError = ComError { hresult: raw::E_NOINTERFACE, error_info: None, }; pub const E_POINTER: ComError = ComError { hresult: raw::E_POINTER, error_info: None, }; pub const E_ABORT: ComError = ComError { hresult: raw::E_ABORT, error_info: None, }; pub const E_FAIL: ComError = ComError { hresult: raw::E_FAIL, error_info: None, }; pub const E_INVALIDARG: ComError = ComError { hresult: raw::E_INVALIDARG, error_info: None, }; pub const E_ACCESSDENIED: ComError = ComError { hresult: raw::E_ACCESSDENIED, error_info: None, }; pub const STG_E_FILENOTFOUND: ComError = ComError { hresult: raw::STG_E_FILENOTFOUND, error_info: None, }; pub const RPC_E_DISCONNECTED: ComError = ComError { hresult: raw::RPC_E_DISCONNECTED, error_info: None, }; pub const RPC_E_CALL_REJECTED: ComError = ComError { hresult: raw::RPC_E_CALL_REJECTED, error_info: None, }; pub const RPC_E_CALL_CANCELED: ComError = ComError { hresult: raw::RPC_E_CALL_CANCELED, error_info: None, }; pub const RPC_E_TIMEOUT: ComError = ComError { hresult: raw::RPC_E_TIMEOUT, error_info: None, }; } impl From<ComError> for std::io::Error { fn from(com_error: ComError) -> std::io::Error { let error_kind = match com_error.hresult { raw::STG_E_FILENOTFOUND => std::io::ErrorKind::NotFound, raw::E_ACCESSDENIED => std::io::ErrorKind::PermissionDenied, raw::RPC_E_CALL_REJECTED => std::io::ErrorKind::ConnectionRefused, raw::RPC_E_DISCONNECTED => std::io::ErrorKind::ConnectionReset, raw::RPC_E_CALL_CANCELED => std::io::ErrorKind::ConnectionAborted, raw::RPC_E_TIMEOUT => std::io::ErrorKind::TimedOut, raw::E_INVALIDARG => std::io::ErrorKind::InvalidInput, _ => std::io::ErrorKind::Other, }; std::io::Error::new( error_kind, com_error.description().unwrap_or("Unknown error"), ) } } impl From<std::io::Error> for ComError { fn from(io_error: std::io::Error) -> ComError { match io_error.kind() { std::io::ErrorKind::NotFound => ComError::STG_E_FILENOTFOUND, std::io::ErrorKind::PermissionDenied => ComError::E_ACCESSDENIED, std::io::ErrorKind::ConnectionRefused => ComError::RPC_E_CALL_REJECTED, std::io::ErrorKind::ConnectionReset => ComError::RPC_E_DISCONNECTED, std::io::ErrorKind::ConnectionAborted => ComError::RPC_E_CALL_CANCELED, std::io::ErrorKind::TimedOut => ComError::RPC_E_TIMEOUT, std::io::ErrorKind::InvalidInput => ComError::E_INVALIDARG, _ => ComError::E_FAIL, } .with_message(io_error.description().to_owned()) } } impl From<raw::HRESULT> for ComResult<()> { fn from(hresult: raw::HRESULT) -> ComResult<()> { match hresult { // TODO: We should have a proper'succeeded' method on HRESULT. raw::S_OK | raw::S_FALSE => Ok(()), e => Err(e.into()), } } } impl From<raw::HRESULT> for ComError { fn from(hresult: raw::HRESULT) -> ComError
} impl From<ComError> for raw::HRESULT { fn from(error: ComError) -> raw::HRESULT { error.hresult } } impl<'a> From<&'a str> for crate::ComError { fn from(s: &'a str) -> Self { s.to_string().into() } } impl From<String> for crate::ComError { fn from(s: String) -> Self { Self::new_message(raw::E_FAIL, s) } } #[cfg(windows)] #[allow(non_snake_case)] mod error_store { use super::*; #[link(name = "oleaut32")] extern "system" { pub(super) fn SetErrorInfo( dw_reserved: u32, errorinfo: Option<crate::raw::InterfacePtr<AutomationTypeSystem, dyn IErrorInfo>>, ) -> raw::HRESULT; #[allow(private_in_public)] pub(super) fn GetErrorInfo( dw_reserved: u32, errorinfo: *mut Option<crate::raw::InterfacePtr<AutomationTypeSystem, dyn IErrorInfo>>, ) -> raw::HRESULT; } } #[cfg(not(windows))] #[allow(non_snake_case)] mod error_store { use super::*; use std::cell::RefCell; thread_local! { static ERROR_STORE: RefCell< Option< ComRc<dyn IErrorInfo> > > = RefCell::new( None ); } fn reset_error_store(value: Option<ComRc<dyn IErrorInfo>>) { ERROR_STORE.with(|store| { store.replace(value); }); } fn take_error() -> Option<ComRc<dyn IErrorInfo>> { ERROR_STORE.with(|store| store.replace(None)) } pub(super) unsafe fn SetErrorInfo( _dw_reserved: u32, errorinfo: Option<crate::raw::InterfacePtr<AutomationTypeSystem, dyn IErrorInfo>>, ) -> raw::HRESULT { reset_error_store(errorinfo.map(ComRc::from)); raw::S_OK } pub(super) unsafe fn GetErrorInfo( _dw_reserved: u32, errorinfo: *mut Option<crate::raw::InterfacePtr<AutomationTypeSystem, dyn IErrorInfo>>, ) -> raw::HRESULT { match take_error() { Some(rc) => { *errorinfo = ComItf::ptr(&ComRc::detach(rc)); raw::S_OK } None => { *errorinfo = None; raw::S_FALSE } } } } /// Error info COM object data. #[com_class( clsid = None, IErrorInfo )] #[derive(Debug, Clone)] pub struct ErrorInfo { guid: GUID, source: String, description: String, help_file: String, help_context: u32, } impl ErrorInfo { pub fn new(description: String) -> ErrorInfo { ErrorInfo { description, guid: GUID::zero_guid(), source: String::new(), help_file: String::new(), help_context: 0, } } pub fn guid(&self) -> &GUID { &self.guid } pub fn source(&self) -> &str { &self.source } pub fn description(&self) -> &str { &self.description } pub fn help_file(&self) -> &str { &self.help_file } pub fn help_context(&self) -> u32 { self.help_context } } impl<'a> TryFrom<&'a dyn IErrorInfo> for ErrorInfo { type Error = raw::HRESULT; fn try_from(source: &'a dyn IErrorInfo) -> Result<Self, Self::Error> { Ok(ErrorInfo { guid: source.get_guid()?, source: source.get_source()?, description: source.get_description()?, help_file: source.get_help_file()?, help_context: source.get_help_context()?, }) } } #[com_interface(com_iid = "1CF2B120-547D-101B-8E65-08002B2BD119")] pub trait IErrorInfo: crate::IUnknown { fn get_guid(&self) -> ComResult<GUID>; fn get_source(&self) -> ComResult<String>; fn get_description(&self) -> ComResult<String>; fn get_help_file(&self) -> ComResult<String>; fn get_help_context(&self) -> ComResult<u32>; } impl IErrorInfo for ErrorInfo { fn get_guid(&self) -> ComResult<GUID> { Ok(self.guid.clone()) } fn get_source(&self) -> ComResult<String> { Ok(self.source.clone()) } fn get_description(&self) -> ComResult<String> { Ok(self.description.clone()) } fn get_help_file(&self) -> ComResult<String> { Ok(self.help_file.clone()) } fn get_help_context(&self) -> ComResult<u32> { Ok(self.help_context) } } /// Extracts the HRESULT from the error result and stores the extended error /// information in thread memory so it can be fetched by the COM client. pub fn store_error<E>(error: E) -> ComError where E: Into<ComError>, { // Convet the error. let com_error = error.into(); match com_error.error_info { Some(ref error_info) => { // ComError contains ErrorInfo. We need to set this in the OS error // store. // Construct the COM class used for IErrorInfo. The class contains the // description in memory. let info = ComBox::<ErrorInfo>::new(error_info.clone()); // Store the IErrorInfo pointer in the SetErrorInfo. let rc = ComRc::<dyn IErrorInfo>::from(info); let ptr = ComItf::ptr(&rc).expect("Intercom did not implement correct type system"); unsafe { error_store::SetErrorInfo(0, Some(ptr)); } } None => { // No error info in the ComError. unsafe { error_store::SetErrorInfo(0, None); } } } // Return the HRESULT of the original error. com_error } pub fn load_error<I: ComInterface +?Sized>( iunk: &ComItf<I>, iid: &GUID, err: raw::HRESULT, ) -> ComError { // Do not try to load error if this is IUnknown or ISupportErrorInfo. // Both of these are used during error handling and may fail. if iid == <dyn IUnknown as ComInterfaceVariant<AutomationTypeSystem>>::iid() || iid == <dyn IUnknown as ComInterfaceVariant<RawTypeSystem>>::iid() || iid == <dyn ISupportErrorInfo as ComInterfaceVariant<AutomationTypeSystem>>::iid() || iid == <dyn ISupportErrorInfo as ComInterfaceVariant<RawTypeSystem>>::iid() { return ComError { hresult: err, error_info: None, }; } // Try to get the ISupportErrorInfo and query that for the IID. let supports_errorinfo = match ComItf::query_interface::<dyn ISupportErrorInfo>(iunk) { Ok(rc) => match rc.interface_supports_error_info(iid) { intercom::raw::S_OK => true, _ => false, }, _ => false, }; ComError { hresult: err, error_info: match supports_errorinfo { true => get_last_error(), false => None, }, } } /// Gets the last COM error that occurred on the current thread. pub fn get_last_error() -> Option<ErrorInfo> { let ierrorinfo = match get_error_info() { Some(ierror) => ierror, None => return None, }; // FIXME ComRc Deref let ierr: &dyn IErrorInfo = &*ierrorinfo; ErrorInfo::try_from(ierr).ok() } /// Defines a way to handle errors based on the method return value type. /// /// The default implementation will terminate the process on the basis that /// errors must not silently leak. The specialization for `HRESULT` will return /// the `HRESULT`. /// /// The user is free to implement this trait for their own types to handle /// custom status codes gracefully. pub trait ErrorValue { /// Attempts to convert a COM error into a custom status code. Must not panic. fn from_error(_: ComError) -> Self; } impl<S, E: ErrorValue> ErrorValue for Result<S, E> { fn from_error(e: ComError) -> Self { Err(E::from_error(e)) } } impl<T: From<ComError>> ErrorValue for T { fn from_error(err: ComError) -> Self { err.into() } } #[com_class(IErrorStore)] #[derive(Default)] pub struct ErrorStore; #[com_interface( com_iid = "d7f996c5-0b51-4053-82f8-19a7261793a9", raw_iid = "7586c49a-abbd-4a06-b588-e3d02b431f01" )] pub trait IErrorStore: crate::IUnknown { fn get_error_info(&self) -> ComResult<ComRc<dyn IErrorInfo>>; fn set_error_info(&self, info: &ComItf<dyn IErrorInfo>) -> ComResult<()>; fn set_error_message(&self, msg: &str) -> ComResult<()>; } impl IErrorStore for ErrorStore { fn get_error_info(&self) -> ComResult<ComRc<dyn IErrorInfo>> { Ok(get_error_info().unwrap()) // FIXME Option } fn set_error_info(&self, info: &ComItf<dyn IErrorInfo>) -> ComResult<()> { set_error_info(&info) } fn set_error_message(&self, msg: &str) -> ComResult<()> { let info = ComBox::<ErrorInfo>::new(ErrorInfo::new(msg.to_string())); let itf = ComRc::<dyn IErrorInfo>::from(&info); self.set_error_info(&*itf) } } fn get_error_info() -> Option<ComRc<dyn IErrorInfo>> { // We're unsafe due to pointer lifetimes. // // The GetErrorInfo gives us a raw pointer which we own so we'll need to // wrap that in a `ComRc` to manage its memory. unsafe { // Get the error info and wrap it in an RC. let mut error_ptr = None; match error_store::GetErrorInfo(0, &mut error_ptr) { raw::S_OK => {} _ => return None, } match error_ptr { Some(ptr) => Some(ComRc::wrap(ptr)), None => None, } } } fn set_error_info(info: &ComItf<dyn IErrorInfo>) -> ComResult<()> { unsafe { error_store::SetErrorInfo(0, ComItf::ptr(info)).into() } } pub mod raw { /// COM method status code. #[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)] #[repr(C)] pub struct HRESULT { /// The numerical HRESULT code. pub hr: i32, } impl HRESULT { /// Constructs a new `HRESULT` with the given numerical code. pub fn new(hr: i32) -> HRESULT { #[allow(overflowing_literals)] HRESULT { hr: hr as i32 } } } macro_rules! make_hr { ( $(#[$attr:meta] )* $hr_name: ident = $hr_value: expr ) => { $(#[$attr])* #[allow(overflowing_literals)] pub const $hr_name : HRESULT = HRESULT { hr: $hr_value as i32 }; } } make_hr!( /// `HRESULT` indicating the operation completed successfully. S_OK = 0 ); make_hr!( /// `HRESULT` indicating the operation completed successfully and returned /// `false`. S_FALSE = 1 ); make_hr!( /// `HRESULT` for unimplemented functionality. E_NOTIMPL = 0x8000_4001 ); make_hr!( /// `HRESULT` indicating the type does not support the requested interface. E_NOINTERFACE = 0x8000_4002 ); make_hr!( /// `HRESULT` indicating a pointer parameter was invalid. E_POINTER = 0x8000_4003 ); make_hr!( /// `HRESULT` for aborted operation. E_ABORT = 0x8000_4004 ); make_hr!( /// `HRESULT` for unspecified failure. E_FAIL = 0x8000_4005 ); make_hr!( /// `HRESULT` for invalid argument. E_INVALIDARG = 0x8007_0057 ); make_hr!( /// `HRESULT` for unavailable CLSID. E_CLASSNOTAVAILABLE = 0x8004_0111 ); // These might be deprecated. They are a bit too specific for cross-platform // support. We'll just need to ensure the winapi HRESULTs are compatible. make_hr!(E_ACCESSDENIED = 0x8007_0005); make_hr!(STG_E_FILENOTFOUND = 0x8003_0002); make_hr!(RPC_E_DISCONNECTED = 0x8001_0108); make_hr!(RPC_E_CALL_REJECTED = 0x8001_0001); make_hr!(RPC_E_CALL_CANCELED = 0x8001_0002); make_hr!(RPC_E_TIMEOUT = 0x8001_011F); }
{ ComError::new_hr(hresult) }
identifier_body
error.rs
use std::convert::TryFrom; use std::error::Error; use super::*; use crate::attributes::{ComInterface, ComInterfaceVariant}; use crate::type_system::{AutomationTypeSystem, ExternOutput, RawTypeSystem, TypeSystem}; /// Error structure containing the available information on a COM error. #[derive(Debug)] pub struct ComError { /// `HRESULT` that triggered the error. pub hresult: raw::HRESULT, /// Possible detailed error info. pub error_info: Option<ErrorInfo>, } impl std::error::Error for ComError { fn description(&self) -> &str { "ComError (Use Display for more information)" } fn cause(&self) -> Option<&dyn Error> { None } fn source(&self) -> Option<&(dyn Error +'static)> { None } } impl std::fmt::Display for ComError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "COM error ({:#x})", self.hresult.hr) } } unsafe impl<TS: TypeSystem> ExternOutput<TS> for ComError { type ForeignType = raw::HRESULT; fn into_foreign_output(self) -> ComResult<Self::ForeignType> { Ok(self.hresult) } unsafe fn from_foreign_output(source: Self::ForeignType) -> ComResult<Self> { Ok(ComError { hresult: source, error_info: None, }) } } unsafe impl<TS: TypeSystem> ExternOutput<TS> for std::io::Error { type ForeignType = raw::HRESULT; fn into_foreign_output(self) -> ComResult<Self::ForeignType> { let com_error: ComError = ComError::from(self); <ComError as ExternOutput<TS>>::into_foreign_output(com_error) } unsafe fn from_foreign_output(source: Self::ForeignType) -> ComResult<Self> { let com_error: ComError = <ComError as ExternOutput<TS>>::from_foreign_output(source)?; Ok(Self::from(com_error)) } } impl ComError { /// Constructs a new `ComError` from a `HRESULT` code. pub fn new_hr(hresult: raw::HRESULT) -> ComError { ComError { hresult, error_info: None, } } /// Construts a new `ComError` with a given message. pub fn new_message(hresult: raw::HRESULT, description: String) -> ComError { ComError { hresult, error_info: Some(ErrorInfo::new(description)), } } pub fn with_message<S: Into<String>>(mut self, msg: S) -> Self { self.error_info = Some(ErrorInfo::new(msg.into())); self } /// Gets the description if it's available. pub fn description(&self) -> Option<&str> { self.error_info.as_ref().map(|e| e.description.as_str()) } pub const E_NOTIMPL: ComError = ComError { hresult: raw::E_NOTIMPL, error_info: None, }; pub const E_NOINTERFACE: ComError = ComError { hresult: raw::E_NOINTERFACE, error_info: None, }; pub const E_POINTER: ComError = ComError { hresult: raw::E_POINTER, error_info: None, }; pub const E_ABORT: ComError = ComError { hresult: raw::E_ABORT, error_info: None, }; pub const E_FAIL: ComError = ComError { hresult: raw::E_FAIL, error_info: None, }; pub const E_INVALIDARG: ComError = ComError { hresult: raw::E_INVALIDARG, error_info: None, }; pub const E_ACCESSDENIED: ComError = ComError { hresult: raw::E_ACCESSDENIED, error_info: None, }; pub const STG_E_FILENOTFOUND: ComError = ComError { hresult: raw::STG_E_FILENOTFOUND, error_info: None, }; pub const RPC_E_DISCONNECTED: ComError = ComError { hresult: raw::RPC_E_DISCONNECTED, error_info: None, }; pub const RPC_E_CALL_REJECTED: ComError = ComError { hresult: raw::RPC_E_CALL_REJECTED, error_info: None, }; pub const RPC_E_CALL_CANCELED: ComError = ComError { hresult: raw::RPC_E_CALL_CANCELED, error_info: None, }; pub const RPC_E_TIMEOUT: ComError = ComError { hresult: raw::RPC_E_TIMEOUT, error_info: None, }; } impl From<ComError> for std::io::Error { fn from(com_error: ComError) -> std::io::Error { let error_kind = match com_error.hresult { raw::STG_E_FILENOTFOUND => std::io::ErrorKind::NotFound, raw::E_ACCESSDENIED => std::io::ErrorKind::PermissionDenied, raw::RPC_E_CALL_REJECTED => std::io::ErrorKind::ConnectionRefused, raw::RPC_E_DISCONNECTED => std::io::ErrorKind::ConnectionReset, raw::RPC_E_CALL_CANCELED => std::io::ErrorKind::ConnectionAborted, raw::RPC_E_TIMEOUT => std::io::ErrorKind::TimedOut, raw::E_INVALIDARG => std::io::ErrorKind::InvalidInput, _ => std::io::ErrorKind::Other, }; std::io::Error::new( error_kind, com_error.description().unwrap_or("Unknown error"), ) } } impl From<std::io::Error> for ComError { fn from(io_error: std::io::Error) -> ComError { match io_error.kind() { std::io::ErrorKind::NotFound => ComError::STG_E_FILENOTFOUND, std::io::ErrorKind::PermissionDenied => ComError::E_ACCESSDENIED, std::io::ErrorKind::ConnectionRefused => ComError::RPC_E_CALL_REJECTED, std::io::ErrorKind::ConnectionReset => ComError::RPC_E_DISCONNECTED, std::io::ErrorKind::ConnectionAborted => ComError::RPC_E_CALL_CANCELED, std::io::ErrorKind::TimedOut => ComError::RPC_E_TIMEOUT, std::io::ErrorKind::InvalidInput => ComError::E_INVALIDARG, _ => ComError::E_FAIL, } .with_message(io_error.description().to_owned()) } } impl From<raw::HRESULT> for ComResult<()> { fn from(hresult: raw::HRESULT) -> ComResult<()> { match hresult { // TODO: We should have a proper'succeeded' method on HRESULT. raw::S_OK | raw::S_FALSE => Ok(()), e => Err(e.into()), } } } impl From<raw::HRESULT> for ComError
{ ComError::new_hr(hresult) } } impl From<ComError> for raw::HRESULT { fn from(error: ComError) -> raw::HRESULT { error.hresult } } impl<'a> From<&'a str> for crate::ComError { fn from(s: &'a str) -> Self { s.to_string().into() } } impl From<String> for crate::ComError { fn from(s: String) -> Self { Self::new_message(raw::E_FAIL, s) } } #[cfg(windows)] #[allow(non_snake_case)] mod error_store { use super::*; #[link(name = "oleaut32")] extern "system" { pub(super) fn SetErrorInfo( dw_reserved: u32, errorinfo: Option<crate::raw::InterfacePtr<AutomationTypeSystem, dyn IErrorInfo>>, ) -> raw::HRESULT; #[allow(private_in_public)] pub(super) fn GetErrorInfo( dw_reserved: u32, errorinfo: *mut Option<crate::raw::InterfacePtr<AutomationTypeSystem, dyn IErrorInfo>>, ) -> raw::HRESULT; } } #[cfg(not(windows))] #[allow(non_snake_case)] mod error_store { use super::*; use std::cell::RefCell; thread_local! { static ERROR_STORE: RefCell< Option< ComRc<dyn IErrorInfo> > > = RefCell::new( None ); } fn reset_error_store(value: Option<ComRc<dyn IErrorInfo>>) { ERROR_STORE.with(|store| { store.replace(value); }); } fn take_error() -> Option<ComRc<dyn IErrorInfo>> { ERROR_STORE.with(|store| store.replace(None)) } pub(super) unsafe fn SetErrorInfo( _dw_reserved: u32, errorinfo: Option<crate::raw::InterfacePtr<AutomationTypeSystem, dyn IErrorInfo>>, ) -> raw::HRESULT { reset_error_store(errorinfo.map(ComRc::from)); raw::S_OK } pub(super) unsafe fn GetErrorInfo( _dw_reserved: u32, errorinfo: *mut Option<crate::raw::InterfacePtr<AutomationTypeSystem, dyn IErrorInfo>>, ) -> raw::HRESULT { match take_error() { Some(rc) => { *errorinfo = ComItf::ptr(&ComRc::detach(rc)); raw::S_OK } None => { *errorinfo = None; raw::S_FALSE } } } } /// Error info COM object data. #[com_class( clsid = None, IErrorInfo )] #[derive(Debug, Clone)] pub struct ErrorInfo { guid: GUID, source: String, description: String, help_file: String, help_context: u32, } impl ErrorInfo { pub fn new(description: String) -> ErrorInfo { ErrorInfo { description, guid: GUID::zero_guid(), source: String::new(), help_file: String::new(), help_context: 0, } } pub fn guid(&self) -> &GUID { &self.guid } pub fn source(&self) -> &str { &self.source } pub fn description(&self) -> &str { &self.description } pub fn help_file(&self) -> &str { &self.help_file } pub fn help_context(&self) -> u32 { self.help_context } } impl<'a> TryFrom<&'a dyn IErrorInfo> for ErrorInfo { type Error = raw::HRESULT; fn try_from(source: &'a dyn IErrorInfo) -> Result<Self, Self::Error> { Ok(ErrorInfo { guid: source.get_guid()?, source: source.get_source()?, description: source.get_description()?, help_file: source.get_help_file()?, help_context: source.get_help_context()?, }) } } #[com_interface(com_iid = "1CF2B120-547D-101B-8E65-08002B2BD119")] pub trait IErrorInfo: crate::IUnknown { fn get_guid(&self) -> ComResult<GUID>; fn get_source(&self) -> ComResult<String>; fn get_description(&self) -> ComResult<String>; fn get_help_file(&self) -> ComResult<String>; fn get_help_context(&self) -> ComResult<u32>; } impl IErrorInfo for ErrorInfo { fn get_guid(&self) -> ComResult<GUID> { Ok(self.guid.clone()) } fn get_source(&self) -> ComResult<String> { Ok(self.source.clone()) } fn get_description(&self) -> ComResult<String> { Ok(self.description.clone()) } fn get_help_file(&self) -> ComResult<String> { Ok(self.help_file.clone()) } fn get_help_context(&self) -> ComResult<u32> { Ok(self.help_context) } } /// Extracts the HRESULT from the error result and stores the extended error /// information in thread memory so it can be fetched by the COM client. pub fn store_error<E>(error: E) -> ComError where E: Into<ComError>, { // Convet the error. let com_error = error.into(); match com_error.error_info { Some(ref error_info) => { // ComError contains ErrorInfo. We need to set this in the OS error // store. // Construct the COM class used for IErrorInfo. The class contains the // description in memory. let info = ComBox::<ErrorInfo>::new(error_info.clone()); // Store the IErrorInfo pointer in the SetErrorInfo. let rc = ComRc::<dyn IErrorInfo>::from(info); let ptr = ComItf::ptr(&rc).expect("Intercom did not implement correct type system"); unsafe { error_store::SetErrorInfo(0, Some(ptr)); } } None => { // No error info in the ComError. unsafe { error_store::SetErrorInfo(0, None); } } } // Return the HRESULT of the original error. com_error } pub fn load_error<I: ComInterface +?Sized>( iunk: &ComItf<I>, iid: &GUID, err: raw::HRESULT, ) -> ComError { // Do not try to load error if this is IUnknown or ISupportErrorInfo. // Both of these are used during error handling and may fail. if iid == <dyn IUnknown as ComInterfaceVariant<AutomationTypeSystem>>::iid() || iid == <dyn IUnknown as ComInterfaceVariant<RawTypeSystem>>::iid() || iid == <dyn ISupportErrorInfo as ComInterfaceVariant<AutomationTypeSystem>>::iid() || iid == <dyn ISupportErrorInfo as ComInterfaceVariant<RawTypeSystem>>::iid() { return ComError { hresult: err, error_info: None, }; } // Try to get the ISupportErrorInfo and query that for the IID. let supports_errorinfo = match ComItf::query_interface::<dyn ISupportErrorInfo>(iunk) { Ok(rc) => match rc.interface_supports_error_info(iid) { intercom::raw::S_OK => true, _ => false, }, _ => false, }; ComError { hresult: err, error_info: match supports_errorinfo { true => get_last_error(), false => None, }, } } /// Gets the last COM error that occurred on the current thread. pub fn get_last_error() -> Option<ErrorInfo> { let ierrorinfo = match get_error_info() { Some(ierror) => ierror, None => return None, }; // FIXME ComRc Deref let ierr: &dyn IErrorInfo = &*ierrorinfo; ErrorInfo::try_from(ierr).ok() } /// Defines a way to handle errors based on the method return value type. /// /// The default implementation will terminate the process on the basis that /// errors must not silently leak. The specialization for `HRESULT` will return /// the `HRESULT`. /// /// The user is free to implement this trait for their own types to handle /// custom status codes gracefully. pub trait ErrorValue { /// Attempts to convert a COM error into a custom status code. Must not panic. fn from_error(_: ComError) -> Self; } impl<S, E: ErrorValue> ErrorValue for Result<S, E> { fn from_error(e: ComError) -> Self { Err(E::from_error(e)) } } impl<T: From<ComError>> ErrorValue for T { fn from_error(err: ComError) -> Self { err.into() } } #[com_class(IErrorStore)] #[derive(Default)] pub struct ErrorStore; #[com_interface( com_iid = "d7f996c5-0b51-4053-82f8-19a7261793a9", raw_iid = "7586c49a-abbd-4a06-b588-e3d02b431f01" )] pub trait IErrorStore: crate::IUnknown { fn get_error_info(&self) -> ComResult<ComRc<dyn IErrorInfo>>; fn set_error_info(&self, info: &ComItf<dyn IErrorInfo>) -> ComResult<()>; fn set_error_message(&self, msg: &str) -> ComResult<()>; } impl IErrorStore for ErrorStore { fn get_error_info(&self) -> ComResult<ComRc<dyn IErrorInfo>> { Ok(get_error_info().unwrap()) // FIXME Option } fn set_error_info(&self, info: &ComItf<dyn IErrorInfo>) -> ComResult<()> { set_error_info(&info) } fn set_error_message(&self, msg: &str) -> ComResult<()> { let info = ComBox::<ErrorInfo>::new(ErrorInfo::new(msg.to_string())); let itf = ComRc::<dyn IErrorInfo>::from(&info); self.set_error_info(&*itf) } } fn get_error_info() -> Option<ComRc<dyn IErrorInfo>> { // We're unsafe due to pointer lifetimes. // // The GetErrorInfo gives us a raw pointer which we own so we'll need to // wrap that in a `ComRc` to manage its memory. unsafe { // Get the error info and wrap it in an RC. let mut error_ptr = None; match error_store::GetErrorInfo(0, &mut error_ptr) { raw::S_OK => {} _ => return None, } match error_ptr { Some(ptr) => Some(ComRc::wrap(ptr)), None => None, } } } fn set_error_info(info: &ComItf<dyn IErrorInfo>) -> ComResult<()> { unsafe { error_store::SetErrorInfo(0, ComItf::ptr(info)).into() } } pub mod raw { /// COM method status code. #[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)] #[repr(C)] pub struct HRESULT { /// The numerical HRESULT code. pub hr: i32, } impl HRESULT { /// Constructs a new `HRESULT` with the given numerical code. pub fn new(hr: i32) -> HRESULT { #[allow(overflowing_literals)] HRESULT { hr: hr as i32 } } } macro_rules! make_hr { ( $(#[$attr:meta] )* $hr_name: ident = $hr_value: expr ) => { $(#[$attr])* #[allow(overflowing_literals)] pub const $hr_name : HRESULT = HRESULT { hr: $hr_value as i32 }; } } make_hr!( /// `HRESULT` indicating the operation completed successfully. S_OK = 0 ); make_hr!( /// `HRESULT` indicating the operation completed successfully and returned /// `false`. S_FALSE = 1 ); make_hr!( /// `HRESULT` for unimplemented functionality. E_NOTIMPL = 0x8000_4001 ); make_hr!( /// `HRESULT` indicating the type does not support the requested interface. E_NOINTERFACE = 0x8000_4002 ); make_hr!( /// `HRESULT` indicating a pointer parameter was invalid. E_POINTER = 0x8000_4003 ); make_hr!( /// `HRESULT` for aborted operation. E_ABORT = 0x8000_4004 ); make_hr!( /// `HRESULT` for unspecified failure. E_FAIL = 0x8000_4005 ); make_hr!( /// `HRESULT` for invalid argument. E_INVALIDARG = 0x8007_0057 ); make_hr!( /// `HRESULT` for unavailable CLSID. E_CLASSNOTAVAILABLE = 0x8004_0111 ); // These might be deprecated. They are a bit too specific for cross-platform // support. We'll just need to ensure the winapi HRESULTs are compatible. make_hr!(E_ACCESSDENIED = 0x8007_0005); make_hr!(STG_E_FILENOTFOUND = 0x8003_0002); make_hr!(RPC_E_DISCONNECTED = 0x8001_0108); make_hr!(RPC_E_CALL_REJECTED = 0x8001_0001); make_hr!(RPC_E_CALL_CANCELED = 0x8001_0002); make_hr!(RPC_E_TIMEOUT = 0x8001_011F); }
{ fn from(hresult: raw::HRESULT) -> ComError
random_line_split
error.rs
use std::convert::TryFrom; use std::error::Error; use super::*; use crate::attributes::{ComInterface, ComInterfaceVariant}; use crate::type_system::{AutomationTypeSystem, ExternOutput, RawTypeSystem, TypeSystem}; /// Error structure containing the available information on a COM error. #[derive(Debug)] pub struct ComError { /// `HRESULT` that triggered the error. pub hresult: raw::HRESULT, /// Possible detailed error info. pub error_info: Option<ErrorInfo>, } impl std::error::Error for ComError { fn description(&self) -> &str { "ComError (Use Display for more information)" } fn cause(&self) -> Option<&dyn Error> { None } fn source(&self) -> Option<&(dyn Error +'static)> { None } } impl std::fmt::Display for ComError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "COM error ({:#x})", self.hresult.hr) } } unsafe impl<TS: TypeSystem> ExternOutput<TS> for ComError { type ForeignType = raw::HRESULT; fn into_foreign_output(self) -> ComResult<Self::ForeignType> { Ok(self.hresult) } unsafe fn from_foreign_output(source: Self::ForeignType) -> ComResult<Self> { Ok(ComError { hresult: source, error_info: None, }) } } unsafe impl<TS: TypeSystem> ExternOutput<TS> for std::io::Error { type ForeignType = raw::HRESULT; fn into_foreign_output(self) -> ComResult<Self::ForeignType> { let com_error: ComError = ComError::from(self); <ComError as ExternOutput<TS>>::into_foreign_output(com_error) } unsafe fn
(source: Self::ForeignType) -> ComResult<Self> { let com_error: ComError = <ComError as ExternOutput<TS>>::from_foreign_output(source)?; Ok(Self::from(com_error)) } } impl ComError { /// Constructs a new `ComError` from a `HRESULT` code. pub fn new_hr(hresult: raw::HRESULT) -> ComError { ComError { hresult, error_info: None, } } /// Construts a new `ComError` with a given message. pub fn new_message(hresult: raw::HRESULT, description: String) -> ComError { ComError { hresult, error_info: Some(ErrorInfo::new(description)), } } pub fn with_message<S: Into<String>>(mut self, msg: S) -> Self { self.error_info = Some(ErrorInfo::new(msg.into())); self } /// Gets the description if it's available. pub fn description(&self) -> Option<&str> { self.error_info.as_ref().map(|e| e.description.as_str()) } pub const E_NOTIMPL: ComError = ComError { hresult: raw::E_NOTIMPL, error_info: None, }; pub const E_NOINTERFACE: ComError = ComError { hresult: raw::E_NOINTERFACE, error_info: None, }; pub const E_POINTER: ComError = ComError { hresult: raw::E_POINTER, error_info: None, }; pub const E_ABORT: ComError = ComError { hresult: raw::E_ABORT, error_info: None, }; pub const E_FAIL: ComError = ComError { hresult: raw::E_FAIL, error_info: None, }; pub const E_INVALIDARG: ComError = ComError { hresult: raw::E_INVALIDARG, error_info: None, }; pub const E_ACCESSDENIED: ComError = ComError { hresult: raw::E_ACCESSDENIED, error_info: None, }; pub const STG_E_FILENOTFOUND: ComError = ComError { hresult: raw::STG_E_FILENOTFOUND, error_info: None, }; pub const RPC_E_DISCONNECTED: ComError = ComError { hresult: raw::RPC_E_DISCONNECTED, error_info: None, }; pub const RPC_E_CALL_REJECTED: ComError = ComError { hresult: raw::RPC_E_CALL_REJECTED, error_info: None, }; pub const RPC_E_CALL_CANCELED: ComError = ComError { hresult: raw::RPC_E_CALL_CANCELED, error_info: None, }; pub const RPC_E_TIMEOUT: ComError = ComError { hresult: raw::RPC_E_TIMEOUT, error_info: None, }; } impl From<ComError> for std::io::Error { fn from(com_error: ComError) -> std::io::Error { let error_kind = match com_error.hresult { raw::STG_E_FILENOTFOUND => std::io::ErrorKind::NotFound, raw::E_ACCESSDENIED => std::io::ErrorKind::PermissionDenied, raw::RPC_E_CALL_REJECTED => std::io::ErrorKind::ConnectionRefused, raw::RPC_E_DISCONNECTED => std::io::ErrorKind::ConnectionReset, raw::RPC_E_CALL_CANCELED => std::io::ErrorKind::ConnectionAborted, raw::RPC_E_TIMEOUT => std::io::ErrorKind::TimedOut, raw::E_INVALIDARG => std::io::ErrorKind::InvalidInput, _ => std::io::ErrorKind::Other, }; std::io::Error::new( error_kind, com_error.description().unwrap_or("Unknown error"), ) } } impl From<std::io::Error> for ComError { fn from(io_error: std::io::Error) -> ComError { match io_error.kind() { std::io::ErrorKind::NotFound => ComError::STG_E_FILENOTFOUND, std::io::ErrorKind::PermissionDenied => ComError::E_ACCESSDENIED, std::io::ErrorKind::ConnectionRefused => ComError::RPC_E_CALL_REJECTED, std::io::ErrorKind::ConnectionReset => ComError::RPC_E_DISCONNECTED, std::io::ErrorKind::ConnectionAborted => ComError::RPC_E_CALL_CANCELED, std::io::ErrorKind::TimedOut => ComError::RPC_E_TIMEOUT, std::io::ErrorKind::InvalidInput => ComError::E_INVALIDARG, _ => ComError::E_FAIL, } .with_message(io_error.description().to_owned()) } } impl From<raw::HRESULT> for ComResult<()> { fn from(hresult: raw::HRESULT) -> ComResult<()> { match hresult { // TODO: We should have a proper'succeeded' method on HRESULT. raw::S_OK | raw::S_FALSE => Ok(()), e => Err(e.into()), } } } impl From<raw::HRESULT> for ComError { fn from(hresult: raw::HRESULT) -> ComError { ComError::new_hr(hresult) } } impl From<ComError> for raw::HRESULT { fn from(error: ComError) -> raw::HRESULT { error.hresult } } impl<'a> From<&'a str> for crate::ComError { fn from(s: &'a str) -> Self { s.to_string().into() } } impl From<String> for crate::ComError { fn from(s: String) -> Self { Self::new_message(raw::E_FAIL, s) } } #[cfg(windows)] #[allow(non_snake_case)] mod error_store { use super::*; #[link(name = "oleaut32")] extern "system" { pub(super) fn SetErrorInfo( dw_reserved: u32, errorinfo: Option<crate::raw::InterfacePtr<AutomationTypeSystem, dyn IErrorInfo>>, ) -> raw::HRESULT; #[allow(private_in_public)] pub(super) fn GetErrorInfo( dw_reserved: u32, errorinfo: *mut Option<crate::raw::InterfacePtr<AutomationTypeSystem, dyn IErrorInfo>>, ) -> raw::HRESULT; } } #[cfg(not(windows))] #[allow(non_snake_case)] mod error_store { use super::*; use std::cell::RefCell; thread_local! { static ERROR_STORE: RefCell< Option< ComRc<dyn IErrorInfo> > > = RefCell::new( None ); } fn reset_error_store(value: Option<ComRc<dyn IErrorInfo>>) { ERROR_STORE.with(|store| { store.replace(value); }); } fn take_error() -> Option<ComRc<dyn IErrorInfo>> { ERROR_STORE.with(|store| store.replace(None)) } pub(super) unsafe fn SetErrorInfo( _dw_reserved: u32, errorinfo: Option<crate::raw::InterfacePtr<AutomationTypeSystem, dyn IErrorInfo>>, ) -> raw::HRESULT { reset_error_store(errorinfo.map(ComRc::from)); raw::S_OK } pub(super) unsafe fn GetErrorInfo( _dw_reserved: u32, errorinfo: *mut Option<crate::raw::InterfacePtr<AutomationTypeSystem, dyn IErrorInfo>>, ) -> raw::HRESULT { match take_error() { Some(rc) => { *errorinfo = ComItf::ptr(&ComRc::detach(rc)); raw::S_OK } None => { *errorinfo = None; raw::S_FALSE } } } } /// Error info COM object data. #[com_class( clsid = None, IErrorInfo )] #[derive(Debug, Clone)] pub struct ErrorInfo { guid: GUID, source: String, description: String, help_file: String, help_context: u32, } impl ErrorInfo { pub fn new(description: String) -> ErrorInfo { ErrorInfo { description, guid: GUID::zero_guid(), source: String::new(), help_file: String::new(), help_context: 0, } } pub fn guid(&self) -> &GUID { &self.guid } pub fn source(&self) -> &str { &self.source } pub fn description(&self) -> &str { &self.description } pub fn help_file(&self) -> &str { &self.help_file } pub fn help_context(&self) -> u32 { self.help_context } } impl<'a> TryFrom<&'a dyn IErrorInfo> for ErrorInfo { type Error = raw::HRESULT; fn try_from(source: &'a dyn IErrorInfo) -> Result<Self, Self::Error> { Ok(ErrorInfo { guid: source.get_guid()?, source: source.get_source()?, description: source.get_description()?, help_file: source.get_help_file()?, help_context: source.get_help_context()?, }) } } #[com_interface(com_iid = "1CF2B120-547D-101B-8E65-08002B2BD119")] pub trait IErrorInfo: crate::IUnknown { fn get_guid(&self) -> ComResult<GUID>; fn get_source(&self) -> ComResult<String>; fn get_description(&self) -> ComResult<String>; fn get_help_file(&self) -> ComResult<String>; fn get_help_context(&self) -> ComResult<u32>; } impl IErrorInfo for ErrorInfo { fn get_guid(&self) -> ComResult<GUID> { Ok(self.guid.clone()) } fn get_source(&self) -> ComResult<String> { Ok(self.source.clone()) } fn get_description(&self) -> ComResult<String> { Ok(self.description.clone()) } fn get_help_file(&self) -> ComResult<String> { Ok(self.help_file.clone()) } fn get_help_context(&self) -> ComResult<u32> { Ok(self.help_context) } } /// Extracts the HRESULT from the error result and stores the extended error /// information in thread memory so it can be fetched by the COM client. pub fn store_error<E>(error: E) -> ComError where E: Into<ComError>, { // Convet the error. let com_error = error.into(); match com_error.error_info { Some(ref error_info) => { // ComError contains ErrorInfo. We need to set this in the OS error // store. // Construct the COM class used for IErrorInfo. The class contains the // description in memory. let info = ComBox::<ErrorInfo>::new(error_info.clone()); // Store the IErrorInfo pointer in the SetErrorInfo. let rc = ComRc::<dyn IErrorInfo>::from(info); let ptr = ComItf::ptr(&rc).expect("Intercom did not implement correct type system"); unsafe { error_store::SetErrorInfo(0, Some(ptr)); } } None => { // No error info in the ComError. unsafe { error_store::SetErrorInfo(0, None); } } } // Return the HRESULT of the original error. com_error } pub fn load_error<I: ComInterface +?Sized>( iunk: &ComItf<I>, iid: &GUID, err: raw::HRESULT, ) -> ComError { // Do not try to load error if this is IUnknown or ISupportErrorInfo. // Both of these are used during error handling and may fail. if iid == <dyn IUnknown as ComInterfaceVariant<AutomationTypeSystem>>::iid() || iid == <dyn IUnknown as ComInterfaceVariant<RawTypeSystem>>::iid() || iid == <dyn ISupportErrorInfo as ComInterfaceVariant<AutomationTypeSystem>>::iid() || iid == <dyn ISupportErrorInfo as ComInterfaceVariant<RawTypeSystem>>::iid() { return ComError { hresult: err, error_info: None, }; } // Try to get the ISupportErrorInfo and query that for the IID. let supports_errorinfo = match ComItf::query_interface::<dyn ISupportErrorInfo>(iunk) { Ok(rc) => match rc.interface_supports_error_info(iid) { intercom::raw::S_OK => true, _ => false, }, _ => false, }; ComError { hresult: err, error_info: match supports_errorinfo { true => get_last_error(), false => None, }, } } /// Gets the last COM error that occurred on the current thread. pub fn get_last_error() -> Option<ErrorInfo> { let ierrorinfo = match get_error_info() { Some(ierror) => ierror, None => return None, }; // FIXME ComRc Deref let ierr: &dyn IErrorInfo = &*ierrorinfo; ErrorInfo::try_from(ierr).ok() } /// Defines a way to handle errors based on the method return value type. /// /// The default implementation will terminate the process on the basis that /// errors must not silently leak. The specialization for `HRESULT` will return /// the `HRESULT`. /// /// The user is free to implement this trait for their own types to handle /// custom status codes gracefully. pub trait ErrorValue { /// Attempts to convert a COM error into a custom status code. Must not panic. fn from_error(_: ComError) -> Self; } impl<S, E: ErrorValue> ErrorValue for Result<S, E> { fn from_error(e: ComError) -> Self { Err(E::from_error(e)) } } impl<T: From<ComError>> ErrorValue for T { fn from_error(err: ComError) -> Self { err.into() } } #[com_class(IErrorStore)] #[derive(Default)] pub struct ErrorStore; #[com_interface( com_iid = "d7f996c5-0b51-4053-82f8-19a7261793a9", raw_iid = "7586c49a-abbd-4a06-b588-e3d02b431f01" )] pub trait IErrorStore: crate::IUnknown { fn get_error_info(&self) -> ComResult<ComRc<dyn IErrorInfo>>; fn set_error_info(&self, info: &ComItf<dyn IErrorInfo>) -> ComResult<()>; fn set_error_message(&self, msg: &str) -> ComResult<()>; } impl IErrorStore for ErrorStore { fn get_error_info(&self) -> ComResult<ComRc<dyn IErrorInfo>> { Ok(get_error_info().unwrap()) // FIXME Option } fn set_error_info(&self, info: &ComItf<dyn IErrorInfo>) -> ComResult<()> { set_error_info(&info) } fn set_error_message(&self, msg: &str) -> ComResult<()> { let info = ComBox::<ErrorInfo>::new(ErrorInfo::new(msg.to_string())); let itf = ComRc::<dyn IErrorInfo>::from(&info); self.set_error_info(&*itf) } } fn get_error_info() -> Option<ComRc<dyn IErrorInfo>> { // We're unsafe due to pointer lifetimes. // // The GetErrorInfo gives us a raw pointer which we own so we'll need to // wrap that in a `ComRc` to manage its memory. unsafe { // Get the error info and wrap it in an RC. let mut error_ptr = None; match error_store::GetErrorInfo(0, &mut error_ptr) { raw::S_OK => {} _ => return None, } match error_ptr { Some(ptr) => Some(ComRc::wrap(ptr)), None => None, } } } fn set_error_info(info: &ComItf<dyn IErrorInfo>) -> ComResult<()> { unsafe { error_store::SetErrorInfo(0, ComItf::ptr(info)).into() } } pub mod raw { /// COM method status code. #[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)] #[repr(C)] pub struct HRESULT { /// The numerical HRESULT code. pub hr: i32, } impl HRESULT { /// Constructs a new `HRESULT` with the given numerical code. pub fn new(hr: i32) -> HRESULT { #[allow(overflowing_literals)] HRESULT { hr: hr as i32 } } } macro_rules! make_hr { ( $(#[$attr:meta] )* $hr_name: ident = $hr_value: expr ) => { $(#[$attr])* #[allow(overflowing_literals)] pub const $hr_name : HRESULT = HRESULT { hr: $hr_value as i32 }; } } make_hr!( /// `HRESULT` indicating the operation completed successfully. S_OK = 0 ); make_hr!( /// `HRESULT` indicating the operation completed successfully and returned /// `false`. S_FALSE = 1 ); make_hr!( /// `HRESULT` for unimplemented functionality. E_NOTIMPL = 0x8000_4001 ); make_hr!( /// `HRESULT` indicating the type does not support the requested interface. E_NOINTERFACE = 0x8000_4002 ); make_hr!( /// `HRESULT` indicating a pointer parameter was invalid. E_POINTER = 0x8000_4003 ); make_hr!( /// `HRESULT` for aborted operation. E_ABORT = 0x8000_4004 ); make_hr!( /// `HRESULT` for unspecified failure. E_FAIL = 0x8000_4005 ); make_hr!( /// `HRESULT` for invalid argument. E_INVALIDARG = 0x8007_0057 ); make_hr!( /// `HRESULT` for unavailable CLSID. E_CLASSNOTAVAILABLE = 0x8004_0111 ); // These might be deprecated. They are a bit too specific for cross-platform // support. We'll just need to ensure the winapi HRESULTs are compatible. make_hr!(E_ACCESSDENIED = 0x8007_0005); make_hr!(STG_E_FILENOTFOUND = 0x8003_0002); make_hr!(RPC_E_DISCONNECTED = 0x8001_0108); make_hr!(RPC_E_CALL_REJECTED = 0x8001_0001); make_hr!(RPC_E_CALL_CANCELED = 0x8001_0002); make_hr!(RPC_E_TIMEOUT = 0x8001_011F); }
from_foreign_output
identifier_name
borrowed-enum.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags:-Z extra-debug-info // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print *the_a_ref // check:$1 = {{TheA, x = 0, y = 8970181431921507452}, {TheA, 0, 2088533116, 2088533116}} // debugger:print *the_b_ref // check:$2 = {{TheB, x = 0, y = 1229782938247303441}, {TheB, 0, 286331153, 286331153}} // debugger:print *univariant_ref // check:$3 = {4820353753753434} #[allow(unused_variable)]; #[feature(struct_variant)]; // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when // datatype layout should be predictable as in this case. enum ABC { TheA { x: i64, y: i64 }, TheB (i64, i32, i32), } // This is a special case since it does not have the implicit discriminant field. enum Univariant { TheOnlyCase(i64) } fn main()
} fn zzz() {()}
{ // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let the_a = TheA { x: 0, y: 8970181431921507452 }; let the_a_ref: &ABC = &the_a; // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441 // 0b00010001000100010001000100010001 = 286331153 // 0b0001000100010001 = 4369 // 0b00010001 = 17 let the_b = TheB (0, 286331153, 286331153); let the_b_ref: &ABC = &the_b; let univariant = TheOnlyCase(4820353753753434); let univariant_ref: &Univariant = &univariant; zzz();
identifier_body
borrowed-enum.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
// debugger:run // debugger:finish // debugger:print *the_a_ref // check:$1 = {{TheA, x = 0, y = 8970181431921507452}, {TheA, 0, 2088533116, 2088533116}} // debugger:print *the_b_ref // check:$2 = {{TheB, x = 0, y = 1229782938247303441}, {TheB, 0, 286331153, 286331153}} // debugger:print *univariant_ref // check:$3 = {4820353753753434} #[allow(unused_variable)]; #[feature(struct_variant)]; // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when // datatype layout should be predictable as in this case. enum ABC { TheA { x: i64, y: i64 }, TheB (i64, i32, i32), } // This is a special case since it does not have the implicit discriminant field. enum Univariant { TheOnlyCase(i64) } fn main() { // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let the_a = TheA { x: 0, y: 8970181431921507452 }; let the_a_ref: &ABC = &the_a; // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441 // 0b00010001000100010001000100010001 = 286331153 // 0b0001000100010001 = 4369 // 0b00010001 = 17 let the_b = TheB (0, 286331153, 286331153); let the_b_ref: &ABC = &the_b; let univariant = TheOnlyCase(4820353753753434); let univariant_ref: &Univariant = &univariant; zzz(); } fn zzz() {()}
// compile-flags:-Z extra-debug-info // debugger:rbreak zzz
random_line_split
borrowed-enum.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags:-Z extra-debug-info // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print *the_a_ref // check:$1 = {{TheA, x = 0, y = 8970181431921507452}, {TheA, 0, 2088533116, 2088533116}} // debugger:print *the_b_ref // check:$2 = {{TheB, x = 0, y = 1229782938247303441}, {TheB, 0, 286331153, 286331153}} // debugger:print *univariant_ref // check:$3 = {4820353753753434} #[allow(unused_variable)]; #[feature(struct_variant)]; // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when // datatype layout should be predictable as in this case. enum ABC { TheA { x: i64, y: i64 }, TheB (i64, i32, i32), } // This is a special case since it does not have the implicit discriminant field. enum Univariant { TheOnlyCase(i64) } fn
() { // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let the_a = TheA { x: 0, y: 8970181431921507452 }; let the_a_ref: &ABC = &the_a; // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441 // 0b00010001000100010001000100010001 = 286331153 // 0b0001000100010001 = 4369 // 0b00010001 = 17 let the_b = TheB (0, 286331153, 286331153); let the_b_ref: &ABC = &the_b; let univariant = TheOnlyCase(4820353753753434); let univariant_ref: &Univariant = &univariant; zzz(); } fn zzz() {()}
main
identifier_name
kinds.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. /*! Primitive traits representing basic 'kinds' of types Rust types can be classified in various useful ways according to intrinsic properties of the type. These classifications, often called 'kinds', are represented as traits. They cannot be implemented by user code, but are instead implemented by the compiler automatically for the types to which they apply. */ /// Types able to be transferred across task boundaries. #[lang="send"] pub trait Send { // empty. } /// Types with a constant size known at compile-time. #[lang="sized"] pub trait Sized { // Empty. } /// Types that can be copied by simply copying bits (i.e. `memcpy`). #[lang="copy"] pub trait Copy { // Empty. } /// Types that can be safely shared between tasks when aliased. /// /// The precise definition is: a type `T` is `Share` if `&T` is /// thread-safe. In other words, there is no possibility of data races /// when passing `&T` references between tasks. /// /// As one would expect, primitive types like `u8` and `f64` are all /// `Share`, and so are simple aggregate types containing them (like /// tuples, structs and enums). More instances of basic `Share` types /// include "immutable" types like `&T` and those with simple /// inherited mutability, such as `~T`, `Vec<T>` and most other /// collection types. (Generic parameters need to be `Share` for their /// container to be `Share`.) /// /// A somewhat surprising consequence of the definition is `&mut T` is /// `Share` (if `T` is `Share`) even though it seems that it might /// provide unsynchronised mutation. The trick is a mutable reference /// stored in an aliasable reference (that is, `& &mut T`) becomes /// read-only, as if it were a `& &T`, hence there is no risk of a data /// race. /// /// Types that are not `Share` are those that have "interior /// mutability" in a non-thread-safe way, such as `Cell` and `RefCell` /// in `std::cell`. These types allow for mutation of their contents /// even when in an immutable, aliasable slot, e.g. the contents of /// `&Cell<T>` can be `.set`, and do not ensure data races are /// impossible, hence they cannot be `Share`. A higher level example /// of a non-`Share` type is the reference counted pointer /// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new /// reference, which modifies the reference counts in a non-atomic /// way. /// /// For cases when one does need thread-safe interior mutability, /// types like the atomics in `std::sync` and `Mutex` & `RWLock` in /// the `sync` crate do ensure that any mutation cannot cause data /// races. Hence these types are `Share`. /// /// Users writing their own types with interior mutability (or anything /// else that is not thread-safe) should use the `NoShare` marker type /// (from `std::kinds::marker`) to ensure that the compiler doesn't /// consider the user-defined type to be `Share`. Any types with /// interior mutability must also use the `std::ty::Unsafe` wrapper /// around the value(s) which can be mutated when behind a `&` /// reference; not doing this is undefined behaviour (for example, /// `transmute`-ing from `&T` to `&mut T` is illegal). #[lang="share"] pub trait Share { // Empty } /// Marker types are special types that are used with unsafe code to /// inform the compiler of special constraints. Marker types should /// only be needed when you are creating an abstraction that is /// implemented using unsafe code. In that case, you may want to embed
/// covariant with respect to the type itself. This is (typically) /// used to indicate that an instance of the type `T` is being stored /// into memory and read from, even though that may not be apparent. /// /// For more information about variance, refer to this Wikipedia /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>. /// /// *Note:* It is very unusual to have to add a covariant constraint. /// If you are not sure, you probably want to use `InvariantType`. /// /// # Example /// /// Given a struct `S` that includes a type parameter `T` /// but does not actually *reference* that type parameter: /// /// ```ignore /// use std::cast; /// /// struct S<T> { x: *() } /// fn get<T>(s: &S<T>) -> T { /// unsafe { /// let x: *T = cast::transmute(s.x); /// *x /// } /// } /// ``` /// /// The type system would currently infer that the value of /// the type parameter `T` is irrelevant, and hence a `S<int>` is /// a subtype of `S<~[int]>` (or, for that matter, `S<U>` for /// any `U`). But this is incorrect because `get()` converts the /// `*()` into a `*T` and reads from it. Therefore, we should include the /// a marker field `CovariantType<T>` to inform the type checker that /// `S<T>` is a subtype of `S<U>` if `T` is a subtype of `U` /// (for example, `S<&'static int>` is a subtype of `S<&'a int>` /// for some lifetime `'a`, but not the other way around). #[lang="covariant_type"] #[deriving(Eq,Clone)] pub struct CovariantType<T>; /// A marker type whose type parameter `T` is considered to be /// contravariant with respect to the type itself. This is (typically) /// used to indicate that an instance of the type `T` will be consumed /// (but not read from), even though that may not be apparent. /// /// For more information about variance, refer to this Wikipedia /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>. /// /// *Note:* It is very unusual to have to add a contravariant constraint. /// If you are not sure, you probably want to use `InvariantType`. /// /// # Example /// /// Given a struct `S` that includes a type parameter `T` /// but does not actually *reference* that type parameter: /// /// ``` /// use std::cast; /// /// struct S<T> { x: *() } /// fn get<T>(s: &S<T>, v: T) { /// unsafe { /// let x: fn(T) = cast::transmute(s.x); /// x(v) /// } /// } /// ``` /// /// The type system would currently infer that the value of /// the type parameter `T` is irrelevant, and hence a `S<int>` is /// a subtype of `S<~[int]>` (or, for that matter, `S<U>` for /// any `U`). But this is incorrect because `get()` converts the /// `*()` into a `fn(T)` and then passes a value of type `T` to it. /// /// Supplying a `ContravariantType` marker would correct the /// problem, because it would mark `S` so that `S<T>` is only a /// subtype of `S<U>` if `U` is a subtype of `T`; given that the /// function requires arguments of type `T`, it must also accept /// arguments of type `U`, hence such a conversion is safe. #[lang="contravariant_type"] #[deriving(Eq,Clone)] pub struct ContravariantType<T>; /// A marker type whose type parameter `T` is considered to be /// invariant with respect to the type itself. This is (typically) /// used to indicate that instances of the type `T` may be read or /// written, even though that may not be apparent. /// /// For more information about variance, refer to this Wikipedia /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>. /// /// # Example /// /// The Cell type is an example which uses unsafe code to achieve /// "interior" mutability: /// /// ``` /// pub struct Cell<T> { value: T } /// # fn main() {} /// ``` /// /// The type system would infer that `value` is only read here and /// never written, but in fact `Cell` uses unsafe code to achieve /// interior mutability. #[lang="invariant_type"] #[deriving(Eq,Clone)] pub struct InvariantType<T>; /// As `CovariantType`, but for lifetime parameters. Using /// `CovariantLifetime<'a>` indicates that it is ok to substitute /// a *longer* lifetime for `'a` than the one you originally /// started with (e.g., you could convert any lifetime `'foo` to /// `'static`). You almost certainly want `ContravariantLifetime` /// instead, or possibly `InvariantLifetime`. The only case where /// it would be appropriate is that you have a (type-casted, and /// hence hidden from the type system) function pointer with a /// signature like `fn(&'a T)` (and no other uses of `'a`). In /// this case, it is ok to substitute a larger lifetime for `'a` /// (e.g., `fn(&'static T)`), because the function is only /// becoming more selective in terms of what it accepts as /// argument. /// /// For more information about variance, refer to this Wikipedia /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>. #[lang="covariant_lifetime"] #[deriving(Eq,Clone)] pub struct CovariantLifetime<'a>; /// As `ContravariantType`, but for lifetime parameters. Using /// `ContravariantLifetime<'a>` indicates that it is ok to /// substitute a *shorter* lifetime for `'a` than the one you /// originally started with (e.g., you could convert `'static` to /// any lifetime `'foo`). This is appropriate for cases where you /// have an unsafe pointer that is actually a pointer into some /// memory with lifetime `'a`, and thus you want to limit the /// lifetime of your data structure to `'a`. An example of where /// this is used is the iterator for vectors. /// /// For more information about variance, refer to this Wikipedia /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>. #[lang="contravariant_lifetime"] #[deriving(Eq,Clone)] pub struct ContravariantLifetime<'a>; /// As `InvariantType`, but for lifetime parameters. Using /// `InvariantLifetime<'a>` indicates that it is not ok to /// substitute any other lifetime for `'a` besides its original /// value. This is appropriate for cases where you have an unsafe /// pointer that is actually a pointer into memory with lifetime `'a`, /// and this pointer is itself stored in an inherently mutable /// location (such as a `Cell`). #[lang="invariant_lifetime"] #[deriving(Eq,Clone)] pub struct InvariantLifetime<'a>; /// A type which is considered "not sendable", meaning that it cannot /// be safely sent between tasks, even if it is owned. This is /// typically embedded in other types, such as `Gc`, to ensure that /// their instances remain thread-local. #[lang="no_send_bound"] #[deriving(Eq,Clone)] pub struct NoSend; /// A type which is considered "not POD", meaning that it is not /// implicitly copyable. This is typically embedded in other types to /// ensure that they are never copied, even if they lack a destructor. #[lang="no_copy_bound"] #[deriving(Eq,Clone)] pub struct NoCopy; /// A type which is considered "not sharable", meaning that /// its contents are not threadsafe, hence they cannot be /// shared between tasks. #[lang="no_share_bound"] #[deriving(Eq,Clone)] pub struct NoShare; /// A type which is considered managed by the GC. This is typically /// embedded in other types. #[lang="managed_bound"] #[deriving(Eq,Clone)] pub struct Managed; }
/// some of the marker types below into your type. pub mod marker { /// A marker type whose type parameter `T` is considered to be
random_line_split
kinds.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. /*! Primitive traits representing basic 'kinds' of types Rust types can be classified in various useful ways according to intrinsic properties of the type. These classifications, often called 'kinds', are represented as traits. They cannot be implemented by user code, but are instead implemented by the compiler automatically for the types to which they apply. */ /// Types able to be transferred across task boundaries. #[lang="send"] pub trait Send { // empty. } /// Types with a constant size known at compile-time. #[lang="sized"] pub trait Sized { // Empty. } /// Types that can be copied by simply copying bits (i.e. `memcpy`). #[lang="copy"] pub trait Copy { // Empty. } /// Types that can be safely shared between tasks when aliased. /// /// The precise definition is: a type `T` is `Share` if `&T` is /// thread-safe. In other words, there is no possibility of data races /// when passing `&T` references between tasks. /// /// As one would expect, primitive types like `u8` and `f64` are all /// `Share`, and so are simple aggregate types containing them (like /// tuples, structs and enums). More instances of basic `Share` types /// include "immutable" types like `&T` and those with simple /// inherited mutability, such as `~T`, `Vec<T>` and most other /// collection types. (Generic parameters need to be `Share` for their /// container to be `Share`.) /// /// A somewhat surprising consequence of the definition is `&mut T` is /// `Share` (if `T` is `Share`) even though it seems that it might /// provide unsynchronised mutation. The trick is a mutable reference /// stored in an aliasable reference (that is, `& &mut T`) becomes /// read-only, as if it were a `& &T`, hence there is no risk of a data /// race. /// /// Types that are not `Share` are those that have "interior /// mutability" in a non-thread-safe way, such as `Cell` and `RefCell` /// in `std::cell`. These types allow for mutation of their contents /// even when in an immutable, aliasable slot, e.g. the contents of /// `&Cell<T>` can be `.set`, and do not ensure data races are /// impossible, hence they cannot be `Share`. A higher level example /// of a non-`Share` type is the reference counted pointer /// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new /// reference, which modifies the reference counts in a non-atomic /// way. /// /// For cases when one does need thread-safe interior mutability, /// types like the atomics in `std::sync` and `Mutex` & `RWLock` in /// the `sync` crate do ensure that any mutation cannot cause data /// races. Hence these types are `Share`. /// /// Users writing their own types with interior mutability (or anything /// else that is not thread-safe) should use the `NoShare` marker type /// (from `std::kinds::marker`) to ensure that the compiler doesn't /// consider the user-defined type to be `Share`. Any types with /// interior mutability must also use the `std::ty::Unsafe` wrapper /// around the value(s) which can be mutated when behind a `&` /// reference; not doing this is undefined behaviour (for example, /// `transmute`-ing from `&T` to `&mut T` is illegal). #[lang="share"] pub trait Share { // Empty } /// Marker types are special types that are used with unsafe code to /// inform the compiler of special constraints. Marker types should /// only be needed when you are creating an abstraction that is /// implemented using unsafe code. In that case, you may want to embed /// some of the marker types below into your type. pub mod marker { /// A marker type whose type parameter `T` is considered to be /// covariant with respect to the type itself. This is (typically) /// used to indicate that an instance of the type `T` is being stored /// into memory and read from, even though that may not be apparent. /// /// For more information about variance, refer to this Wikipedia /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>. /// /// *Note:* It is very unusual to have to add a covariant constraint. /// If you are not sure, you probably want to use `InvariantType`. /// /// # Example /// /// Given a struct `S` that includes a type parameter `T` /// but does not actually *reference* that type parameter: /// /// ```ignore /// use std::cast; /// /// struct S<T> { x: *() } /// fn get<T>(s: &S<T>) -> T { /// unsafe { /// let x: *T = cast::transmute(s.x); /// *x /// } /// } /// ``` /// /// The type system would currently infer that the value of /// the type parameter `T` is irrelevant, and hence a `S<int>` is /// a subtype of `S<~[int]>` (or, for that matter, `S<U>` for /// any `U`). But this is incorrect because `get()` converts the /// `*()` into a `*T` and reads from it. Therefore, we should include the /// a marker field `CovariantType<T>` to inform the type checker that /// `S<T>` is a subtype of `S<U>` if `T` is a subtype of `U` /// (for example, `S<&'static int>` is a subtype of `S<&'a int>` /// for some lifetime `'a`, but not the other way around). #[lang="covariant_type"] #[deriving(Eq,Clone)] pub struct CovariantType<T>; /// A marker type whose type parameter `T` is considered to be /// contravariant with respect to the type itself. This is (typically) /// used to indicate that an instance of the type `T` will be consumed /// (but not read from), even though that may not be apparent. /// /// For more information about variance, refer to this Wikipedia /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>. /// /// *Note:* It is very unusual to have to add a contravariant constraint. /// If you are not sure, you probably want to use `InvariantType`. /// /// # Example /// /// Given a struct `S` that includes a type parameter `T` /// but does not actually *reference* that type parameter: /// /// ``` /// use std::cast; /// /// struct S<T> { x: *() } /// fn get<T>(s: &S<T>, v: T) { /// unsafe { /// let x: fn(T) = cast::transmute(s.x); /// x(v) /// } /// } /// ``` /// /// The type system would currently infer that the value of /// the type parameter `T` is irrelevant, and hence a `S<int>` is /// a subtype of `S<~[int]>` (or, for that matter, `S<U>` for /// any `U`). But this is incorrect because `get()` converts the /// `*()` into a `fn(T)` and then passes a value of type `T` to it. /// /// Supplying a `ContravariantType` marker would correct the /// problem, because it would mark `S` so that `S<T>` is only a /// subtype of `S<U>` if `U` is a subtype of `T`; given that the /// function requires arguments of type `T`, it must also accept /// arguments of type `U`, hence such a conversion is safe. #[lang="contravariant_type"] #[deriving(Eq,Clone)] pub struct ContravariantType<T>; /// A marker type whose type parameter `T` is considered to be /// invariant with respect to the type itself. This is (typically) /// used to indicate that instances of the type `T` may be read or /// written, even though that may not be apparent. /// /// For more information about variance, refer to this Wikipedia /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>. /// /// # Example /// /// The Cell type is an example which uses unsafe code to achieve /// "interior" mutability: /// /// ``` /// pub struct Cell<T> { value: T } /// # fn main() {} /// ``` /// /// The type system would infer that `value` is only read here and /// never written, but in fact `Cell` uses unsafe code to achieve /// interior mutability. #[lang="invariant_type"] #[deriving(Eq,Clone)] pub struct InvariantType<T>; /// As `CovariantType`, but for lifetime parameters. Using /// `CovariantLifetime<'a>` indicates that it is ok to substitute /// a *longer* lifetime for `'a` than the one you originally /// started with (e.g., you could convert any lifetime `'foo` to /// `'static`). You almost certainly want `ContravariantLifetime` /// instead, or possibly `InvariantLifetime`. The only case where /// it would be appropriate is that you have a (type-casted, and /// hence hidden from the type system) function pointer with a /// signature like `fn(&'a T)` (and no other uses of `'a`). In /// this case, it is ok to substitute a larger lifetime for `'a` /// (e.g., `fn(&'static T)`), because the function is only /// becoming more selective in terms of what it accepts as /// argument. /// /// For more information about variance, refer to this Wikipedia /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>. #[lang="covariant_lifetime"] #[deriving(Eq,Clone)] pub struct CovariantLifetime<'a>; /// As `ContravariantType`, but for lifetime parameters. Using /// `ContravariantLifetime<'a>` indicates that it is ok to /// substitute a *shorter* lifetime for `'a` than the one you /// originally started with (e.g., you could convert `'static` to /// any lifetime `'foo`). This is appropriate for cases where you /// have an unsafe pointer that is actually a pointer into some /// memory with lifetime `'a`, and thus you want to limit the /// lifetime of your data structure to `'a`. An example of where /// this is used is the iterator for vectors. /// /// For more information about variance, refer to this Wikipedia /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>. #[lang="contravariant_lifetime"] #[deriving(Eq,Clone)] pub struct ContravariantLifetime<'a>; /// As `InvariantType`, but for lifetime parameters. Using /// `InvariantLifetime<'a>` indicates that it is not ok to /// substitute any other lifetime for `'a` besides its original /// value. This is appropriate for cases where you have an unsafe /// pointer that is actually a pointer into memory with lifetime `'a`, /// and this pointer is itself stored in an inherently mutable /// location (such as a `Cell`). #[lang="invariant_lifetime"] #[deriving(Eq,Clone)] pub struct InvariantLifetime<'a>; /// A type which is considered "not sendable", meaning that it cannot /// be safely sent between tasks, even if it is owned. This is /// typically embedded in other types, such as `Gc`, to ensure that /// their instances remain thread-local. #[lang="no_send_bound"] #[deriving(Eq,Clone)] pub struct NoSend; /// A type which is considered "not POD", meaning that it is not /// implicitly copyable. This is typically embedded in other types to /// ensure that they are never copied, even if they lack a destructor. #[lang="no_copy_bound"] #[deriving(Eq,Clone)] pub struct NoCopy; /// A type which is considered "not sharable", meaning that /// its contents are not threadsafe, hence they cannot be /// shared between tasks. #[lang="no_share_bound"] #[deriving(Eq,Clone)] pub struct
; /// A type which is considered managed by the GC. This is typically /// embedded in other types. #[lang="managed_bound"] #[deriving(Eq,Clone)] pub struct Managed; }
NoShare
identifier_name
wc.rs
use std::process::Command; use util::*; static PROGNAME: &'static str = "./wc"; #[path = "common/util.rs"] #[macro_use]
fn test_stdin_default() { let mut cmd = Command::new(PROGNAME); let result = run_piped_stdin(&mut cmd, get_file_contents("lorem_ipsum.txt")); assert_eq!(result.stdout, " 13 109 772\n"); } #[test] fn test_stdin_only_bytes() { let mut cmd = Command::new(PROGNAME); let result = run_piped_stdin(&mut cmd.args(&["-c"]), get_file_contents("lorem_ipsum.txt")); assert_eq!(result.stdout, " 772\n"); } #[test] fn test_stdin_all_counts() { let mut cmd = Command::new(PROGNAME); let result = run_piped_stdin(&mut cmd.args(&["-c", "-m", "-l", "-L", "-w"]), get_file_contents("alice_in_wonderland.txt")); assert_eq!(result.stdout, " 5 57 302 302 66\n"); } #[test] fn test_single_default() { let mut cmd = Command::new(PROGNAME); let result = run(&mut cmd.arg("moby_dick.txt")); assert_eq!(result.stdout, " 18 204 1115 moby_dick.txt\n"); } #[test] fn test_single_only_lines() { let mut cmd = Command::new(PROGNAME); let result = run(&mut cmd.args(&["-l", "moby_dick.txt"])); assert_eq!(result.stdout, " 18 moby_dick.txt\n"); } #[test] fn test_single_all_counts() { let mut cmd = Command::new(PROGNAME); let result = run(&mut cmd.args(&["-c", "-l", "-L", "-m", "-w", "alice_in_wonderland.txt"])); assert_eq!(result.stdout, " 5 57 302 302 66 alice_in_wonderland.txt\n"); } #[test] fn test_multiple_default() { let mut cmd = Command::new(PROGNAME); let result = run(&mut cmd.args(&["lorem_ipsum.txt", "moby_dick.txt", "alice_in_wonderland.txt"])); assert_eq!(result.stdout, " 13 109 772 lorem_ipsum.txt\n 18 204 1115 moby_dick.txt\n 5 57 302 alice_in_wonderland.txt\n 36 370 2189 total\n"); }
mod util; #[test]
random_line_split
wc.rs
use std::process::Command; use util::*; static PROGNAME: &'static str = "./wc"; #[path = "common/util.rs"] #[macro_use] mod util; #[test] fn test_stdin_default() { let mut cmd = Command::new(PROGNAME); let result = run_piped_stdin(&mut cmd, get_file_contents("lorem_ipsum.txt")); assert_eq!(result.stdout, " 13 109 772\n"); } #[test] fn test_stdin_only_bytes() { let mut cmd = Command::new(PROGNAME); let result = run_piped_stdin(&mut cmd.args(&["-c"]), get_file_contents("lorem_ipsum.txt")); assert_eq!(result.stdout, " 772\n"); } #[test] fn test_stdin_all_counts() { let mut cmd = Command::new(PROGNAME); let result = run_piped_stdin(&mut cmd.args(&["-c", "-m", "-l", "-L", "-w"]), get_file_contents("alice_in_wonderland.txt")); assert_eq!(result.stdout, " 5 57 302 302 66\n"); } #[test] fn test_single_default() { let mut cmd = Command::new(PROGNAME); let result = run(&mut cmd.arg("moby_dick.txt")); assert_eq!(result.stdout, " 18 204 1115 moby_dick.txt\n"); } #[test] fn test_single_only_lines() { let mut cmd = Command::new(PROGNAME); let result = run(&mut cmd.args(&["-l", "moby_dick.txt"])); assert_eq!(result.stdout, " 18 moby_dick.txt\n"); } #[test] fn test_single_all_counts()
#[test] fn test_multiple_default() { let mut cmd = Command::new(PROGNAME); let result = run(&mut cmd.args(&["lorem_ipsum.txt", "moby_dick.txt", "alice_in_wonderland.txt"])); assert_eq!(result.stdout, " 13 109 772 lorem_ipsum.txt\n 18 204 1115 moby_dick.txt\n 5 57 302 alice_in_wonderland.txt\n 36 370 2189 total\n"); }
{ let mut cmd = Command::new(PROGNAME); let result = run(&mut cmd.args(&["-c", "-l", "-L", "-m", "-w", "alice_in_wonderland.txt"])); assert_eq!(result.stdout, " 5 57 302 302 66 alice_in_wonderland.txt\n"); }
identifier_body
wc.rs
use std::process::Command; use util::*; static PROGNAME: &'static str = "./wc"; #[path = "common/util.rs"] #[macro_use] mod util; #[test] fn test_stdin_default() { let mut cmd = Command::new(PROGNAME); let result = run_piped_stdin(&mut cmd, get_file_contents("lorem_ipsum.txt")); assert_eq!(result.stdout, " 13 109 772\n"); } #[test] fn test_stdin_only_bytes() { let mut cmd = Command::new(PROGNAME); let result = run_piped_stdin(&mut cmd.args(&["-c"]), get_file_contents("lorem_ipsum.txt")); assert_eq!(result.stdout, " 772\n"); } #[test] fn test_stdin_all_counts() { let mut cmd = Command::new(PROGNAME); let result = run_piped_stdin(&mut cmd.args(&["-c", "-m", "-l", "-L", "-w"]), get_file_contents("alice_in_wonderland.txt")); assert_eq!(result.stdout, " 5 57 302 302 66\n"); } #[test] fn test_single_default() { let mut cmd = Command::new(PROGNAME); let result = run(&mut cmd.arg("moby_dick.txt")); assert_eq!(result.stdout, " 18 204 1115 moby_dick.txt\n"); } #[test] fn test_single_only_lines() { let mut cmd = Command::new(PROGNAME); let result = run(&mut cmd.args(&["-l", "moby_dick.txt"])); assert_eq!(result.stdout, " 18 moby_dick.txt\n"); } #[test] fn test_single_all_counts() { let mut cmd = Command::new(PROGNAME); let result = run(&mut cmd.args(&["-c", "-l", "-L", "-m", "-w", "alice_in_wonderland.txt"])); assert_eq!(result.stdout, " 5 57 302 302 66 alice_in_wonderland.txt\n"); } #[test] fn
() { let mut cmd = Command::new(PROGNAME); let result = run(&mut cmd.args(&["lorem_ipsum.txt", "moby_dick.txt", "alice_in_wonderland.txt"])); assert_eq!(result.stdout, " 13 109 772 lorem_ipsum.txt\n 18 204 1115 moby_dick.txt\n 5 57 302 alice_in_wonderland.txt\n 36 370 2189 total\n"); }
test_multiple_default
identifier_name
subst.rs
> for (T, T, T) { fn len(&self) -> uint { 3 } fn as_slice<'a>(&'a self) -> &'a [T] { unsafe { let ptr: *const T = mem::transmute(self); let slice = raw::Slice { data: ptr, len: 3 }; mem::transmute(slice) } } fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] { unsafe { let ptr: *const T = mem::transmute(self); let slice = raw::Slice { data: ptr, len: 3 }; mem::transmute(slice) } } fn iter<'a>(&'a self) -> Items<'a, T> { let slice: &'a [T] = self.as_slice(); slice.iter() } fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> { self.as_mut_slice().iter_mut() } fn get<'a>(&'a self, index: uint) -> Option<&'a T> { self.as_slice().get(index) } fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut T> { Some(&mut self.as_mut_slice()[index]) // wrong: fallible } } /////////////////////////////////////////////////////////////////////////// /** * A substitution mapping type/region parameters to new values. We * identify each in-scope parameter by an *index* and a *parameter * space* (which indices where the parameter is defined; see * `ParamSpace`). */ #[deriving(Clone, PartialEq, Eq, Hash, Show)] pub struct Substs { pub types: VecPerParamSpace<ty::t>, pub regions: RegionSubsts, } /** * Represents the values to use when substituting lifetime parameters. * If the value is `ErasedRegions`, then this subst is occurring during * trans, and all region parameters will be replaced with `ty::ReStatic`. */ #[deriving(Clone, PartialEq, Eq, Hash, Show)] pub enum RegionSubsts { ErasedRegions, NonerasedRegions(VecPerParamSpace<ty::Region>) } impl Substs { pub fn new(t: VecPerParamSpace<ty::t>, r: VecPerParamSpace<ty::Region>) -> Substs { Substs { types: t, regions: NonerasedRegions(r) } } pub fn new_type(t: Vec<ty::t>, r: Vec<ty::Region>) -> Substs { Substs::new(VecPerParamSpace::new(t, Vec::new(), Vec::new()), VecPerParamSpace::new(r, Vec::new(), Vec::new())) } pub fn new_trait(t: Vec<ty::t>, r: Vec<ty::Region>, s: ty::t) -> Substs { Substs::new(VecPerParamSpace::new(t, vec!(s), Vec::new()), VecPerParamSpace::new(r, Vec::new(), Vec::new())) } pub fn erased(t: VecPerParamSpace<ty::t>) -> Substs { Substs { types: t, regions: ErasedRegions } } pub fn empty() -> Substs { Substs { types: VecPerParamSpace::empty(), regions: NonerasedRegions(VecPerParamSpace::empty()), } } pub fn trans_empty() -> Substs { Substs { types: VecPerParamSpace::empty(), regions: ErasedRegions } } pub fn is_noop(&self) -> bool { let regions_is_noop = match self.regions { ErasedRegions => false, // may be used to canonicalize NonerasedRegions(ref regions) => regions.is_empty(), }; regions_is_noop && self.types.is_empty() } pub fn self_ty(&self) -> Option<ty::t> { self.types.get_self().map(|&t| t) } pub fn with_self_ty(&self, self_ty: ty::t) -> Substs { assert!(self.self_ty().is_none()); let mut s = (*self).clone(); s.types.push(SelfSpace, self_ty); s } pub fn erase_regions(self) -> Substs { let Substs { types: types, regions: _ } = self; Substs { types: types, regions: ErasedRegions } } pub fn regions<'a>(&'a self) -> &'a VecPerParamSpace<ty::Region> { /*! * Since ErasedRegions are only to be used in trans, most of * the compiler can use this method to easily access the set * of region substitutions. */ match self.regions { ErasedRegions => fail!("Erased regions only expected in trans"), NonerasedRegions(ref r) => r } } pub fn mut_regions<'a>(&'a mut self) -> &'a mut VecPerParamSpace<ty::Region> { /*! * Since ErasedRegions are only to be used in trans, most of * the compiler can use this method to easily access the set * of region substitutions. */ match self.regions { ErasedRegions => fail!("Erased regions only expected in trans"), NonerasedRegions(ref mut r) => r } } pub fn with_method(self, m_types: Vec<ty::t>, m_regions: Vec<ty::Region>) -> Substs { let Substs { types, regions } = self; let types = types.with_vec(FnSpace, m_types); let regions = regions.map(m_regions, |r, m_regions| r.with_vec(FnSpace, m_regions)); Substs { types: types, regions: regions } } } impl RegionSubsts { fn map<A>(self, a: A, op: |VecPerParamSpace<ty::Region>, A| -> VecPerParamSpace<ty::Region>) -> RegionSubsts { match self { ErasedRegions => ErasedRegions, NonerasedRegions(r) => NonerasedRegions(op(r, a)) } } } /////////////////////////////////////////////////////////////////////////// // ParamSpace #[deriving(PartialOrd, Ord, PartialEq, Eq, Clone, Hash, Encodable, Decodable, Show)] pub enum ParamSpace { TypeSpace, // Type parameters attached to a type definition, trait, or impl SelfSpace, // Self parameter on a trait FnSpace, // Type parameters attached to a method or fn } impl ParamSpace { pub fn all() -> [ParamSpace,..3] { [TypeSpace, SelfSpace, FnSpace] } pub fn to_uint(self) -> uint { match self { TypeSpace => 0, SelfSpace => 1, FnSpace => 2, } } pub fn from_uint(u: uint) -> ParamSpace { match u { 0 => TypeSpace, 1 => SelfSpace, 2 => FnSpace, _ => fail!("Invalid ParamSpace: {}", u) } } } /** * Vector of things sorted by param space. Used to keep * the set of things declared on the type, self, or method * distinct. */ #[deriving(PartialEq, Eq, Clone, Hash, Encodable, Decodable)] pub struct VecPerParamSpace<T> { // This was originally represented as a tuple with one Vec<T> for // each variant of ParamSpace, and that remains the abstraction // that it provides to its clients. // // Here is how the representation corresponds to the abstraction // i.e. the "abstraction function" AF: // // AF(self) = (self.content.slice_to(self.type_limit), // self.content.slice(self.type_limit, self.self_limit), // self.content.slice_from(self.self_limit)) type_limit: uint, self_limit: uint, content: Vec<T>, } impl<T:fmt::Show> fmt::Show for VecPerParamSpace<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "VecPerParamSpace {{")); for space in ParamSpace::all().iter() { try!(write!(fmt, "{}: {}, ", *space, self.get_slice(*space))); } try!(write!(fmt, "}}")); Ok(()) } } impl<T> VecPerParamSpace<T> { fn limits(&self, space: ParamSpace) -> (uint, uint) { match space { TypeSpace => (0, self.type_limit), SelfSpace => (self.type_limit, self.self_limit), FnSpace => (self.self_limit, self.content.len()), } } pub fn empty() -> VecPerParamSpace<T> { VecPerParamSpace { type_limit: 0, self_limit: 0, content: Vec::new() } } pub fn params_from_type(types: Vec<T>) -> VecPerParamSpace<T> { VecPerParamSpace::empty().with_vec(TypeSpace, types) } /// `t` is the type space. /// `s` is the self space. /// `f` is the fn space. pub fn new(t: Vec<T>, s: Vec<T>, f: Vec<T>) -> VecPerParamSpace<T> { let type_limit = t.len(); let self_limit = t.len() + s.len(); let mut content = t; content.push_all_move(s); content.push_all_move(f); VecPerParamSpace { type_limit: type_limit, self_limit: self_limit, content: content, } } fn new_internal(content: Vec<T>, type_limit: uint, self_limit: uint) -> VecPerParamSpace<T> { VecPerParamSpace { type_limit: type_limit, self_limit: self_limit, content: content, } } /// Appends `value` to the vector associated with `space`. /// /// Unlike the `push` method in `Vec`, this should not be assumed /// to be a cheap operation (even when amortized over many calls). pub fn push(&mut self, space: ParamSpace, value: T) { let (_, limit) = self.limits(space); match space { TypeSpace => { self.type_limit += 1; self.self_limit += 1; } SelfSpace => { self.self_limit += 1; } FnSpace => {} } self.content.insert(limit, value); } pub fn pop(&mut self, space: ParamSpace) -> Option<T> { let (start, limit) = self.limits(space); if start == limit { None } else { match space { TypeSpace => { self.type_limit -= 1; self.self_limit -= 1; } SelfSpace => { self.self_limit -= 1; } FnSpace => {} } self.content.remove(limit - 1) } } pub fn truncate(&mut self, space: ParamSpace, len: uint) { // FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n). while self.len(space) > len { self.pop(space); } } pub fn replace(&mut self, space: ParamSpace, elems: Vec<T>) { // FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n). self.truncate(space, 0); for t in elems.into_iter() { self.push(space, t); } } pub fn get_self<'a>(&'a self) -> Option<&'a T> { let v = self.get_slice(SelfSpace); assert!(v.len() <= 1); if v.len() == 0 { None } else { Some(&v[0]) } } pub fn len(&self, space: ParamSpace) -> uint { self.get_slice(space).len() } pub fn is_empty_in(&self, space: ParamSpace) -> bool { self.len(space) == 0 } pub fn
<'a>(&'a self, space: ParamSpace) -> &'a [T] { let (start, limit) = self.limits(space); self.content.slice(start, limit) } pub fn get_mut_slice<'a>(&'a mut self, space: ParamSpace) -> &'a mut [T] { let (start, limit) = self.limits(space); self.content.slice_mut(start, limit) } pub fn opt_get<'a>(&'a self, space: ParamSpace, index: uint) -> Option<&'a T> { let v = self.get_slice(space); if index < v.len() { Some(&v[index]) } else { None } } pub fn get<'a>(&'a self, space: ParamSpace, index: uint) -> &'a T { &self.get_slice(space)[index] } pub fn iter<'a>(&'a self) -> Items<'a,T> { self.content.iter() } pub fn as_slice(&self) -> &[T] { self.content.as_slice() } pub fn all_vecs(&self, pred: |&[T]| -> bool) -> bool { let spaces = [TypeSpace, SelfSpace, FnSpace]; spaces.iter().all(|&space| { pred(self.get_slice(space)) }) } pub fn all(&self, pred: |&T| -> bool) -> bool { self.iter().all(pred) } pub fn any(&self, pred: |&T| -> bool) -> bool { self.iter().any(pred) } pub fn is_empty(&self) -> bool { self.all_vecs(|v| v.is_empty()) } pub fn map<U>(&self, pred: |&T| -> U) -> VecPerParamSpace<U> { let result = self.iter().map(pred).collect(); VecPerParamSpace::new_internal(result, self.type_limit, self.self_limit) } pub fn map_move<U>(self, pred: |T| -> U) -> VecPerParamSpace<U> { let (t, s, f) = self.split(); VecPerParamSpace::new(t.into_iter().map(|p| pred(p)).collect(), s.into_iter().map(|p| pred(p)).collect(), f.into_iter().map(|p| pred(p)).collect()) } pub fn split(self) -> (Vec<T>, Vec<T>, Vec<T>) { // FIXME (#15418): this does two traversals when in principle // one would suffice. i.e. change to use `move_iter`. let VecPerParamSpace { type_limit, self_limit, content } = self; let mut i = 0; let (prefix, fn_vec) = content.partition(|_| { let on_left = i < self_limit; i += 1; on_left }); let mut i = 0; let (type_vec, self_vec) = prefix.partition(|_| { let on_left = i < type_limit; i += 1; on_left }); (type_vec, self_vec, fn_vec) } pub fn with_vec(mut self, space: ParamSpace, vec: Vec<T>) -> VecPerParamSpace<T> { assert!(self.is_empty_in(space)); self.replace(space, vec); self } } /////////////////////////////////////////////////////////////////////////// // Public trait `Subst` // // Just call `foo.subst(tcx, substs)` to perform a substitution across // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when // there is more information available (for better errors). pub trait Subst { fn subst(&self, tcx: &ty::ctxt, substs: &Substs) -> Self { self.subst_spanned(tcx, substs, None) } fn subst_spanned(&self, tcx: &ty::ctxt, substs: &Substs, span: Option<Span>) -> Self; } impl<T:TypeFoldable> Subst for T { fn subst_spanned(&self, tcx: &ty::ctxt, substs: &Substs, span: Option<Span>) -> T { let mut folder = SubstFolder { tcx: tcx, substs: substs, span: span, root_ty: None, ty_stack_depth: 0 }; (*self).fold_with(&mut folder) } } /////////////////////////////////////////////////////////////////////////// // The actual substitution engine itself is a type folder. struct SubstFolder<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx>, substs: &'a Substs, // The location for which the substitution is performed, if available. span: Option<Span>, // The root type that is being substituted, if available. root_ty: Option<ty::t>, // Depth of type stack ty_stack_depth: uint, } impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> { fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.tcx } fn fold_region(&mut self, r: ty::Region) -> ty::Region { // Note: This routine only handles regions that are bound on // type declarations and other outer declarations, not those // bound in *fn types*. Region substitution of the bound // regions that appear in a function signature is done using // the specialized routine // `middle::typeck::check::regionmanip::replace_late_regions_in_fn_sig()`. match r { ty::ReEarlyBound(_, space, i, region_name) => { match self.substs.regions { ErasedRegions => ty::ReStatic, NonerasedRegions(ref regions) => match regions.opt_get(space, i) { Some(t) => *t, None => { let span = self.span.unwrap_or(DUMMY_SP); self.tcx().sess.span_bug( span, format!("Type parameter out of range \ when substituting in region {} (root type={}) \ (space={}, index={})", region_name.as_str(), self.root_ty.repr(self.tcx()), space, i).as_slice()); } } } } _ => r } } fn fold_ty(&mut self, t: ty::t) -> ty::t { if!ty::type_needs_subst(t) { return t; } // track the root type we were asked to substitute let depth = self.ty_stack_depth; if depth == 0 { self.root_ty = Some(t); } self.ty_stack_depth += 1; let t1 = match ty::get(t).sty { ty::ty_param(p
get_slice
identifier_name
subst.rs
<T> for (T, T, T) { fn len(&self) -> uint { 3 } fn as_slice<'a>(&'a self) -> &'a [T] { unsafe { let ptr: *const T = mem::transmute(self); let slice = raw::Slice { data: ptr, len: 3 }; mem::transmute(slice) } } fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] { unsafe { let ptr: *const T = mem::transmute(self); let slice = raw::Slice { data: ptr, len: 3 }; mem::transmute(slice) } } fn iter<'a>(&'a self) -> Items<'a, T> { let slice: &'a [T] = self.as_slice(); slice.iter() } fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> { self.as_mut_slice().iter_mut() } fn get<'a>(&'a self, index: uint) -> Option<&'a T> { self.as_slice().get(index) } fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut T> { Some(&mut self.as_mut_slice()[index]) // wrong: fallible } } /////////////////////////////////////////////////////////////////////////// /** * A substitution mapping type/region parameters to new values. We * identify each in-scope parameter by an *index* and a *parameter * space* (which indices where the parameter is defined; see * `ParamSpace`). */ #[deriving(Clone, PartialEq, Eq, Hash, Show)] pub struct Substs { pub types: VecPerParamSpace<ty::t>, pub regions: RegionSubsts, } /** * Represents the values to use when substituting lifetime parameters. * If the value is `ErasedRegions`, then this subst is occurring during * trans, and all region parameters will be replaced with `ty::ReStatic`. */ #[deriving(Clone, PartialEq, Eq, Hash, Show)] pub enum RegionSubsts { ErasedRegions, NonerasedRegions(VecPerParamSpace<ty::Region>) } impl Substs { pub fn new(t: VecPerParamSpace<ty::t>, r: VecPerParamSpace<ty::Region>) -> Substs { Substs { types: t, regions: NonerasedRegions(r) } } pub fn new_type(t: Vec<ty::t>, r: Vec<ty::Region>) -> Substs { Substs::new(VecPerParamSpace::new(t, Vec::new(), Vec::new()), VecPerParamSpace::new(r, Vec::new(), Vec::new())) } pub fn new_trait(t: Vec<ty::t>, r: Vec<ty::Region>, s: ty::t) -> Substs { Substs::new(VecPerParamSpace::new(t, vec!(s), Vec::new()), VecPerParamSpace::new(r, Vec::new(), Vec::new())) } pub fn erased(t: VecPerParamSpace<ty::t>) -> Substs { Substs { types: t, regions: ErasedRegions } } pub fn empty() -> Substs { Substs { types: VecPerParamSpace::empty(), regions: NonerasedRegions(VecPerParamSpace::empty()), } } pub fn trans_empty() -> Substs { Substs { types: VecPerParamSpace::empty(), regions: ErasedRegions } } pub fn is_noop(&self) -> bool { let regions_is_noop = match self.regions { ErasedRegions => false, // may be used to canonicalize NonerasedRegions(ref regions) => regions.is_empty(), }; regions_is_noop && self.types.is_empty() } pub fn self_ty(&self) -> Option<ty::t> { self.types.get_self().map(|&t| t) } pub fn with_self_ty(&self, self_ty: ty::t) -> Substs { assert!(self.self_ty().is_none()); let mut s = (*self).clone(); s.types.push(SelfSpace, self_ty); s } pub fn erase_regions(self) -> Substs { let Substs { types: types, regions: _ } = self; Substs { types: types, regions: ErasedRegions } } pub fn regions<'a>(&'a self) -> &'a VecPerParamSpace<ty::Region> { /*! * Since ErasedRegions are only to be used in trans, most of * the compiler can use this method to easily access the set * of region substitutions. */ match self.regions { ErasedRegions => fail!("Erased regions only expected in trans"), NonerasedRegions(ref r) => r } } pub fn mut_regions<'a>(&'a mut self) -> &'a mut VecPerParamSpace<ty::Region> { /*! * Since ErasedRegions are only to be used in trans, most of * the compiler can use this method to easily access the set * of region substitutions. */ match self.regions { ErasedRegions => fail!("Erased regions only expected in trans"), NonerasedRegions(ref mut r) => r } } pub fn with_method(self, m_types: Vec<ty::t>, m_regions: Vec<ty::Region>) -> Substs { let Substs { types, regions } = self; let types = types.with_vec(FnSpace, m_types); let regions = regions.map(m_regions, |r, m_regions| r.with_vec(FnSpace, m_regions)); Substs { types: types, regions: regions } } } impl RegionSubsts { fn map<A>(self, a: A, op: |VecPerParamSpace<ty::Region>, A| -> VecPerParamSpace<ty::Region>) -> RegionSubsts { match self { ErasedRegions => ErasedRegions, NonerasedRegions(r) => NonerasedRegions(op(r, a)) } } } /////////////////////////////////////////////////////////////////////////// // ParamSpace #[deriving(PartialOrd, Ord, PartialEq, Eq, Clone, Hash, Encodable, Decodable, Show)] pub enum ParamSpace { TypeSpace, // Type parameters attached to a type definition, trait, or impl SelfSpace, // Self parameter on a trait FnSpace, // Type parameters attached to a method or fn } impl ParamSpace { pub fn all() -> [ParamSpace,..3] { [TypeSpace, SelfSpace, FnSpace] } pub fn to_uint(self) -> uint { match self { TypeSpace => 0, SelfSpace => 1, FnSpace => 2, } } pub fn from_uint(u: uint) -> ParamSpace { match u { 0 => TypeSpace, 1 => SelfSpace, 2 => FnSpace, _ => fail!("Invalid ParamSpace: {}", u) } } } /** * Vector of things sorted by param space. Used to keep * the set of things declared on the type, self, or method * distinct. */ #[deriving(PartialEq, Eq, Clone, Hash, Encodable, Decodable)] pub struct VecPerParamSpace<T> { // This was originally represented as a tuple with one Vec<T> for // each variant of ParamSpace, and that remains the abstraction // that it provides to its clients. // // Here is how the representation corresponds to the abstraction // i.e. the "abstraction function" AF: // // AF(self) = (self.content.slice_to(self.type_limit), // self.content.slice(self.type_limit, self.self_limit), // self.content.slice_from(self.self_limit)) type_limit: uint, self_limit: uint, content: Vec<T>, } impl<T:fmt::Show> fmt::Show for VecPerParamSpace<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "VecPerParamSpace {{")); for space in ParamSpace::all().iter() { try!(write!(fmt, "{}: {}, ", *space, self.get_slice(*space))); } try!(write!(fmt, "}}")); Ok(()) } } impl<T> VecPerParamSpace<T> {
match space { TypeSpace => (0, self.type_limit), SelfSpace => (self.type_limit, self.self_limit), FnSpace => (self.self_limit, self.content.len()), } } pub fn empty() -> VecPerParamSpace<T> { VecPerParamSpace { type_limit: 0, self_limit: 0, content: Vec::new() } } pub fn params_from_type(types: Vec<T>) -> VecPerParamSpace<T> { VecPerParamSpace::empty().with_vec(TypeSpace, types) } /// `t` is the type space. /// `s` is the self space. /// `f` is the fn space. pub fn new(t: Vec<T>, s: Vec<T>, f: Vec<T>) -> VecPerParamSpace<T> { let type_limit = t.len(); let self_limit = t.len() + s.len(); let mut content = t; content.push_all_move(s); content.push_all_move(f); VecPerParamSpace { type_limit: type_limit, self_limit: self_limit, content: content, } } fn new_internal(content: Vec<T>, type_limit: uint, self_limit: uint) -> VecPerParamSpace<T> { VecPerParamSpace { type_limit: type_limit, self_limit: self_limit, content: content, } } /// Appends `value` to the vector associated with `space`. /// /// Unlike the `push` method in `Vec`, this should not be assumed /// to be a cheap operation (even when amortized over many calls). pub fn push(&mut self, space: ParamSpace, value: T) { let (_, limit) = self.limits(space); match space { TypeSpace => { self.type_limit += 1; self.self_limit += 1; } SelfSpace => { self.self_limit += 1; } FnSpace => {} } self.content.insert(limit, value); } pub fn pop(&mut self, space: ParamSpace) -> Option<T> { let (start, limit) = self.limits(space); if start == limit { None } else { match space { TypeSpace => { self.type_limit -= 1; self.self_limit -= 1; } SelfSpace => { self.self_limit -= 1; } FnSpace => {} } self.content.remove(limit - 1) } } pub fn truncate(&mut self, space: ParamSpace, len: uint) { // FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n). while self.len(space) > len { self.pop(space); } } pub fn replace(&mut self, space: ParamSpace, elems: Vec<T>) { // FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n). self.truncate(space, 0); for t in elems.into_iter() { self.push(space, t); } } pub fn get_self<'a>(&'a self) -> Option<&'a T> { let v = self.get_slice(SelfSpace); assert!(v.len() <= 1); if v.len() == 0 { None } else { Some(&v[0]) } } pub fn len(&self, space: ParamSpace) -> uint { self.get_slice(space).len() } pub fn is_empty_in(&self, space: ParamSpace) -> bool { self.len(space) == 0 } pub fn get_slice<'a>(&'a self, space: ParamSpace) -> &'a [T] { let (start, limit) = self.limits(space); self.content.slice(start, limit) } pub fn get_mut_slice<'a>(&'a mut self, space: ParamSpace) -> &'a mut [T] { let (start, limit) = self.limits(space); self.content.slice_mut(start, limit) } pub fn opt_get<'a>(&'a self, space: ParamSpace, index: uint) -> Option<&'a T> { let v = self.get_slice(space); if index < v.len() { Some(&v[index]) } else { None } } pub fn get<'a>(&'a self, space: ParamSpace, index: uint) -> &'a T { &self.get_slice(space)[index] } pub fn iter<'a>(&'a self) -> Items<'a,T> { self.content.iter() } pub fn as_slice(&self) -> &[T] { self.content.as_slice() } pub fn all_vecs(&self, pred: |&[T]| -> bool) -> bool { let spaces = [TypeSpace, SelfSpace, FnSpace]; spaces.iter().all(|&space| { pred(self.get_slice(space)) }) } pub fn all(&self, pred: |&T| -> bool) -> bool { self.iter().all(pred) } pub fn any(&self, pred: |&T| -> bool) -> bool { self.iter().any(pred) } pub fn is_empty(&self) -> bool { self.all_vecs(|v| v.is_empty()) } pub fn map<U>(&self, pred: |&T| -> U) -> VecPerParamSpace<U> { let result = self.iter().map(pred).collect(); VecPerParamSpace::new_internal(result, self.type_limit, self.self_limit) } pub fn map_move<U>(self, pred: |T| -> U) -> VecPerParamSpace<U> { let (t, s, f) = self.split(); VecPerParamSpace::new(t.into_iter().map(|p| pred(p)).collect(), s.into_iter().map(|p| pred(p)).collect(), f.into_iter().map(|p| pred(p)).collect()) } pub fn split(self) -> (Vec<T>, Vec<T>, Vec<T>) { // FIXME (#15418): this does two traversals when in principle // one would suffice. i.e. change to use `move_iter`. let VecPerParamSpace { type_limit, self_limit, content } = self; let mut i = 0; let (prefix, fn_vec) = content.partition(|_| { let on_left = i < self_limit; i += 1; on_left }); let mut i = 0; let (type_vec, self_vec) = prefix.partition(|_| { let on_left = i < type_limit; i += 1; on_left }); (type_vec, self_vec, fn_vec) } pub fn with_vec(mut self, space: ParamSpace, vec: Vec<T>) -> VecPerParamSpace<T> { assert!(self.is_empty_in(space)); self.replace(space, vec); self } } /////////////////////////////////////////////////////////////////////////// // Public trait `Subst` // // Just call `foo.subst(tcx, substs)` to perform a substitution across // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when // there is more information available (for better errors). pub trait Subst { fn subst(&self, tcx: &ty::ctxt, substs: &Substs) -> Self { self.subst_spanned(tcx, substs, None) } fn subst_spanned(&self, tcx: &ty::ctxt, substs: &Substs, span: Option<Span>) -> Self; } impl<T:TypeFoldable> Subst for T { fn subst_spanned(&self, tcx: &ty::ctxt, substs: &Substs, span: Option<Span>) -> T { let mut folder = SubstFolder { tcx: tcx, substs: substs, span: span, root_ty: None, ty_stack_depth: 0 }; (*self).fold_with(&mut folder) } } /////////////////////////////////////////////////////////////////////////// // The actual substitution engine itself is a type folder. struct SubstFolder<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx>, substs: &'a Substs, // The location for which the substitution is performed, if available. span: Option<Span>, // The root type that is being substituted, if available. root_ty: Option<ty::t>, // Depth of type stack ty_stack_depth: uint, } impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> { fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.tcx } fn fold_region(&mut self, r: ty::Region) -> ty::Region { // Note: This routine only handles regions that are bound on // type declarations and other outer declarations, not those // bound in *fn types*. Region substitution of the bound // regions that appear in a function signature is done using // the specialized routine // `middle::typeck::check::regionmanip::replace_late_regions_in_fn_sig()`. match r { ty::ReEarlyBound(_, space, i, region_name) => { match self.substs.regions { ErasedRegions => ty::ReStatic, NonerasedRegions(ref regions) => match regions.opt_get(space, i) { Some(t) => *t, None => { let span = self.span.unwrap_or(DUMMY_SP); self.tcx().sess.span_bug( span, format!("Type parameter out of range \ when substituting in region {} (root type={}) \ (space={}, index={})", region_name.as_str(), self.root_ty.repr(self.tcx()), space, i).as_slice()); } } } } _ => r } } fn fold_ty(&mut self, t: ty::t) -> ty::t { if!ty::type_needs_subst(t) { return t; } // track the root type we were asked to substitute let depth = self.ty_stack_depth; if depth == 0 { self.root_ty = Some(t); } self.ty_stack_depth += 1; let t1 = match ty::get(t).sty { ty::ty_param(p)
fn limits(&self, space: ParamSpace) -> (uint, uint) {
random_line_split
subst.rs
> for (T, T, T) { fn len(&self) -> uint { 3 } fn as_slice<'a>(&'a self) -> &'a [T] { unsafe { let ptr: *const T = mem::transmute(self); let slice = raw::Slice { data: ptr, len: 3 }; mem::transmute(slice) } } fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] { unsafe { let ptr: *const T = mem::transmute(self); let slice = raw::Slice { data: ptr, len: 3 }; mem::transmute(slice) } } fn iter<'a>(&'a self) -> Items<'a, T> { let slice: &'a [T] = self.as_slice(); slice.iter() } fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> { self.as_mut_slice().iter_mut() } fn get<'a>(&'a self, index: uint) -> Option<&'a T> { self.as_slice().get(index) } fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut T> { Some(&mut self.as_mut_slice()[index]) // wrong: fallible } } /////////////////////////////////////////////////////////////////////////// /** * A substitution mapping type/region parameters to new values. We * identify each in-scope parameter by an *index* and a *parameter * space* (which indices where the parameter is defined; see * `ParamSpace`). */ #[deriving(Clone, PartialEq, Eq, Hash, Show)] pub struct Substs { pub types: VecPerParamSpace<ty::t>, pub regions: RegionSubsts, } /** * Represents the values to use when substituting lifetime parameters. * If the value is `ErasedRegions`, then this subst is occurring during * trans, and all region parameters will be replaced with `ty::ReStatic`. */ #[deriving(Clone, PartialEq, Eq, Hash, Show)] pub enum RegionSubsts { ErasedRegions, NonerasedRegions(VecPerParamSpace<ty::Region>) } impl Substs { pub fn new(t: VecPerParamSpace<ty::t>, r: VecPerParamSpace<ty::Region>) -> Substs { Substs { types: t, regions: NonerasedRegions(r) } } pub fn new_type(t: Vec<ty::t>, r: Vec<ty::Region>) -> Substs { Substs::new(VecPerParamSpace::new(t, Vec::new(), Vec::new()), VecPerParamSpace::new(r, Vec::new(), Vec::new())) } pub fn new_trait(t: Vec<ty::t>, r: Vec<ty::Region>, s: ty::t) -> Substs { Substs::new(VecPerParamSpace::new(t, vec!(s), Vec::new()), VecPerParamSpace::new(r, Vec::new(), Vec::new())) } pub fn erased(t: VecPerParamSpace<ty::t>) -> Substs { Substs { types: t, regions: ErasedRegions } } pub fn empty() -> Substs { Substs { types: VecPerParamSpace::empty(), regions: NonerasedRegions(VecPerParamSpace::empty()), } } pub fn trans_empty() -> Substs { Substs { types: VecPerParamSpace::empty(), regions: ErasedRegions } } pub fn is_noop(&self) -> bool { let regions_is_noop = match self.regions { ErasedRegions => false, // may be used to canonicalize NonerasedRegions(ref regions) => regions.is_empty(), }; regions_is_noop && self.types.is_empty() } pub fn self_ty(&self) -> Option<ty::t> { self.types.get_self().map(|&t| t) } pub fn with_self_ty(&self, self_ty: ty::t) -> Substs { assert!(self.self_ty().is_none()); let mut s = (*self).clone(); s.types.push(SelfSpace, self_ty); s } pub fn erase_regions(self) -> Substs { let Substs { types: types, regions: _ } = self; Substs { types: types, regions: ErasedRegions } } pub fn regions<'a>(&'a self) -> &'a VecPerParamSpace<ty::Region> { /*! * Since ErasedRegions are only to be used in trans, most of * the compiler can use this method to easily access the set * of region substitutions. */ match self.regions { ErasedRegions => fail!("Erased regions only expected in trans"), NonerasedRegions(ref r) => r } } pub fn mut_regions<'a>(&'a mut self) -> &'a mut VecPerParamSpace<ty::Region> { /*! * Since ErasedRegions are only to be used in trans, most of * the compiler can use this method to easily access the set * of region substitutions. */ match self.regions { ErasedRegions => fail!("Erased regions only expected in trans"), NonerasedRegions(ref mut r) => r } } pub fn with_method(self, m_types: Vec<ty::t>, m_regions: Vec<ty::Region>) -> Substs { let Substs { types, regions } = self; let types = types.with_vec(FnSpace, m_types); let regions = regions.map(m_regions, |r, m_regions| r.with_vec(FnSpace, m_regions)); Substs { types: types, regions: regions } } } impl RegionSubsts { fn map<A>(self, a: A, op: |VecPerParamSpace<ty::Region>, A| -> VecPerParamSpace<ty::Region>) -> RegionSubsts { match self { ErasedRegions => ErasedRegions, NonerasedRegions(r) => NonerasedRegions(op(r, a)) } } } /////////////////////////////////////////////////////////////////////////// // ParamSpace #[deriving(PartialOrd, Ord, PartialEq, Eq, Clone, Hash, Encodable, Decodable, Show)] pub enum ParamSpace { TypeSpace, // Type parameters attached to a type definition, trait, or impl SelfSpace, // Self parameter on a trait FnSpace, // Type parameters attached to a method or fn } impl ParamSpace { pub fn all() -> [ParamSpace,..3] { [TypeSpace, SelfSpace, FnSpace] } pub fn to_uint(self) -> uint { match self { TypeSpace => 0, SelfSpace => 1, FnSpace => 2, } } pub fn from_uint(u: uint) -> ParamSpace { match u { 0 => TypeSpace, 1 => SelfSpace, 2 => FnSpace, _ => fail!("Invalid ParamSpace: {}", u) } } } /** * Vector of things sorted by param space. Used to keep * the set of things declared on the type, self, or method * distinct. */ #[deriving(PartialEq, Eq, Clone, Hash, Encodable, Decodable)] pub struct VecPerParamSpace<T> { // This was originally represented as a tuple with one Vec<T> for // each variant of ParamSpace, and that remains the abstraction // that it provides to its clients. // // Here is how the representation corresponds to the abstraction // i.e. the "abstraction function" AF: // // AF(self) = (self.content.slice_to(self.type_limit), // self.content.slice(self.type_limit, self.self_limit), // self.content.slice_from(self.self_limit)) type_limit: uint, self_limit: uint, content: Vec<T>, } impl<T:fmt::Show> fmt::Show for VecPerParamSpace<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "VecPerParamSpace {{")); for space in ParamSpace::all().iter() { try!(write!(fmt, "{}: {}, ", *space, self.get_slice(*space))); } try!(write!(fmt, "}}")); Ok(()) } } impl<T> VecPerParamSpace<T> { fn limits(&self, space: ParamSpace) -> (uint, uint) { match space { TypeSpace => (0, self.type_limit), SelfSpace => (self.type_limit, self.self_limit), FnSpace => (self.self_limit, self.content.len()), } } pub fn empty() -> VecPerParamSpace<T> { VecPerParamSpace { type_limit: 0, self_limit: 0, content: Vec::new() } } pub fn params_from_type(types: Vec<T>) -> VecPerParamSpace<T> { VecPerParamSpace::empty().with_vec(TypeSpace, types) } /// `t` is the type space. /// `s` is the self space. /// `f` is the fn space. pub fn new(t: Vec<T>, s: Vec<T>, f: Vec<T>) -> VecPerParamSpace<T> { let type_limit = t.len(); let self_limit = t.len() + s.len(); let mut content = t; content.push_all_move(s); content.push_all_move(f); VecPerParamSpace { type_limit: type_limit, self_limit: self_limit, content: content, } } fn new_internal(content: Vec<T>, type_limit: uint, self_limit: uint) -> VecPerParamSpace<T> { VecPerParamSpace { type_limit: type_limit, self_limit: self_limit, content: content, } } /// Appends `value` to the vector associated with `space`. /// /// Unlike the `push` method in `Vec`, this should not be assumed /// to be a cheap operation (even when amortized over many calls). pub fn push(&mut self, space: ParamSpace, value: T) { let (_, limit) = self.limits(space); match space { TypeSpace => { self.type_limit += 1; self.self_limit += 1; } SelfSpace => { self.self_limit += 1; } FnSpace => {} } self.content.insert(limit, value); } pub fn pop(&mut self, space: ParamSpace) -> Option<T> { let (start, limit) = self.limits(space); if start == limit { None } else { match space { TypeSpace => { self.type_limit -= 1; self.self_limit -= 1; } SelfSpace => { self.self_limit -= 1; } FnSpace => {} } self.content.remove(limit - 1) } } pub fn truncate(&mut self, space: ParamSpace, len: uint)
pub fn replace(&mut self, space: ParamSpace, elems: Vec<T>) { // FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n). self.truncate(space, 0); for t in elems.into_iter() { self.push(space, t); } } pub fn get_self<'a>(&'a self) -> Option<&'a T> { let v = self.get_slice(SelfSpace); assert!(v.len() <= 1); if v.len() == 0 { None } else { Some(&v[0]) } } pub fn len(&self, space: ParamSpace) -> uint { self.get_slice(space).len() } pub fn is_empty_in(&self, space: ParamSpace) -> bool { self.len(space) == 0 } pub fn get_slice<'a>(&'a self, space: ParamSpace) -> &'a [T] { let (start, limit) = self.limits(space); self.content.slice(start, limit) } pub fn get_mut_slice<'a>(&'a mut self, space: ParamSpace) -> &'a mut [T] { let (start, limit) = self.limits(space); self.content.slice_mut(start, limit) } pub fn opt_get<'a>(&'a self, space: ParamSpace, index: uint) -> Option<&'a T> { let v = self.get_slice(space); if index < v.len() { Some(&v[index]) } else { None } } pub fn get<'a>(&'a self, space: ParamSpace, index: uint) -> &'a T { &self.get_slice(space)[index] } pub fn iter<'a>(&'a self) -> Items<'a,T> { self.content.iter() } pub fn as_slice(&self) -> &[T] { self.content.as_slice() } pub fn all_vecs(&self, pred: |&[T]| -> bool) -> bool { let spaces = [TypeSpace, SelfSpace, FnSpace]; spaces.iter().all(|&space| { pred(self.get_slice(space)) }) } pub fn all(&self, pred: |&T| -> bool) -> bool { self.iter().all(pred) } pub fn any(&self, pred: |&T| -> bool) -> bool { self.iter().any(pred) } pub fn is_empty(&self) -> bool { self.all_vecs(|v| v.is_empty()) } pub fn map<U>(&self, pred: |&T| -> U) -> VecPerParamSpace<U> { let result = self.iter().map(pred).collect(); VecPerParamSpace::new_internal(result, self.type_limit, self.self_limit) } pub fn map_move<U>(self, pred: |T| -> U) -> VecPerParamSpace<U> { let (t, s, f) = self.split(); VecPerParamSpace::new(t.into_iter().map(|p| pred(p)).collect(), s.into_iter().map(|p| pred(p)).collect(), f.into_iter().map(|p| pred(p)).collect()) } pub fn split(self) -> (Vec<T>, Vec<T>, Vec<T>) { // FIXME (#15418): this does two traversals when in principle // one would suffice. i.e. change to use `move_iter`. let VecPerParamSpace { type_limit, self_limit, content } = self; let mut i = 0; let (prefix, fn_vec) = content.partition(|_| { let on_left = i < self_limit; i += 1; on_left }); let mut i = 0; let (type_vec, self_vec) = prefix.partition(|_| { let on_left = i < type_limit; i += 1; on_left }); (type_vec, self_vec, fn_vec) } pub fn with_vec(mut self, space: ParamSpace, vec: Vec<T>) -> VecPerParamSpace<T> { assert!(self.is_empty_in(space)); self.replace(space, vec); self } } /////////////////////////////////////////////////////////////////////////// // Public trait `Subst` // // Just call `foo.subst(tcx, substs)` to perform a substitution across // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when // there is more information available (for better errors). pub trait Subst { fn subst(&self, tcx: &ty::ctxt, substs: &Substs) -> Self { self.subst_spanned(tcx, substs, None) } fn subst_spanned(&self, tcx: &ty::ctxt, substs: &Substs, span: Option<Span>) -> Self; } impl<T:TypeFoldable> Subst for T { fn subst_spanned(&self, tcx: &ty::ctxt, substs: &Substs, span: Option<Span>) -> T { let mut folder = SubstFolder { tcx: tcx, substs: substs, span: span, root_ty: None, ty_stack_depth: 0 }; (*self).fold_with(&mut folder) } } /////////////////////////////////////////////////////////////////////////// // The actual substitution engine itself is a type folder. struct SubstFolder<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx>, substs: &'a Substs, // The location for which the substitution is performed, if available. span: Option<Span>, // The root type that is being substituted, if available. root_ty: Option<ty::t>, // Depth of type stack ty_stack_depth: uint, } impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> { fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.tcx } fn fold_region(&mut self, r: ty::Region) -> ty::Region { // Note: This routine only handles regions that are bound on // type declarations and other outer declarations, not those // bound in *fn types*. Region substitution of the bound // regions that appear in a function signature is done using // the specialized routine // `middle::typeck::check::regionmanip::replace_late_regions_in_fn_sig()`. match r { ty::ReEarlyBound(_, space, i, region_name) => { match self.substs.regions { ErasedRegions => ty::ReStatic, NonerasedRegions(ref regions) => match regions.opt_get(space, i) { Some(t) => *t, None => { let span = self.span.unwrap_or(DUMMY_SP); self.tcx().sess.span_bug( span, format!("Type parameter out of range \ when substituting in region {} (root type={}) \ (space={}, index={})", region_name.as_str(), self.root_ty.repr(self.tcx()), space, i).as_slice()); } } } } _ => r } } fn fold_ty(&mut self, t: ty::t) -> ty::t { if!ty::type_needs_subst(t) { return t; } // track the root type we were asked to substitute let depth = self.ty_stack_depth; if depth == 0 { self.root_ty = Some(t); } self.ty_stack_depth += 1; let t1 = match ty::get(t).sty { ty::ty_param(p
{ // FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n). while self.len(space) > len { self.pop(space); } }
identifier_body
associated-types-normalize-in-bounds.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
// Test that we normalize associated types that appear in bounds; if // we didn't, the call to `self.split2()` fails to type check. // pretty-expanded FIXME #23616 use std::marker::PhantomData; struct Splits<'a, T, P>(PhantomData<(&'a(),T,P)>); struct SplitsN<I>(PhantomData<I>); trait SliceExt2 { type Item; fn split2<'a, P>(&'a self, pred: P) -> Splits<'a, Self::Item, P> where P: FnMut(&Self::Item) -> bool; fn splitn2<'a, P>(&'a self, n: usize, pred: P) -> SplitsN<Splits<'a, Self::Item, P>> where P: FnMut(&Self::Item) -> bool; } impl<T> SliceExt2 for [T] { type Item = T; fn split2<P>(&self, pred: P) -> Splits<T, P> where P: FnMut(&T) -> bool { loop {} } fn splitn2<P>(&self, n: usize, pred: P) -> SplitsN<Splits<T, P>> where P: FnMut(&T) -> bool { self.split2(pred); loop {} } } fn main() { }
// 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
associated-types-normalize-in-bounds.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 that we normalize associated types that appear in bounds; if // we didn't, the call to `self.split2()` fails to type check. // pretty-expanded FIXME #23616 use std::marker::PhantomData; struct Splits<'a, T, P>(PhantomData<(&'a(),T,P)>); struct SplitsN<I>(PhantomData<I>); trait SliceExt2 { type Item; fn split2<'a, P>(&'a self, pred: P) -> Splits<'a, Self::Item, P> where P: FnMut(&Self::Item) -> bool; fn splitn2<'a, P>(&'a self, n: usize, pred: P) -> SplitsN<Splits<'a, Self::Item, P>> where P: FnMut(&Self::Item) -> bool; } impl<T> SliceExt2 for [T] { type Item = T; fn split2<P>(&self, pred: P) -> Splits<T, P> where P: FnMut(&T) -> bool { loop {} } fn splitn2<P>(&self, n: usize, pred: P) -> SplitsN<Splits<T, P>> where P: FnMut(&T) -> bool { self.split2(pred); loop {} } } fn
() { }
main
identifier_name
lib.rs
#![forbid(missing_docs, warnings)] #![deny(deprecated, improper_ctypes, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] #![warn(trivial_casts, trivial_numeric_casts, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results, variant_size_differences)] extern crate ntru; extern crate sha1; extern crate rand; use rand::Rng; use ntru::encparams::{EncParams, ALL_PARAM_SETS}; use ntru::rand::{RNG_DEFAULT, RNG_CTR_DRBG}; use ntru::types::{IntPoly, TernPoly, PrivateKey, PublicKey, KeyPair}; fn encrypt_poly(m: IntPoly, r: &TernPoly, h: &IntPoly, q: u16) -> IntPoly { let (mut res, _) = h.mult_tern(r, q); res = res + m; res.mod_mask(q - 1); res } fn decrypt_poly(e: IntPoly, private: &PrivateKey, modulus: u16) -> IntPoly { let (mut d, _) = if private.get_t().is_product() { e.mult_prod(private.get_t().get_poly_prod(), modulus - 1) } else { e.mult_tern(private.get_t().get_poly_tern(), modulus - 1) }; d.mod_mask(modulus - 1); d.mult_fac(3); d = d + e; d.mod_center(modulus); d.mod3(); for i in 0..d.get_coeffs().len() { if d.get_coeffs()[i] == 2 { d.set_coeff(i, -1) } } d } fn gen_key_pair(seed: &str, params: &EncParams) -> KeyPair { let seed_u8 = seed.as_bytes(); let rng = RNG_CTR_DRBG; let rand_ctx = ntru::rand::init_det(&rng, seed_u8).unwrap(); ntru::generate_key_pair(params, &rand_ctx).unwrap() } fn sha1(input: &[u8]) -> [u8; 20] { let mut hasher = sha1::Sha1::new(); hasher.update(input); hasher.digest().bytes() } #[test] fn it_keygen() { let param_arr = &ALL_PARAM_SETS; for params in param_arr { let rand_ctx = ntru::rand::init(&RNG_DEFAULT).unwrap(); let mut kp = ntru::generate_key_pair(params, &rand_ctx).unwrap(); // Encrypt a random message let m = TernPoly::rand( params.get_n(), params.get_n() / 3, params.get_n() / 3, &rand_ctx, ).unwrap(); let m_int = m.to_int_poly(); let r = TernPoly::rand( params.get_n(), params.get_n() / 3, params.get_n() / 3, &rand_ctx, ).unwrap(); let e = encrypt_poly(m_int.clone(), &r, kp.get_public().get_h(), params.get_q()); // Decrypt and verify let c = decrypt_poly(e, kp.get_private(), params.get_q()); assert_eq!(m_int, c); // Test deterministic key generation kp = gen_key_pair("my test password", params); let rng = RNG_CTR_DRBG; let rand_ctx2 = ntru::rand::init_det(&rng, b"my test password").unwrap(); let kp2 = ntru::generate_key_pair(params, &rand_ctx2).unwrap(); assert_eq!(kp, kp2); } } // Tests ntru_encrypt() with a non-deterministic RNG fn test_encr_decr_nondet(params: &EncParams) { let rng = RNG_DEFAULT; let rand_ctx = ntru::rand::init(&rng).unwrap(); let kp = ntru::generate_key_pair(params, &rand_ctx).unwrap(); // Randomly choose the number of public keys for testing ntru::generate_multiple_key_pairs and // ntru::generate_public let num_pub_keys: usize = rand::thread_rng().gen_range(1, 10); // Create a key pair with multiple public keys (using ntru_gen_key_pair_multi) let (priv_multi1, pub_multi1) = ntru::generate_multiple_key_pairs(params, &rand_ctx, num_pub_keys).unwrap(); // Create a key pair with multiple public keys (using ntru::generate_public) let kp_multi2 = ntru::generate_key_pair(params, &rand_ctx).unwrap(); let mut pub_multi2 = Vec::with_capacity(num_pub_keys); for _ in 0..num_pub_keys { pub_multi2.push( ntru::generate_public(params, kp_multi2.get_private(), &rand_ctx).unwrap(), ); } let max_len = params.max_msg_len(); let plain = ntru::rand::generate(u16::from(max_len), &rand_ctx).unwrap(); for plain_len in 0..max_len + 1 { // Test single public key let encrypted = ntru::encrypt( &plain[..plain_len as usize], kp.get_public(), params, &rand_ctx, ).unwrap(); let decrypted = ntru::decrypt(&encrypted, &kp, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i as usize], decrypted[i as usize]); } // Test multiple public keys for (i, pub_key) in pub_multi1.into_iter().enumerate() { let rand_value = rand::thread_rng().gen_range(1, 100); if rand_value % 100!= 0 { continue; } // Test priv_multi1/pub_multi1 let encrypted = ntru::encrypt(&plain[0..plain_len as usize], pub_key, params, &rand_ctx).unwrap(); let kp_decrypt1 = KeyPair::new(priv_multi1.clone(), pub_key.clone()); let decrypted = ntru::decrypt(&encrypted, &kp_decrypt1, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i as usize], decrypted[i as usize]); } // Test kp_multi2 + pub_multi2 let public = if i == 0 { kp_multi2.get_public() } else
; let encrypted = ntru::encrypt(&plain[0..plain_len as usize], public, params, &rand_ctx) .unwrap(); let kp_decrypt2 = KeyPair::new(kp_multi2.get_private().clone(), public.clone()); let decrypted = ntru::decrypt(&encrypted, &kp_decrypt2, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i as usize], decrypted[i as usize]); } } } } // Tests ntru_encrypt() with a deterministic RNG fn test_encr_decr_det(params: &EncParams, digest_expected: &[u8]) { let kp = gen_key_pair("seed value for key generation", params); let pub_arr = kp.get_public().export(params); let pub2 = PublicKey::import(&pub_arr); assert_eq!(kp.get_public().get_h(), pub2.get_h()); let max_len = params.max_msg_len(); let rng_plaintext = RNG_CTR_DRBG; let plain_seed = b"seed value for plaintext"; let rand_ctx_plaintext = ntru::rand::init_det(&rng_plaintext, plain_seed).unwrap(); let plain = ntru::rand::generate(u16::from(max_len), &rand_ctx_plaintext).unwrap(); let plain2 = plain.clone(); let seed = b"seed value"; let seed2 = b"seed value"; let rng = RNG_CTR_DRBG; let rand_ctx = ntru::rand::init_det(&rng, seed).unwrap(); let rng2 = RNG_CTR_DRBG; let rand_ctx2 = ntru::rand::init_det(&rng2, seed2).unwrap(); for plain_len in 0..max_len as usize { let encrypted = ntru::encrypt(&plain[0..plain_len], kp.get_public(), params, &rand_ctx) .unwrap(); let encrypted2 = ntru::encrypt(&plain2[0..plain_len], &pub2, params, &rand_ctx2).unwrap(); for (i, c) in encrypted.iter().enumerate() { assert_eq!(*c, encrypted2[i]); } let decrypted = ntru::decrypt(&encrypted, &kp, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i], decrypted[i]); } } let encrypted = ntru::encrypt(&plain, kp.get_public(), params, &rand_ctx).unwrap(); let digest = sha1(&encrypted); assert_eq!(digest, digest_expected); } #[test] fn it_encr_decr() { let param_arr = ALL_PARAM_SETS; // SHA-1 digests of deterministic ciphertexts, one set for big-endian environments and one for // little-endian ones. If/when the CTR_DRBG implementation is made endian independent, only one // set of digests will be needed here. let digests_expected: [[u8; 20]; 18] = // EES401EP1 [[0xdf, 0xad, 0xcd, 0x25, 0x01, 0x9f, 0x3d, 0xb1, 0x06, 0x5f, 0x15, 0xbe, 0x8f, 0x69, 0xfd, 0x23, 0x88, 0x88, 0x2a, 0xc8], // EES449EP1 [0xc3, 0x8b, 0x8d, 0xdc, 0xfd, 0xef, 0xf8, 0x1b, 0xa6, 0x57, 0xeb, 0x66, 0x49, 0xe8, 0xe9, 0x4d, 0x70, 0xab, 0xce, 0x02], // EES677EP1 [0xfd, 0xa8, 0xb1, 0xdb, 0x96, 0xc4, 0x3a, 0xeb, 0x0c, 0x07, 0xef, 0xf7, 0xc0, 0xf4, 0x73, 0x59, 0x6e, 0xd9, 0x97, 0xb7], // EES1087EP2 [0xe7, 0x53, 0xd6, 0x89, 0xc6, 0x06, 0x3d, 0xf1, 0x12, 0xf1, 0xeb, 0x8b, 0xd8, 0x7c, 0x26, 0x67, 0xc9, 0xe5, 0x4a, 0x0e], // EES541EP1 [0x7a, 0x5d, 0x41, 0x88, 0x70, 0xef, 0x4f, 0xf3, 0xdf, 0xb9, 0xa8, 0x76, 0x00, 0x00, 0x6d, 0x65, 0x61, 0xe0, 0xce, 0x44], // EES613EP1 [0x69, 0x7b, 0x0a, 0x4f, 0xd6, 0x41, 0x04, 0x3f, 0x91, 0xe9, 0xb0, 0xa9, 0x42, 0xfe, 0x66, 0x4e, 0xcc, 0x4e, 0xbb, 0xd7], // EES887EP1 [0xac, 0x3a, 0x51, 0xd6, 0xaf, 0x6c, 0x38, 0xa8, 0x67, 0xde, 0xc8, 0xfe, 0xf7, 0xaf, 0x4a, 0x28, 0x6e, 0x30, 0xad, 0x98], // EES1171EP1 [0x5f, 0x34, 0x5f, 0xf7, 0x32, 0x13, 0x06, 0x55, 0x6b, 0xb7, 0x02, 0x7d, 0xb3, 0x16, 0xef, 0x84, 0x09, 0xe9, 0xa0, 0xff], // EES659EP1 [0x2e, 0x35, 0xd4, 0xa6, 0x99, 0xb8, 0x5e, 0x06, 0x47, 0x61, 0x68, 0x20, 0x26, 0xb0, 0x17, 0xa9, 0xc6, 0x37, 0xb7, 0x8e], // EES761EP1 [0x15, 0xde, 0x51, 0xbb, 0xc0, 0xe0, 0x39, 0xf2, 0xb6, 0x0e, 0x98, 0xa7, 0xae, 0x10, 0xbf, 0xfd, 0x02, 0xcc, 0x76, 0x43], // EES1087EP1 [0x29, 0xac, 0x2d, 0x21, 0x29, 0x79, 0x98, 0x89, 0x1c, 0xa0, 0x6c, 0xed, 0x7d, 0x68, 0x29, 0x9b, 0xb4, 0x9f, 0xe4, 0xd0], // EES1499EP1 [0x2f, 0xf9, 0x32, 0x25, 0xbc, 0xd5, 0xad, 0xc4, 0x4b, 0x19, 0xca, 0xe6, 0x52, 0x89, 0x2e, 0x29, 0x38, 0x5a, 0x61, 0xd7], // EES401EP2 [0xaf, 0x39, 0x02, 0xd5, 0xaa, 0xab, 0x29, 0xaa, 0x01, 0x99, 0xd1, 0xf4, 0x0f, 0x02, 0x35, 0x58, 0x71, 0x58, 0xdb, 0xdb], // EES439EP1 [0xa3, 0xd6, 0x5f, 0x7d, 0x5d, 0x66, 0x49, 0x1e, 0x15, 0xbc, 0xba, 0xf0, 0xfa, 0x07, 0x9d, 0xd3, 0x33, 0xf5, 0x9f, 0x37], // EES443EP1 [0xac, 0xea, 0xa3, 0xc8, 0x05, 0x8b, 0x23, 0x68, 0xaa, 0x9a, 0x3c, 0x9b, 0xdb, 0x7f, 0xbe, 0x7b, 0x49, 0x03, 0x94, 0xc8], // EES593EP1 [0x49, 0xfb, 0x90, 0x33, 0xaf, 0x12, 0xc7, 0x29, 0x17, 0x47, 0xf2, 0x09, 0xb9, 0xc3, 0x5d, 0xf4, 0x21, 0x5a, 0xbf, 0x98], // EES587EP1 [0x69, 0xa8, 0x36, 0x3d, 0xe1, 0xec, 0x9e, 0x89, 0xa1, 0x0a, 0xa5, 0xb7, 0x35, 0xbe, 0x5b, 0x75, 0xb6, 0xd8, 0xe1, 0x9a], // EES743EP1 [0x93, 0xfe, 0x81, 0xd5, 0x79, 0x2e, 0x34, 0xd8, 0xe3, 0x1f, 0xe5, 0x03, 0xb9, 0x06, 0xdc, 0x4f, 0x28, 0xb9, 0xaf, 0x37]]; for (i, param) in param_arr.iter().enumerate() { test_encr_decr_nondet(param); test_encr_decr_det(param, &digests_expected[i]); } }
{ &pub_multi2[i - 1] }
conditional_block
lib.rs
#![forbid(missing_docs, warnings)] #![deny(deprecated, improper_ctypes, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] #![warn(trivial_casts, trivial_numeric_casts, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results, variant_size_differences)] extern crate ntru; extern crate sha1; extern crate rand; use rand::Rng; use ntru::encparams::{EncParams, ALL_PARAM_SETS}; use ntru::rand::{RNG_DEFAULT, RNG_CTR_DRBG}; use ntru::types::{IntPoly, TernPoly, PrivateKey, PublicKey, KeyPair}; fn encrypt_poly(m: IntPoly, r: &TernPoly, h: &IntPoly, q: u16) -> IntPoly { let (mut res, _) = h.mult_tern(r, q); res = res + m; res.mod_mask(q - 1); res } fn decrypt_poly(e: IntPoly, private: &PrivateKey, modulus: u16) -> IntPoly { let (mut d, _) = if private.get_t().is_product() { e.mult_prod(private.get_t().get_poly_prod(), modulus - 1) } else { e.mult_tern(private.get_t().get_poly_tern(), modulus - 1) }; d.mod_mask(modulus - 1); d.mult_fac(3); d = d + e; d.mod_center(modulus); d.mod3(); for i in 0..d.get_coeffs().len() { if d.get_coeffs()[i] == 2 { d.set_coeff(i, -1) } } d } fn gen_key_pair(seed: &str, params: &EncParams) -> KeyPair { let seed_u8 = seed.as_bytes(); let rng = RNG_CTR_DRBG; let rand_ctx = ntru::rand::init_det(&rng, seed_u8).unwrap(); ntru::generate_key_pair(params, &rand_ctx).unwrap() } fn sha1(input: &[u8]) -> [u8; 20] { let mut hasher = sha1::Sha1::new(); hasher.update(input); hasher.digest().bytes() } #[test] fn it_keygen() { let param_arr = &ALL_PARAM_SETS; for params in param_arr { let rand_ctx = ntru::rand::init(&RNG_DEFAULT).unwrap(); let mut kp = ntru::generate_key_pair(params, &rand_ctx).unwrap(); // Encrypt a random message let m = TernPoly::rand( params.get_n(), params.get_n() / 3, params.get_n() / 3, &rand_ctx, ).unwrap(); let m_int = m.to_int_poly(); let r = TernPoly::rand( params.get_n(), params.get_n() / 3, params.get_n() / 3, &rand_ctx, ).unwrap(); let e = encrypt_poly(m_int.clone(), &r, kp.get_public().get_h(), params.get_q()); // Decrypt and verify let c = decrypt_poly(e, kp.get_private(), params.get_q()); assert_eq!(m_int, c); // Test deterministic key generation kp = gen_key_pair("my test password", params); let rng = RNG_CTR_DRBG; let rand_ctx2 = ntru::rand::init_det(&rng, b"my test password").unwrap(); let kp2 = ntru::generate_key_pair(params, &rand_ctx2).unwrap(); assert_eq!(kp, kp2); } } // Tests ntru_encrypt() with a non-deterministic RNG fn test_encr_decr_nondet(params: &EncParams) { let rng = RNG_DEFAULT; let rand_ctx = ntru::rand::init(&rng).unwrap(); let kp = ntru::generate_key_pair(params, &rand_ctx).unwrap(); // Randomly choose the number of public keys for testing ntru::generate_multiple_key_pairs and // ntru::generate_public let num_pub_keys: usize = rand::thread_rng().gen_range(1, 10); // Create a key pair with multiple public keys (using ntru_gen_key_pair_multi) let (priv_multi1, pub_multi1) = ntru::generate_multiple_key_pairs(params, &rand_ctx, num_pub_keys).unwrap(); // Create a key pair with multiple public keys (using ntru::generate_public) let kp_multi2 = ntru::generate_key_pair(params, &rand_ctx).unwrap(); let mut pub_multi2 = Vec::with_capacity(num_pub_keys); for _ in 0..num_pub_keys { pub_multi2.push( ntru::generate_public(params, kp_multi2.get_private(), &rand_ctx).unwrap(), ); } let max_len = params.max_msg_len(); let plain = ntru::rand::generate(u16::from(max_len), &rand_ctx).unwrap(); for plain_len in 0..max_len + 1 { // Test single public key let encrypted = ntru::encrypt( &plain[..plain_len as usize], kp.get_public(), params, &rand_ctx, ).unwrap(); let decrypted = ntru::decrypt(&encrypted, &kp, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i as usize], decrypted[i as usize]); } // Test multiple public keys for (i, pub_key) in pub_multi1.into_iter().enumerate() { let rand_value = rand::thread_rng().gen_range(1, 100); if rand_value % 100!= 0 { continue; } // Test priv_multi1/pub_multi1 let encrypted = ntru::encrypt(&plain[0..plain_len as usize], pub_key, params, &rand_ctx).unwrap(); let kp_decrypt1 = KeyPair::new(priv_multi1.clone(), pub_key.clone()); let decrypted = ntru::decrypt(&encrypted, &kp_decrypt1, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i as usize], decrypted[i as usize]); } // Test kp_multi2 + pub_multi2 let public = if i == 0 { kp_multi2.get_public() } else { &pub_multi2[i - 1] }; let encrypted = ntru::encrypt(&plain[0..plain_len as usize], public, params, &rand_ctx) .unwrap(); let kp_decrypt2 = KeyPair::new(kp_multi2.get_private().clone(), public.clone()); let decrypted = ntru::decrypt(&encrypted, &kp_decrypt2, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i as usize], decrypted[i as usize]); } } } } // Tests ntru_encrypt() with a deterministic RNG fn test_encr_decr_det(params: &EncParams, digest_expected: &[u8]) { let kp = gen_key_pair("seed value for key generation", params); let pub_arr = kp.get_public().export(params); let pub2 = PublicKey::import(&pub_arr); assert_eq!(kp.get_public().get_h(), pub2.get_h()); let max_len = params.max_msg_len(); let rng_plaintext = RNG_CTR_DRBG; let plain_seed = b"seed value for plaintext"; let rand_ctx_plaintext = ntru::rand::init_det(&rng_plaintext, plain_seed).unwrap();
let seed2 = b"seed value"; let rng = RNG_CTR_DRBG; let rand_ctx = ntru::rand::init_det(&rng, seed).unwrap(); let rng2 = RNG_CTR_DRBG; let rand_ctx2 = ntru::rand::init_det(&rng2, seed2).unwrap(); for plain_len in 0..max_len as usize { let encrypted = ntru::encrypt(&plain[0..plain_len], kp.get_public(), params, &rand_ctx) .unwrap(); let encrypted2 = ntru::encrypt(&plain2[0..plain_len], &pub2, params, &rand_ctx2).unwrap(); for (i, c) in encrypted.iter().enumerate() { assert_eq!(*c, encrypted2[i]); } let decrypted = ntru::decrypt(&encrypted, &kp, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i], decrypted[i]); } } let encrypted = ntru::encrypt(&plain, kp.get_public(), params, &rand_ctx).unwrap(); let digest = sha1(&encrypted); assert_eq!(digest, digest_expected); } #[test] fn it_encr_decr() { let param_arr = ALL_PARAM_SETS; // SHA-1 digests of deterministic ciphertexts, one set for big-endian environments and one for // little-endian ones. If/when the CTR_DRBG implementation is made endian independent, only one // set of digests will be needed here. let digests_expected: [[u8; 20]; 18] = // EES401EP1 [[0xdf, 0xad, 0xcd, 0x25, 0x01, 0x9f, 0x3d, 0xb1, 0x06, 0x5f, 0x15, 0xbe, 0x8f, 0x69, 0xfd, 0x23, 0x88, 0x88, 0x2a, 0xc8], // EES449EP1 [0xc3, 0x8b, 0x8d, 0xdc, 0xfd, 0xef, 0xf8, 0x1b, 0xa6, 0x57, 0xeb, 0x66, 0x49, 0xe8, 0xe9, 0x4d, 0x70, 0xab, 0xce, 0x02], // EES677EP1 [0xfd, 0xa8, 0xb1, 0xdb, 0x96, 0xc4, 0x3a, 0xeb, 0x0c, 0x07, 0xef, 0xf7, 0xc0, 0xf4, 0x73, 0x59, 0x6e, 0xd9, 0x97, 0xb7], // EES1087EP2 [0xe7, 0x53, 0xd6, 0x89, 0xc6, 0x06, 0x3d, 0xf1, 0x12, 0xf1, 0xeb, 0x8b, 0xd8, 0x7c, 0x26, 0x67, 0xc9, 0xe5, 0x4a, 0x0e], // EES541EP1 [0x7a, 0x5d, 0x41, 0x88, 0x70, 0xef, 0x4f, 0xf3, 0xdf, 0xb9, 0xa8, 0x76, 0x00, 0x00, 0x6d, 0x65, 0x61, 0xe0, 0xce, 0x44], // EES613EP1 [0x69, 0x7b, 0x0a, 0x4f, 0xd6, 0x41, 0x04, 0x3f, 0x91, 0xe9, 0xb0, 0xa9, 0x42, 0xfe, 0x66, 0x4e, 0xcc, 0x4e, 0xbb, 0xd7], // EES887EP1 [0xac, 0x3a, 0x51, 0xd6, 0xaf, 0x6c, 0x38, 0xa8, 0x67, 0xde, 0xc8, 0xfe, 0xf7, 0xaf, 0x4a, 0x28, 0x6e, 0x30, 0xad, 0x98], // EES1171EP1 [0x5f, 0x34, 0x5f, 0xf7, 0x32, 0x13, 0x06, 0x55, 0x6b, 0xb7, 0x02, 0x7d, 0xb3, 0x16, 0xef, 0x84, 0x09, 0xe9, 0xa0, 0xff], // EES659EP1 [0x2e, 0x35, 0xd4, 0xa6, 0x99, 0xb8, 0x5e, 0x06, 0x47, 0x61, 0x68, 0x20, 0x26, 0xb0, 0x17, 0xa9, 0xc6, 0x37, 0xb7, 0x8e], // EES761EP1 [0x15, 0xde, 0x51, 0xbb, 0xc0, 0xe0, 0x39, 0xf2, 0xb6, 0x0e, 0x98, 0xa7, 0xae, 0x10, 0xbf, 0xfd, 0x02, 0xcc, 0x76, 0x43], // EES1087EP1 [0x29, 0xac, 0x2d, 0x21, 0x29, 0x79, 0x98, 0x89, 0x1c, 0xa0, 0x6c, 0xed, 0x7d, 0x68, 0x29, 0x9b, 0xb4, 0x9f, 0xe4, 0xd0], // EES1499EP1 [0x2f, 0xf9, 0x32, 0x25, 0xbc, 0xd5, 0xad, 0xc4, 0x4b, 0x19, 0xca, 0xe6, 0x52, 0x89, 0x2e, 0x29, 0x38, 0x5a, 0x61, 0xd7], // EES401EP2 [0xaf, 0x39, 0x02, 0xd5, 0xaa, 0xab, 0x29, 0xaa, 0x01, 0x99, 0xd1, 0xf4, 0x0f, 0x02, 0x35, 0x58, 0x71, 0x58, 0xdb, 0xdb], // EES439EP1 [0xa3, 0xd6, 0x5f, 0x7d, 0x5d, 0x66, 0x49, 0x1e, 0x15, 0xbc, 0xba, 0xf0, 0xfa, 0x07, 0x9d, 0xd3, 0x33, 0xf5, 0x9f, 0x37], // EES443EP1 [0xac, 0xea, 0xa3, 0xc8, 0x05, 0x8b, 0x23, 0x68, 0xaa, 0x9a, 0x3c, 0x9b, 0xdb, 0x7f, 0xbe, 0x7b, 0x49, 0x03, 0x94, 0xc8], // EES593EP1 [0x49, 0xfb, 0x90, 0x33, 0xaf, 0x12, 0xc7, 0x29, 0x17, 0x47, 0xf2, 0x09, 0xb9, 0xc3, 0x5d, 0xf4, 0x21, 0x5a, 0xbf, 0x98], // EES587EP1 [0x69, 0xa8, 0x36, 0x3d, 0xe1, 0xec, 0x9e, 0x89, 0xa1, 0x0a, 0xa5, 0xb7, 0x35, 0xbe, 0x5b, 0x75, 0xb6, 0xd8, 0xe1, 0x9a], // EES743EP1 [0x93, 0xfe, 0x81, 0xd5, 0x79, 0x2e, 0x34, 0xd8, 0xe3, 0x1f, 0xe5, 0x03, 0xb9, 0x06, 0xdc, 0x4f, 0x28, 0xb9, 0xaf, 0x37]]; for (i, param) in param_arr.iter().enumerate() { test_encr_decr_nondet(param); test_encr_decr_det(param, &digests_expected[i]); } }
let plain = ntru::rand::generate(u16::from(max_len), &rand_ctx_plaintext).unwrap(); let plain2 = plain.clone(); let seed = b"seed value";
random_line_split
lib.rs
#![forbid(missing_docs, warnings)] #![deny(deprecated, improper_ctypes, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] #![warn(trivial_casts, trivial_numeric_casts, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results, variant_size_differences)] extern crate ntru; extern crate sha1; extern crate rand; use rand::Rng; use ntru::encparams::{EncParams, ALL_PARAM_SETS}; use ntru::rand::{RNG_DEFAULT, RNG_CTR_DRBG}; use ntru::types::{IntPoly, TernPoly, PrivateKey, PublicKey, KeyPair}; fn encrypt_poly(m: IntPoly, r: &TernPoly, h: &IntPoly, q: u16) -> IntPoly { let (mut res, _) = h.mult_tern(r, q); res = res + m; res.mod_mask(q - 1); res } fn decrypt_poly(e: IntPoly, private: &PrivateKey, modulus: u16) -> IntPoly
fn gen_key_pair(seed: &str, params: &EncParams) -> KeyPair { let seed_u8 = seed.as_bytes(); let rng = RNG_CTR_DRBG; let rand_ctx = ntru::rand::init_det(&rng, seed_u8).unwrap(); ntru::generate_key_pair(params, &rand_ctx).unwrap() } fn sha1(input: &[u8]) -> [u8; 20] { let mut hasher = sha1::Sha1::new(); hasher.update(input); hasher.digest().bytes() } #[test] fn it_keygen() { let param_arr = &ALL_PARAM_SETS; for params in param_arr { let rand_ctx = ntru::rand::init(&RNG_DEFAULT).unwrap(); let mut kp = ntru::generate_key_pair(params, &rand_ctx).unwrap(); // Encrypt a random message let m = TernPoly::rand( params.get_n(), params.get_n() / 3, params.get_n() / 3, &rand_ctx, ).unwrap(); let m_int = m.to_int_poly(); let r = TernPoly::rand( params.get_n(), params.get_n() / 3, params.get_n() / 3, &rand_ctx, ).unwrap(); let e = encrypt_poly(m_int.clone(), &r, kp.get_public().get_h(), params.get_q()); // Decrypt and verify let c = decrypt_poly(e, kp.get_private(), params.get_q()); assert_eq!(m_int, c); // Test deterministic key generation kp = gen_key_pair("my test password", params); let rng = RNG_CTR_DRBG; let rand_ctx2 = ntru::rand::init_det(&rng, b"my test password").unwrap(); let kp2 = ntru::generate_key_pair(params, &rand_ctx2).unwrap(); assert_eq!(kp, kp2); } } // Tests ntru_encrypt() with a non-deterministic RNG fn test_encr_decr_nondet(params: &EncParams) { let rng = RNG_DEFAULT; let rand_ctx = ntru::rand::init(&rng).unwrap(); let kp = ntru::generate_key_pair(params, &rand_ctx).unwrap(); // Randomly choose the number of public keys for testing ntru::generate_multiple_key_pairs and // ntru::generate_public let num_pub_keys: usize = rand::thread_rng().gen_range(1, 10); // Create a key pair with multiple public keys (using ntru_gen_key_pair_multi) let (priv_multi1, pub_multi1) = ntru::generate_multiple_key_pairs(params, &rand_ctx, num_pub_keys).unwrap(); // Create a key pair with multiple public keys (using ntru::generate_public) let kp_multi2 = ntru::generate_key_pair(params, &rand_ctx).unwrap(); let mut pub_multi2 = Vec::with_capacity(num_pub_keys); for _ in 0..num_pub_keys { pub_multi2.push( ntru::generate_public(params, kp_multi2.get_private(), &rand_ctx).unwrap(), ); } let max_len = params.max_msg_len(); let plain = ntru::rand::generate(u16::from(max_len), &rand_ctx).unwrap(); for plain_len in 0..max_len + 1 { // Test single public key let encrypted = ntru::encrypt( &plain[..plain_len as usize], kp.get_public(), params, &rand_ctx, ).unwrap(); let decrypted = ntru::decrypt(&encrypted, &kp, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i as usize], decrypted[i as usize]); } // Test multiple public keys for (i, pub_key) in pub_multi1.into_iter().enumerate() { let rand_value = rand::thread_rng().gen_range(1, 100); if rand_value % 100!= 0 { continue; } // Test priv_multi1/pub_multi1 let encrypted = ntru::encrypt(&plain[0..plain_len as usize], pub_key, params, &rand_ctx).unwrap(); let kp_decrypt1 = KeyPair::new(priv_multi1.clone(), pub_key.clone()); let decrypted = ntru::decrypt(&encrypted, &kp_decrypt1, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i as usize], decrypted[i as usize]); } // Test kp_multi2 + pub_multi2 let public = if i == 0 { kp_multi2.get_public() } else { &pub_multi2[i - 1] }; let encrypted = ntru::encrypt(&plain[0..plain_len as usize], public, params, &rand_ctx) .unwrap(); let kp_decrypt2 = KeyPair::new(kp_multi2.get_private().clone(), public.clone()); let decrypted = ntru::decrypt(&encrypted, &kp_decrypt2, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i as usize], decrypted[i as usize]); } } } } // Tests ntru_encrypt() with a deterministic RNG fn test_encr_decr_det(params: &EncParams, digest_expected: &[u8]) { let kp = gen_key_pair("seed value for key generation", params); let pub_arr = kp.get_public().export(params); let pub2 = PublicKey::import(&pub_arr); assert_eq!(kp.get_public().get_h(), pub2.get_h()); let max_len = params.max_msg_len(); let rng_plaintext = RNG_CTR_DRBG; let plain_seed = b"seed value for plaintext"; let rand_ctx_plaintext = ntru::rand::init_det(&rng_plaintext, plain_seed).unwrap(); let plain = ntru::rand::generate(u16::from(max_len), &rand_ctx_plaintext).unwrap(); let plain2 = plain.clone(); let seed = b"seed value"; let seed2 = b"seed value"; let rng = RNG_CTR_DRBG; let rand_ctx = ntru::rand::init_det(&rng, seed).unwrap(); let rng2 = RNG_CTR_DRBG; let rand_ctx2 = ntru::rand::init_det(&rng2, seed2).unwrap(); for plain_len in 0..max_len as usize { let encrypted = ntru::encrypt(&plain[0..plain_len], kp.get_public(), params, &rand_ctx) .unwrap(); let encrypted2 = ntru::encrypt(&plain2[0..plain_len], &pub2, params, &rand_ctx2).unwrap(); for (i, c) in encrypted.iter().enumerate() { assert_eq!(*c, encrypted2[i]); } let decrypted = ntru::decrypt(&encrypted, &kp, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i], decrypted[i]); } } let encrypted = ntru::encrypt(&plain, kp.get_public(), params, &rand_ctx).unwrap(); let digest = sha1(&encrypted); assert_eq!(digest, digest_expected); } #[test] fn it_encr_decr() { let param_arr = ALL_PARAM_SETS; // SHA-1 digests of deterministic ciphertexts, one set for big-endian environments and one for // little-endian ones. If/when the CTR_DRBG implementation is made endian independent, only one // set of digests will be needed here. let digests_expected: [[u8; 20]; 18] = // EES401EP1 [[0xdf, 0xad, 0xcd, 0x25, 0x01, 0x9f, 0x3d, 0xb1, 0x06, 0x5f, 0x15, 0xbe, 0x8f, 0x69, 0xfd, 0x23, 0x88, 0x88, 0x2a, 0xc8], // EES449EP1 [0xc3, 0x8b, 0x8d, 0xdc, 0xfd, 0xef, 0xf8, 0x1b, 0xa6, 0x57, 0xeb, 0x66, 0x49, 0xe8, 0xe9, 0x4d, 0x70, 0xab, 0xce, 0x02], // EES677EP1 [0xfd, 0xa8, 0xb1, 0xdb, 0x96, 0xc4, 0x3a, 0xeb, 0x0c, 0x07, 0xef, 0xf7, 0xc0, 0xf4, 0x73, 0x59, 0x6e, 0xd9, 0x97, 0xb7], // EES1087EP2 [0xe7, 0x53, 0xd6, 0x89, 0xc6, 0x06, 0x3d, 0xf1, 0x12, 0xf1, 0xeb, 0x8b, 0xd8, 0x7c, 0x26, 0x67, 0xc9, 0xe5, 0x4a, 0x0e], // EES541EP1 [0x7a, 0x5d, 0x41, 0x88, 0x70, 0xef, 0x4f, 0xf3, 0xdf, 0xb9, 0xa8, 0x76, 0x00, 0x00, 0x6d, 0x65, 0x61, 0xe0, 0xce, 0x44], // EES613EP1 [0x69, 0x7b, 0x0a, 0x4f, 0xd6, 0x41, 0x04, 0x3f, 0x91, 0xe9, 0xb0, 0xa9, 0x42, 0xfe, 0x66, 0x4e, 0xcc, 0x4e, 0xbb, 0xd7], // EES887EP1 [0xac, 0x3a, 0x51, 0xd6, 0xaf, 0x6c, 0x38, 0xa8, 0x67, 0xde, 0xc8, 0xfe, 0xf7, 0xaf, 0x4a, 0x28, 0x6e, 0x30, 0xad, 0x98], // EES1171EP1 [0x5f, 0x34, 0x5f, 0xf7, 0x32, 0x13, 0x06, 0x55, 0x6b, 0xb7, 0x02, 0x7d, 0xb3, 0x16, 0xef, 0x84, 0x09, 0xe9, 0xa0, 0xff], // EES659EP1 [0x2e, 0x35, 0xd4, 0xa6, 0x99, 0xb8, 0x5e, 0x06, 0x47, 0x61, 0x68, 0x20, 0x26, 0xb0, 0x17, 0xa9, 0xc6, 0x37, 0xb7, 0x8e], // EES761EP1 [0x15, 0xde, 0x51, 0xbb, 0xc0, 0xe0, 0x39, 0xf2, 0xb6, 0x0e, 0x98, 0xa7, 0xae, 0x10, 0xbf, 0xfd, 0x02, 0xcc, 0x76, 0x43], // EES1087EP1 [0x29, 0xac, 0x2d, 0x21, 0x29, 0x79, 0x98, 0x89, 0x1c, 0xa0, 0x6c, 0xed, 0x7d, 0x68, 0x29, 0x9b, 0xb4, 0x9f, 0xe4, 0xd0], // EES1499EP1 [0x2f, 0xf9, 0x32, 0x25, 0xbc, 0xd5, 0xad, 0xc4, 0x4b, 0x19, 0xca, 0xe6, 0x52, 0x89, 0x2e, 0x29, 0x38, 0x5a, 0x61, 0xd7], // EES401EP2 [0xaf, 0x39, 0x02, 0xd5, 0xaa, 0xab, 0x29, 0xaa, 0x01, 0x99, 0xd1, 0xf4, 0x0f, 0x02, 0x35, 0x58, 0x71, 0x58, 0xdb, 0xdb], // EES439EP1 [0xa3, 0xd6, 0x5f, 0x7d, 0x5d, 0x66, 0x49, 0x1e, 0x15, 0xbc, 0xba, 0xf0, 0xfa, 0x07, 0x9d, 0xd3, 0x33, 0xf5, 0x9f, 0x37], // EES443EP1 [0xac, 0xea, 0xa3, 0xc8, 0x05, 0x8b, 0x23, 0x68, 0xaa, 0x9a, 0x3c, 0x9b, 0xdb, 0x7f, 0xbe, 0x7b, 0x49, 0x03, 0x94, 0xc8], // EES593EP1 [0x49, 0xfb, 0x90, 0x33, 0xaf, 0x12, 0xc7, 0x29, 0x17, 0x47, 0xf2, 0x09, 0xb9, 0xc3, 0x5d, 0xf4, 0x21, 0x5a, 0xbf, 0x98], // EES587EP1 [0x69, 0xa8, 0x36, 0x3d, 0xe1, 0xec, 0x9e, 0x89, 0xa1, 0x0a, 0xa5, 0xb7, 0x35, 0xbe, 0x5b, 0x75, 0xb6, 0xd8, 0xe1, 0x9a], // EES743EP1 [0x93, 0xfe, 0x81, 0xd5, 0x79, 0x2e, 0x34, 0xd8, 0xe3, 0x1f, 0xe5, 0x03, 0xb9, 0x06, 0xdc, 0x4f, 0x28, 0xb9, 0xaf, 0x37]]; for (i, param) in param_arr.iter().enumerate() { test_encr_decr_nondet(param); test_encr_decr_det(param, &digests_expected[i]); } }
{ let (mut d, _) = if private.get_t().is_product() { e.mult_prod(private.get_t().get_poly_prod(), modulus - 1) } else { e.mult_tern(private.get_t().get_poly_tern(), modulus - 1) }; d.mod_mask(modulus - 1); d.mult_fac(3); d = d + e; d.mod_center(modulus); d.mod3(); for i in 0..d.get_coeffs().len() { if d.get_coeffs()[i] == 2 { d.set_coeff(i, -1) } } d }
identifier_body
lib.rs
#![forbid(missing_docs, warnings)] #![deny(deprecated, improper_ctypes, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] #![warn(trivial_casts, trivial_numeric_casts, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results, variant_size_differences)] extern crate ntru; extern crate sha1; extern crate rand; use rand::Rng; use ntru::encparams::{EncParams, ALL_PARAM_SETS}; use ntru::rand::{RNG_DEFAULT, RNG_CTR_DRBG}; use ntru::types::{IntPoly, TernPoly, PrivateKey, PublicKey, KeyPair}; fn encrypt_poly(m: IntPoly, r: &TernPoly, h: &IntPoly, q: u16) -> IntPoly { let (mut res, _) = h.mult_tern(r, q); res = res + m; res.mod_mask(q - 1); res } fn decrypt_poly(e: IntPoly, private: &PrivateKey, modulus: u16) -> IntPoly { let (mut d, _) = if private.get_t().is_product() { e.mult_prod(private.get_t().get_poly_prod(), modulus - 1) } else { e.mult_tern(private.get_t().get_poly_tern(), modulus - 1) }; d.mod_mask(modulus - 1); d.mult_fac(3); d = d + e; d.mod_center(modulus); d.mod3(); for i in 0..d.get_coeffs().len() { if d.get_coeffs()[i] == 2 { d.set_coeff(i, -1) } } d } fn gen_key_pair(seed: &str, params: &EncParams) -> KeyPair { let seed_u8 = seed.as_bytes(); let rng = RNG_CTR_DRBG; let rand_ctx = ntru::rand::init_det(&rng, seed_u8).unwrap(); ntru::generate_key_pair(params, &rand_ctx).unwrap() } fn
(input: &[u8]) -> [u8; 20] { let mut hasher = sha1::Sha1::new(); hasher.update(input); hasher.digest().bytes() } #[test] fn it_keygen() { let param_arr = &ALL_PARAM_SETS; for params in param_arr { let rand_ctx = ntru::rand::init(&RNG_DEFAULT).unwrap(); let mut kp = ntru::generate_key_pair(params, &rand_ctx).unwrap(); // Encrypt a random message let m = TernPoly::rand( params.get_n(), params.get_n() / 3, params.get_n() / 3, &rand_ctx, ).unwrap(); let m_int = m.to_int_poly(); let r = TernPoly::rand( params.get_n(), params.get_n() / 3, params.get_n() / 3, &rand_ctx, ).unwrap(); let e = encrypt_poly(m_int.clone(), &r, kp.get_public().get_h(), params.get_q()); // Decrypt and verify let c = decrypt_poly(e, kp.get_private(), params.get_q()); assert_eq!(m_int, c); // Test deterministic key generation kp = gen_key_pair("my test password", params); let rng = RNG_CTR_DRBG; let rand_ctx2 = ntru::rand::init_det(&rng, b"my test password").unwrap(); let kp2 = ntru::generate_key_pair(params, &rand_ctx2).unwrap(); assert_eq!(kp, kp2); } } // Tests ntru_encrypt() with a non-deterministic RNG fn test_encr_decr_nondet(params: &EncParams) { let rng = RNG_DEFAULT; let rand_ctx = ntru::rand::init(&rng).unwrap(); let kp = ntru::generate_key_pair(params, &rand_ctx).unwrap(); // Randomly choose the number of public keys for testing ntru::generate_multiple_key_pairs and // ntru::generate_public let num_pub_keys: usize = rand::thread_rng().gen_range(1, 10); // Create a key pair with multiple public keys (using ntru_gen_key_pair_multi) let (priv_multi1, pub_multi1) = ntru::generate_multiple_key_pairs(params, &rand_ctx, num_pub_keys).unwrap(); // Create a key pair with multiple public keys (using ntru::generate_public) let kp_multi2 = ntru::generate_key_pair(params, &rand_ctx).unwrap(); let mut pub_multi2 = Vec::with_capacity(num_pub_keys); for _ in 0..num_pub_keys { pub_multi2.push( ntru::generate_public(params, kp_multi2.get_private(), &rand_ctx).unwrap(), ); } let max_len = params.max_msg_len(); let plain = ntru::rand::generate(u16::from(max_len), &rand_ctx).unwrap(); for plain_len in 0..max_len + 1 { // Test single public key let encrypted = ntru::encrypt( &plain[..plain_len as usize], kp.get_public(), params, &rand_ctx, ).unwrap(); let decrypted = ntru::decrypt(&encrypted, &kp, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i as usize], decrypted[i as usize]); } // Test multiple public keys for (i, pub_key) in pub_multi1.into_iter().enumerate() { let rand_value = rand::thread_rng().gen_range(1, 100); if rand_value % 100!= 0 { continue; } // Test priv_multi1/pub_multi1 let encrypted = ntru::encrypt(&plain[0..plain_len as usize], pub_key, params, &rand_ctx).unwrap(); let kp_decrypt1 = KeyPair::new(priv_multi1.clone(), pub_key.clone()); let decrypted = ntru::decrypt(&encrypted, &kp_decrypt1, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i as usize], decrypted[i as usize]); } // Test kp_multi2 + pub_multi2 let public = if i == 0 { kp_multi2.get_public() } else { &pub_multi2[i - 1] }; let encrypted = ntru::encrypt(&plain[0..plain_len as usize], public, params, &rand_ctx) .unwrap(); let kp_decrypt2 = KeyPair::new(kp_multi2.get_private().clone(), public.clone()); let decrypted = ntru::decrypt(&encrypted, &kp_decrypt2, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i as usize], decrypted[i as usize]); } } } } // Tests ntru_encrypt() with a deterministic RNG fn test_encr_decr_det(params: &EncParams, digest_expected: &[u8]) { let kp = gen_key_pair("seed value for key generation", params); let pub_arr = kp.get_public().export(params); let pub2 = PublicKey::import(&pub_arr); assert_eq!(kp.get_public().get_h(), pub2.get_h()); let max_len = params.max_msg_len(); let rng_plaintext = RNG_CTR_DRBG; let plain_seed = b"seed value for plaintext"; let rand_ctx_plaintext = ntru::rand::init_det(&rng_plaintext, plain_seed).unwrap(); let plain = ntru::rand::generate(u16::from(max_len), &rand_ctx_plaintext).unwrap(); let plain2 = plain.clone(); let seed = b"seed value"; let seed2 = b"seed value"; let rng = RNG_CTR_DRBG; let rand_ctx = ntru::rand::init_det(&rng, seed).unwrap(); let rng2 = RNG_CTR_DRBG; let rand_ctx2 = ntru::rand::init_det(&rng2, seed2).unwrap(); for plain_len in 0..max_len as usize { let encrypted = ntru::encrypt(&plain[0..plain_len], kp.get_public(), params, &rand_ctx) .unwrap(); let encrypted2 = ntru::encrypt(&plain2[0..plain_len], &pub2, params, &rand_ctx2).unwrap(); for (i, c) in encrypted.iter().enumerate() { assert_eq!(*c, encrypted2[i]); } let decrypted = ntru::decrypt(&encrypted, &kp, params).unwrap(); for i in 0..plain_len { assert_eq!(plain[i], decrypted[i]); } } let encrypted = ntru::encrypt(&plain, kp.get_public(), params, &rand_ctx).unwrap(); let digest = sha1(&encrypted); assert_eq!(digest, digest_expected); } #[test] fn it_encr_decr() { let param_arr = ALL_PARAM_SETS; // SHA-1 digests of deterministic ciphertexts, one set for big-endian environments and one for // little-endian ones. If/when the CTR_DRBG implementation is made endian independent, only one // set of digests will be needed here. let digests_expected: [[u8; 20]; 18] = // EES401EP1 [[0xdf, 0xad, 0xcd, 0x25, 0x01, 0x9f, 0x3d, 0xb1, 0x06, 0x5f, 0x15, 0xbe, 0x8f, 0x69, 0xfd, 0x23, 0x88, 0x88, 0x2a, 0xc8], // EES449EP1 [0xc3, 0x8b, 0x8d, 0xdc, 0xfd, 0xef, 0xf8, 0x1b, 0xa6, 0x57, 0xeb, 0x66, 0x49, 0xe8, 0xe9, 0x4d, 0x70, 0xab, 0xce, 0x02], // EES677EP1 [0xfd, 0xa8, 0xb1, 0xdb, 0x96, 0xc4, 0x3a, 0xeb, 0x0c, 0x07, 0xef, 0xf7, 0xc0, 0xf4, 0x73, 0x59, 0x6e, 0xd9, 0x97, 0xb7], // EES1087EP2 [0xe7, 0x53, 0xd6, 0x89, 0xc6, 0x06, 0x3d, 0xf1, 0x12, 0xf1, 0xeb, 0x8b, 0xd8, 0x7c, 0x26, 0x67, 0xc9, 0xe5, 0x4a, 0x0e], // EES541EP1 [0x7a, 0x5d, 0x41, 0x88, 0x70, 0xef, 0x4f, 0xf3, 0xdf, 0xb9, 0xa8, 0x76, 0x00, 0x00, 0x6d, 0x65, 0x61, 0xe0, 0xce, 0x44], // EES613EP1 [0x69, 0x7b, 0x0a, 0x4f, 0xd6, 0x41, 0x04, 0x3f, 0x91, 0xe9, 0xb0, 0xa9, 0x42, 0xfe, 0x66, 0x4e, 0xcc, 0x4e, 0xbb, 0xd7], // EES887EP1 [0xac, 0x3a, 0x51, 0xd6, 0xaf, 0x6c, 0x38, 0xa8, 0x67, 0xde, 0xc8, 0xfe, 0xf7, 0xaf, 0x4a, 0x28, 0x6e, 0x30, 0xad, 0x98], // EES1171EP1 [0x5f, 0x34, 0x5f, 0xf7, 0x32, 0x13, 0x06, 0x55, 0x6b, 0xb7, 0x02, 0x7d, 0xb3, 0x16, 0xef, 0x84, 0x09, 0xe9, 0xa0, 0xff], // EES659EP1 [0x2e, 0x35, 0xd4, 0xa6, 0x99, 0xb8, 0x5e, 0x06, 0x47, 0x61, 0x68, 0x20, 0x26, 0xb0, 0x17, 0xa9, 0xc6, 0x37, 0xb7, 0x8e], // EES761EP1 [0x15, 0xde, 0x51, 0xbb, 0xc0, 0xe0, 0x39, 0xf2, 0xb6, 0x0e, 0x98, 0xa7, 0xae, 0x10, 0xbf, 0xfd, 0x02, 0xcc, 0x76, 0x43], // EES1087EP1 [0x29, 0xac, 0x2d, 0x21, 0x29, 0x79, 0x98, 0x89, 0x1c, 0xa0, 0x6c, 0xed, 0x7d, 0x68, 0x29, 0x9b, 0xb4, 0x9f, 0xe4, 0xd0], // EES1499EP1 [0x2f, 0xf9, 0x32, 0x25, 0xbc, 0xd5, 0xad, 0xc4, 0x4b, 0x19, 0xca, 0xe6, 0x52, 0x89, 0x2e, 0x29, 0x38, 0x5a, 0x61, 0xd7], // EES401EP2 [0xaf, 0x39, 0x02, 0xd5, 0xaa, 0xab, 0x29, 0xaa, 0x01, 0x99, 0xd1, 0xf4, 0x0f, 0x02, 0x35, 0x58, 0x71, 0x58, 0xdb, 0xdb], // EES439EP1 [0xa3, 0xd6, 0x5f, 0x7d, 0x5d, 0x66, 0x49, 0x1e, 0x15, 0xbc, 0xba, 0xf0, 0xfa, 0x07, 0x9d, 0xd3, 0x33, 0xf5, 0x9f, 0x37], // EES443EP1 [0xac, 0xea, 0xa3, 0xc8, 0x05, 0x8b, 0x23, 0x68, 0xaa, 0x9a, 0x3c, 0x9b, 0xdb, 0x7f, 0xbe, 0x7b, 0x49, 0x03, 0x94, 0xc8], // EES593EP1 [0x49, 0xfb, 0x90, 0x33, 0xaf, 0x12, 0xc7, 0x29, 0x17, 0x47, 0xf2, 0x09, 0xb9, 0xc3, 0x5d, 0xf4, 0x21, 0x5a, 0xbf, 0x98], // EES587EP1 [0x69, 0xa8, 0x36, 0x3d, 0xe1, 0xec, 0x9e, 0x89, 0xa1, 0x0a, 0xa5, 0xb7, 0x35, 0xbe, 0x5b, 0x75, 0xb6, 0xd8, 0xe1, 0x9a], // EES743EP1 [0x93, 0xfe, 0x81, 0xd5, 0x79, 0x2e, 0x34, 0xd8, 0xe3, 0x1f, 0xe5, 0x03, 0xb9, 0x06, 0xdc, 0x4f, 0x28, 0xb9, 0xaf, 0x37]]; for (i, param) in param_arr.iter().enumerate() { test_encr_decr_nondet(param); test_encr_decr_det(param, &digests_expected[i]); } }
sha1
identifier_name
borrowed-unique-basic.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // Gdb doesn't know about UTF-32 character encoding and will print a rust char as only // its numerical value. // compile-flags:-g // gdb-command:rbreak zzz // gdb-command:run // gdb-command:finish // gdb-command:print *bool_ref // gdb-check:$1 = true // gdb-command:print *int_ref // gdb-check:$2 = -1 // gdb-command:print *char_ref // gdb-check:$3 = 97 // gdb-command:print/d *i8_ref // gdb-check:$4 = 68 // gdb-command:print *i16_ref // gdb-check:$5 = -16 // gdb-command:print *i32_ref // gdb-check:$6 = -32 // gdb-command:print *i64_ref // gdb-check:$7 = -64 // gdb-command:print *uint_ref // gdb-check:$8 = 1 // gdb-command:print/d *u8_ref // gdb-check:$9 = 100 // gdb-command:print *u16_ref // gdb-check:$10 = 16 // gdb-command:print *u32_ref // gdb-check:$11 = 32 // gdb-command:print *u64_ref // gdb-check:$12 = 64 // gdb-command:print *f32_ref // gdb-check:$13 = 2.5 // gdb-command:print *f64_ref // gdb-check:$14 = 3.5 #![allow(unused_variable)] fn main()
let i64_ref: &i64 = i64_box; let uint_box: Box<uint> = box 1; let uint_ref: &uint = uint_box; let u8_box: Box<u8> = box 100; let u8_ref: &u8 = u8_box; let u16_box: Box<u16> = box 16; let u16_ref: &u16 = u16_box; let u32_box: Box<u32> = box 32; let u32_ref: &u32 = u32_box; let u64_box: Box<u64> = box 64; let u64_ref: &u64 = u64_box; let f32_box: Box<f32> = box 2.5; let f32_ref: &f32 = f32_box; let f64_box: Box<f64> = box 3.5; let f64_ref: &f64 = f64_box; zzz(); } fn zzz() {()}
{ let bool_box: Box<bool> = box true; let bool_ref: &bool = bool_box; let int_box: Box<int> = box -1; let int_ref: &int = int_box; let char_box: Box<char> = box 'a'; let char_ref: &char = char_box; let i8_box: Box<i8> = box 68; let i8_ref: &i8 = i8_box; let i16_box: Box<i16> = box -16; let i16_ref: &i16 = i16_box; let i32_box: Box<i32> = box -32; let i32_ref: &i32 = i32_box; let i64_box: Box<i64> = box -64;
identifier_body
borrowed-unique-basic.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // Gdb doesn't know about UTF-32 character encoding and will print a rust char as only // its numerical value. // compile-flags:-g // gdb-command:rbreak zzz // gdb-command:run // gdb-command:finish // gdb-command:print *bool_ref // gdb-check:$1 = true // gdb-command:print *int_ref // gdb-check:$2 = -1 // gdb-command:print *char_ref // gdb-check:$3 = 97 // gdb-command:print/d *i8_ref // gdb-check:$4 = 68 // gdb-command:print *i16_ref // gdb-check:$5 = -16 // gdb-command:print *i32_ref // gdb-check:$6 = -32 // gdb-command:print *i64_ref // gdb-check:$7 = -64 // gdb-command:print *uint_ref // gdb-check:$8 = 1 // gdb-command:print/d *u8_ref // gdb-check:$9 = 100 // gdb-command:print *u16_ref // gdb-check:$10 = 16 // gdb-command:print *u32_ref // gdb-check:$11 = 32 // gdb-command:print *u64_ref // gdb-check:$12 = 64 // gdb-command:print *f32_ref // gdb-check:$13 = 2.5 // gdb-command:print *f64_ref // gdb-check:$14 = 3.5 #![allow(unused_variable)]
let bool_box: Box<bool> = box true; let bool_ref: &bool = bool_box; let int_box: Box<int> = box -1; let int_ref: &int = int_box; let char_box: Box<char> = box 'a'; let char_ref: &char = char_box; let i8_box: Box<i8> = box 68; let i8_ref: &i8 = i8_box; let i16_box: Box<i16> = box -16; let i16_ref: &i16 = i16_box; let i32_box: Box<i32> = box -32; let i32_ref: &i32 = i32_box; let i64_box: Box<i64> = box -64; let i64_ref: &i64 = i64_box; let uint_box: Box<uint> = box 1; let uint_ref: &uint = uint_box; let u8_box: Box<u8> = box 100; let u8_ref: &u8 = u8_box; let u16_box: Box<u16> = box 16; let u16_ref: &u16 = u16_box; let u32_box: Box<u32> = box 32; let u32_ref: &u32 = u32_box; let u64_box: Box<u64> = box 64; let u64_ref: &u64 = u64_box; let f32_box: Box<f32> = box 2.5; let f32_ref: &f32 = f32_box; let f64_box: Box<f64> = box 3.5; let f64_ref: &f64 = f64_box; zzz(); } fn zzz() {()}
fn main() {
random_line_split
borrowed-unique-basic.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // Gdb doesn't know about UTF-32 character encoding and will print a rust char as only // its numerical value. // compile-flags:-g // gdb-command:rbreak zzz // gdb-command:run // gdb-command:finish // gdb-command:print *bool_ref // gdb-check:$1 = true // gdb-command:print *int_ref // gdb-check:$2 = -1 // gdb-command:print *char_ref // gdb-check:$3 = 97 // gdb-command:print/d *i8_ref // gdb-check:$4 = 68 // gdb-command:print *i16_ref // gdb-check:$5 = -16 // gdb-command:print *i32_ref // gdb-check:$6 = -32 // gdb-command:print *i64_ref // gdb-check:$7 = -64 // gdb-command:print *uint_ref // gdb-check:$8 = 1 // gdb-command:print/d *u8_ref // gdb-check:$9 = 100 // gdb-command:print *u16_ref // gdb-check:$10 = 16 // gdb-command:print *u32_ref // gdb-check:$11 = 32 // gdb-command:print *u64_ref // gdb-check:$12 = 64 // gdb-command:print *f32_ref // gdb-check:$13 = 2.5 // gdb-command:print *f64_ref // gdb-check:$14 = 3.5 #![allow(unused_variable)] fn main() { let bool_box: Box<bool> = box true; let bool_ref: &bool = bool_box; let int_box: Box<int> = box -1; let int_ref: &int = int_box; let char_box: Box<char> = box 'a'; let char_ref: &char = char_box; let i8_box: Box<i8> = box 68; let i8_ref: &i8 = i8_box; let i16_box: Box<i16> = box -16; let i16_ref: &i16 = i16_box; let i32_box: Box<i32> = box -32; let i32_ref: &i32 = i32_box; let i64_box: Box<i64> = box -64; let i64_ref: &i64 = i64_box; let uint_box: Box<uint> = box 1; let uint_ref: &uint = uint_box; let u8_box: Box<u8> = box 100; let u8_ref: &u8 = u8_box; let u16_box: Box<u16> = box 16; let u16_ref: &u16 = u16_box; let u32_box: Box<u32> = box 32; let u32_ref: &u32 = u32_box; let u64_box: Box<u64> = box 64; let u64_ref: &u64 = u64_box; let f32_box: Box<f32> = box 2.5; let f32_ref: &f32 = f32_box; let f64_box: Box<f64> = box 3.5; let f64_ref: &f64 = f64_box; zzz(); } fn
() {()}
zzz
identifier_name
io.rs
use std::error; use std::fmt::{self, Display}; use std::io::{self, BufRead}; use {Grid, P}; /// The type for errors occurring in reading puzrs data. #[derive(Debug)] pub enum ReadError { Io(io::Error), InvalidFormat, InvalidValue, } impl fmt::Display for ReadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; match *self { ReadError::Io(ref err) => Display::fmt(err, f), _ => write!(f, "{}", self.description()), } } } impl error::Error for ReadError { fn description(&self) -> &str { match *self { ReadError::Io(ref err) => err.description(), ReadError::InvalidFormat => "invalid format", ReadError::InvalidValue => "invalid value", } } } impl From<io::Error> for ReadError { fn from(err: io::Error) -> ReadError { ReadError::Io(err) } } fn is_comment(s: &String) -> bool { s.chars().next().unwrap() == '%' } pub fn next_valid_line(reader: &mut BufRead, buf: &mut String) -> io::Result<usize> { loop { buf.clear(); let len = reader.read_line(buf)?; if len == 0 { return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "")); } if!buf.trim().is_empty() &&!is_comment(buf) { return Ok(len); } } } pub fn
<R, F, T>(reader: &mut R, converter: F, default: T) -> Result<Grid<T>, ReadError> where R: BufRead, F: Fn(&str) -> Result<T, ReadError>, T: Clone, { let mut buffer = String::new(); let height; let width; { next_valid_line(reader, &mut buffer)?; let mut header = buffer.split(' '); height = header .next() .ok_or(ReadError::InvalidFormat)? .trim() .parse::<i32>() .map_err(|_| ReadError::InvalidValue)?; width = header .next() .ok_or(ReadError::InvalidFormat)? .trim() .parse::<i32>() .map_err(|_| ReadError::InvalidValue)?; } let mut ret = Grid::new(height, width, default); for y in 0..height { next_valid_line(reader, &mut buffer)?; let mut row = buffer.trim_end().split(' '); for x in 0..width { let elem = row.next().ok_or(ReadError::InvalidFormat)?; let converted_elem = converter(elem.as_ref())?; ret[P(y, x)] = converted_elem; } } Ok(ret) } #[cfg(test)] mod tests { use super::*; #[test] fn test_read_grid() { let mut src = " 3 4 % this line is a comment! 1 2 3 4 x y z w p q r s " .as_bytes(); let grid = read_grid(&mut src, |s| Ok(s.to_string()), String::new()).unwrap(); assert_eq!(grid.height(), 3); assert_eq!(grid.width(), 4); assert_eq!(grid[P(1, 2)], "z".to_string()); } }
read_grid
identifier_name
io.rs
use std::error; use std::fmt::{self, Display}; use std::io::{self, BufRead}; use {Grid, P}; /// The type for errors occurring in reading puzrs data. #[derive(Debug)] pub enum ReadError { Io(io::Error), InvalidFormat, InvalidValue, } impl fmt::Display for ReadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; match *self { ReadError::Io(ref err) => Display::fmt(err, f), _ => write!(f, "{}", self.description()), } } } impl error::Error for ReadError { fn description(&self) -> &str { match *self { ReadError::Io(ref err) => err.description(), ReadError::InvalidFormat => "invalid format", ReadError::InvalidValue => "invalid value", } } } impl From<io::Error> for ReadError { fn from(err: io::Error) -> ReadError { ReadError::Io(err) } } fn is_comment(s: &String) -> bool { s.chars().next().unwrap() == '%' } pub fn next_valid_line(reader: &mut BufRead, buf: &mut String) -> io::Result<usize> { loop { buf.clear(); let len = reader.read_line(buf)?; if len == 0 { return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "")); } if!buf.trim().is_empty() &&!is_comment(buf) { return Ok(len); }
} pub fn read_grid<R, F, T>(reader: &mut R, converter: F, default: T) -> Result<Grid<T>, ReadError> where R: BufRead, F: Fn(&str) -> Result<T, ReadError>, T: Clone, { let mut buffer = String::new(); let height; let width; { next_valid_line(reader, &mut buffer)?; let mut header = buffer.split(' '); height = header .next() .ok_or(ReadError::InvalidFormat)? .trim() .parse::<i32>() .map_err(|_| ReadError::InvalidValue)?; width = header .next() .ok_or(ReadError::InvalidFormat)? .trim() .parse::<i32>() .map_err(|_| ReadError::InvalidValue)?; } let mut ret = Grid::new(height, width, default); for y in 0..height { next_valid_line(reader, &mut buffer)?; let mut row = buffer.trim_end().split(' '); for x in 0..width { let elem = row.next().ok_or(ReadError::InvalidFormat)?; let converted_elem = converter(elem.as_ref())?; ret[P(y, x)] = converted_elem; } } Ok(ret) } #[cfg(test)] mod tests { use super::*; #[test] fn test_read_grid() { let mut src = " 3 4 % this line is a comment! 1 2 3 4 x y z w p q r s " .as_bytes(); let grid = read_grid(&mut src, |s| Ok(s.to_string()), String::new()).unwrap(); assert_eq!(grid.height(), 3); assert_eq!(grid.width(), 4); assert_eq!(grid[P(1, 2)], "z".to_string()); } }
}
random_line_split
associated-types-binding-in-where-clause.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 equality constraints on associated types in a where clause. pub trait Foo { type A; fn boo(&self) -> <Self as Foo>::A; } #[derive(PartialEq)] pub struct Bar; impl Foo for int { type A = uint; fn boo(&self) -> uint { 42 } } impl Foo for char { type A = Bar; fn boo(&self) -> Bar { Bar } } fn
<I: Foo<A=Bar>>(x: I) -> Bar { x.boo() } fn foo_uint<I: Foo<A=uint>>(x: I) -> uint { x.boo() } pub fn main() { let a = 42; foo_uint(a); let a = 'a'; foo_bar(a); }
foo_bar
identifier_name
associated-types-binding-in-where-clause.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 equality constraints on associated types in a where clause. pub trait Foo { type A; fn boo(&self) -> <Self as Foo>::A; } #[derive(PartialEq)] pub struct Bar; impl Foo for int { type A = uint; fn boo(&self) -> uint
} impl Foo for char { type A = Bar; fn boo(&self) -> Bar { Bar } } fn foo_bar<I: Foo<A=Bar>>(x: I) -> Bar { x.boo() } fn foo_uint<I: Foo<A=uint>>(x: I) -> uint { x.boo() } pub fn main() { let a = 42; foo_uint(a); let a = 'a'; foo_bar(a); }
{ 42 }
identifier_body
associated-types-binding-in-where-clause.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 equality constraints on associated types in a where clause. pub trait Foo { type A; fn boo(&self) -> <Self as Foo>::A; } #[derive(PartialEq)] pub struct Bar; impl Foo for int { type A = uint; fn boo(&self) -> uint { 42 } } impl Foo for char { type A = Bar; fn boo(&self) -> Bar { Bar } } fn foo_bar<I: Foo<A=Bar>>(x: I) -> Bar { x.boo() } fn foo_uint<I: Foo<A=uint>>(x: I) -> uint { x.boo()
pub fn main() { let a = 42; foo_uint(a); let a = 'a'; foo_bar(a); }
}
random_line_split
build.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/. */ #[macro_use] extern crate lazy_static; #[cfg(feature = "bindgen")] extern crate libbindgen; #[cfg(feature = "bindgen")] extern crate regex; extern crate walkdir; extern crate phf_codegen; use std::env; use std::fs::File; use std::io::{BufWriter, BufReader, BufRead, Write}; use std::path::Path; use std::process::{Command, exit}; use walkdir::WalkDir; #[cfg(feature = "gecko")] mod build_gecko; #[cfg(not(feature = "gecko"))] mod build_gecko { pub fn generate() {} } #[cfg(windows)] fn find_python() -> String { if Command::new("python2.7.exe").arg("--version").output().is_ok() { return "python2.7.exe".to_owned(); } if Command::new("python27.exe").arg("--version").output().is_ok() { return "python27.exe".to_owned(); } if Command::new("python.exe").arg("--version").output().is_ok() { return "python.exe".to_owned(); } panic!(concat!("Can't find python (tried python2.7.exe, python27.exe, and python.exe)! ", "Try fixing PATH or setting the PYTHON env var")); } #[cfg(not(windows))] fn find_python() -> String { if Command::new("python2.7").arg("--version").output().unwrap().status.success() { "python2.7" } else { "python" }.to_owned() } fn generate_properties() { for entry in WalkDir::new("properties") { let entry = entry.unwrap(); match entry.path().extension().and_then(|e| e.to_str()) { Some("mako") | Some("rs") | Some("py") | Some("zip") => { println!("cargo:rerun-if-changed={}", entry.path().display()); } _ => {} } } let python = env::var("PYTHON").ok().unwrap_or_else(find_python); let script = Path::new(file!()).parent().unwrap().join("properties").join("build.py"); let product = if cfg!(feature = "gecko") { "gecko" } else { "servo" }; let status = Command::new(python) .arg(&script) .arg(product) .arg("style-crate") .arg(if cfg!(feature = "testing") { "testing" } else { "regular" }) .status() .unwrap(); if!status.success() { exit(1) } let path = Path::new(&env::var("OUT_DIR").unwrap()).join("static_ids.rs"); let static_ids = Path::new(&env::var("OUT_DIR").unwrap()).join("static_ids.txt"); let mut file = BufWriter::new(File::create(&path).unwrap()); let static_ids = BufReader::new(File::open(&static_ids).unwrap()); write!(&mut file, "static STATIC_IDS: ::phf::Map<&'static str, StaticId> = ").unwrap(); let mut map = phf_codegen::Map::new(); for result in static_ids.lines() { let line = result.unwrap(); let mut split = line.split('\t'); let key = split.next().unwrap().to_owned(); let value = split.next().unwrap(); map.entry(key, value); } map.build(&mut file).unwrap(); write!(&mut file, ";\n").unwrap(); } fn main()
{ println!("cargo:rerun-if-changed=build.rs"); generate_properties(); build_gecko::generate(); }
identifier_body
build.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/. */ #[macro_use] extern crate lazy_static; #[cfg(feature = "bindgen")] extern crate libbindgen; #[cfg(feature = "bindgen")] extern crate regex; extern crate walkdir; extern crate phf_codegen; use std::env; use std::fs::File; use std::io::{BufWriter, BufReader, BufRead, Write}; use std::path::Path; use std::process::{Command, exit}; use walkdir::WalkDir; #[cfg(feature = "gecko")] mod build_gecko; #[cfg(not(feature = "gecko"))] mod build_gecko { pub fn generate() {} } #[cfg(windows)] fn find_python() -> String { if Command::new("python2.7.exe").arg("--version").output().is_ok() { return "python2.7.exe".to_owned(); } if Command::new("python27.exe").arg("--version").output().is_ok() { return "python27.exe".to_owned(); } if Command::new("python.exe").arg("--version").output().is_ok() { return "python.exe".to_owned(); } panic!(concat!("Can't find python (tried python2.7.exe, python27.exe, and python.exe)! ", "Try fixing PATH or setting the PYTHON env var")); } #[cfg(not(windows))] fn find_python() -> String { if Command::new("python2.7").arg("--version").output().unwrap().status.success() { "python2.7" } else { "python" }.to_owned() } fn generate_properties() { for entry in WalkDir::new("properties") { let entry = entry.unwrap(); match entry.path().extension().and_then(|e| e.to_str()) { Some("mako") | Some("rs") | Some("py") | Some("zip") => { println!("cargo:rerun-if-changed={}", entry.path().display()); } _ => {} } } let python = env::var("PYTHON").ok().unwrap_or_else(find_python); let script = Path::new(file!()).parent().unwrap().join("properties").join("build.py"); let product = if cfg!(feature = "gecko") { "gecko" } else { "servo" }; let status = Command::new(python) .arg(&script) .arg(product) .arg("style-crate") .arg(if cfg!(feature = "testing")
else { "regular" }) .status() .unwrap(); if!status.success() { exit(1) } let path = Path::new(&env::var("OUT_DIR").unwrap()).join("static_ids.rs"); let static_ids = Path::new(&env::var("OUT_DIR").unwrap()).join("static_ids.txt"); let mut file = BufWriter::new(File::create(&path).unwrap()); let static_ids = BufReader::new(File::open(&static_ids).unwrap()); write!(&mut file, "static STATIC_IDS: ::phf::Map<&'static str, StaticId> = ").unwrap(); let mut map = phf_codegen::Map::new(); for result in static_ids.lines() { let line = result.unwrap(); let mut split = line.split('\t'); let key = split.next().unwrap().to_owned(); let value = split.next().unwrap(); map.entry(key, value); } map.build(&mut file).unwrap(); write!(&mut file, ";\n").unwrap(); } fn main() { println!("cargo:rerun-if-changed=build.rs"); generate_properties(); build_gecko::generate(); }
{ "testing" }
conditional_block
build.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/. */ #[macro_use] extern crate lazy_static; #[cfg(feature = "bindgen")] extern crate libbindgen; #[cfg(feature = "bindgen")] extern crate regex; extern crate walkdir; extern crate phf_codegen; use std::env; use std::fs::File; use std::io::{BufWriter, BufReader, BufRead, Write}; use std::path::Path; use std::process::{Command, exit}; use walkdir::WalkDir; #[cfg(feature = "gecko")] mod build_gecko; #[cfg(not(feature = "gecko"))] mod build_gecko { pub fn generate() {} } #[cfg(windows)] fn find_python() -> String { if Command::new("python2.7.exe").arg("--version").output().is_ok() { return "python2.7.exe".to_owned(); } if Command::new("python27.exe").arg("--version").output().is_ok() { return "python27.exe".to_owned(); } if Command::new("python.exe").arg("--version").output().is_ok() { return "python.exe".to_owned(); } panic!(concat!("Can't find python (tried python2.7.exe, python27.exe, and python.exe)! ", "Try fixing PATH or setting the PYTHON env var")); } #[cfg(not(windows))] fn find_python() -> String { if Command::new("python2.7").arg("--version").output().unwrap().status.success() { "python2.7" } else { "python" }.to_owned() } fn generate_properties() { for entry in WalkDir::new("properties") { let entry = entry.unwrap(); match entry.path().extension().and_then(|e| e.to_str()) { Some("mako") | Some("rs") | Some("py") | Some("zip") => { println!("cargo:rerun-if-changed={}", entry.path().display()); } _ => {} } } let python = env::var("PYTHON").ok().unwrap_or_else(find_python); let script = Path::new(file!()).parent().unwrap().join("properties").join("build.py"); let product = if cfg!(feature = "gecko") { "gecko" } else { "servo" }; let status = Command::new(python) .arg(&script) .arg(product) .arg("style-crate") .arg(if cfg!(feature = "testing") { "testing" } else { "regular" }) .status() .unwrap(); if!status.success() { exit(1) } let path = Path::new(&env::var("OUT_DIR").unwrap()).join("static_ids.rs"); let static_ids = Path::new(&env::var("OUT_DIR").unwrap()).join("static_ids.txt"); let mut file = BufWriter::new(File::create(&path).unwrap()); let static_ids = BufReader::new(File::open(&static_ids).unwrap()); write!(&mut file, "static STATIC_IDS: ::phf::Map<&'static str, StaticId> = ").unwrap(); let mut map = phf_codegen::Map::new(); for result in static_ids.lines() { let line = result.unwrap(); let mut split = line.split('\t'); let key = split.next().unwrap().to_owned(); let value = split.next().unwrap();
map.build(&mut file).unwrap(); write!(&mut file, ";\n").unwrap(); } fn main() { println!("cargo:rerun-if-changed=build.rs"); generate_properties(); build_gecko::generate(); }
map.entry(key, value); }
random_line_split
build.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/. */ #[macro_use] extern crate lazy_static; #[cfg(feature = "bindgen")] extern crate libbindgen; #[cfg(feature = "bindgen")] extern crate regex; extern crate walkdir; extern crate phf_codegen; use std::env; use std::fs::File; use std::io::{BufWriter, BufReader, BufRead, Write}; use std::path::Path; use std::process::{Command, exit}; use walkdir::WalkDir; #[cfg(feature = "gecko")] mod build_gecko; #[cfg(not(feature = "gecko"))] mod build_gecko { pub fn generate() {} } #[cfg(windows)] fn
() -> String { if Command::new("python2.7.exe").arg("--version").output().is_ok() { return "python2.7.exe".to_owned(); } if Command::new("python27.exe").arg("--version").output().is_ok() { return "python27.exe".to_owned(); } if Command::new("python.exe").arg("--version").output().is_ok() { return "python.exe".to_owned(); } panic!(concat!("Can't find python (tried python2.7.exe, python27.exe, and python.exe)! ", "Try fixing PATH or setting the PYTHON env var")); } #[cfg(not(windows))] fn find_python() -> String { if Command::new("python2.7").arg("--version").output().unwrap().status.success() { "python2.7" } else { "python" }.to_owned() } fn generate_properties() { for entry in WalkDir::new("properties") { let entry = entry.unwrap(); match entry.path().extension().and_then(|e| e.to_str()) { Some("mako") | Some("rs") | Some("py") | Some("zip") => { println!("cargo:rerun-if-changed={}", entry.path().display()); } _ => {} } } let python = env::var("PYTHON").ok().unwrap_or_else(find_python); let script = Path::new(file!()).parent().unwrap().join("properties").join("build.py"); let product = if cfg!(feature = "gecko") { "gecko" } else { "servo" }; let status = Command::new(python) .arg(&script) .arg(product) .arg("style-crate") .arg(if cfg!(feature = "testing") { "testing" } else { "regular" }) .status() .unwrap(); if!status.success() { exit(1) } let path = Path::new(&env::var("OUT_DIR").unwrap()).join("static_ids.rs"); let static_ids = Path::new(&env::var("OUT_DIR").unwrap()).join("static_ids.txt"); let mut file = BufWriter::new(File::create(&path).unwrap()); let static_ids = BufReader::new(File::open(&static_ids).unwrap()); write!(&mut file, "static STATIC_IDS: ::phf::Map<&'static str, StaticId> = ").unwrap(); let mut map = phf_codegen::Map::new(); for result in static_ids.lines() { let line = result.unwrap(); let mut split = line.split('\t'); let key = split.next().unwrap().to_owned(); let value = split.next().unwrap(); map.entry(key, value); } map.build(&mut file).unwrap(); write!(&mut file, ";\n").unwrap(); } fn main() { println!("cargo:rerun-if-changed=build.rs"); generate_properties(); build_gecko::generate(); }
find_python
identifier_name
data.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/. */ //! Per-node data used in style calculation. #![deny(missing_docs)] use context::SharedStyleContext; use dom::TElement; use properties::ComputedValues; use properties::longhands::display::computed_value as display; use restyle_hints::{RESTYLE_DESCENDANTS, RESTYLE_LATER_SIBLINGS, RESTYLE_SELF, RestyleHint}; use rule_tree::StrongRuleNode; use selector_parser::{EAGER_PSEUDO_COUNT, PseudoElement, RestyleDamage}; #[cfg(feature = "servo")] use std::collections::HashMap; use std::fmt; #[cfg(feature = "servo")] use std::hash::BuildHasherDefault; <<<<<<< HEAD use std::ops::Deref; <<<<<<< HEAD use std::sync::Arc; ======= use stylearc::Arc; >>>>>>> 896a920ff53f683cdaac8bc6b2f796633a436a7f use stylist::Stylist; use thread_state; ======= use stylearc::Arc; >>>>>>> 37d173a4d6df3b140afdaf174f12d49e77f07c86 use traversal::TraversalFlags; /// The structure that represents the result of style computation. This is /// effectively a tuple of rules and computed values, that is, the rule node, /// and the result of computing that rule node's rules, the `ComputedValues`. #[derive(Clone)] pub struct ComputedStyle { /// The rule node representing the ordered list of rules matched for this /// node. pub rules: StrongRuleNode, /// The computed values for each property obtained by cascading the /// matched rules. This can only be none during a transient interval of /// the styling algorithm, and callers can safely unwrap it. pub values: Option<Arc<ComputedValues>>, } impl ComputedStyle { /// Trivially construct a new `ComputedStyle`. pub fn new(rules: StrongRuleNode, values: Arc<ComputedValues>) -> Self { ComputedStyle { rules: rules, values: Some(values), } } /// Constructs a partial ComputedStyle, whose ComputedVaues will be filled /// in later. pub fn new_partial(rules: StrongRuleNode) -> Self { ComputedStyle { rules: rules, values: None, } } /// Returns a reference to the ComputedValues. The values can only be null during /// the styling algorithm, so this is safe to call elsewhere. pub fn values(&self) -> &Arc<ComputedValues> { self.values.as_ref().unwrap() } /// Mutable version of the above. pub fn values_mut(&mut self) -> &mut Arc<ComputedValues> { self.values.as_mut().unwrap() } } // We manually implement Debug for ComputedStyle so that we can avoid the // verbose stringification of ComputedValues for normal logging. impl fmt::Debug for ComputedStyle { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ComputedStyle {{ rules: {:?}, values: {{..}} }}", self.rules) } } /// A list of styles for eagerly-cascaded pseudo-elements. Lazily-allocated. #[derive(Clone, Debug)] pub struct EagerPseudoStyles(Option<Box<[Option<ComputedStyle>]>>); impl EagerPseudoStyles { /// Returns whether there are any pseudo styles. pub fn is_empty(&self) -> bool { <<<<<<< HEAD self.0.is_some() ======= self.0.is_none() >>>>>>> 896a920ff53f683cdaac8bc6b2f796633a436a7f } /// Returns a reference to the style for a given eager pseudo, if it exists. pub fn get(&self, pseudo: &PseudoElement) -> Option<&ComputedStyle> { debug_assert!(pseudo.is_eager()); self.0.as_ref().and_then(|p| p[pseudo.eager_index()].as_ref()) } /// Returns a mutable reference to the style for a given eager pseudo, if it exists. pub fn get_mut(&mut self, pseudo: &PseudoElement) -> Option<&mut ComputedStyle> { debug_assert!(pseudo.is_eager()); self.0.as_mut().and_then(|p| p[pseudo.eager_index()].as_mut()) } <<<<<<< HEAD /// Returns true if the EagerPseudoStyles has a ComputedStyle for |pseudo|. pub fn has(&self, pseudo: &PseudoElement) -> bool { self.get(pseudo).is_some() } /// Inserts a pseudo-element. The pseudo-element must not already exist. pub fn insert(&mut self, pseudo: &PseudoElement, style: ComputedStyle) { debug_assert!(!self.has(pseudo)); if self.0.is_none() { self.0 = Some(vec![None; EAGER_PSEUDO_COUNT].into_boxed_slice()); } self.0.as_mut().unwrap()[pseudo.eager_index()] = Some(style); } /// Removes a pseudo-element style if it exists, and returns it. pub fn take(&mut self, pseudo: &PseudoElement) -> Option<ComputedStyle> { let result = match self.0.as_mut() { None => return None, Some(arr) => arr[pseudo.eager_index()].take(), }; let empty = self.0.as_ref().unwrap().iter().all(|x| x.is_none()); if empty { self.0 = None; } result } /// Returns a list of the pseudo-elements. pub fn keys(&self) -> Vec<PseudoElement> { let mut v = Vec::new(); if let Some(ref arr) = self.0 { for i in 0..EAGER_PSEUDO_COUNT { if arr[i].is_some() { v.push(PseudoElement::from_eager_index(i)); } } } v } ======= /// Returns true if the EagerPseudoStyles has a ComputedStyle for |pseudo|. pub fn has(&self, pseudo: &PseudoElement) -> bool { self.get(pseudo).is_some() } /// Inserts a pseudo-element. The pseudo-element must not already exist. pub fn insert(&mut self, pseudo: &PseudoElement, style: ComputedStyle) { debug_assert!(!self.has(pseudo)); if self.0.is_none() { self.0 = Some(vec![None; EAGER_PSEUDO_COUNT].into_boxed_slice()); } self.0.as_mut().unwrap()[pseudo.eager_index()] = Some(style); } /// Removes a pseudo-element style if it exists, and returns it. pub fn take(&mut self, pseudo: &PseudoElement) -> Option<ComputedStyle> { let result = match self.0.as_mut() { None => return None, Some(arr) => arr[pseudo.eager_index()].take(), }; let empty = self.0.as_ref().unwrap().iter().all(|x| x.is_none()); if empty { self.0 = None; } result } /// Returns a list of the pseudo-elements. pub fn keys(&self) -> Vec<PseudoElement> { let mut v = Vec::new(); if let Some(ref arr) = self.0 { for i in 0..EAGER_PSEUDO_COUNT { if arr[i].is_some() { v.push(PseudoElement::from_eager_index(i)); } } } v } >>>>>>> 896a920ff53f683cdaac8bc6b2f796633a436a7f /// Sets the rule node for a given pseudo-element, which must already have an entry. /// /// Returns true if the rule node changed. pub fn set_rules(&mut self, pseudo: &PseudoElement, rules: StrongRuleNode) -> bool { debug_assert!(self.has(pseudo)); let mut style = self.get_mut(pseudo).unwrap(); let changed = style.rules!= rules; style.rules = rules; changed } } /// A cache of precomputed and lazy pseudo-elements, used by servo. This isn't /// a very efficient design, but is the result of servo having previously used /// the eager pseudo map (when it was a map) for this cache. #[cfg(feature = "servo")] type PseudoElementCache = HashMap<PseudoElement, ComputedStyle, BuildHasherDefault<::fnv::FnvHasher>>; #[cfg(feature = "gecko")] type PseudoElementCache = (); /// The styles associated with a node, including the styles for any /// pseudo-elements. #[derive(Clone, Debug)] pub struct ElementStyles { /// The element's style. pub primary: ComputedStyle, /// A list of the styles for the element's eagerly-cascaded pseudo-elements. pub pseudos: EagerPseudoStyles, /// NB: This is an empty field for gecko. pub cached_pseudos: PseudoElementCache, } impl ElementStyles { /// Trivially construct a new `ElementStyles`. pub fn new(primary: ComputedStyle) -> Self { ElementStyles { primary: primary, pseudos: EagerPseudoStyles(None), cached_pseudos: PseudoElementCache::default(), } } /// Whether this element `display` value is `none`. pub fn is_display_none(&self) -> bool { self.primary.values().get_box().clone_display() == display::T::none } } /// Restyle hint for storing on ElementData. /// /// We wrap it in a newtype to force the encapsulation of the complexity of /// handling the correct invalidations in this file. #[derive(Clone, Debug)] pub struct StoredRestyleHint(RestyleHint); impl StoredRestyleHint { /// Propagates this restyle hint to a child element. pub fn propagate(&mut self, traversal_flags: &TraversalFlags) -> Self { use std::mem; // In the middle of an animation only restyle, we don't need to // propagate any restyle hints, and we need to remove ourselves. if traversal_flags.for_animation_only() { self.0.remove(RestyleHint::for_animations()); return Self::empty(); } debug_assert!(!self.0.intersects(RestyleHint::for_animations()), "There should not be any animation restyle hints \ during normal traversal"); // Else we should clear ourselves, and return the propagated hint. let hint = mem::replace(&mut self.0, RestyleHint::empty()); StoredRestyleHint(if hint.contains(RESTYLE_DESCENDANTS) { RESTYLE_SELF | RESTYLE_DESCENDANTS } else { RestyleHint::empty() }) } /// Creates an empty `StoredRestyleHint`. pub fn empty() -> Self { StoredRestyleHint(RestyleHint::empty()) } /// Creates a restyle hint that forces the whole subtree to be restyled, /// including the element. pub fn subtree() -> Self { StoredRestyleHint(RESTYLE_SELF | RESTYLE_DESCENDANTS) } /// Creates a restyle hint that forces the element and all its later /// siblings to have their whole subtrees restyled, including the elements /// themselves. pub fn subtree_and_later_siblings() -> Self { StoredRestyleHint(RESTYLE_SELF | RESTYLE_DESCENDANTS | RESTYLE_LATER_SIBLINGS) } /// Returns true if the hint indicates that our style may be invalidated. pub fn has_self_invalidations(&self) -> bool { self.0.intersects(RestyleHint::for_self()) } /// Returns true if the hint indicates that our sibling's style may be /// invalidated. pub fn has_sibling_invalidations(&self) -> bool { self.0.intersects(RESTYLE_LATER_SIBLINGS) } /// Whether the restyle hint is empty (nothing requires to be restyled). pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Insert another restyle hint, effectively resulting in the union of both. pub fn insert(&mut self, other: &Self)
/// Returns true if the hint has animation-only restyle. pub fn has_animation_hint(&self) -> bool { self.0.intersects(RestyleHint::for_animations()) } } impl Default for StoredRestyleHint { fn default() -> Self { StoredRestyleHint::empty() } } impl From<RestyleHint> for StoredRestyleHint { fn from(hint: RestyleHint) -> Self { StoredRestyleHint(hint) } } /// Transient data used by the restyle algorithm. This structure is instantiated /// either before or during restyle traversal, and is cleared at the end of node /// processing. #[derive(Debug, Default)] pub struct RestyleData { /// The restyle hint, which indicates whether selectors need to be rematched /// for this element, its children, and its descendants. pub hint: StoredRestyleHint, /// Whether we need to recascade. /// FIXME(bholley): This should eventually become more fine-grained. pub recascade: bool, /// The restyle damage, indicating what kind of layout changes are required /// afte restyling. pub damage: RestyleDamage, /// The restyle damage that has already been handled by our ancestors, and does /// not need to be applied again at this element. Only non-empty during the /// traversal, once ancestor damage has been calculated. /// /// Note that this optimization mostly makes sense in terms of Gecko's top-down /// frame constructor and change list processing model. We don't bother with it /// for Servo for now. #[cfg(feature = "gecko")] pub damage_handled: RestyleDamage, } impl RestyleData { /// Returns true if this RestyleData might invalidate the current style. pub fn has_invalidations(&self) -> bool { self.hint.has_self_invalidations() || self.recascade } /// Returns true if this RestyleData might invalidate sibling styles. pub fn has_sibling_invalidations(&self) -> bool { self.hint.has_sibling_invalidations() } /// Returns damage handled. #[cfg(feature = "gecko")] pub fn damage_handled(&self) -> RestyleDamage { self.damage_handled } /// Returns damage handled (always empty for servo). #[cfg(feature = "servo")] pub fn damage_handled(&self) -> RestyleDamage { RestyleDamage::empty() } /// Sets damage handled. #[cfg(feature = "gecko")] pub fn set_damage_handled(&mut self, d: RestyleDamage) { self.damage_handled = d; } /// Sets damage handled. No-op for Servo. #[cfg(feature = "servo")] pub fn set_damage_handled(&mut self, _: RestyleDamage) {} } /// Style system data associated with an Element. /// /// In Gecko, this hangs directly off the Element. Servo, this is embedded /// inside of layout data, which itself hangs directly off the Element. In /// both cases, it is wrapped inside an AtomicRefCell to ensure thread safety. #[derive(Debug)] pub struct ElementData { /// The computed styles for the element and its pseudo-elements. styles: Option<ElementStyles>, /// Restyle tracking. We separate this into a separate allocation so that /// we can drop it when no restyles are pending on the elemnt. restyle: Option<Box<RestyleData>>, } /// The kind of restyle that a single element should do. pub enum RestyleKind { /// We need to run selector matching plus re-cascade, that is, a full /// restyle. MatchAndCascade, /// We need to recascade with some replacement rule, such as the style /// attribute, or animation rules. CascadeWithReplacements(RestyleHint), /// We only need to recascade, for example, because only inherited /// properties in the parent changed. CascadeOnly, } impl ElementData { /// Computes the final restyle hint for this element, potentially allocating /// a `RestyleData` if we need to. /// /// This expands the snapshot (if any) into a restyle hint, and handles /// explicit sibling restyle hints from the stored restyle hint. /// /// Returns true if later siblings must be restyled. pub fn compute_final_hint<E: TElement>( &mut self, element: E, context: &SharedStyleContext) -> bool { debug!("compute_final_hint: {:?}, {:?}", element, context.traversal_flags); let mut hint = match self.get_restyle() { Some(r) => r.hint.0, None => RestyleHint::empty(), }; if element.has_snapshot() &&!element.handled_snapshot() { hint |= context.stylist.compute_restyle_hint(&element, context.snapshot_map); unsafe { element.set_handled_snapshot() } debug_assert!(element.handled_snapshot()); } let empty_hint = hint.is_empty(); // If the hint includes a directive for later siblings, strip it out and // notify the caller to modify the base hint for future siblings. let later_siblings = hint.contains(RESTYLE_LATER_SIBLINGS); hint.remove(RESTYLE_LATER_SIBLINGS); // Insert the hint, overriding the previous hint. This effectively takes // care of removing the later siblings restyle hint. if!empty_hint { self.ensure_restyle().hint = hint.into(); } later_siblings } /// Trivially construct an ElementData. pub fn new(existing: Option<ElementStyles>) -> Self { ElementData { styles: existing, restyle: None, } } /// Returns true if this element has a computed style. pub fn has_styles(&self) -> bool { self.styles.is_some() } /// Returns whether we have any outstanding style invalidation. pub fn has_invalidations(&self) -> bool { self.restyle.as_ref().map_or(false, |r| r.has_invalidations()) } /// Returns the kind of restyling that we're going to need to do on this /// element, based of the stored restyle hint. pub fn restyle_kind(&self) -> RestyleKind { debug_assert!(!self.has_styles() || self.has_invalidations(), "Should've stopped earlier"); if!self.has_styles() { return RestyleKind::MatchAndCascade; } debug_assert!(self.restyle.is_some()); let restyle_data = self.restyle.as_ref().unwrap(); let hint = restyle_data.hint.0; if hint.contains(RESTYLE_SELF) { return RestyleKind::MatchAndCascade; } if!hint.is_empty() { return RestyleKind::CascadeWithReplacements(hint); } debug_assert!(restyle_data.recascade, "We definitely need to do something!"); return RestyleKind::CascadeOnly; } /// Gets the element styles, if any. pub fn get_styles(&self) -> Option<&ElementStyles> { self.styles.as_ref() } /// Gets the element styles. Panic if the element has never been styled. pub fn styles(&self) -> &ElementStyles { self.styles.as_ref().expect("Calling styles() on unstyled ElementData") } /// Gets a mutable reference to the element styles, if any. pub fn get_styles_mut(&mut self) -> Option<&mut ElementStyles> { self.styles.as_mut() } /// Gets a mutable reference to the element styles. Panic if the element has /// never been styled. pub fn styles_mut(&mut self) -> &mut ElementStyles { self.styles.as_mut().expect("Calling styles_mut() on unstyled ElementData") } /// Borrows both styles and restyle mutably at the same time. pub fn styles_and_restyle_mut(&mut self) -> (&mut ElementStyles, Option<&mut RestyleData>) { (self.styles.as_mut().unwrap(), self.restyle.as_mut().map(|r| &mut **r)) } /// Sets the computed element styles. pub fn set_styles(&mut self, styles: ElementStyles) { self.styles = Some(styles); } /// Sets the computed element rules, and returns whether the rules changed. pub fn set_primary_rules(&mut self, rules: StrongRuleNode) -> bool { if!self.has_styles() { self.set_styles(ElementStyles::new(ComputedStyle::new_partial(rules))); return true; } if self.styles().primary.rules == rules { return false; } self.styles_mut().primary.rules = rules; true } /// Returns true if the Element has a RestyleData. pub fn has_restyle(&self) -> bool { self.restyle.is_some() } /// Drops any RestyleData. pub fn clear_restyle(&mut self) { self.restyle = None; } /// Creates a RestyleData if one doesn't exist. /// /// Asserts that the Element has been styled. pub fn ensure_restyle(&mut self) -> &mut RestyleData { debug_assert!(self.styles.is_some(), "restyling unstyled element"); if self.restyle.is_none() { self.restyle = Some(Box::new(RestyleData::default())); } self.restyle.as_mut().unwrap() } /// Gets a reference to the restyle data, if any. pub fn get_restyle(&self) -> Option<&RestyleData> { self.restyle.as_ref().map(|r| &**r) } /// Gets a reference to the restyle data. Panic if the element does not /// have restyle data. pub fn restyle(&self) -> &RestyleData { self.get_restyle().expect("Calling restyle without RestyleData") } /// Gets a mutable reference to the restyle data, if any. pub fn get_restyle_mut(&mut self) -> Option<&mut RestyleData> { self.restyle.as_mut().map(|r| &mut **r) } /// Gets a mutable reference to the restyle data. Panic if the element does /// not have restyle data. pub fn restyle_mut(&mut self) -> &mut RestyleData { self.get_restyle_mut().expect("Calling restyle_mut without RestyleData") } }
{ self.0 |= other.0 }
identifier_body
data.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/. */ //! Per-node data used in style calculation. #![deny(missing_docs)] use context::SharedStyleContext; use dom::TElement; use properties::ComputedValues; use properties::longhands::display::computed_value as display; use restyle_hints::{RESTYLE_DESCENDANTS, RESTYLE_LATER_SIBLINGS, RESTYLE_SELF, RestyleHint}; use rule_tree::StrongRuleNode; use selector_parser::{EAGER_PSEUDO_COUNT, PseudoElement, RestyleDamage}; #[cfg(feature = "servo")] use std::collections::HashMap; use std::fmt; #[cfg(feature = "servo")] use std::hash::BuildHasherDefault; <<<<<<< HEAD use std::ops::Deref; <<<<<<< HEAD use std::sync::Arc; ======= use stylearc::Arc; >>>>>>> 896a920ff53f683cdaac8bc6b2f796633a436a7f use stylist::Stylist; use thread_state; ======= use stylearc::Arc; >>>>>>> 37d173a4d6df3b140afdaf174f12d49e77f07c86 use traversal::TraversalFlags; /// The structure that represents the result of style computation. This is /// effectively a tuple of rules and computed values, that is, the rule node, /// and the result of computing that rule node's rules, the `ComputedValues`. #[derive(Clone)] pub struct ComputedStyle { /// The rule node representing the ordered list of rules matched for this /// node. pub rules: StrongRuleNode, /// The computed values for each property obtained by cascading the /// matched rules. This can only be none during a transient interval of /// the styling algorithm, and callers can safely unwrap it. pub values: Option<Arc<ComputedValues>>, } impl ComputedStyle { /// Trivially construct a new `ComputedStyle`. pub fn new(rules: StrongRuleNode, values: Arc<ComputedValues>) -> Self { ComputedStyle { rules: rules, values: Some(values), } } /// Constructs a partial ComputedStyle, whose ComputedVaues will be filled /// in later. pub fn new_partial(rules: StrongRuleNode) -> Self { ComputedStyle { rules: rules, values: None, } } /// Returns a reference to the ComputedValues. The values can only be null during /// the styling algorithm, so this is safe to call elsewhere. pub fn values(&self) -> &Arc<ComputedValues> { self.values.as_ref().unwrap() } /// Mutable version of the above. pub fn values_mut(&mut self) -> &mut Arc<ComputedValues> { self.values.as_mut().unwrap() } } // We manually implement Debug for ComputedStyle so that we can avoid the // verbose stringification of ComputedValues for normal logging. impl fmt::Debug for ComputedStyle { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ComputedStyle {{ rules: {:?}, values: {{..}} }}", self.rules) } } /// A list of styles for eagerly-cascaded pseudo-elements. Lazily-allocated. #[derive(Clone, Debug)] pub struct EagerPseudoStyles(Option<Box<[Option<ComputedStyle>]>>); impl EagerPseudoStyles { /// Returns whether there are any pseudo styles. pub fn is_empty(&self) -> bool { <<<<<<< HEAD self.0.is_some() ======= self.0.is_none() >>>>>>> 896a920ff53f683cdaac8bc6b2f796633a436a7f } /// Returns a reference to the style for a given eager pseudo, if it exists. pub fn get(&self, pseudo: &PseudoElement) -> Option<&ComputedStyle> { debug_assert!(pseudo.is_eager()); self.0.as_ref().and_then(|p| p[pseudo.eager_index()].as_ref()) } /// Returns a mutable reference to the style for a given eager pseudo, if it exists. pub fn get_mut(&mut self, pseudo: &PseudoElement) -> Option<&mut ComputedStyle> { debug_assert!(pseudo.is_eager()); self.0.as_mut().and_then(|p| p[pseudo.eager_index()].as_mut()) } <<<<<<< HEAD /// Returns true if the EagerPseudoStyles has a ComputedStyle for |pseudo|. pub fn has(&self, pseudo: &PseudoElement) -> bool { self.get(pseudo).is_some() } /// Inserts a pseudo-element. The pseudo-element must not already exist. pub fn insert(&mut self, pseudo: &PseudoElement, style: ComputedStyle) { debug_assert!(!self.has(pseudo)); if self.0.is_none() { self.0 = Some(vec![None; EAGER_PSEUDO_COUNT].into_boxed_slice()); } self.0.as_mut().unwrap()[pseudo.eager_index()] = Some(style); } /// Removes a pseudo-element style if it exists, and returns it. pub fn take(&mut self, pseudo: &PseudoElement) -> Option<ComputedStyle> { let result = match self.0.as_mut() { None => return None, Some(arr) => arr[pseudo.eager_index()].take(), }; let empty = self.0.as_ref().unwrap().iter().all(|x| x.is_none()); if empty
result } /// Returns a list of the pseudo-elements. pub fn keys(&self) -> Vec<PseudoElement> { let mut v = Vec::new(); if let Some(ref arr) = self.0 { for i in 0..EAGER_PSEUDO_COUNT { if arr[i].is_some() { v.push(PseudoElement::from_eager_index(i)); } } } v } ======= /// Returns true if the EagerPseudoStyles has a ComputedStyle for |pseudo|. pub fn has(&self, pseudo: &PseudoElement) -> bool { self.get(pseudo).is_some() } /// Inserts a pseudo-element. The pseudo-element must not already exist. pub fn insert(&mut self, pseudo: &PseudoElement, style: ComputedStyle) { debug_assert!(!self.has(pseudo)); if self.0.is_none() { self.0 = Some(vec![None; EAGER_PSEUDO_COUNT].into_boxed_slice()); } self.0.as_mut().unwrap()[pseudo.eager_index()] = Some(style); } /// Removes a pseudo-element style if it exists, and returns it. pub fn take(&mut self, pseudo: &PseudoElement) -> Option<ComputedStyle> { let result = match self.0.as_mut() { None => return None, Some(arr) => arr[pseudo.eager_index()].take(), }; let empty = self.0.as_ref().unwrap().iter().all(|x| x.is_none()); if empty { self.0 = None; } result } /// Returns a list of the pseudo-elements. pub fn keys(&self) -> Vec<PseudoElement> { let mut v = Vec::new(); if let Some(ref arr) = self.0 { for i in 0..EAGER_PSEUDO_COUNT { if arr[i].is_some() { v.push(PseudoElement::from_eager_index(i)); } } } v } >>>>>>> 896a920ff53f683cdaac8bc6b2f796633a436a7f /// Sets the rule node for a given pseudo-element, which must already have an entry. /// /// Returns true if the rule node changed. pub fn set_rules(&mut self, pseudo: &PseudoElement, rules: StrongRuleNode) -> bool { debug_assert!(self.has(pseudo)); let mut style = self.get_mut(pseudo).unwrap(); let changed = style.rules!= rules; style.rules = rules; changed } } /// A cache of precomputed and lazy pseudo-elements, used by servo. This isn't /// a very efficient design, but is the result of servo having previously used /// the eager pseudo map (when it was a map) for this cache. #[cfg(feature = "servo")] type PseudoElementCache = HashMap<PseudoElement, ComputedStyle, BuildHasherDefault<::fnv::FnvHasher>>; #[cfg(feature = "gecko")] type PseudoElementCache = (); /// The styles associated with a node, including the styles for any /// pseudo-elements. #[derive(Clone, Debug)] pub struct ElementStyles { /// The element's style. pub primary: ComputedStyle, /// A list of the styles for the element's eagerly-cascaded pseudo-elements. pub pseudos: EagerPseudoStyles, /// NB: This is an empty field for gecko. pub cached_pseudos: PseudoElementCache, } impl ElementStyles { /// Trivially construct a new `ElementStyles`. pub fn new(primary: ComputedStyle) -> Self { ElementStyles { primary: primary, pseudos: EagerPseudoStyles(None), cached_pseudos: PseudoElementCache::default(), } } /// Whether this element `display` value is `none`. pub fn is_display_none(&self) -> bool { self.primary.values().get_box().clone_display() == display::T::none } } /// Restyle hint for storing on ElementData. /// /// We wrap it in a newtype to force the encapsulation of the complexity of /// handling the correct invalidations in this file. #[derive(Clone, Debug)] pub struct StoredRestyleHint(RestyleHint); impl StoredRestyleHint { /// Propagates this restyle hint to a child element. pub fn propagate(&mut self, traversal_flags: &TraversalFlags) -> Self { use std::mem; // In the middle of an animation only restyle, we don't need to // propagate any restyle hints, and we need to remove ourselves. if traversal_flags.for_animation_only() { self.0.remove(RestyleHint::for_animations()); return Self::empty(); } debug_assert!(!self.0.intersects(RestyleHint::for_animations()), "There should not be any animation restyle hints \ during normal traversal"); // Else we should clear ourselves, and return the propagated hint. let hint = mem::replace(&mut self.0, RestyleHint::empty()); StoredRestyleHint(if hint.contains(RESTYLE_DESCENDANTS) { RESTYLE_SELF | RESTYLE_DESCENDANTS } else { RestyleHint::empty() }) } /// Creates an empty `StoredRestyleHint`. pub fn empty() -> Self { StoredRestyleHint(RestyleHint::empty()) } /// Creates a restyle hint that forces the whole subtree to be restyled, /// including the element. pub fn subtree() -> Self { StoredRestyleHint(RESTYLE_SELF | RESTYLE_DESCENDANTS) } /// Creates a restyle hint that forces the element and all its later /// siblings to have their whole subtrees restyled, including the elements /// themselves. pub fn subtree_and_later_siblings() -> Self { StoredRestyleHint(RESTYLE_SELF | RESTYLE_DESCENDANTS | RESTYLE_LATER_SIBLINGS) } /// Returns true if the hint indicates that our style may be invalidated. pub fn has_self_invalidations(&self) -> bool { self.0.intersects(RestyleHint::for_self()) } /// Returns true if the hint indicates that our sibling's style may be /// invalidated. pub fn has_sibling_invalidations(&self) -> bool { self.0.intersects(RESTYLE_LATER_SIBLINGS) } /// Whether the restyle hint is empty (nothing requires to be restyled). pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Insert another restyle hint, effectively resulting in the union of both. pub fn insert(&mut self, other: &Self) { self.0 |= other.0 } /// Returns true if the hint has animation-only restyle. pub fn has_animation_hint(&self) -> bool { self.0.intersects(RestyleHint::for_animations()) } } impl Default for StoredRestyleHint { fn default() -> Self { StoredRestyleHint::empty() } } impl From<RestyleHint> for StoredRestyleHint { fn from(hint: RestyleHint) -> Self { StoredRestyleHint(hint) } } /// Transient data used by the restyle algorithm. This structure is instantiated /// either before or during restyle traversal, and is cleared at the end of node /// processing. #[derive(Debug, Default)] pub struct RestyleData { /// The restyle hint, which indicates whether selectors need to be rematched /// for this element, its children, and its descendants. pub hint: StoredRestyleHint, /// Whether we need to recascade. /// FIXME(bholley): This should eventually become more fine-grained. pub recascade: bool, /// The restyle damage, indicating what kind of layout changes are required /// afte restyling. pub damage: RestyleDamage, /// The restyle damage that has already been handled by our ancestors, and does /// not need to be applied again at this element. Only non-empty during the /// traversal, once ancestor damage has been calculated. /// /// Note that this optimization mostly makes sense in terms of Gecko's top-down /// frame constructor and change list processing model. We don't bother with it /// for Servo for now. #[cfg(feature = "gecko")] pub damage_handled: RestyleDamage, } impl RestyleData { /// Returns true if this RestyleData might invalidate the current style. pub fn has_invalidations(&self) -> bool { self.hint.has_self_invalidations() || self.recascade } /// Returns true if this RestyleData might invalidate sibling styles. pub fn has_sibling_invalidations(&self) -> bool { self.hint.has_sibling_invalidations() } /// Returns damage handled. #[cfg(feature = "gecko")] pub fn damage_handled(&self) -> RestyleDamage { self.damage_handled } /// Returns damage handled (always empty for servo). #[cfg(feature = "servo")] pub fn damage_handled(&self) -> RestyleDamage { RestyleDamage::empty() } /// Sets damage handled. #[cfg(feature = "gecko")] pub fn set_damage_handled(&mut self, d: RestyleDamage) { self.damage_handled = d; } /// Sets damage handled. No-op for Servo. #[cfg(feature = "servo")] pub fn set_damage_handled(&mut self, _: RestyleDamage) {} } /// Style system data associated with an Element. /// /// In Gecko, this hangs directly off the Element. Servo, this is embedded /// inside of layout data, which itself hangs directly off the Element. In /// both cases, it is wrapped inside an AtomicRefCell to ensure thread safety. #[derive(Debug)] pub struct ElementData { /// The computed styles for the element and its pseudo-elements. styles: Option<ElementStyles>, /// Restyle tracking. We separate this into a separate allocation so that /// we can drop it when no restyles are pending on the elemnt. restyle: Option<Box<RestyleData>>, } /// The kind of restyle that a single element should do. pub enum RestyleKind { /// We need to run selector matching plus re-cascade, that is, a full /// restyle. MatchAndCascade, /// We need to recascade with some replacement rule, such as the style /// attribute, or animation rules. CascadeWithReplacements(RestyleHint), /// We only need to recascade, for example, because only inherited /// properties in the parent changed. CascadeOnly, } impl ElementData { /// Computes the final restyle hint for this element, potentially allocating /// a `RestyleData` if we need to. /// /// This expands the snapshot (if any) into a restyle hint, and handles /// explicit sibling restyle hints from the stored restyle hint. /// /// Returns true if later siblings must be restyled. pub fn compute_final_hint<E: TElement>( &mut self, element: E, context: &SharedStyleContext) -> bool { debug!("compute_final_hint: {:?}, {:?}", element, context.traversal_flags); let mut hint = match self.get_restyle() { Some(r) => r.hint.0, None => RestyleHint::empty(), }; if element.has_snapshot() &&!element.handled_snapshot() { hint |= context.stylist.compute_restyle_hint(&element, context.snapshot_map); unsafe { element.set_handled_snapshot() } debug_assert!(element.handled_snapshot()); } let empty_hint = hint.is_empty(); // If the hint includes a directive for later siblings, strip it out and // notify the caller to modify the base hint for future siblings. let later_siblings = hint.contains(RESTYLE_LATER_SIBLINGS); hint.remove(RESTYLE_LATER_SIBLINGS); // Insert the hint, overriding the previous hint. This effectively takes // care of removing the later siblings restyle hint. if!empty_hint { self.ensure_restyle().hint = hint.into(); } later_siblings } /// Trivially construct an ElementData. pub fn new(existing: Option<ElementStyles>) -> Self { ElementData { styles: existing, restyle: None, } } /// Returns true if this element has a computed style. pub fn has_styles(&self) -> bool { self.styles.is_some() } /// Returns whether we have any outstanding style invalidation. pub fn has_invalidations(&self) -> bool { self.restyle.as_ref().map_or(false, |r| r.has_invalidations()) } /// Returns the kind of restyling that we're going to need to do on this /// element, based of the stored restyle hint. pub fn restyle_kind(&self) -> RestyleKind { debug_assert!(!self.has_styles() || self.has_invalidations(), "Should've stopped earlier"); if!self.has_styles() { return RestyleKind::MatchAndCascade; } debug_assert!(self.restyle.is_some()); let restyle_data = self.restyle.as_ref().unwrap(); let hint = restyle_data.hint.0; if hint.contains(RESTYLE_SELF) { return RestyleKind::MatchAndCascade; } if!hint.is_empty() { return RestyleKind::CascadeWithReplacements(hint); } debug_assert!(restyle_data.recascade, "We definitely need to do something!"); return RestyleKind::CascadeOnly; } /// Gets the element styles, if any. pub fn get_styles(&self) -> Option<&ElementStyles> { self.styles.as_ref() } /// Gets the element styles. Panic if the element has never been styled. pub fn styles(&self) -> &ElementStyles { self.styles.as_ref().expect("Calling styles() on unstyled ElementData") } /// Gets a mutable reference to the element styles, if any. pub fn get_styles_mut(&mut self) -> Option<&mut ElementStyles> { self.styles.as_mut() } /// Gets a mutable reference to the element styles. Panic if the element has /// never been styled. pub fn styles_mut(&mut self) -> &mut ElementStyles { self.styles.as_mut().expect("Calling styles_mut() on unstyled ElementData") } /// Borrows both styles and restyle mutably at the same time. pub fn styles_and_restyle_mut(&mut self) -> (&mut ElementStyles, Option<&mut RestyleData>) { (self.styles.as_mut().unwrap(), self.restyle.as_mut().map(|r| &mut **r)) } /// Sets the computed element styles. pub fn set_styles(&mut self, styles: ElementStyles) { self.styles = Some(styles); } /// Sets the computed element rules, and returns whether the rules changed. pub fn set_primary_rules(&mut self, rules: StrongRuleNode) -> bool { if!self.has_styles() { self.set_styles(ElementStyles::new(ComputedStyle::new_partial(rules))); return true; } if self.styles().primary.rules == rules { return false; } self.styles_mut().primary.rules = rules; true } /// Returns true if the Element has a RestyleData. pub fn has_restyle(&self) -> bool { self.restyle.is_some() } /// Drops any RestyleData. pub fn clear_restyle(&mut self) { self.restyle = None; } /// Creates a RestyleData if one doesn't exist. /// /// Asserts that the Element has been styled. pub fn ensure_restyle(&mut self) -> &mut RestyleData { debug_assert!(self.styles.is_some(), "restyling unstyled element"); if self.restyle.is_none() { self.restyle = Some(Box::new(RestyleData::default())); } self.restyle.as_mut().unwrap() } /// Gets a reference to the restyle data, if any. pub fn get_restyle(&self) -> Option<&RestyleData> { self.restyle.as_ref().map(|r| &**r) } /// Gets a reference to the restyle data. Panic if the element does not /// have restyle data. pub fn restyle(&self) -> &RestyleData { self.get_restyle().expect("Calling restyle without RestyleData") } /// Gets a mutable reference to the restyle data, if any. pub fn get_restyle_mut(&mut self) -> Option<&mut RestyleData> { self.restyle.as_mut().map(|r| &mut **r) } /// Gets a mutable reference to the restyle data. Panic if the element does /// not have restyle data. pub fn restyle_mut(&mut self) -> &mut RestyleData { self.get_restyle_mut().expect("Calling restyle_mut without RestyleData") } }
{ self.0 = None; }
conditional_block
data.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/. */ //! Per-node data used in style calculation. #![deny(missing_docs)] use context::SharedStyleContext; use dom::TElement; use properties::ComputedValues; use properties::longhands::display::computed_value as display; use restyle_hints::{RESTYLE_DESCENDANTS, RESTYLE_LATER_SIBLINGS, RESTYLE_SELF, RestyleHint}; use rule_tree::StrongRuleNode; use selector_parser::{EAGER_PSEUDO_COUNT, PseudoElement, RestyleDamage}; #[cfg(feature = "servo")] use std::collections::HashMap; use std::fmt; #[cfg(feature = "servo")] use std::hash::BuildHasherDefault; <<<<<<< HEAD use std::ops::Deref; <<<<<<< HEAD use std::sync::Arc; ======= use stylearc::Arc; >>>>>>> 896a920ff53f683cdaac8bc6b2f796633a436a7f use stylist::Stylist; use thread_state; ======= use stylearc::Arc; >>>>>>> 37d173a4d6df3b140afdaf174f12d49e77f07c86 use traversal::TraversalFlags; /// The structure that represents the result of style computation. This is /// effectively a tuple of rules and computed values, that is, the rule node, /// and the result of computing that rule node's rules, the `ComputedValues`. #[derive(Clone)] pub struct ComputedStyle { /// The rule node representing the ordered list of rules matched for this /// node. pub rules: StrongRuleNode, /// The computed values for each property obtained by cascading the /// matched rules. This can only be none during a transient interval of /// the styling algorithm, and callers can safely unwrap it. pub values: Option<Arc<ComputedValues>>, } impl ComputedStyle { /// Trivially construct a new `ComputedStyle`. pub fn new(rules: StrongRuleNode, values: Arc<ComputedValues>) -> Self { ComputedStyle { rules: rules, values: Some(values), } } /// Constructs a partial ComputedStyle, whose ComputedVaues will be filled /// in later. pub fn new_partial(rules: StrongRuleNode) -> Self { ComputedStyle { rules: rules, values: None, } } /// Returns a reference to the ComputedValues. The values can only be null during /// the styling algorithm, so this is safe to call elsewhere. pub fn values(&self) -> &Arc<ComputedValues> { self.values.as_ref().unwrap() } /// Mutable version of the above. pub fn values_mut(&mut self) -> &mut Arc<ComputedValues> { self.values.as_mut().unwrap() } } // We manually implement Debug for ComputedStyle so that we can avoid the // verbose stringification of ComputedValues for normal logging. impl fmt::Debug for ComputedStyle { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ComputedStyle {{ rules: {:?}, values: {{..}} }}", self.rules) } } /// A list of styles for eagerly-cascaded pseudo-elements. Lazily-allocated. #[derive(Clone, Debug)] pub struct EagerPseudoStyles(Option<Box<[Option<ComputedStyle>]>>); impl EagerPseudoStyles { /// Returns whether there are any pseudo styles. pub fn is_empty(&self) -> bool { <<<<<<< HEAD self.0.is_some() ======= self.0.is_none() >>>>>>> 896a920ff53f683cdaac8bc6b2f796633a436a7f } /// Returns a reference to the style for a given eager pseudo, if it exists. pub fn get(&self, pseudo: &PseudoElement) -> Option<&ComputedStyle> { debug_assert!(pseudo.is_eager()); self.0.as_ref().and_then(|p| p[pseudo.eager_index()].as_ref()) } /// Returns a mutable reference to the style for a given eager pseudo, if it exists. pub fn get_mut(&mut self, pseudo: &PseudoElement) -> Option<&mut ComputedStyle> { debug_assert!(pseudo.is_eager()); self.0.as_mut().and_then(|p| p[pseudo.eager_index()].as_mut()) } <<<<<<< HEAD /// Returns true if the EagerPseudoStyles has a ComputedStyle for |pseudo|. pub fn has(&self, pseudo: &PseudoElement) -> bool { self.get(pseudo).is_some() } /// Inserts a pseudo-element. The pseudo-element must not already exist. pub fn insert(&mut self, pseudo: &PseudoElement, style: ComputedStyle) { debug_assert!(!self.has(pseudo)); if self.0.is_none() { self.0 = Some(vec![None; EAGER_PSEUDO_COUNT].into_boxed_slice()); } self.0.as_mut().unwrap()[pseudo.eager_index()] = Some(style); } /// Removes a pseudo-element style if it exists, and returns it. pub fn take(&mut self, pseudo: &PseudoElement) -> Option<ComputedStyle> { let result = match self.0.as_mut() { None => return None, Some(arr) => arr[pseudo.eager_index()].take(), }; let empty = self.0.as_ref().unwrap().iter().all(|x| x.is_none()); if empty { self.0 = None; } result } /// Returns a list of the pseudo-elements. pub fn keys(&self) -> Vec<PseudoElement> { let mut v = Vec::new(); if let Some(ref arr) = self.0 { for i in 0..EAGER_PSEUDO_COUNT { if arr[i].is_some() { v.push(PseudoElement::from_eager_index(i)); } } } v } ======= /// Returns true if the EagerPseudoStyles has a ComputedStyle for |pseudo|. pub fn has(&self, pseudo: &PseudoElement) -> bool { self.get(pseudo).is_some() } /// Inserts a pseudo-element. The pseudo-element must not already exist. pub fn insert(&mut self, pseudo: &PseudoElement, style: ComputedStyle) { debug_assert!(!self.has(pseudo)); if self.0.is_none() { self.0 = Some(vec![None; EAGER_PSEUDO_COUNT].into_boxed_slice()); } self.0.as_mut().unwrap()[pseudo.eager_index()] = Some(style); } /// Removes a pseudo-element style if it exists, and returns it. pub fn take(&mut self, pseudo: &PseudoElement) -> Option<ComputedStyle> { let result = match self.0.as_mut() { None => return None, Some(arr) => arr[pseudo.eager_index()].take(), }; let empty = self.0.as_ref().unwrap().iter().all(|x| x.is_none()); if empty { self.0 = None; } result } /// Returns a list of the pseudo-elements. pub fn keys(&self) -> Vec<PseudoElement> { let mut v = Vec::new(); if let Some(ref arr) = self.0 { for i in 0..EAGER_PSEUDO_COUNT { if arr[i].is_some() { v.push(PseudoElement::from_eager_index(i)); } } } v } >>>>>>> 896a920ff53f683cdaac8bc6b2f796633a436a7f /// Sets the rule node for a given pseudo-element, which must already have an entry. /// /// Returns true if the rule node changed. pub fn set_rules(&mut self, pseudo: &PseudoElement, rules: StrongRuleNode) -> bool { debug_assert!(self.has(pseudo)); let mut style = self.get_mut(pseudo).unwrap(); let changed = style.rules!= rules; style.rules = rules; changed } } /// A cache of precomputed and lazy pseudo-elements, used by servo. This isn't /// a very efficient design, but is the result of servo having previously used /// the eager pseudo map (when it was a map) for this cache. #[cfg(feature = "servo")] type PseudoElementCache = HashMap<PseudoElement, ComputedStyle, BuildHasherDefault<::fnv::FnvHasher>>; #[cfg(feature = "gecko")] type PseudoElementCache = (); /// The styles associated with a node, including the styles for any /// pseudo-elements. #[derive(Clone, Debug)] pub struct ElementStyles { /// The element's style. pub primary: ComputedStyle, /// A list of the styles for the element's eagerly-cascaded pseudo-elements. pub pseudos: EagerPseudoStyles, /// NB: This is an empty field for gecko. pub cached_pseudos: PseudoElementCache, } impl ElementStyles { /// Trivially construct a new `ElementStyles`. pub fn new(primary: ComputedStyle) -> Self { ElementStyles { primary: primary, pseudos: EagerPseudoStyles(None),
/// Whether this element `display` value is `none`. pub fn is_display_none(&self) -> bool { self.primary.values().get_box().clone_display() == display::T::none } } /// Restyle hint for storing on ElementData. /// /// We wrap it in a newtype to force the encapsulation of the complexity of /// handling the correct invalidations in this file. #[derive(Clone, Debug)] pub struct StoredRestyleHint(RestyleHint); impl StoredRestyleHint { /// Propagates this restyle hint to a child element. pub fn propagate(&mut self, traversal_flags: &TraversalFlags) -> Self { use std::mem; // In the middle of an animation only restyle, we don't need to // propagate any restyle hints, and we need to remove ourselves. if traversal_flags.for_animation_only() { self.0.remove(RestyleHint::for_animations()); return Self::empty(); } debug_assert!(!self.0.intersects(RestyleHint::for_animations()), "There should not be any animation restyle hints \ during normal traversal"); // Else we should clear ourselves, and return the propagated hint. let hint = mem::replace(&mut self.0, RestyleHint::empty()); StoredRestyleHint(if hint.contains(RESTYLE_DESCENDANTS) { RESTYLE_SELF | RESTYLE_DESCENDANTS } else { RestyleHint::empty() }) } /// Creates an empty `StoredRestyleHint`. pub fn empty() -> Self { StoredRestyleHint(RestyleHint::empty()) } /// Creates a restyle hint that forces the whole subtree to be restyled, /// including the element. pub fn subtree() -> Self { StoredRestyleHint(RESTYLE_SELF | RESTYLE_DESCENDANTS) } /// Creates a restyle hint that forces the element and all its later /// siblings to have their whole subtrees restyled, including the elements /// themselves. pub fn subtree_and_later_siblings() -> Self { StoredRestyleHint(RESTYLE_SELF | RESTYLE_DESCENDANTS | RESTYLE_LATER_SIBLINGS) } /// Returns true if the hint indicates that our style may be invalidated. pub fn has_self_invalidations(&self) -> bool { self.0.intersects(RestyleHint::for_self()) } /// Returns true if the hint indicates that our sibling's style may be /// invalidated. pub fn has_sibling_invalidations(&self) -> bool { self.0.intersects(RESTYLE_LATER_SIBLINGS) } /// Whether the restyle hint is empty (nothing requires to be restyled). pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Insert another restyle hint, effectively resulting in the union of both. pub fn insert(&mut self, other: &Self) { self.0 |= other.0 } /// Returns true if the hint has animation-only restyle. pub fn has_animation_hint(&self) -> bool { self.0.intersects(RestyleHint::for_animations()) } } impl Default for StoredRestyleHint { fn default() -> Self { StoredRestyleHint::empty() } } impl From<RestyleHint> for StoredRestyleHint { fn from(hint: RestyleHint) -> Self { StoredRestyleHint(hint) } } /// Transient data used by the restyle algorithm. This structure is instantiated /// either before or during restyle traversal, and is cleared at the end of node /// processing. #[derive(Debug, Default)] pub struct RestyleData { /// The restyle hint, which indicates whether selectors need to be rematched /// for this element, its children, and its descendants. pub hint: StoredRestyleHint, /// Whether we need to recascade. /// FIXME(bholley): This should eventually become more fine-grained. pub recascade: bool, /// The restyle damage, indicating what kind of layout changes are required /// afte restyling. pub damage: RestyleDamage, /// The restyle damage that has already been handled by our ancestors, and does /// not need to be applied again at this element. Only non-empty during the /// traversal, once ancestor damage has been calculated. /// /// Note that this optimization mostly makes sense in terms of Gecko's top-down /// frame constructor and change list processing model. We don't bother with it /// for Servo for now. #[cfg(feature = "gecko")] pub damage_handled: RestyleDamage, } impl RestyleData { /// Returns true if this RestyleData might invalidate the current style. pub fn has_invalidations(&self) -> bool { self.hint.has_self_invalidations() || self.recascade } /// Returns true if this RestyleData might invalidate sibling styles. pub fn has_sibling_invalidations(&self) -> bool { self.hint.has_sibling_invalidations() } /// Returns damage handled. #[cfg(feature = "gecko")] pub fn damage_handled(&self) -> RestyleDamage { self.damage_handled } /// Returns damage handled (always empty for servo). #[cfg(feature = "servo")] pub fn damage_handled(&self) -> RestyleDamage { RestyleDamage::empty() } /// Sets damage handled. #[cfg(feature = "gecko")] pub fn set_damage_handled(&mut self, d: RestyleDamage) { self.damage_handled = d; } /// Sets damage handled. No-op for Servo. #[cfg(feature = "servo")] pub fn set_damage_handled(&mut self, _: RestyleDamage) {} } /// Style system data associated with an Element. /// /// In Gecko, this hangs directly off the Element. Servo, this is embedded /// inside of layout data, which itself hangs directly off the Element. In /// both cases, it is wrapped inside an AtomicRefCell to ensure thread safety. #[derive(Debug)] pub struct ElementData { /// The computed styles for the element and its pseudo-elements. styles: Option<ElementStyles>, /// Restyle tracking. We separate this into a separate allocation so that /// we can drop it when no restyles are pending on the elemnt. restyle: Option<Box<RestyleData>>, } /// The kind of restyle that a single element should do. pub enum RestyleKind { /// We need to run selector matching plus re-cascade, that is, a full /// restyle. MatchAndCascade, /// We need to recascade with some replacement rule, such as the style /// attribute, or animation rules. CascadeWithReplacements(RestyleHint), /// We only need to recascade, for example, because only inherited /// properties in the parent changed. CascadeOnly, } impl ElementData { /// Computes the final restyle hint for this element, potentially allocating /// a `RestyleData` if we need to. /// /// This expands the snapshot (if any) into a restyle hint, and handles /// explicit sibling restyle hints from the stored restyle hint. /// /// Returns true if later siblings must be restyled. pub fn compute_final_hint<E: TElement>( &mut self, element: E, context: &SharedStyleContext) -> bool { debug!("compute_final_hint: {:?}, {:?}", element, context.traversal_flags); let mut hint = match self.get_restyle() { Some(r) => r.hint.0, None => RestyleHint::empty(), }; if element.has_snapshot() &&!element.handled_snapshot() { hint |= context.stylist.compute_restyle_hint(&element, context.snapshot_map); unsafe { element.set_handled_snapshot() } debug_assert!(element.handled_snapshot()); } let empty_hint = hint.is_empty(); // If the hint includes a directive for later siblings, strip it out and // notify the caller to modify the base hint for future siblings. let later_siblings = hint.contains(RESTYLE_LATER_SIBLINGS); hint.remove(RESTYLE_LATER_SIBLINGS); // Insert the hint, overriding the previous hint. This effectively takes // care of removing the later siblings restyle hint. if!empty_hint { self.ensure_restyle().hint = hint.into(); } later_siblings } /// Trivially construct an ElementData. pub fn new(existing: Option<ElementStyles>) -> Self { ElementData { styles: existing, restyle: None, } } /// Returns true if this element has a computed style. pub fn has_styles(&self) -> bool { self.styles.is_some() } /// Returns whether we have any outstanding style invalidation. pub fn has_invalidations(&self) -> bool { self.restyle.as_ref().map_or(false, |r| r.has_invalidations()) } /// Returns the kind of restyling that we're going to need to do on this /// element, based of the stored restyle hint. pub fn restyle_kind(&self) -> RestyleKind { debug_assert!(!self.has_styles() || self.has_invalidations(), "Should've stopped earlier"); if!self.has_styles() { return RestyleKind::MatchAndCascade; } debug_assert!(self.restyle.is_some()); let restyle_data = self.restyle.as_ref().unwrap(); let hint = restyle_data.hint.0; if hint.contains(RESTYLE_SELF) { return RestyleKind::MatchAndCascade; } if!hint.is_empty() { return RestyleKind::CascadeWithReplacements(hint); } debug_assert!(restyle_data.recascade, "We definitely need to do something!"); return RestyleKind::CascadeOnly; } /// Gets the element styles, if any. pub fn get_styles(&self) -> Option<&ElementStyles> { self.styles.as_ref() } /// Gets the element styles. Panic if the element has never been styled. pub fn styles(&self) -> &ElementStyles { self.styles.as_ref().expect("Calling styles() on unstyled ElementData") } /// Gets a mutable reference to the element styles, if any. pub fn get_styles_mut(&mut self) -> Option<&mut ElementStyles> { self.styles.as_mut() } /// Gets a mutable reference to the element styles. Panic if the element has /// never been styled. pub fn styles_mut(&mut self) -> &mut ElementStyles { self.styles.as_mut().expect("Calling styles_mut() on unstyled ElementData") } /// Borrows both styles and restyle mutably at the same time. pub fn styles_and_restyle_mut(&mut self) -> (&mut ElementStyles, Option<&mut RestyleData>) { (self.styles.as_mut().unwrap(), self.restyle.as_mut().map(|r| &mut **r)) } /// Sets the computed element styles. pub fn set_styles(&mut self, styles: ElementStyles) { self.styles = Some(styles); } /// Sets the computed element rules, and returns whether the rules changed. pub fn set_primary_rules(&mut self, rules: StrongRuleNode) -> bool { if!self.has_styles() { self.set_styles(ElementStyles::new(ComputedStyle::new_partial(rules))); return true; } if self.styles().primary.rules == rules { return false; } self.styles_mut().primary.rules = rules; true } /// Returns true if the Element has a RestyleData. pub fn has_restyle(&self) -> bool { self.restyle.is_some() } /// Drops any RestyleData. pub fn clear_restyle(&mut self) { self.restyle = None; } /// Creates a RestyleData if one doesn't exist. /// /// Asserts that the Element has been styled. pub fn ensure_restyle(&mut self) -> &mut RestyleData { debug_assert!(self.styles.is_some(), "restyling unstyled element"); if self.restyle.is_none() { self.restyle = Some(Box::new(RestyleData::default())); } self.restyle.as_mut().unwrap() } /// Gets a reference to the restyle data, if any. pub fn get_restyle(&self) -> Option<&RestyleData> { self.restyle.as_ref().map(|r| &**r) } /// Gets a reference to the restyle data. Panic if the element does not /// have restyle data. pub fn restyle(&self) -> &RestyleData { self.get_restyle().expect("Calling restyle without RestyleData") } /// Gets a mutable reference to the restyle data, if any. pub fn get_restyle_mut(&mut self) -> Option<&mut RestyleData> { self.restyle.as_mut().map(|r| &mut **r) } /// Gets a mutable reference to the restyle data. Panic if the element does /// not have restyle data. pub fn restyle_mut(&mut self) -> &mut RestyleData { self.get_restyle_mut().expect("Calling restyle_mut without RestyleData") } }
cached_pseudos: PseudoElementCache::default(), } }
random_line_split
data.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/. */ //! Per-node data used in style calculation. #![deny(missing_docs)] use context::SharedStyleContext; use dom::TElement; use properties::ComputedValues; use properties::longhands::display::computed_value as display; use restyle_hints::{RESTYLE_DESCENDANTS, RESTYLE_LATER_SIBLINGS, RESTYLE_SELF, RestyleHint}; use rule_tree::StrongRuleNode; use selector_parser::{EAGER_PSEUDO_COUNT, PseudoElement, RestyleDamage}; #[cfg(feature = "servo")] use std::collections::HashMap; use std::fmt; #[cfg(feature = "servo")] use std::hash::BuildHasherDefault; <<<<<<< HEAD use std::ops::Deref; <<<<<<< HEAD use std::sync::Arc; ======= use stylearc::Arc; >>>>>>> 896a920ff53f683cdaac8bc6b2f796633a436a7f use stylist::Stylist; use thread_state; ======= use stylearc::Arc; >>>>>>> 37d173a4d6df3b140afdaf174f12d49e77f07c86 use traversal::TraversalFlags; /// The structure that represents the result of style computation. This is /// effectively a tuple of rules and computed values, that is, the rule node, /// and the result of computing that rule node's rules, the `ComputedValues`. #[derive(Clone)] pub struct ComputedStyle { /// The rule node representing the ordered list of rules matched for this /// node. pub rules: StrongRuleNode, /// The computed values for each property obtained by cascading the /// matched rules. This can only be none during a transient interval of /// the styling algorithm, and callers can safely unwrap it. pub values: Option<Arc<ComputedValues>>, } impl ComputedStyle { /// Trivially construct a new `ComputedStyle`. pub fn new(rules: StrongRuleNode, values: Arc<ComputedValues>) -> Self { ComputedStyle { rules: rules, values: Some(values), } } /// Constructs a partial ComputedStyle, whose ComputedVaues will be filled /// in later. pub fn new_partial(rules: StrongRuleNode) -> Self { ComputedStyle { rules: rules, values: None, } } /// Returns a reference to the ComputedValues. The values can only be null during /// the styling algorithm, so this is safe to call elsewhere. pub fn values(&self) -> &Arc<ComputedValues> { self.values.as_ref().unwrap() } /// Mutable version of the above. pub fn values_mut(&mut self) -> &mut Arc<ComputedValues> { self.values.as_mut().unwrap() } } // We manually implement Debug for ComputedStyle so that we can avoid the // verbose stringification of ComputedValues for normal logging. impl fmt::Debug for ComputedStyle { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ComputedStyle {{ rules: {:?}, values: {{..}} }}", self.rules) } } /// A list of styles for eagerly-cascaded pseudo-elements. Lazily-allocated. #[derive(Clone, Debug)] pub struct EagerPseudoStyles(Option<Box<[Option<ComputedStyle>]>>); impl EagerPseudoStyles { /// Returns whether there are any pseudo styles. pub fn is_empty(&self) -> bool { <<<<<<< HEAD self.0.is_some() ======= self.0.is_none() >>>>>>> 896a920ff53f683cdaac8bc6b2f796633a436a7f } /// Returns a reference to the style for a given eager pseudo, if it exists. pub fn get(&self, pseudo: &PseudoElement) -> Option<&ComputedStyle> { debug_assert!(pseudo.is_eager()); self.0.as_ref().and_then(|p| p[pseudo.eager_index()].as_ref()) } /// Returns a mutable reference to the style for a given eager pseudo, if it exists. pub fn get_mut(&mut self, pseudo: &PseudoElement) -> Option<&mut ComputedStyle> { debug_assert!(pseudo.is_eager()); self.0.as_mut().and_then(|p| p[pseudo.eager_index()].as_mut()) } <<<<<<< HEAD /// Returns true if the EagerPseudoStyles has a ComputedStyle for |pseudo|. pub fn has(&self, pseudo: &PseudoElement) -> bool { self.get(pseudo).is_some() } /// Inserts a pseudo-element. The pseudo-element must not already exist. pub fn insert(&mut self, pseudo: &PseudoElement, style: ComputedStyle) { debug_assert!(!self.has(pseudo)); if self.0.is_none() { self.0 = Some(vec![None; EAGER_PSEUDO_COUNT].into_boxed_slice()); } self.0.as_mut().unwrap()[pseudo.eager_index()] = Some(style); } /// Removes a pseudo-element style if it exists, and returns it. pub fn take(&mut self, pseudo: &PseudoElement) -> Option<ComputedStyle> { let result = match self.0.as_mut() { None => return None, Some(arr) => arr[pseudo.eager_index()].take(), }; let empty = self.0.as_ref().unwrap().iter().all(|x| x.is_none()); if empty { self.0 = None; } result } /// Returns a list of the pseudo-elements. pub fn keys(&self) -> Vec<PseudoElement> { let mut v = Vec::new(); if let Some(ref arr) = self.0 { for i in 0..EAGER_PSEUDO_COUNT { if arr[i].is_some() { v.push(PseudoElement::from_eager_index(i)); } } } v } ======= /// Returns true if the EagerPseudoStyles has a ComputedStyle for |pseudo|. pub fn has(&self, pseudo: &PseudoElement) -> bool { self.get(pseudo).is_some() } /// Inserts a pseudo-element. The pseudo-element must not already exist. pub fn insert(&mut self, pseudo: &PseudoElement, style: ComputedStyle) { debug_assert!(!self.has(pseudo)); if self.0.is_none() { self.0 = Some(vec![None; EAGER_PSEUDO_COUNT].into_boxed_slice()); } self.0.as_mut().unwrap()[pseudo.eager_index()] = Some(style); } /// Removes a pseudo-element style if it exists, and returns it. pub fn take(&mut self, pseudo: &PseudoElement) -> Option<ComputedStyle> { let result = match self.0.as_mut() { None => return None, Some(arr) => arr[pseudo.eager_index()].take(), }; let empty = self.0.as_ref().unwrap().iter().all(|x| x.is_none()); if empty { self.0 = None; } result } /// Returns a list of the pseudo-elements. pub fn keys(&self) -> Vec<PseudoElement> { let mut v = Vec::new(); if let Some(ref arr) = self.0 { for i in 0..EAGER_PSEUDO_COUNT { if arr[i].is_some() { v.push(PseudoElement::from_eager_index(i)); } } } v } >>>>>>> 896a920ff53f683cdaac8bc6b2f796633a436a7f /// Sets the rule node for a given pseudo-element, which must already have an entry. /// /// Returns true if the rule node changed. pub fn set_rules(&mut self, pseudo: &PseudoElement, rules: StrongRuleNode) -> bool { debug_assert!(self.has(pseudo)); let mut style = self.get_mut(pseudo).unwrap(); let changed = style.rules!= rules; style.rules = rules; changed } } /// A cache of precomputed and lazy pseudo-elements, used by servo. This isn't /// a very efficient design, but is the result of servo having previously used /// the eager pseudo map (when it was a map) for this cache. #[cfg(feature = "servo")] type PseudoElementCache = HashMap<PseudoElement, ComputedStyle, BuildHasherDefault<::fnv::FnvHasher>>; #[cfg(feature = "gecko")] type PseudoElementCache = (); /// The styles associated with a node, including the styles for any /// pseudo-elements. #[derive(Clone, Debug)] pub struct ElementStyles { /// The element's style. pub primary: ComputedStyle, /// A list of the styles for the element's eagerly-cascaded pseudo-elements. pub pseudos: EagerPseudoStyles, /// NB: This is an empty field for gecko. pub cached_pseudos: PseudoElementCache, } impl ElementStyles { /// Trivially construct a new `ElementStyles`. pub fn new(primary: ComputedStyle) -> Self { ElementStyles { primary: primary, pseudos: EagerPseudoStyles(None), cached_pseudos: PseudoElementCache::default(), } } /// Whether this element `display` value is `none`. pub fn is_display_none(&self) -> bool { self.primary.values().get_box().clone_display() == display::T::none } } /// Restyle hint for storing on ElementData. /// /// We wrap it in a newtype to force the encapsulation of the complexity of /// handling the correct invalidations in this file. #[derive(Clone, Debug)] pub struct StoredRestyleHint(RestyleHint); impl StoredRestyleHint { /// Propagates this restyle hint to a child element. pub fn propagate(&mut self, traversal_flags: &TraversalFlags) -> Self { use std::mem; // In the middle of an animation only restyle, we don't need to // propagate any restyle hints, and we need to remove ourselves. if traversal_flags.for_animation_only() { self.0.remove(RestyleHint::for_animations()); return Self::empty(); } debug_assert!(!self.0.intersects(RestyleHint::for_animations()), "There should not be any animation restyle hints \ during normal traversal"); // Else we should clear ourselves, and return the propagated hint. let hint = mem::replace(&mut self.0, RestyleHint::empty()); StoredRestyleHint(if hint.contains(RESTYLE_DESCENDANTS) { RESTYLE_SELF | RESTYLE_DESCENDANTS } else { RestyleHint::empty() }) } /// Creates an empty `StoredRestyleHint`. pub fn empty() -> Self { StoredRestyleHint(RestyleHint::empty()) } /// Creates a restyle hint that forces the whole subtree to be restyled, /// including the element. pub fn subtree() -> Self { StoredRestyleHint(RESTYLE_SELF | RESTYLE_DESCENDANTS) } /// Creates a restyle hint that forces the element and all its later /// siblings to have their whole subtrees restyled, including the elements /// themselves. pub fn subtree_and_later_siblings() -> Self { StoredRestyleHint(RESTYLE_SELF | RESTYLE_DESCENDANTS | RESTYLE_LATER_SIBLINGS) } /// Returns true if the hint indicates that our style may be invalidated. pub fn
(&self) -> bool { self.0.intersects(RestyleHint::for_self()) } /// Returns true if the hint indicates that our sibling's style may be /// invalidated. pub fn has_sibling_invalidations(&self) -> bool { self.0.intersects(RESTYLE_LATER_SIBLINGS) } /// Whether the restyle hint is empty (nothing requires to be restyled). pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Insert another restyle hint, effectively resulting in the union of both. pub fn insert(&mut self, other: &Self) { self.0 |= other.0 } /// Returns true if the hint has animation-only restyle. pub fn has_animation_hint(&self) -> bool { self.0.intersects(RestyleHint::for_animations()) } } impl Default for StoredRestyleHint { fn default() -> Self { StoredRestyleHint::empty() } } impl From<RestyleHint> for StoredRestyleHint { fn from(hint: RestyleHint) -> Self { StoredRestyleHint(hint) } } /// Transient data used by the restyle algorithm. This structure is instantiated /// either before or during restyle traversal, and is cleared at the end of node /// processing. #[derive(Debug, Default)] pub struct RestyleData { /// The restyle hint, which indicates whether selectors need to be rematched /// for this element, its children, and its descendants. pub hint: StoredRestyleHint, /// Whether we need to recascade. /// FIXME(bholley): This should eventually become more fine-grained. pub recascade: bool, /// The restyle damage, indicating what kind of layout changes are required /// afte restyling. pub damage: RestyleDamage, /// The restyle damage that has already been handled by our ancestors, and does /// not need to be applied again at this element. Only non-empty during the /// traversal, once ancestor damage has been calculated. /// /// Note that this optimization mostly makes sense in terms of Gecko's top-down /// frame constructor and change list processing model. We don't bother with it /// for Servo for now. #[cfg(feature = "gecko")] pub damage_handled: RestyleDamage, } impl RestyleData { /// Returns true if this RestyleData might invalidate the current style. pub fn has_invalidations(&self) -> bool { self.hint.has_self_invalidations() || self.recascade } /// Returns true if this RestyleData might invalidate sibling styles. pub fn has_sibling_invalidations(&self) -> bool { self.hint.has_sibling_invalidations() } /// Returns damage handled. #[cfg(feature = "gecko")] pub fn damage_handled(&self) -> RestyleDamage { self.damage_handled } /// Returns damage handled (always empty for servo). #[cfg(feature = "servo")] pub fn damage_handled(&self) -> RestyleDamage { RestyleDamage::empty() } /// Sets damage handled. #[cfg(feature = "gecko")] pub fn set_damage_handled(&mut self, d: RestyleDamage) { self.damage_handled = d; } /// Sets damage handled. No-op for Servo. #[cfg(feature = "servo")] pub fn set_damage_handled(&mut self, _: RestyleDamage) {} } /// Style system data associated with an Element. /// /// In Gecko, this hangs directly off the Element. Servo, this is embedded /// inside of layout data, which itself hangs directly off the Element. In /// both cases, it is wrapped inside an AtomicRefCell to ensure thread safety. #[derive(Debug)] pub struct ElementData { /// The computed styles for the element and its pseudo-elements. styles: Option<ElementStyles>, /// Restyle tracking. We separate this into a separate allocation so that /// we can drop it when no restyles are pending on the elemnt. restyle: Option<Box<RestyleData>>, } /// The kind of restyle that a single element should do. pub enum RestyleKind { /// We need to run selector matching plus re-cascade, that is, a full /// restyle. MatchAndCascade, /// We need to recascade with some replacement rule, such as the style /// attribute, or animation rules. CascadeWithReplacements(RestyleHint), /// We only need to recascade, for example, because only inherited /// properties in the parent changed. CascadeOnly, } impl ElementData { /// Computes the final restyle hint for this element, potentially allocating /// a `RestyleData` if we need to. /// /// This expands the snapshot (if any) into a restyle hint, and handles /// explicit sibling restyle hints from the stored restyle hint. /// /// Returns true if later siblings must be restyled. pub fn compute_final_hint<E: TElement>( &mut self, element: E, context: &SharedStyleContext) -> bool { debug!("compute_final_hint: {:?}, {:?}", element, context.traversal_flags); let mut hint = match self.get_restyle() { Some(r) => r.hint.0, None => RestyleHint::empty(), }; if element.has_snapshot() &&!element.handled_snapshot() { hint |= context.stylist.compute_restyle_hint(&element, context.snapshot_map); unsafe { element.set_handled_snapshot() } debug_assert!(element.handled_snapshot()); } let empty_hint = hint.is_empty(); // If the hint includes a directive for later siblings, strip it out and // notify the caller to modify the base hint for future siblings. let later_siblings = hint.contains(RESTYLE_LATER_SIBLINGS); hint.remove(RESTYLE_LATER_SIBLINGS); // Insert the hint, overriding the previous hint. This effectively takes // care of removing the later siblings restyle hint. if!empty_hint { self.ensure_restyle().hint = hint.into(); } later_siblings } /// Trivially construct an ElementData. pub fn new(existing: Option<ElementStyles>) -> Self { ElementData { styles: existing, restyle: None, } } /// Returns true if this element has a computed style. pub fn has_styles(&self) -> bool { self.styles.is_some() } /// Returns whether we have any outstanding style invalidation. pub fn has_invalidations(&self) -> bool { self.restyle.as_ref().map_or(false, |r| r.has_invalidations()) } /// Returns the kind of restyling that we're going to need to do on this /// element, based of the stored restyle hint. pub fn restyle_kind(&self) -> RestyleKind { debug_assert!(!self.has_styles() || self.has_invalidations(), "Should've stopped earlier"); if!self.has_styles() { return RestyleKind::MatchAndCascade; } debug_assert!(self.restyle.is_some()); let restyle_data = self.restyle.as_ref().unwrap(); let hint = restyle_data.hint.0; if hint.contains(RESTYLE_SELF) { return RestyleKind::MatchAndCascade; } if!hint.is_empty() { return RestyleKind::CascadeWithReplacements(hint); } debug_assert!(restyle_data.recascade, "We definitely need to do something!"); return RestyleKind::CascadeOnly; } /// Gets the element styles, if any. pub fn get_styles(&self) -> Option<&ElementStyles> { self.styles.as_ref() } /// Gets the element styles. Panic if the element has never been styled. pub fn styles(&self) -> &ElementStyles { self.styles.as_ref().expect("Calling styles() on unstyled ElementData") } /// Gets a mutable reference to the element styles, if any. pub fn get_styles_mut(&mut self) -> Option<&mut ElementStyles> { self.styles.as_mut() } /// Gets a mutable reference to the element styles. Panic if the element has /// never been styled. pub fn styles_mut(&mut self) -> &mut ElementStyles { self.styles.as_mut().expect("Calling styles_mut() on unstyled ElementData") } /// Borrows both styles and restyle mutably at the same time. pub fn styles_and_restyle_mut(&mut self) -> (&mut ElementStyles, Option<&mut RestyleData>) { (self.styles.as_mut().unwrap(), self.restyle.as_mut().map(|r| &mut **r)) } /// Sets the computed element styles. pub fn set_styles(&mut self, styles: ElementStyles) { self.styles = Some(styles); } /// Sets the computed element rules, and returns whether the rules changed. pub fn set_primary_rules(&mut self, rules: StrongRuleNode) -> bool { if!self.has_styles() { self.set_styles(ElementStyles::new(ComputedStyle::new_partial(rules))); return true; } if self.styles().primary.rules == rules { return false; } self.styles_mut().primary.rules = rules; true } /// Returns true if the Element has a RestyleData. pub fn has_restyle(&self) -> bool { self.restyle.is_some() } /// Drops any RestyleData. pub fn clear_restyle(&mut self) { self.restyle = None; } /// Creates a RestyleData if one doesn't exist. /// /// Asserts that the Element has been styled. pub fn ensure_restyle(&mut self) -> &mut RestyleData { debug_assert!(self.styles.is_some(), "restyling unstyled element"); if self.restyle.is_none() { self.restyle = Some(Box::new(RestyleData::default())); } self.restyle.as_mut().unwrap() } /// Gets a reference to the restyle data, if any. pub fn get_restyle(&self) -> Option<&RestyleData> { self.restyle.as_ref().map(|r| &**r) } /// Gets a reference to the restyle data. Panic if the element does not /// have restyle data. pub fn restyle(&self) -> &RestyleData { self.get_restyle().expect("Calling restyle without RestyleData") } /// Gets a mutable reference to the restyle data, if any. pub fn get_restyle_mut(&mut self) -> Option<&mut RestyleData> { self.restyle.as_mut().map(|r| &mut **r) } /// Gets a mutable reference to the restyle data. Panic if the element does /// not have restyle data. pub fn restyle_mut(&mut self) -> &mut RestyleData { self.get_restyle_mut().expect("Calling restyle_mut without RestyleData") } }
has_self_invalidations
identifier_name
main.rs
#![feature(plugin, no_std, core, start, core_intrinsics)] #![crate_type="staticlib"] #![no_std] #![plugin(macro_platformtree)] extern crate zinc; #[macro_use] #[no_link] extern crate macro_platformtree; use zinc::drivers::chario::CharIO; platformtree!( tiva_c@mcu { clock { source = "MOSC"; xtal = "X16_0MHz"; pll = true; div = 5; } timer { /* The mcu contain both 16/32bit and "wide" 32/64bit timers. */ timer@w0 { /* prescale sysclk to 1Mhz since the wait code expects 1us * granularity */ prescale = 80; mode = "periodic"; } } gpio { a { uart_rx@0 { direction = "in"; function = 1; } uart_tx@1 { direction = "in"; function = 1; } } f { txled@2 { direction = "out"; } } } uart { uart@0 { mode = "115200,8n1"; } } } os { single_task { loop = "run"; args { timer = &timer; uart = &uart; txled = &txled; uart_tx = &uart_tx; } } } ); fn run(args: &pt::run_args)
{ use zinc::hal::timer::Timer; use zinc::hal::pin::Gpio; args.uart.puts("Hello, world\r\n"); let mut i = 0; loop { args.txled.set_high(); args.uart.puts("Waiting for "); args.uart.puti(i); args.uart.puts(" seconds...\r\n"); i += 1; args.txled.set_low(); args.timer.wait(1); } }
identifier_body
main.rs
#![feature(plugin, no_std, core, start, core_intrinsics)] #![crate_type="staticlib"] #![no_std] #![plugin(macro_platformtree)] extern crate zinc; #[macro_use] #[no_link] extern crate macro_platformtree; use zinc::drivers::chario::CharIO; platformtree!( tiva_c@mcu { clock { source = "MOSC"; xtal = "X16_0MHz"; pll = true; div = 5; } timer { /* The mcu contain both 16/32bit and "wide" 32/64bit timers. */ timer@w0 { /* prescale sysclk to 1Mhz since the wait code expects 1us * granularity */ prescale = 80; mode = "periodic"; } } gpio { a { uart_rx@0 { direction = "in"; function = 1; } uart_tx@1 { direction = "in"; function = 1; } } f { txled@2 { direction = "out"; } } } uart { uart@0 { mode = "115200,8n1"; }
single_task { loop = "run"; args { timer = &timer; uart = &uart; txled = &txled; uart_tx = &uart_tx; } } } ); fn run(args: &pt::run_args) { use zinc::hal::timer::Timer; use zinc::hal::pin::Gpio; args.uart.puts("Hello, world\r\n"); let mut i = 0; loop { args.txled.set_high(); args.uart.puts("Waiting for "); args.uart.puti(i); args.uart.puts(" seconds...\r\n"); i += 1; args.txled.set_low(); args.timer.wait(1); } }
} } os {
random_line_split
main.rs
#![feature(plugin, no_std, core, start, core_intrinsics)] #![crate_type="staticlib"] #![no_std] #![plugin(macro_platformtree)] extern crate zinc; #[macro_use] #[no_link] extern crate macro_platformtree; use zinc::drivers::chario::CharIO; platformtree!( tiva_c@mcu { clock { source = "MOSC"; xtal = "X16_0MHz"; pll = true; div = 5; } timer { /* The mcu contain both 16/32bit and "wide" 32/64bit timers. */ timer@w0 { /* prescale sysclk to 1Mhz since the wait code expects 1us * granularity */ prescale = 80; mode = "periodic"; } } gpio { a { uart_rx@0 { direction = "in"; function = 1; } uart_tx@1 { direction = "in"; function = 1; } } f { txled@2 { direction = "out"; } } } uart { uart@0 { mode = "115200,8n1"; } } } os { single_task { loop = "run"; args { timer = &timer; uart = &uart; txled = &txled; uart_tx = &uart_tx; } } } ); fn
(args: &pt::run_args) { use zinc::hal::timer::Timer; use zinc::hal::pin::Gpio; args.uart.puts("Hello, world\r\n"); let mut i = 0; loop { args.txled.set_high(); args.uart.puts("Waiting for "); args.uart.puti(i); args.uart.puts(" seconds...\r\n"); i += 1; args.txled.set_low(); args.timer.wait(1); } }
run
identifier_name
program_parsers.rs
use crate::asm::directive_parsers::*; use crate::asm::instruction_parsers::*; use nom::types::CompleteStr; #[derive(Debug, PartialEq)] pub struct Program { pub instructions: Vec<Instruction>, } named!(pub program<CompleteStr, Program>, do_parse!( instructions: many1!(alt!(instruction | directive)) >> ( Program { instructions } ) ) ); #[cfg(test)] mod tests { use super::*; use crate::asm::opcode::Opcode; use crate::asm::Token; #[test] fn
() { let result = program(CompleteStr("load $i1 #42\nload $r2 #10.4\n")); assert!(result.is_ok()); let (left, program) = result.unwrap(); assert_eq!(left, CompleteStr("")); assert_eq!(2, program.instructions.len()); assert_eq!( program.instructions, vec![ Instruction::new_opcode( Token::Op { code: Opcode::LOAD }, Some(Token::IntRegister { idx: 1 }), Some(Token::Integer { value: 42 }), None ), Instruction::new_opcode( Token::Op { code: Opcode::LOAD }, Some(Token::RealRegister { idx: 2 }), Some(Token::Real { value: 10.4 }), None ), ] ) } #[test] fn test_complete_program() { let test_program = CompleteStr(".data\nhello:.str 'Hello!'\n.code\nhlt"); let result = program(test_program); assert!(result.is_ok()); } }
test_parse_program
identifier_name
program_parsers.rs
use crate::asm::directive_parsers::*; use crate::asm::instruction_parsers::*; use nom::types::CompleteStr; #[derive(Debug, PartialEq)] pub struct Program { pub instructions: Vec<Instruction>, } named!(pub program<CompleteStr, Program>, do_parse!( instructions: many1!(alt!(instruction | directive)) >> ( Program { instructions } ) )
); #[cfg(test)] mod tests { use super::*; use crate::asm::opcode::Opcode; use crate::asm::Token; #[test] fn test_parse_program() { let result = program(CompleteStr("load $i1 #42\nload $r2 #10.4\n")); assert!(result.is_ok()); let (left, program) = result.unwrap(); assert_eq!(left, CompleteStr("")); assert_eq!(2, program.instructions.len()); assert_eq!( program.instructions, vec![ Instruction::new_opcode( Token::Op { code: Opcode::LOAD }, Some(Token::IntRegister { idx: 1 }), Some(Token::Integer { value: 42 }), None ), Instruction::new_opcode( Token::Op { code: Opcode::LOAD }, Some(Token::RealRegister { idx: 2 }), Some(Token::Real { value: 10.4 }), None ), ] ) } #[test] fn test_complete_program() { let test_program = CompleteStr(".data\nhello:.str 'Hello!'\n.code\nhlt"); let result = program(test_program); assert!(result.is_ok()); } }
random_line_split
shootout-binarytrees.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. extern crate arena; use std::iter::range_step; use std::thread; use arena::TypedArena; struct Tree<'a> { l: Option<&'a Tree<'a>>, r: Option<&'a Tree<'a>>, i: i32 } fn item_check(t: &Option<&Tree>) -> i32 { match *t { None => 0, Some(&Tree { ref l, ref r, i }) => i + item_check(l) - item_check(r) } } fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: i32, depth: i32) -> Option<&'r Tree<'r>> { if depth > 0 { let t: &Tree<'r> = arena.alloc(Tree { l: bottom_up_tree(arena, 2 * item - 1, depth - 1), r: bottom_up_tree(arena, 2 * item, depth - 1), i: item }); Some(t) } else { None } } fn inner(depth: i32, iterations: i32) -> String { let mut chk = 0;
let arena = TypedArena::new(); let a = bottom_up_tree(&arena, i, depth); let b = bottom_up_tree(&arena, -i, depth); chk += item_check(&a) + item_check(&b); } format!("{}\t trees of depth {}\t check: {}", iterations * 2, depth, chk) } fn main() { let mut args = std::env::args(); let n = if std::env::var_os("RUST_BENCH").is_some() { 17 } else if args.len() <= 1 { 8 } else { args.nth(1).unwrap().parse().unwrap() }; let min_depth = 4; let max_depth = if min_depth + 2 > n {min_depth + 2} else {n}; { let arena = TypedArena::new(); let depth = max_depth + 1; let tree = bottom_up_tree(&arena, 0, depth); println!("stretch tree of depth {}\t check: {}", depth, item_check(&tree)); } let long_lived_arena = TypedArena::new(); let long_lived_tree = bottom_up_tree(&long_lived_arena, 0, max_depth); let messages = range_step(min_depth, max_depth + 1, 2).map(|depth| { use std::num::Int; let iterations = 2.pow((max_depth - depth + min_depth) as usize); thread::scoped(move || inner(depth, iterations)) }).collect::<Vec<_>>(); for message in messages { println!("{}", message.join()); } println!("long lived tree of depth {}\t check: {}", max_depth, item_check(&long_lived_tree)); }
for i in 1 .. iterations + 1 {
random_line_split
shootout-binarytrees.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. extern crate arena; use std::iter::range_step; use std::thread; use arena::TypedArena; struct
<'a> { l: Option<&'a Tree<'a>>, r: Option<&'a Tree<'a>>, i: i32 } fn item_check(t: &Option<&Tree>) -> i32 { match *t { None => 0, Some(&Tree { ref l, ref r, i }) => i + item_check(l) - item_check(r) } } fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: i32, depth: i32) -> Option<&'r Tree<'r>> { if depth > 0 { let t: &Tree<'r> = arena.alloc(Tree { l: bottom_up_tree(arena, 2 * item - 1, depth - 1), r: bottom_up_tree(arena, 2 * item, depth - 1), i: item }); Some(t) } else { None } } fn inner(depth: i32, iterations: i32) -> String { let mut chk = 0; for i in 1.. iterations + 1 { let arena = TypedArena::new(); let a = bottom_up_tree(&arena, i, depth); let b = bottom_up_tree(&arena, -i, depth); chk += item_check(&a) + item_check(&b); } format!("{}\t trees of depth {}\t check: {}", iterations * 2, depth, chk) } fn main() { let mut args = std::env::args(); let n = if std::env::var_os("RUST_BENCH").is_some() { 17 } else if args.len() <= 1 { 8 } else { args.nth(1).unwrap().parse().unwrap() }; let min_depth = 4; let max_depth = if min_depth + 2 > n {min_depth + 2} else {n}; { let arena = TypedArena::new(); let depth = max_depth + 1; let tree = bottom_up_tree(&arena, 0, depth); println!("stretch tree of depth {}\t check: {}", depth, item_check(&tree)); } let long_lived_arena = TypedArena::new(); let long_lived_tree = bottom_up_tree(&long_lived_arena, 0, max_depth); let messages = range_step(min_depth, max_depth + 1, 2).map(|depth| { use std::num::Int; let iterations = 2.pow((max_depth - depth + min_depth) as usize); thread::scoped(move || inner(depth, iterations)) }).collect::<Vec<_>>(); for message in messages { println!("{}", message.join()); } println!("long lived tree of depth {}\t check: {}", max_depth, item_check(&long_lived_tree)); }
Tree
identifier_name
shootout-binarytrees.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. extern crate arena; use std::iter::range_step; use std::thread; use arena::TypedArena; struct Tree<'a> { l: Option<&'a Tree<'a>>, r: Option<&'a Tree<'a>>, i: i32 } fn item_check(t: &Option<&Tree>) -> i32 { match *t { None => 0, Some(&Tree { ref l, ref r, i }) => i + item_check(l) - item_check(r) } } fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: i32, depth: i32) -> Option<&'r Tree<'r>> { if depth > 0 { let t: &Tree<'r> = arena.alloc(Tree { l: bottom_up_tree(arena, 2 * item - 1, depth - 1), r: bottom_up_tree(arena, 2 * item, depth - 1), i: item }); Some(t) } else
} fn inner(depth: i32, iterations: i32) -> String { let mut chk = 0; for i in 1.. iterations + 1 { let arena = TypedArena::new(); let a = bottom_up_tree(&arena, i, depth); let b = bottom_up_tree(&arena, -i, depth); chk += item_check(&a) + item_check(&b); } format!("{}\t trees of depth {}\t check: {}", iterations * 2, depth, chk) } fn main() { let mut args = std::env::args(); let n = if std::env::var_os("RUST_BENCH").is_some() { 17 } else if args.len() <= 1 { 8 } else { args.nth(1).unwrap().parse().unwrap() }; let min_depth = 4; let max_depth = if min_depth + 2 > n {min_depth + 2} else {n}; { let arena = TypedArena::new(); let depth = max_depth + 1; let tree = bottom_up_tree(&arena, 0, depth); println!("stretch tree of depth {}\t check: {}", depth, item_check(&tree)); } let long_lived_arena = TypedArena::new(); let long_lived_tree = bottom_up_tree(&long_lived_arena, 0, max_depth); let messages = range_step(min_depth, max_depth + 1, 2).map(|depth| { use std::num::Int; let iterations = 2.pow((max_depth - depth + min_depth) as usize); thread::scoped(move || inner(depth, iterations)) }).collect::<Vec<_>>(); for message in messages { println!("{}", message.join()); } println!("long lived tree of depth {}\t check: {}", max_depth, item_check(&long_lived_tree)); }
{ None }
conditional_block
shootout-binarytrees.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. extern crate arena; use std::iter::range_step; use std::thread; use arena::TypedArena; struct Tree<'a> { l: Option<&'a Tree<'a>>, r: Option<&'a Tree<'a>>, i: i32 } fn item_check(t: &Option<&Tree>) -> i32 { match *t { None => 0, Some(&Tree { ref l, ref r, i }) => i + item_check(l) - item_check(r) } } fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: i32, depth: i32) -> Option<&'r Tree<'r>> { if depth > 0 { let t: &Tree<'r> = arena.alloc(Tree { l: bottom_up_tree(arena, 2 * item - 1, depth - 1), r: bottom_up_tree(arena, 2 * item, depth - 1), i: item }); Some(t) } else { None } } fn inner(depth: i32, iterations: i32) -> String
fn main() { let mut args = std::env::args(); let n = if std::env::var_os("RUST_BENCH").is_some() { 17 } else if args.len() <= 1 { 8 } else { args.nth(1).unwrap().parse().unwrap() }; let min_depth = 4; let max_depth = if min_depth + 2 > n {min_depth + 2} else {n}; { let arena = TypedArena::new(); let depth = max_depth + 1; let tree = bottom_up_tree(&arena, 0, depth); println!("stretch tree of depth {}\t check: {}", depth, item_check(&tree)); } let long_lived_arena = TypedArena::new(); let long_lived_tree = bottom_up_tree(&long_lived_arena, 0, max_depth); let messages = range_step(min_depth, max_depth + 1, 2).map(|depth| { use std::num::Int; let iterations = 2.pow((max_depth - depth + min_depth) as usize); thread::scoped(move || inner(depth, iterations)) }).collect::<Vec<_>>(); for message in messages { println!("{}", message.join()); } println!("long lived tree of depth {}\t check: {}", max_depth, item_check(&long_lived_tree)); }
{ let mut chk = 0; for i in 1 .. iterations + 1 { let arena = TypedArena::new(); let a = bottom_up_tree(&arena, i, depth); let b = bottom_up_tree(&arena, -i, depth); chk += item_check(&a) + item_check(&b); } format!("{}\t trees of depth {}\t check: {}", iterations * 2, depth, chk) }
identifier_body
classpath.rs
// rustyVM - Java VM written in pure Rust // Copyright (c) 2013 Alexander Gessler // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // extern mod std; extern mod extra; use extra::arc::{Arc}; use std::io::{File,result, IoError}; use std::path::{PosixPath}; pub struct ClassPath { priv elems : Arc<~[~str]>, } impl ClassPath { // ---------------------------------------------- /** Convert from semicolon-separated list of paths to a ClassPath instance */ pub fn new_from_string(invar : &str) -> ClassPath { // current folder is always included let mut v = ~[~"."]; // TODO: how to construct a vector directly from an iter? for s in invar.split_str(";") .map(|s : &str| { s.trim().to_owned() }) .filter(|s : &~str| {s.len() > 0}){ v.push(s); } ClassPath { elems : Arc::new(v) } } // ---------------------------------------------- pub fn get_paths<'a>(&'a self) -> &'a ~[~str] { return self.elems.get(); } // ---------------------------------------------- /** Locate a given class (given by fully qualified name) and return * the bytes of its classfile. */ pub fn
(&self, name : &str) -> Option<~[u8]> { let cname = name.to_owned(); let pname = cname.replace(&".", "/") + ".class"; for path in self.elems.get().iter() { match result(|| { let p = *path + "/" + pname; debug!("locate class {}, trying path {}", cname, p); File::open(&PosixPath::new(p)).read_to_end() }) { Err(e) => continue, Ok(bytes) => { debug!("found.class file"); return Some(bytes) } }; } return None } } impl Clone for ClassPath { fn clone(&self) -> ClassPath { ClassPath { elems : self.elems.clone() } } } #[cfg(test)] mod tests { use classpath::*; #[test] fn test_class_path_decomposition() { let cp = ClassPath::new_from_string("~/some/other/bar; /bar/baz;dir ;"); assert_eq!(*cp.get_paths(),~[~".",~"~/some/other/bar", ~"/bar/baz", ~"dir"]); assert_eq!(*cp.get_paths(),~[~".",~"~/some/other/bar", ~"/bar/baz", ~"dir"]); } }
locate_and_read
identifier_name
classpath.rs
// rustyVM - Java VM written in pure Rust // Copyright (c) 2013 Alexander Gessler // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // extern mod std; extern mod extra; use extra::arc::{Arc}; use std::io::{File,result, IoError}; use std::path::{PosixPath}; pub struct ClassPath { priv elems : Arc<~[~str]>, } impl ClassPath { // ---------------------------------------------- /** Convert from semicolon-separated list of paths to a ClassPath instance */ pub fn new_from_string(invar : &str) -> ClassPath { // current folder is always included let mut v = ~[~"."]; // TODO: how to construct a vector directly from an iter? for s in invar.split_str(";") .map(|s : &str| { s.trim().to_owned() }) .filter(|s : &~str| {s.len() > 0}){ v.push(s); } ClassPath { elems : Arc::new(v) } } // ---------------------------------------------- pub fn get_paths<'a>(&'a self) -> &'a ~[~str] { return self.elems.get(); } // ---------------------------------------------- /** Locate a given class (given by fully qualified name) and return * the bytes of its classfile. */ pub fn locate_and_read(&self, name : &str) -> Option<~[u8]>
} impl Clone for ClassPath { fn clone(&self) -> ClassPath { ClassPath { elems : self.elems.clone() } } } #[cfg(test)] mod tests { use classpath::*; #[test] fn test_class_path_decomposition() { let cp = ClassPath::new_from_string("~/some/other/bar; /bar/baz;dir ;"); assert_eq!(*cp.get_paths(),~[~".",~"~/some/other/bar", ~"/bar/baz", ~"dir"]); assert_eq!(*cp.get_paths(),~[~".",~"~/some/other/bar", ~"/bar/baz", ~"dir"]); } }
{ let cname = name.to_owned(); let pname = cname.replace(&".", "/") + ".class"; for path in self.elems.get().iter() { match result(|| { let p = *path + "/" + pname; debug!("locate class {}, trying path {}", cname, p); File::open(&PosixPath::new(p)).read_to_end() }) { Err(e) => continue, Ok(bytes) => { debug!("found .class file"); return Some(bytes) } }; } return None }
identifier_body
classpath.rs
// rustyVM - Java VM written in pure Rust // Copyright (c) 2013 Alexander Gessler // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // extern mod std; extern mod extra; use extra::arc::{Arc}; use std::io::{File,result, IoError}; use std::path::{PosixPath}; pub struct ClassPath { priv elems : Arc<~[~str]>, }
impl ClassPath { // ---------------------------------------------- /** Convert from semicolon-separated list of paths to a ClassPath instance */ pub fn new_from_string(invar : &str) -> ClassPath { // current folder is always included let mut v = ~[~"."]; // TODO: how to construct a vector directly from an iter? for s in invar.split_str(";") .map(|s : &str| { s.trim().to_owned() }) .filter(|s : &~str| {s.len() > 0}){ v.push(s); } ClassPath { elems : Arc::new(v) } } // ---------------------------------------------- pub fn get_paths<'a>(&'a self) -> &'a ~[~str] { return self.elems.get(); } // ---------------------------------------------- /** Locate a given class (given by fully qualified name) and return * the bytes of its classfile. */ pub fn locate_and_read(&self, name : &str) -> Option<~[u8]> { let cname = name.to_owned(); let pname = cname.replace(&".", "/") + ".class"; for path in self.elems.get().iter() { match result(|| { let p = *path + "/" + pname; debug!("locate class {}, trying path {}", cname, p); File::open(&PosixPath::new(p)).read_to_end() }) { Err(e) => continue, Ok(bytes) => { debug!("found.class file"); return Some(bytes) } }; } return None } } impl Clone for ClassPath { fn clone(&self) -> ClassPath { ClassPath { elems : self.elems.clone() } } } #[cfg(test)] mod tests { use classpath::*; #[test] fn test_class_path_decomposition() { let cp = ClassPath::new_from_string("~/some/other/bar; /bar/baz;dir ;"); assert_eq!(*cp.get_paths(),~[~".",~"~/some/other/bar", ~"/bar/baz", ~"dir"]); assert_eq!(*cp.get_paths(),~[~".",~"~/some/other/bar", ~"/bar/baz", ~"dir"]); } }
random_line_split
extension.rs
use std::borrow::Cow; #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum Extension<'s> { FlatUsage(Cow<'s, str>), Hierarchy, NoBody, Other(Cow<'s, str>, Cow<'s, str>), } impl Extension<'_> { pub fn key(&self) -> &'_ str { match self { Extension::Other(k, _) => k, Extension::FlatUsage(..) => "flat_usage", Extension::Hierarchy => "hierarchy", Extension::NoBody => "no_body", } } pub fn value(&self) -> &'_ str { match self { Extension::Other(_, v) | Extension::FlatUsage(v) => v, Extension::Hierarchy | Extension::NoBody => "1", } } pub fn to_cow(&self) -> Cow<'_, str> { use crate::encoding::encode; // This avoids encoding known extensions by issuing the final "encoded" form. match self { Extension::Other(k, v) => encode(k) + "=" + encode(v), Extension::FlatUsage(value) => Cow::from("flat_usage=") + value.as_ref(), Extension::Hierarchy => "hierarchy=1".into(), Extension::NoBody => "no_body=1".into(), } } } #[cfg(test)] // Place here methods which are only useful for tests // We need this to ensure we output the right format when "taking shortcuts". // Ideally we'd be able to ensure this at compile time via const fns. impl Extension<'_> { pub fn to_encoded_string(&self) -> String
} impl ToString for Extension<'_> { fn to_string(&self) -> String { self.to_cow().into() } } #[cfg(test)] mod tests { use super::*; // Hardcoded known extensions could contain typos and not properly encoded characters, so test them. // Perhaps at some point this could be statically guaranteed. #[test] fn test_to_cow_is_well_encoded() { assert_eq!(Extension::NoBody.to_cow(), Extension::NoBody.to_encoded_string()); assert_eq!(Extension::Hierarchy.to_string(), Extension::Hierarchy.to_encoded_string()); assert_eq!(Extension::FlatUsage(1.to_string().into()).to_string(), Extension::FlatUsage(1.to_string().into()).to_encoded_string()); let ext = Extension::Other("some;[]key&%1".into(), "a_^&[]%:;@value".into()); assert_eq!(ext.to_string(), ext.to_encoded_string()); } }
{ use crate::encoding::encode; [encode(self.key()), "=".into(), encode(self.value().as_ref())].concat() }
identifier_body
extension.rs
use std::borrow::Cow; #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum
<'s> { FlatUsage(Cow<'s, str>), Hierarchy, NoBody, Other(Cow<'s, str>, Cow<'s, str>), } impl Extension<'_> { pub fn key(&self) -> &'_ str { match self { Extension::Other(k, _) => k, Extension::FlatUsage(..) => "flat_usage", Extension::Hierarchy => "hierarchy", Extension::NoBody => "no_body", } } pub fn value(&self) -> &'_ str { match self { Extension::Other(_, v) | Extension::FlatUsage(v) => v, Extension::Hierarchy | Extension::NoBody => "1", } } pub fn to_cow(&self) -> Cow<'_, str> { use crate::encoding::encode; // This avoids encoding known extensions by issuing the final "encoded" form. match self { Extension::Other(k, v) => encode(k) + "=" + encode(v), Extension::FlatUsage(value) => Cow::from("flat_usage=") + value.as_ref(), Extension::Hierarchy => "hierarchy=1".into(), Extension::NoBody => "no_body=1".into(), } } } #[cfg(test)] // Place here methods which are only useful for tests // We need this to ensure we output the right format when "taking shortcuts". // Ideally we'd be able to ensure this at compile time via const fns. impl Extension<'_> { pub fn to_encoded_string(&self) -> String { use crate::encoding::encode; [encode(self.key()), "=".into(), encode(self.value().as_ref())].concat() } } impl ToString for Extension<'_> { fn to_string(&self) -> String { self.to_cow().into() } } #[cfg(test)] mod tests { use super::*; // Hardcoded known extensions could contain typos and not properly encoded characters, so test them. // Perhaps at some point this could be statically guaranteed. #[test] fn test_to_cow_is_well_encoded() { assert_eq!(Extension::NoBody.to_cow(), Extension::NoBody.to_encoded_string()); assert_eq!(Extension::Hierarchy.to_string(), Extension::Hierarchy.to_encoded_string()); assert_eq!(Extension::FlatUsage(1.to_string().into()).to_string(), Extension::FlatUsage(1.to_string().into()).to_encoded_string()); let ext = Extension::Other("some;[]key&%1".into(), "a_^&[]%:;@value".into()); assert_eq!(ext.to_string(), ext.to_encoded_string()); } }
Extension
identifier_name
extension.rs
use std::borrow::Cow; #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum Extension<'s> { FlatUsage(Cow<'s, str>), Hierarchy, NoBody, Other(Cow<'s, str>, Cow<'s, str>), } impl Extension<'_> { pub fn key(&self) -> &'_ str { match self { Extension::Other(k, _) => k, Extension::FlatUsage(..) => "flat_usage", Extension::Hierarchy => "hierarchy", Extension::NoBody => "no_body", } } pub fn value(&self) -> &'_ str { match self { Extension::Other(_, v) | Extension::FlatUsage(v) => v, Extension::Hierarchy | Extension::NoBody => "1", } } pub fn to_cow(&self) -> Cow<'_, str> { use crate::encoding::encode; // This avoids encoding known extensions by issuing the final "encoded" form. match self { Extension::Other(k, v) => encode(k) + "=" + encode(v), Extension::FlatUsage(value) => Cow::from("flat_usage=") + value.as_ref(), Extension::Hierarchy => "hierarchy=1".into(), Extension::NoBody => "no_body=1".into(), } } } #[cfg(test)] // Place here methods which are only useful for tests // We need this to ensure we output the right format when "taking shortcuts". // Ideally we'd be able to ensure this at compile time via const fns. impl Extension<'_> { pub fn to_encoded_string(&self) -> String { use crate::encoding::encode; [encode(self.key()), "=".into(), encode(self.value().as_ref())].concat() } }
impl ToString for Extension<'_> { fn to_string(&self) -> String { self.to_cow().into() } } #[cfg(test)] mod tests { use super::*; // Hardcoded known extensions could contain typos and not properly encoded characters, so test them. // Perhaps at some point this could be statically guaranteed. #[test] fn test_to_cow_is_well_encoded() { assert_eq!(Extension::NoBody.to_cow(), Extension::NoBody.to_encoded_string()); assert_eq!(Extension::Hierarchy.to_string(), Extension::Hierarchy.to_encoded_string()); assert_eq!(Extension::FlatUsage(1.to_string().into()).to_string(), Extension::FlatUsage(1.to_string().into()).to_encoded_string()); let ext = Extension::Other("some;[]key&%1".into(), "a_^&[]%:;@value".into()); assert_eq!(ext.to_string(), ext.to_encoded_string()); } }
random_line_split
issue-83760.rs
struct Struct; fn test1() { let mut val = Some(Struct); while let Some(foo) = val { //~ ERROR use of moved value if true { val = None; } else { } } } fn test2() { let mut foo = Some(Struct); let _x = foo.unwrap(); if true { foo = Some(Struct); } else { } let _y = foo; //~ ERROR use of moved value: `foo` } fn test3()
fn main() {}
{ let mut foo = Some(Struct); let _x = foo.unwrap(); if true { foo = Some(Struct); } else if true { foo = Some(Struct); } else if true { foo = Some(Struct); } else if true { foo = Some(Struct); } else { } let _y = foo; //~ ERROR use of moved value: `foo` }
identifier_body
issue-83760.rs
struct Struct; fn
() { let mut val = Some(Struct); while let Some(foo) = val { //~ ERROR use of moved value if true { val = None; } else { } } } fn test2() { let mut foo = Some(Struct); let _x = foo.unwrap(); if true { foo = Some(Struct); } else { } let _y = foo; //~ ERROR use of moved value: `foo` } fn test3() { let mut foo = Some(Struct); let _x = foo.unwrap(); if true { foo = Some(Struct); } else if true { foo = Some(Struct); } else if true { foo = Some(Struct); } else if true { foo = Some(Struct); } else { } let _y = foo; //~ ERROR use of moved value: `foo` } fn main() {}
test1
identifier_name
issue-83760.rs
struct Struct; fn test1() {
let mut val = Some(Struct); while let Some(foo) = val { //~ ERROR use of moved value if true { val = None; } else { } } } fn test2() { let mut foo = Some(Struct); let _x = foo.unwrap(); if true { foo = Some(Struct); } else { } let _y = foo; //~ ERROR use of moved value: `foo` } fn test3() { let mut foo = Some(Struct); let _x = foo.unwrap(); if true { foo = Some(Struct); } else if true { foo = Some(Struct); } else if true { foo = Some(Struct); } else if true { foo = Some(Struct); } else { } let _y = foo; //~ ERROR use of moved value: `foo` } fn main() {}
random_line_split
nullable.rs
use backend::Backend; use expression::{Expression, SelectableExpression, NonAggregate}; use query_builder::*; use types::IntoNullable; pub struct Nullable<T>(T); impl<T> Nullable<T> { pub fn new(expr: T) -> Self { Nullable(expr) } } impl<T> Expression for Nullable<T> where T: Expression, <T as Expression>::SqlType: IntoNullable, { type SqlType = <<T as Expression>::SqlType as IntoNullable>::Nullable; } impl<T, DB> QueryFragment<DB> for Nullable<T> where DB: Backend, T: QueryFragment<DB>, { fn
(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult { self.0.to_sql(out) } } impl<T, QS> SelectableExpression<QS> for Nullable<T> where T: SelectableExpression<QS>, Nullable<T>: Expression, { } impl<T> NonAggregate for Nullable<T> where T: NonAggregate, Nullable<T>: Expression, { }
to_sql
identifier_name
nullable.rs
use backend::Backend; use expression::{Expression, SelectableExpression, NonAggregate}; use query_builder::*; use types::IntoNullable; pub struct Nullable<T>(T); impl<T> Nullable<T> { pub fn new(expr: T) -> Self
} impl<T> Expression for Nullable<T> where T: Expression, <T as Expression>::SqlType: IntoNullable, { type SqlType = <<T as Expression>::SqlType as IntoNullable>::Nullable; } impl<T, DB> QueryFragment<DB> for Nullable<T> where DB: Backend, T: QueryFragment<DB>, { fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult { self.0.to_sql(out) } } impl<T, QS> SelectableExpression<QS> for Nullable<T> where T: SelectableExpression<QS>, Nullable<T>: Expression, { } impl<T> NonAggregate for Nullable<T> where T: NonAggregate, Nullable<T>: Expression, { }
{ Nullable(expr) }
identifier_body
nullable.rs
use backend::Backend; use expression::{Expression, SelectableExpression, NonAggregate}; use query_builder::*; use types::IntoNullable;
pub struct Nullable<T>(T); impl<T> Nullable<T> { pub fn new(expr: T) -> Self { Nullable(expr) } } impl<T> Expression for Nullable<T> where T: Expression, <T as Expression>::SqlType: IntoNullable, { type SqlType = <<T as Expression>::SqlType as IntoNullable>::Nullable; } impl<T, DB> QueryFragment<DB> for Nullable<T> where DB: Backend, T: QueryFragment<DB>, { fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult { self.0.to_sql(out) } } impl<T, QS> SelectableExpression<QS> for Nullable<T> where T: SelectableExpression<QS>, Nullable<T>: Expression, { } impl<T> NonAggregate for Nullable<T> where T: NonAggregate, Nullable<T>: Expression, { }
random_line_split
ci_statuses.rs
use std::collections::HashMap; use std::collections::hash_map::Entry; use std::vec::IntoIter; use git2::{ Oid, Repository, Note }; use super::{ CIStatus }; use refs; pub struct CIStatuses { iter: IntoIter<CIStatus>, } fn
(git: &Repository, id: Oid) -> Vec<CIStatus> { git.find_note(refs::CI_STATUSES, id).map(|note| from_note(id, note)).unwrap_or(Vec::new()) } fn from_note<'r>(id: Oid, note: Note<'r>) -> Vec<CIStatus> { note.message() .map(|msg| from_msg(id, msg)) .unwrap_or(Vec::new()) } fn from_msg<'r>(id: Oid, msg: &'r str) -> Vec<CIStatus> { msg.lines() .filter(|line|!line.is_empty()) .filter_map(|line| CIStatus::from_str(id, line).map_err(|e| println!("{}", e)).ok()) .collect() } fn filter_to_latest(vec: Vec<CIStatus>) -> Vec<CIStatus> { let mut unkeyed: Vec<CIStatus> = Vec::new(); let mut latest: HashMap<String, CIStatus> = HashMap::new(); for status in vec { match status.key().map(|key| key.to_string()) { Some(key) => { match latest.entry(key) { Entry::Occupied(mut entry) => { if status.timestamp() > entry.get().timestamp() { entry.insert(status); } }, Entry::Vacant(entry) => { entry.insert(status); } } }, None => { unkeyed.push(status); } } } unkeyed.into_iter().chain(latest.into_iter().map(|(_, status)| status)).collect() } impl CIStatuses { pub fn all_for_commit(git: &Repository, id: Oid) -> CIStatuses { CIStatuses::new(find_all_for_commit(git, id)) } pub fn latest_for_commit(git: &Repository, id: Oid) -> CIStatuses { CIStatuses::new(filter_to_latest(find_all_for_commit(git, id))) } fn new(vec: Vec<CIStatus>) -> CIStatuses { CIStatuses { iter: vec.into_iter(), } } } impl Iterator for CIStatuses { type Item = CIStatus; fn next(&mut self) -> Option<CIStatus> { self.iter.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } }
find_all_for_commit
identifier_name
ci_statuses.rs
use std::collections::HashMap; use std::collections::hash_map::Entry; use std::vec::IntoIter; use git2::{ Oid, Repository, Note }; use super::{ CIStatus }; use refs; pub struct CIStatuses { iter: IntoIter<CIStatus>, } fn find_all_for_commit(git: &Repository, id: Oid) -> Vec<CIStatus> { git.find_note(refs::CI_STATUSES, id).map(|note| from_note(id, note)).unwrap_or(Vec::new()) } fn from_note<'r>(id: Oid, note: Note<'r>) -> Vec<CIStatus> { note.message() .map(|msg| from_msg(id, msg)) .unwrap_or(Vec::new())
.filter_map(|line| CIStatus::from_str(id, line).map_err(|e| println!("{}", e)).ok()) .collect() } fn filter_to_latest(vec: Vec<CIStatus>) -> Vec<CIStatus> { let mut unkeyed: Vec<CIStatus> = Vec::new(); let mut latest: HashMap<String, CIStatus> = HashMap::new(); for status in vec { match status.key().map(|key| key.to_string()) { Some(key) => { match latest.entry(key) { Entry::Occupied(mut entry) => { if status.timestamp() > entry.get().timestamp() { entry.insert(status); } }, Entry::Vacant(entry) => { entry.insert(status); } } }, None => { unkeyed.push(status); } } } unkeyed.into_iter().chain(latest.into_iter().map(|(_, status)| status)).collect() } impl CIStatuses { pub fn all_for_commit(git: &Repository, id: Oid) -> CIStatuses { CIStatuses::new(find_all_for_commit(git, id)) } pub fn latest_for_commit(git: &Repository, id: Oid) -> CIStatuses { CIStatuses::new(filter_to_latest(find_all_for_commit(git, id))) } fn new(vec: Vec<CIStatus>) -> CIStatuses { CIStatuses { iter: vec.into_iter(), } } } impl Iterator for CIStatuses { type Item = CIStatus; fn next(&mut self) -> Option<CIStatus> { self.iter.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } }
} fn from_msg<'r>(id: Oid, msg: &'r str) -> Vec<CIStatus> { msg.lines() .filter(|line| !line.is_empty())
random_line_split
ci_statuses.rs
use std::collections::HashMap; use std::collections::hash_map::Entry; use std::vec::IntoIter; use git2::{ Oid, Repository, Note }; use super::{ CIStatus }; use refs; pub struct CIStatuses { iter: IntoIter<CIStatus>, } fn find_all_for_commit(git: &Repository, id: Oid) -> Vec<CIStatus>
fn from_note<'r>(id: Oid, note: Note<'r>) -> Vec<CIStatus> { note.message() .map(|msg| from_msg(id, msg)) .unwrap_or(Vec::new()) } fn from_msg<'r>(id: Oid, msg: &'r str) -> Vec<CIStatus> { msg.lines() .filter(|line|!line.is_empty()) .filter_map(|line| CIStatus::from_str(id, line).map_err(|e| println!("{}", e)).ok()) .collect() } fn filter_to_latest(vec: Vec<CIStatus>) -> Vec<CIStatus> { let mut unkeyed: Vec<CIStatus> = Vec::new(); let mut latest: HashMap<String, CIStatus> = HashMap::new(); for status in vec { match status.key().map(|key| key.to_string()) { Some(key) => { match latest.entry(key) { Entry::Occupied(mut entry) => { if status.timestamp() > entry.get().timestamp() { entry.insert(status); } }, Entry::Vacant(entry) => { entry.insert(status); } } }, None => { unkeyed.push(status); } } } unkeyed.into_iter().chain(latest.into_iter().map(|(_, status)| status)).collect() } impl CIStatuses { pub fn all_for_commit(git: &Repository, id: Oid) -> CIStatuses { CIStatuses::new(find_all_for_commit(git, id)) } pub fn latest_for_commit(git: &Repository, id: Oid) -> CIStatuses { CIStatuses::new(filter_to_latest(find_all_for_commit(git, id))) } fn new(vec: Vec<CIStatus>) -> CIStatuses { CIStatuses { iter: vec.into_iter(), } } } impl Iterator for CIStatuses { type Item = CIStatus; fn next(&mut self) -> Option<CIStatus> { self.iter.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } }
{ git.find_note(refs::CI_STATUSES, id).map(|note| from_note(id, note)).unwrap_or(Vec::new()) }
identifier_body
main.rs
extern crate clap; use std::io::prelude::*; use std::io::{Error, ErrorKind}; use std::fs::File; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Direction { Up, Down, Left, Right, } struct Key(char); impl Key { fn new() -> Key { Key('5') } fn shift_1(&self, dir: Direction) -> Key { use Direction::*; let &Key(n) = self; match dir { Up => match n as u8 - '0' as u8 { 1 | 2 | 3 => Key(n), _ => Key((n as u8 - 3) as char), }, Down => match n as u8 - '0' as u8 { 7 | 8 | 9 => Key(n), _ => Key((n as u8 + 3) as char), }, Left => match n as u8 - '0' as u8 { 1 | 4 | 7 => Key(n), _ => Key((n as u8 - 1) as char), }, Right => match n as u8 - '0' as u8 { 3 | 6 | 9 => Key(n), _ => Key((n as u8 + 1) as char), }, } } fn shift_2(&self, dir: Direction) -> Key { use Direction::*; let &Key(key) = self; match dir { Up => match key { '1' | '2' | '4' | '5' | '9' => Key(key), '3' => Key('1'), '6' => Key('2'), '7' => Key('3'), '8' => Key('4'), 'A' => Key('6'), 'B' => Key('7'), 'C' => Key('8'), 'D' => Key('B'), _ => panic!("Invalid key: {}", key) }, Down => match key { '5' | '9' | 'A' | 'C' | 'D' => Key(key), '1' => Key('3'), '2' => Key('6'), '3' => Key('7'), '4' => Key('8'), '6' => Key('A'), '7' => Key('B'), '8' => Key('C'), 'B' => Key('D'), _ => panic!("Invalid key: {}", key) }, Left => match key { '1' | '2' | '5' | 'A' | 'D' => Key(key), '3' | '4' => Key((key as u8 - 1) as char), '6'... '9' => Key((key as u8 - 1) as char), 'B' | 'C' => Key((key as u8 - 1) as char), _ => panic!("Invalid key: {}", key) }, Right => match key { '1' | '4' | '9' | 'C' | 'D' => Key(key), '2' | '3' => Key((key as u8 + 1) as char), '5'... '8' => Key((key as u8 + 1) as char), 'A' | 'B' => Key((key as u8 + 1) as char), _ => panic!("Invalid key: {}", key) }, } } } fn invalid_data(msg: &str) -> Error
fn parse_args() -> std::io::Result<Box<Read>> { let source = clap::App::new("Day 02") .author("Devon Hollowood") .arg(clap::Arg::with_name("instructions") .index(1) .short("f") .long("instructions") .help("file to read instructions from. Reads from stdin otherwise") .takes_value(true) ) .get_matches() .value_of_os("instructions") .map(|str| str.to_owned()); match source { Some(filename) => Ok(Box::new(File::open(filename)?)), None => Ok(Box::new(std::io::stdin())), } } fn read_instructions<R: Read>(source: &mut R) -> std::io::Result<Vec<Vec<Direction>>> { use Direction::*; let mut contents = String::new(); source.read_to_string(&mut contents)?; contents.lines().map( |line| line.trim().chars().map( |c| match c { 'U' => Ok(Up), 'D' => Ok(Down), 'L' => Ok(Left), 'R' => Ok(Right), _ => Err(invalid_data(&format!("Invalid direction: {}", c))), } ).collect() ).collect() } fn main() { let mut source = parse_args() .unwrap_or_else(|err| panic!("Error reading file: {}", err)); let mut keycode_1 = String::new(); let mut keycode_2 = String::new(); for key_instructions in read_instructions(&mut source) .unwrap_or_else(|err| panic!("Error reading instructions: {}", err)) { let mut current_key_1 = Key::new(); let mut current_key_2 = Key::new(); for instruction in key_instructions { current_key_1 = current_key_1.shift_1(instruction); current_key_2 = current_key_2.shift_2(instruction); } keycode_1.push(current_key_1.0); keycode_2.push(current_key_2.0); } println!("Keycode 1: {}", keycode_1); println!("Keycode 2: {}", keycode_2); }
{ Error::new(ErrorKind::InvalidData, msg) }
identifier_body
main.rs
extern crate clap; use std::io::prelude::*; use std::io::{Error, ErrorKind}; use std::fs::File; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum
{ Up, Down, Left, Right, } struct Key(char); impl Key { fn new() -> Key { Key('5') } fn shift_1(&self, dir: Direction) -> Key { use Direction::*; let &Key(n) = self; match dir { Up => match n as u8 - '0' as u8 { 1 | 2 | 3 => Key(n), _ => Key((n as u8 - 3) as char), }, Down => match n as u8 - '0' as u8 { 7 | 8 | 9 => Key(n), _ => Key((n as u8 + 3) as char), }, Left => match n as u8 - '0' as u8 { 1 | 4 | 7 => Key(n), _ => Key((n as u8 - 1) as char), }, Right => match n as u8 - '0' as u8 { 3 | 6 | 9 => Key(n), _ => Key((n as u8 + 1) as char), }, } } fn shift_2(&self, dir: Direction) -> Key { use Direction::*; let &Key(key) = self; match dir { Up => match key { '1' | '2' | '4' | '5' | '9' => Key(key), '3' => Key('1'), '6' => Key('2'), '7' => Key('3'), '8' => Key('4'), 'A' => Key('6'), 'B' => Key('7'), 'C' => Key('8'), 'D' => Key('B'), _ => panic!("Invalid key: {}", key) }, Down => match key { '5' | '9' | 'A' | 'C' | 'D' => Key(key), '1' => Key('3'), '2' => Key('6'), '3' => Key('7'), '4' => Key('8'), '6' => Key('A'), '7' => Key('B'), '8' => Key('C'), 'B' => Key('D'), _ => panic!("Invalid key: {}", key) }, Left => match key { '1' | '2' | '5' | 'A' | 'D' => Key(key), '3' | '4' => Key((key as u8 - 1) as char), '6'... '9' => Key((key as u8 - 1) as char), 'B' | 'C' => Key((key as u8 - 1) as char), _ => panic!("Invalid key: {}", key) }, Right => match key { '1' | '4' | '9' | 'C' | 'D' => Key(key), '2' | '3' => Key((key as u8 + 1) as char), '5'... '8' => Key((key as u8 + 1) as char), 'A' | 'B' => Key((key as u8 + 1) as char), _ => panic!("Invalid key: {}", key) }, } } } fn invalid_data(msg: &str) -> Error { Error::new(ErrorKind::InvalidData, msg) } fn parse_args() -> std::io::Result<Box<Read>> { let source = clap::App::new("Day 02") .author("Devon Hollowood") .arg(clap::Arg::with_name("instructions") .index(1) .short("f") .long("instructions") .help("file to read instructions from. Reads from stdin otherwise") .takes_value(true) ) .get_matches() .value_of_os("instructions") .map(|str| str.to_owned()); match source { Some(filename) => Ok(Box::new(File::open(filename)?)), None => Ok(Box::new(std::io::stdin())), } } fn read_instructions<R: Read>(source: &mut R) -> std::io::Result<Vec<Vec<Direction>>> { use Direction::*; let mut contents = String::new(); source.read_to_string(&mut contents)?; contents.lines().map( |line| line.trim().chars().map( |c| match c { 'U' => Ok(Up), 'D' => Ok(Down), 'L' => Ok(Left), 'R' => Ok(Right), _ => Err(invalid_data(&format!("Invalid direction: {}", c))), } ).collect() ).collect() } fn main() { let mut source = parse_args() .unwrap_or_else(|err| panic!("Error reading file: {}", err)); let mut keycode_1 = String::new(); let mut keycode_2 = String::new(); for key_instructions in read_instructions(&mut source) .unwrap_or_else(|err| panic!("Error reading instructions: {}", err)) { let mut current_key_1 = Key::new(); let mut current_key_2 = Key::new(); for instruction in key_instructions { current_key_1 = current_key_1.shift_1(instruction); current_key_2 = current_key_2.shift_2(instruction); } keycode_1.push(current_key_1.0); keycode_2.push(current_key_2.0); } println!("Keycode 1: {}", keycode_1); println!("Keycode 2: {}", keycode_2); }
Direction
identifier_name
main.rs
extern crate clap;
use std::io::prelude::*; use std::io::{Error, ErrorKind}; use std::fs::File; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Direction { Up, Down, Left, Right, } struct Key(char); impl Key { fn new() -> Key { Key('5') } fn shift_1(&self, dir: Direction) -> Key { use Direction::*; let &Key(n) = self; match dir { Up => match n as u8 - '0' as u8 { 1 | 2 | 3 => Key(n), _ => Key((n as u8 - 3) as char), }, Down => match n as u8 - '0' as u8 { 7 | 8 | 9 => Key(n), _ => Key((n as u8 + 3) as char), }, Left => match n as u8 - '0' as u8 { 1 | 4 | 7 => Key(n), _ => Key((n as u8 - 1) as char), }, Right => match n as u8 - '0' as u8 { 3 | 6 | 9 => Key(n), _ => Key((n as u8 + 1) as char), }, } } fn shift_2(&self, dir: Direction) -> Key { use Direction::*; let &Key(key) = self; match dir { Up => match key { '1' | '2' | '4' | '5' | '9' => Key(key), '3' => Key('1'), '6' => Key('2'), '7' => Key('3'), '8' => Key('4'), 'A' => Key('6'), 'B' => Key('7'), 'C' => Key('8'), 'D' => Key('B'), _ => panic!("Invalid key: {}", key) }, Down => match key { '5' | '9' | 'A' | 'C' | 'D' => Key(key), '1' => Key('3'), '2' => Key('6'), '3' => Key('7'), '4' => Key('8'), '6' => Key('A'), '7' => Key('B'), '8' => Key('C'), 'B' => Key('D'), _ => panic!("Invalid key: {}", key) }, Left => match key { '1' | '2' | '5' | 'A' | 'D' => Key(key), '3' | '4' => Key((key as u8 - 1) as char), '6'... '9' => Key((key as u8 - 1) as char), 'B' | 'C' => Key((key as u8 - 1) as char), _ => panic!("Invalid key: {}", key) }, Right => match key { '1' | '4' | '9' | 'C' | 'D' => Key(key), '2' | '3' => Key((key as u8 + 1) as char), '5'... '8' => Key((key as u8 + 1) as char), 'A' | 'B' => Key((key as u8 + 1) as char), _ => panic!("Invalid key: {}", key) }, } } } fn invalid_data(msg: &str) -> Error { Error::new(ErrorKind::InvalidData, msg) } fn parse_args() -> std::io::Result<Box<Read>> { let source = clap::App::new("Day 02") .author("Devon Hollowood") .arg(clap::Arg::with_name("instructions") .index(1) .short("f") .long("instructions") .help("file to read instructions from. Reads from stdin otherwise") .takes_value(true) ) .get_matches() .value_of_os("instructions") .map(|str| str.to_owned()); match source { Some(filename) => Ok(Box::new(File::open(filename)?)), None => Ok(Box::new(std::io::stdin())), } } fn read_instructions<R: Read>(source: &mut R) -> std::io::Result<Vec<Vec<Direction>>> { use Direction::*; let mut contents = String::new(); source.read_to_string(&mut contents)?; contents.lines().map( |line| line.trim().chars().map( |c| match c { 'U' => Ok(Up), 'D' => Ok(Down), 'L' => Ok(Left), 'R' => Ok(Right), _ => Err(invalid_data(&format!("Invalid direction: {}", c))), } ).collect() ).collect() } fn main() { let mut source = parse_args() .unwrap_or_else(|err| panic!("Error reading file: {}", err)); let mut keycode_1 = String::new(); let mut keycode_2 = String::new(); for key_instructions in read_instructions(&mut source) .unwrap_or_else(|err| panic!("Error reading instructions: {}", err)) { let mut current_key_1 = Key::new(); let mut current_key_2 = Key::new(); for instruction in key_instructions { current_key_1 = current_key_1.shift_1(instruction); current_key_2 = current_key_2.shift_2(instruction); } keycode_1.push(current_key_1.0); keycode_2.push(current_key_2.0); } println!("Keycode 1: {}", keycode_1); println!("Keycode 2: {}", keycode_2); }
random_line_split
poll.rs
use crate::future::FutureExt; use core::pin::Pin; use futures_core::future::Future; use futures_core::task::{Context, Poll}; /// A macro which returns the result of polling a future once within the /// current `async` context. /// /// This macro is only usable inside of `async` functions, closures, and blocks. /// It is also gated behind the `async-await` feature of this library, which is /// activated by default. /// /// If you need the result of polling a [`Stream`](crate::stream::Stream), /// you can use this macro with the [`next`](crate::stream::StreamExt::next) method: /// `poll!(stream.next())`. #[macro_export] macro_rules! poll { ($x:expr $(,)?) => { $crate::__private::async_await::poll($x).await }; } #[doc(hidden)] pub fn poll<F: Future + Unpin>(future: F) -> PollOnce<F> { PollOnce { future } } #[allow(missing_debug_implementations)] #[doc(hidden)] pub struct
<F: Future + Unpin> { future: F, } impl<F: Future + Unpin> Future for PollOnce<F> { type Output = Poll<F::Output>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { Poll::Ready(self.future.poll_unpin(cx)) } }
PollOnce
identifier_name
poll.rs
use crate::future::FutureExt; use core::pin::Pin; use futures_core::future::Future; use futures_core::task::{Context, Poll}; /// A macro which returns the result of polling a future once within the /// current `async` context. /// /// This macro is only usable inside of `async` functions, closures, and blocks. /// It is also gated behind the `async-await` feature of this library, which is /// activated by default. /// /// If you need the result of polling a [`Stream`](crate::stream::Stream), /// you can use this macro with the [`next`](crate::stream::StreamExt::next) method: /// `poll!(stream.next())`. #[macro_export] macro_rules! poll { ($x:expr $(,)?) => { $crate::__private::async_await::poll($x).await }; } #[doc(hidden)] pub fn poll<F: Future + Unpin>(future: F) -> PollOnce<F> { PollOnce { future } } #[allow(missing_debug_implementations)] #[doc(hidden)] pub struct PollOnce<F: Future + Unpin> { future: F, } impl<F: Future + Unpin> Future for PollOnce<F> { type Output = Poll<F::Output>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>
}
{ Poll::Ready(self.future.poll_unpin(cx)) }
identifier_body
poll.rs
use crate::future::FutureExt; use core::pin::Pin;
/// A macro which returns the result of polling a future once within the /// current `async` context. /// /// This macro is only usable inside of `async` functions, closures, and blocks. /// It is also gated behind the `async-await` feature of this library, which is /// activated by default. /// /// If you need the result of polling a [`Stream`](crate::stream::Stream), /// you can use this macro with the [`next`](crate::stream::StreamExt::next) method: /// `poll!(stream.next())`. #[macro_export] macro_rules! poll { ($x:expr $(,)?) => { $crate::__private::async_await::poll($x).await }; } #[doc(hidden)] pub fn poll<F: Future + Unpin>(future: F) -> PollOnce<F> { PollOnce { future } } #[allow(missing_debug_implementations)] #[doc(hidden)] pub struct PollOnce<F: Future + Unpin> { future: F, } impl<F: Future + Unpin> Future for PollOnce<F> { type Output = Poll<F::Output>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { Poll::Ready(self.future.poll_unpin(cx)) } }
use futures_core::future::Future; use futures_core::task::{Context, Poll};
random_line_split
issue-7911.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // (Closes #7911) Test that we can use the same self expression // with different mutability in macro in two methods #![allow(unused_variables)] // unused foobar_immut + foobar_mut trait FooBar { fn dummy(&self) { } } struct
(i32); struct Foo { bar: Bar } impl FooBar for Bar {} trait Test { fn get_immut(&self) -> &FooBar; fn get_mut(&mut self) -> &mut FooBar; } macro_rules! generate_test { ($type_:path, $slf:ident, $field:expr) => ( impl Test for $type_ { fn get_immut(&$slf) -> &FooBar { &$field as &FooBar } fn get_mut(&mut $slf) -> &mut FooBar { &mut $field as &mut FooBar } } )} generate_test!(Foo, self, self.bar); pub fn main() { let mut foo: Foo = Foo { bar: Bar(42) }; { let foobar_immut = foo.get_immut(); } { let foobar_mut = foo.get_mut(); } }
Bar
identifier_name
issue-7911.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // (Closes #7911) Test that we can use the same self expression // with different mutability in macro in two methods #![allow(unused_variables)] // unused foobar_immut + foobar_mut trait FooBar { fn dummy(&self)
} struct Bar(i32); struct Foo { bar: Bar } impl FooBar for Bar {} trait Test { fn get_immut(&self) -> &FooBar; fn get_mut(&mut self) -> &mut FooBar; } macro_rules! generate_test { ($type_:path, $slf:ident, $field:expr) => ( impl Test for $type_ { fn get_immut(&$slf) -> &FooBar { &$field as &FooBar } fn get_mut(&mut $slf) -> &mut FooBar { &mut $field as &mut FooBar } } )} generate_test!(Foo, self, self.bar); pub fn main() { let mut foo: Foo = Foo { bar: Bar(42) }; { let foobar_immut = foo.get_immut(); } { let foobar_mut = foo.get_mut(); } }
{ }
identifier_body
issue-7911.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass
// with different mutability in macro in two methods #![allow(unused_variables)] // unused foobar_immut + foobar_mut trait FooBar { fn dummy(&self) { } } struct Bar(i32); struct Foo { bar: Bar } impl FooBar for Bar {} trait Test { fn get_immut(&self) -> &FooBar; fn get_mut(&mut self) -> &mut FooBar; } macro_rules! generate_test { ($type_:path, $slf:ident, $field:expr) => ( impl Test for $type_ { fn get_immut(&$slf) -> &FooBar { &$field as &FooBar } fn get_mut(&mut $slf) -> &mut FooBar { &mut $field as &mut FooBar } } )} generate_test!(Foo, self, self.bar); pub fn main() { let mut foo: Foo = Foo { bar: Bar(42) }; { let foobar_immut = foo.get_immut(); } { let foobar_mut = foo.get_mut(); } }
// (Closes #7911) Test that we can use the same self expression
random_line_split
coherence-impls-copy.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. #![feature(optin_builtin_traits)] use std::marker::Copy; enum TestE { A } struct MyType; struct NotSync; impl!Sync for NotSync {} impl Copy for TestE {} impl Copy for MyType {} impl Copy for (MyType, MyType) {} //~^ ERROR E0206 impl Copy for &'static NotSync {} //~^ ERROR E0206 impl Copy for [MyType] {} //~^ ERROR E0206 impl Copy for &'static [NotSync] {} //~^ ERROR E0206 fn
() { }
main
identifier_name
coherence-impls-copy.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. #![feature(optin_builtin_traits)] use std::marker::Copy; enum TestE { A } struct MyType; struct NotSync; impl!Sync for NotSync {} impl Copy for TestE {} impl Copy for MyType {} impl Copy for (MyType, MyType) {} //~^ ERROR E0206 impl Copy for &'static NotSync {} //~^ ERROR E0206 impl Copy for [MyType] {} //~^ ERROR E0206
fn main() { }
impl Copy for &'static [NotSync] {} //~^ ERROR E0206
random_line_split
input.rs
// Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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. // // cancer 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 cancer. If not, see <http://www.gnu.org/licenses/>. use toml; use platform::{Key, key}; #[derive(PartialEq, Clone, Debug)] pub struct Input { prefix: Key, mouse: bool, locale: Option<String>, } impl Default for Input { fn default() -> Self { Input { prefix: Key::new("a".to_string().into(), key::LOGO, Default::default()), mouse: true, locale: None, } } } impl Input { pub fn load(&mut self, table: &toml::value::Table) { if let Some(value) = table.get("prefix").and_then(|v| v.as_str()) { self.prefix = to_key(value); }
self.mouse = value; } if let Some(value) = table.get("locale").and_then(|v| v.as_str()) { self.locale = Some(value.into()); } } pub fn prefix(&self) -> &Key { &self.prefix } pub fn mouse(&self) -> bool { self.mouse } pub fn locale(&self) -> Option<&str> { self.locale.as_ref().map(AsRef::as_ref) } } fn to_key<T: AsRef<str>>(value: T) -> Key { let value = value.as_ref(); let mut modifiers = value.split('-').collect::<Vec<&str>>(); let button = modifiers.pop().unwrap().to_lowercase(); let modifiers = modifiers.iter().fold(Default::default(), |acc, modifier| match *modifier { "C" => acc | key::CTRL, "A" => acc | key::ALT, "S" => acc | key::SHIFT, "L" => acc | key::LOGO, _ => acc, }); let key = match &*button { "esc" => key::Button::Escape.into(), "backspace" | "bs" => key::Button::Backspace.into(), "enter" | "return" => key::Button::Enter.into(), "delete" | "del" => key::Button::Delete.into(), "insert" | "ins" => key::Button::Insert.into(), "home" => key::Button::Home.into(), "end" => key::Button::End.into(), "pageup" | "pagup" | "pup" | "previous" | "prev" | "prior" => key::Button::PageUp.into(), "pagedown" | "pagdown" | "pdown" | "next" => key::Button::PageDown.into(), "up" => key::Button::Up.into(), "down" => key::Button::Down.into(), "right" => key::Button::Right.into(), "left" => key::Button::Left.into(), "menu" => key::Button::Menu.into(), _ => button.into() }; Key::new(key, modifiers, Default::default()) }
if let Some(value) = table.get("mouse").and_then(|v| v.as_bool()) {
random_line_split
input.rs
// Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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. // // cancer 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 cancer. If not, see <http://www.gnu.org/licenses/>. use toml; use platform::{Key, key}; #[derive(PartialEq, Clone, Debug)] pub struct Input { prefix: Key, mouse: bool, locale: Option<String>, } impl Default for Input { fn default() -> Self { Input { prefix: Key::new("a".to_string().into(), key::LOGO, Default::default()), mouse: true, locale: None, } } } impl Input { pub fn load(&mut self, table: &toml::value::Table) { if let Some(value) = table.get("prefix").and_then(|v| v.as_str()) { self.prefix = to_key(value); } if let Some(value) = table.get("mouse").and_then(|v| v.as_bool()) { self.mouse = value; } if let Some(value) = table.get("locale").and_then(|v| v.as_str()) { self.locale = Some(value.into()); } } pub fn prefix(&self) -> &Key { &self.prefix } pub fn mouse(&self) -> bool { self.mouse } pub fn locale(&self) -> Option<&str> { self.locale.as_ref().map(AsRef::as_ref) } } fn to
: AsRef<str>>(value: T) -> Key { let value = value.as_ref(); let mut modifiers = value.split('-').collect::<Vec<&str>>(); let button = modifiers.pop().unwrap().to_lowercase(); let modifiers = modifiers.iter().fold(Default::default(), |acc, modifier| match *modifier { "C" => acc | key::CTRL, "A" => acc | key::ALT, "S" => acc | key::SHIFT, "L" => acc | key::LOGO, _ => acc, }); let key = match &*button { "esc" => key::Button::Escape.into(), "backspace" | "bs" => key::Button::Backspace.into(), "enter" | "return" => key::Button::Enter.into(), "delete" | "del" => key::Button::Delete.into(), "insert" | "ins" => key::Button::Insert.into(), "home" => key::Button::Home.into(), "end" => key::Button::End.into(), "pageup" | "pagup" | "pup" | "previous" | "prev" | "prior" => key::Button::PageUp.into(), "pagedown" | "pagdown" | "pdown" | "next" => key::Button::PageDown.into(), "up" => key::Button::Up.into(), "down" => key::Button::Down.into(), "right" => key::Button::Right.into(), "left" => key::Button::Left.into(), "menu" => key::Button::Menu.into(), _ => button.into() }; Key::new(key, modifiers, Default::default()) }
_key<T
identifier_name
viewer.rs
use std::f32::consts::PI; use std::os::raw::c_void; use std::path::Path; use std::process; use std::time::Instant; use cgmath::{ Deg, Point3 }; use collision::Aabb; use gl; use gltf; use glutin; use glutin::{ Api, MouseScrollDelta, MouseButton, GlContext, GlRequest, GlProfile, VirtualKeyCode, WindowEvent, }; use glutin::dpi::PhysicalSize; use glutin::ElementState::*; use image::{DynamicImage}; use log::{error, warn, info}; use crate::controls::{OrbitControls, NavState}; use crate::controls::CameraMovement::*; use crate::framebuffer::Framebuffer; use crate::importdata::ImportData; use crate::render::*; use crate::render::math::*; use crate::utils::{print_elapsed, FrameTimer, gl_check_error, print_context_info}; // TODO!: complete and pass through draw calls? or get rid of multiple shaders? // How about state ordering anyway? // struct DrawState { // current_shader: ShaderFlags, // back_face_culling_enabled: bool // } #[derive(Copy, Clone)] pub struct CameraOptions { pub index: i32, pub position: Option<Vector3>, pub target: Option<Vector3>, pub fovy: Deg<f32>, pub straight: bool, } pub struct GltfViewer { size: PhysicalSize, dpi_factor: f64, orbit_controls: OrbitControls, events_loop: Option<glutin::EventsLoop>, gl_window: Option<glutin::GlWindow>, // TODO!: get rid of scene? root: Root, scene: Scene, delta_time: f64, // seconds last_frame: Instant, render_timer: FrameTimer, } /// Note about `headless` and `visible`: True headless rendering doesn't work on /// all operating systems, but an invisible window usually works impl GltfViewer { pub fn new( source: &str, width: u32, height: u32, headless: bool, visible: bool, camera_options: CameraOptions, scene_index: usize, ) -> GltfViewer { let gl_request = GlRequest::Specific(Api::OpenGl, (3, 3)); let gl_profile = GlProfile::Core; let (events_loop, gl_window, dpi_factor, inner_size) = if headless { let headless_context = glutin::HeadlessRendererBuilder::new(width, height) //.with_gl(gl_request) //.with_gl_profile(gl_profile) .build() .unwrap(); unsafe { headless_context.make_current().unwrap() } gl::load_with(|symbol| headless_context.get_proc_address(symbol) as *const _); let framebuffer = Framebuffer::new(width, height); framebuffer.bind(); unsafe { gl::Viewport(0, 0, width as i32, height as i32); } (None, None, 1.0, PhysicalSize::new(width as f64, height as f64)) // TODO: real height (retina? (should be the same as PhysicalSize when headless?)) } else { // glutin: initialize and configure let events_loop = glutin::EventsLoop::new(); let window_size = glutin::dpi::LogicalSize::new(width as f64, height as f64); // TODO?: hints for 4.1, core profile, forward compat let window = glutin::WindowBuilder::new() .with_title("gltf-viewer") .with_dimensions(window_size) .with_visibility(visible); let context = glutin::ContextBuilder::new() .with_gl(gl_request) .with_gl_profile(gl_profile) .with_vsync(true); let gl_window = glutin::GlWindow::new(window, context, &events_loop).unwrap(); // Real dimensions might be much higher on High-DPI displays let dpi_factor = gl_window.get_hidpi_factor(); let inner_size = gl_window.get_inner_size().unwrap().to_physical(dpi_factor); unsafe { gl_window.make_current().unwrap(); } // gl: load all OpenGL function pointers gl::load_with(|symbol| gl_window.get_proc_address(symbol) as *const _); (Some(events_loop), Some(gl_window), dpi_factor, inner_size) }; let mut orbit_controls = OrbitControls::new( Point3::new(0.0, 0.0, 2.0), inner_size); orbit_controls.camera = Camera::default(); orbit_controls.camera.fovy = camera_options.fovy; orbit_controls.camera.update_aspect_ratio(inner_size.width as f32 / inner_size.height as f32); // updates projection matrix unsafe { print_context_info(); gl::ClearColor(0.0, 1.0, 0.0, 1.0); // green for debugging gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); if headless ||!visible { // transparent background for screenshots gl::ClearColor(0.0, 0.0, 0.0, 0.0); } else { gl::ClearColor(0.1, 0.2, 0.3, 1.0); } gl::Enable(gl::DEPTH_TEST); // TODO: keyboard switch? // draw in wireframe // gl::PolygonMode(gl::FRONT_AND_BACK, gl::LINE); }; let (root, scene) = Self::load(source, scene_index); let mut viewer = GltfViewer { size: inner_size, dpi_factor, orbit_controls, events_loop, gl_window, root, scene, delta_time: 0.0, // seconds last_frame: Instant::now(), render_timer: FrameTimer::new("rendering", 300), }; unsafe { gl_check_error!(); }; if camera_options.index!= 0 && camera_options.index >= viewer.root.camera_nodes.len() as i32 { error!("No camera with index {} found in glTF file (max: {})", camera_options.index, viewer.root.camera_nodes.len() as i32 - 1); process::exit(2) } if!viewer.root.camera_nodes.is_empty() && camera_options.index!= -1 { let cam_node = &viewer.root.get_camera_node(camera_options.index as usize); let cam_node_info = format!("{} ({:?})", cam_node.index, cam_node.name); let cam = cam_node.camera.as_ref().unwrap(); info!("Using camera {} on node {}", cam.description(), cam_node_info); viewer.orbit_controls.set_camera(cam, &cam_node.final_transform); if camera_options.position.is_some() || camera_options.target.is_some() { warn!("Ignoring --cam-pos / --cam-target since --cam-index is given.") } } else { info!("Determining camera view from bounding box"); viewer.set_camera_from_bounds(camera_options.straight); if let Some(p) = camera_options.position { viewer.orbit_controls.position = Point3::from_vec(p) } if let Some(target) = camera_options.target { viewer.orbit_controls.target = Point3::from_vec(target) } } viewer } pub fn load(source: &str, scene_index: usize) -> (Root, Scene) { let mut start_time = Instant::now(); // TODO!: http source // let gltf = if source.starts_with("http") { panic!("not implemented: HTTP support temporarily removed.") // let http_source = HttpSource::new(source); // let import = gltf::Import::custom(http_source, Default::default()); // let gltf = import_gltf(import); // println!(); // to end the "progress dots" // gltf } // else { let (doc, buffers, images) = match gltf::import(source) { Ok(tuple) => tuple, Err(err) => { error!("glTF import failed: {:?}", err); if let gltf::Error::Io(_) = err { error!("Hint: Are the.bin file(s) referenced by the.gltf file available?") } process::exit(1) }, }; let imp = ImportData { doc, buffers, images }; print_elapsed("Imported glTF in ", start_time); start_time = Instant::now(); // load first scene if scene_index >= imp.doc.scenes().len() { error!("Scene index too high - file has only {} scene(s)", imp.doc.scenes().len()); process::exit(3) } let base_path = Path::new(source); let mut root = Root::from_gltf(&imp, base_path); let scene = Scene::from_gltf(&imp.doc.scenes().nth(scene_index).unwrap(), &mut root); print_elapsed(&format!("Loaded scene with {} nodes, {} meshes in ", imp.doc.nodes().count(), imp.doc.meshes().len()), start_time); (root, scene) } /// determine "nice" camera perspective from bounding box. Inspired by donmccurdy/three-gltf-viewer fn set_camera_from_bounds(&mut self, straight: bool) { let bounds = &self.scene.bounds; let size = (bounds.max - bounds.min).magnitude(); let center = bounds.center(); // TODO: x,y addition optional let cam_pos = if straight { Point3::new( center.x, center.y, center.z + size * 0.75, ) } else { Point3::new( center.x + size / 2.0, center.y + size / 5.0, center.z + size / 2.0, ) }; self.orbit_controls.position = cam_pos; self.orbit_controls.target = center; self.orbit_controls.camera.znear = size / 100.0; self.orbit_controls.camera.zfar = Some(size * 20.0); self.orbit_controls.camera.update_projection_matrix(); } pub fn start_render_loop(&mut self) { loop { // per-frame time logic // NOTE: Deliberately ignoring the seconds of `elapsed()` self.delta_time = f64::from(self.last_frame.elapsed().subsec_nanos()) / 1_000_000_000.0; self.last_frame = Instant::now(); // events let keep_running = process_events( &mut self.events_loop.as_mut().unwrap(), self.gl_window.as_mut().unwrap(), &mut self.orbit_controls, &mut self.dpi_factor, &mut self.size); if!keep_running { unsafe { gl_check_error!(); } // final error check so errors don't go unnoticed break } self.orbit_controls.frame_update(self.delta_time); // keyboard navigation self.draw(); self.gl_window.as_ref().unwrap().swap_buffers().unwrap(); } } // Returns whether to keep running pub fn draw(&mut self) { // render unsafe { self.render_timer.start(); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); let cam_params = self.orbit_controls.camera_params(); self.scene.draw(&mut self.root, &cam_params); self.render_timer.end(); } } pub fn screenshot(&mut self, filename: &str) { self.draw(); let mut img = DynamicImage::new_rgba8(self.size.width as u32, self.size.height as u32); unsafe { let pixels = img.as_mut_rgba8().unwrap(); gl::PixelStorei(gl::PACK_ALIGNMENT, 1); gl::ReadPixels(0, 0, self.size.width as i32, self.size.height as i32, gl::RGBA, gl::UNSIGNED_BYTE, pixels.as_mut_ptr() as *mut c_void); gl_check_error!(); } let img = img.flipv(); if let Err(err) = img.save(filename) { error!("{}", err); } else { println!("Saved {}x{} screenshot to {}", self.size.width, self.size.height, filename); } } pub fn multiscreenshot(&mut self, filename: &str, count: u32) { let min_angle : f32 = 0.0 ; let max_angle : f32 = 2.0 * PI ; let increment_angle : f32 = ((max_angle - min_angle)/(count as f32)) as f32; let suffix_length = count.to_string().len(); for i in 1..=count { self.orbit_controls.rotate_object(increment_angle); let dot = filename.rfind('.').unwrap_or_else(|| filename.len()); let mut actual_name = filename.to_string(); actual_name.insert_str(dot, &format!("_{:0suffix_length$}", i, suffix_length = suffix_length)); self.screenshot(&actual_name[..]); } } } #[allow(clippy::too_many_arguments)] fn process_events( events_loop: &mut glutin::EventsLoop, gl_window: &glutin::GlWindow, mut orbit_controls: &mut OrbitControls, dpi_factor: &mut f64, size: &mut PhysicalSize) -> bool { let mut keep_running = true; #[allow(clippy::single_match)] events_loop.poll_events(|event| { match event { glutin::Event::WindowEvent{ event,.. } => match event { WindowEvent::CloseRequested => { keep_running = false; }, WindowEvent::Destroyed => { // Log and exit? panic!("WindowEvent::Destroyed, unimplemented."); }, WindowEvent::Resized(logical) => { let ph = logical.to_physical(*dpi_factor); gl_window.resize(ph); // This doesn't seem to be needed on macOS but linux X11, Wayland and Windows // do need it. unsafe { gl::Viewport(0, 0, ph.width as i32, ph.height as i32); } *size = ph; orbit_controls.camera.update_aspect_ratio((ph.width / ph.height) as f32); orbit_controls.screen_size = ph; }, WindowEvent::HiDpiFactorChanged(f) => { *dpi_factor = f; }, WindowEvent::DroppedFile(_path_buf) => { // TODO: drag file in } WindowEvent::MouseInput { button, state: Pressed,..} => { match button { MouseButton::Left => { orbit_controls.state = NavState::Rotating; }, MouseButton::Right => { orbit_controls.state = NavState::Panning; }, _ => () } }, WindowEvent::MouseInput { button, state: Released,..} => { match (button, orbit_controls.state.clone()) { (MouseButton::Left, NavState::Rotating) | (MouseButton::Right, NavState::Panning) => { orbit_controls.state = NavState::None; orbit_controls.handle_mouse_up(); }, _ => () } } WindowEvent::CursorMoved { position,.. } => { let ph = position.to_physical(*dpi_factor); orbit_controls.handle_mouse_move(ph) }, WindowEvent::MouseWheel { delta: MouseScrollDelta::PixelDelta(logical),.. } => { let ph = logical.to_physical(*dpi_factor); orbit_controls.process_mouse_scroll(ph.y as f32); } WindowEvent::MouseWheel { delta: MouseScrollDelta::LineDelta(_rows, lines),.. } => { orbit_controls.process_mouse_scroll(lines * 3.0); } WindowEvent::KeyboardInput { input,.. } => { keep_running = process_input(input, &mut orbit_controls); } _ => () }, _ => () } }); keep_running } fn process_input(input: glutin::KeyboardInput, controls: &mut OrbitControls) -> bool
{ let pressed = match input.state { Pressed => true, Released => false }; if let Some(code) = input.virtual_keycode { match code { VirtualKeyCode::Escape if pressed => return false, VirtualKeyCode::W | VirtualKeyCode::Up => controls.process_keyboard(FORWARD, pressed), VirtualKeyCode::S | VirtualKeyCode::Down => controls.process_keyboard(BACKWARD, pressed), VirtualKeyCode::A | VirtualKeyCode::Left => controls.process_keyboard(LEFT, pressed), VirtualKeyCode::D | VirtualKeyCode::Right => controls.process_keyboard(RIGHT, pressed), _ => () } } true }
identifier_body
viewer.rs
use std::f32::consts::PI; use std::os::raw::c_void; use std::path::Path; use std::process; use std::time::Instant; use cgmath::{ Deg, Point3 }; use collision::Aabb; use gl; use gltf; use glutin; use glutin::{ Api, MouseScrollDelta, MouseButton, GlContext, GlRequest, GlProfile, VirtualKeyCode, WindowEvent, }; use glutin::dpi::PhysicalSize; use glutin::ElementState::*; use image::{DynamicImage}; use log::{error, warn, info}; use crate::controls::{OrbitControls, NavState}; use crate::controls::CameraMovement::*; use crate::framebuffer::Framebuffer; use crate::importdata::ImportData; use crate::render::*; use crate::render::math::*; use crate::utils::{print_elapsed, FrameTimer, gl_check_error, print_context_info}; // TODO!: complete and pass through draw calls? or get rid of multiple shaders? // How about state ordering anyway? // struct DrawState { // current_shader: ShaderFlags, // back_face_culling_enabled: bool // } #[derive(Copy, Clone)] pub struct CameraOptions { pub index: i32, pub position: Option<Vector3>, pub target: Option<Vector3>, pub fovy: Deg<f32>, pub straight: bool, } pub struct GltfViewer {
size: PhysicalSize, dpi_factor: f64, orbit_controls: OrbitControls, events_loop: Option<glutin::EventsLoop>, gl_window: Option<glutin::GlWindow>, // TODO!: get rid of scene? root: Root, scene: Scene, delta_time: f64, // seconds last_frame: Instant, render_timer: FrameTimer, } /// Note about `headless` and `visible`: True headless rendering doesn't work on /// all operating systems, but an invisible window usually works impl GltfViewer { pub fn new( source: &str, width: u32, height: u32, headless: bool, visible: bool, camera_options: CameraOptions, scene_index: usize, ) -> GltfViewer { let gl_request = GlRequest::Specific(Api::OpenGl, (3, 3)); let gl_profile = GlProfile::Core; let (events_loop, gl_window, dpi_factor, inner_size) = if headless { let headless_context = glutin::HeadlessRendererBuilder::new(width, height) //.with_gl(gl_request) //.with_gl_profile(gl_profile) .build() .unwrap(); unsafe { headless_context.make_current().unwrap() } gl::load_with(|symbol| headless_context.get_proc_address(symbol) as *const _); let framebuffer = Framebuffer::new(width, height); framebuffer.bind(); unsafe { gl::Viewport(0, 0, width as i32, height as i32); } (None, None, 1.0, PhysicalSize::new(width as f64, height as f64)) // TODO: real height (retina? (should be the same as PhysicalSize when headless?)) } else { // glutin: initialize and configure let events_loop = glutin::EventsLoop::new(); let window_size = glutin::dpi::LogicalSize::new(width as f64, height as f64); // TODO?: hints for 4.1, core profile, forward compat let window = glutin::WindowBuilder::new() .with_title("gltf-viewer") .with_dimensions(window_size) .with_visibility(visible); let context = glutin::ContextBuilder::new() .with_gl(gl_request) .with_gl_profile(gl_profile) .with_vsync(true); let gl_window = glutin::GlWindow::new(window, context, &events_loop).unwrap(); // Real dimensions might be much higher on High-DPI displays let dpi_factor = gl_window.get_hidpi_factor(); let inner_size = gl_window.get_inner_size().unwrap().to_physical(dpi_factor); unsafe { gl_window.make_current().unwrap(); } // gl: load all OpenGL function pointers gl::load_with(|symbol| gl_window.get_proc_address(symbol) as *const _); (Some(events_loop), Some(gl_window), dpi_factor, inner_size) }; let mut orbit_controls = OrbitControls::new( Point3::new(0.0, 0.0, 2.0), inner_size); orbit_controls.camera = Camera::default(); orbit_controls.camera.fovy = camera_options.fovy; orbit_controls.camera.update_aspect_ratio(inner_size.width as f32 / inner_size.height as f32); // updates projection matrix unsafe { print_context_info(); gl::ClearColor(0.0, 1.0, 0.0, 1.0); // green for debugging gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); if headless ||!visible { // transparent background for screenshots gl::ClearColor(0.0, 0.0, 0.0, 0.0); } else { gl::ClearColor(0.1, 0.2, 0.3, 1.0); } gl::Enable(gl::DEPTH_TEST); // TODO: keyboard switch? // draw in wireframe // gl::PolygonMode(gl::FRONT_AND_BACK, gl::LINE); }; let (root, scene) = Self::load(source, scene_index); let mut viewer = GltfViewer { size: inner_size, dpi_factor, orbit_controls, events_loop, gl_window, root, scene, delta_time: 0.0, // seconds last_frame: Instant::now(), render_timer: FrameTimer::new("rendering", 300), }; unsafe { gl_check_error!(); }; if camera_options.index!= 0 && camera_options.index >= viewer.root.camera_nodes.len() as i32 { error!("No camera with index {} found in glTF file (max: {})", camera_options.index, viewer.root.camera_nodes.len() as i32 - 1); process::exit(2) } if!viewer.root.camera_nodes.is_empty() && camera_options.index!= -1 { let cam_node = &viewer.root.get_camera_node(camera_options.index as usize); let cam_node_info = format!("{} ({:?})", cam_node.index, cam_node.name); let cam = cam_node.camera.as_ref().unwrap(); info!("Using camera {} on node {}", cam.description(), cam_node_info); viewer.orbit_controls.set_camera(cam, &cam_node.final_transform); if camera_options.position.is_some() || camera_options.target.is_some() { warn!("Ignoring --cam-pos / --cam-target since --cam-index is given.") } } else { info!("Determining camera view from bounding box"); viewer.set_camera_from_bounds(camera_options.straight); if let Some(p) = camera_options.position { viewer.orbit_controls.position = Point3::from_vec(p) } if let Some(target) = camera_options.target { viewer.orbit_controls.target = Point3::from_vec(target) } } viewer } pub fn load(source: &str, scene_index: usize) -> (Root, Scene) { let mut start_time = Instant::now(); // TODO!: http source // let gltf = if source.starts_with("http") { panic!("not implemented: HTTP support temporarily removed.") // let http_source = HttpSource::new(source); // let import = gltf::Import::custom(http_source, Default::default()); // let gltf = import_gltf(import); // println!(); // to end the "progress dots" // gltf } // else { let (doc, buffers, images) = match gltf::import(source) { Ok(tuple) => tuple, Err(err) => { error!("glTF import failed: {:?}", err); if let gltf::Error::Io(_) = err { error!("Hint: Are the.bin file(s) referenced by the.gltf file available?") } process::exit(1) }, }; let imp = ImportData { doc, buffers, images }; print_elapsed("Imported glTF in ", start_time); start_time = Instant::now(); // load first scene if scene_index >= imp.doc.scenes().len() { error!("Scene index too high - file has only {} scene(s)", imp.doc.scenes().len()); process::exit(3) } let base_path = Path::new(source); let mut root = Root::from_gltf(&imp, base_path); let scene = Scene::from_gltf(&imp.doc.scenes().nth(scene_index).unwrap(), &mut root); print_elapsed(&format!("Loaded scene with {} nodes, {} meshes in ", imp.doc.nodes().count(), imp.doc.meshes().len()), start_time); (root, scene) } /// determine "nice" camera perspective from bounding box. Inspired by donmccurdy/three-gltf-viewer fn set_camera_from_bounds(&mut self, straight: bool) { let bounds = &self.scene.bounds; let size = (bounds.max - bounds.min).magnitude(); let center = bounds.center(); // TODO: x,y addition optional let cam_pos = if straight { Point3::new( center.x, center.y, center.z + size * 0.75, ) } else { Point3::new( center.x + size / 2.0, center.y + size / 5.0, center.z + size / 2.0, ) }; self.orbit_controls.position = cam_pos; self.orbit_controls.target = center; self.orbit_controls.camera.znear = size / 100.0; self.orbit_controls.camera.zfar = Some(size * 20.0); self.orbit_controls.camera.update_projection_matrix(); } pub fn start_render_loop(&mut self) { loop { // per-frame time logic // NOTE: Deliberately ignoring the seconds of `elapsed()` self.delta_time = f64::from(self.last_frame.elapsed().subsec_nanos()) / 1_000_000_000.0; self.last_frame = Instant::now(); // events let keep_running = process_events( &mut self.events_loop.as_mut().unwrap(), self.gl_window.as_mut().unwrap(), &mut self.orbit_controls, &mut self.dpi_factor, &mut self.size); if!keep_running { unsafe { gl_check_error!(); } // final error check so errors don't go unnoticed break } self.orbit_controls.frame_update(self.delta_time); // keyboard navigation self.draw(); self.gl_window.as_ref().unwrap().swap_buffers().unwrap(); } } // Returns whether to keep running pub fn draw(&mut self) { // render unsafe { self.render_timer.start(); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); let cam_params = self.orbit_controls.camera_params(); self.scene.draw(&mut self.root, &cam_params); self.render_timer.end(); } } pub fn screenshot(&mut self, filename: &str) { self.draw(); let mut img = DynamicImage::new_rgba8(self.size.width as u32, self.size.height as u32); unsafe { let pixels = img.as_mut_rgba8().unwrap(); gl::PixelStorei(gl::PACK_ALIGNMENT, 1); gl::ReadPixels(0, 0, self.size.width as i32, self.size.height as i32, gl::RGBA, gl::UNSIGNED_BYTE, pixels.as_mut_ptr() as *mut c_void); gl_check_error!(); } let img = img.flipv(); if let Err(err) = img.save(filename) { error!("{}", err); } else { println!("Saved {}x{} screenshot to {}", self.size.width, self.size.height, filename); } } pub fn multiscreenshot(&mut self, filename: &str, count: u32) { let min_angle : f32 = 0.0 ; let max_angle : f32 = 2.0 * PI ; let increment_angle : f32 = ((max_angle - min_angle)/(count as f32)) as f32; let suffix_length = count.to_string().len(); for i in 1..=count { self.orbit_controls.rotate_object(increment_angle); let dot = filename.rfind('.').unwrap_or_else(|| filename.len()); let mut actual_name = filename.to_string(); actual_name.insert_str(dot, &format!("_{:0suffix_length$}", i, suffix_length = suffix_length)); self.screenshot(&actual_name[..]); } } } #[allow(clippy::too_many_arguments)] fn process_events( events_loop: &mut glutin::EventsLoop, gl_window: &glutin::GlWindow, mut orbit_controls: &mut OrbitControls, dpi_factor: &mut f64, size: &mut PhysicalSize) -> bool { let mut keep_running = true; #[allow(clippy::single_match)] events_loop.poll_events(|event| { match event { glutin::Event::WindowEvent{ event,.. } => match event { WindowEvent::CloseRequested => { keep_running = false; }, WindowEvent::Destroyed => { // Log and exit? panic!("WindowEvent::Destroyed, unimplemented."); }, WindowEvent::Resized(logical) => { let ph = logical.to_physical(*dpi_factor); gl_window.resize(ph); // This doesn't seem to be needed on macOS but linux X11, Wayland and Windows // do need it. unsafe { gl::Viewport(0, 0, ph.width as i32, ph.height as i32); } *size = ph; orbit_controls.camera.update_aspect_ratio((ph.width / ph.height) as f32); orbit_controls.screen_size = ph; }, WindowEvent::HiDpiFactorChanged(f) => { *dpi_factor = f; }, WindowEvent::DroppedFile(_path_buf) => { // TODO: drag file in } WindowEvent::MouseInput { button, state: Pressed,..} => { match button { MouseButton::Left => { orbit_controls.state = NavState::Rotating; }, MouseButton::Right => { orbit_controls.state = NavState::Panning; }, _ => () } }, WindowEvent::MouseInput { button, state: Released,..} => { match (button, orbit_controls.state.clone()) { (MouseButton::Left, NavState::Rotating) | (MouseButton::Right, NavState::Panning) => { orbit_controls.state = NavState::None; orbit_controls.handle_mouse_up(); }, _ => () } } WindowEvent::CursorMoved { position,.. } => { let ph = position.to_physical(*dpi_factor); orbit_controls.handle_mouse_move(ph) }, WindowEvent::MouseWheel { delta: MouseScrollDelta::PixelDelta(logical),.. } => { let ph = logical.to_physical(*dpi_factor); orbit_controls.process_mouse_scroll(ph.y as f32); } WindowEvent::MouseWheel { delta: MouseScrollDelta::LineDelta(_rows, lines),.. } => { orbit_controls.process_mouse_scroll(lines * 3.0); } WindowEvent::KeyboardInput { input,.. } => { keep_running = process_input(input, &mut orbit_controls); } _ => () }, _ => () } }); keep_running } fn process_input(input: glutin::KeyboardInput, controls: &mut OrbitControls) -> bool { let pressed = match input.state { Pressed => true, Released => false }; if let Some(code) = input.virtual_keycode { match code { VirtualKeyCode::Escape if pressed => return false, VirtualKeyCode::W | VirtualKeyCode::Up => controls.process_keyboard(FORWARD, pressed), VirtualKeyCode::S | VirtualKeyCode::Down => controls.process_keyboard(BACKWARD, pressed), VirtualKeyCode::A | VirtualKeyCode::Left => controls.process_keyboard(LEFT, pressed), VirtualKeyCode::D | VirtualKeyCode::Right => controls.process_keyboard(RIGHT, pressed), _ => () } } true }
random_line_split
viewer.rs
use std::f32::consts::PI; use std::os::raw::c_void; use std::path::Path; use std::process; use std::time::Instant; use cgmath::{ Deg, Point3 }; use collision::Aabb; use gl; use gltf; use glutin; use glutin::{ Api, MouseScrollDelta, MouseButton, GlContext, GlRequest, GlProfile, VirtualKeyCode, WindowEvent, }; use glutin::dpi::PhysicalSize; use glutin::ElementState::*; use image::{DynamicImage}; use log::{error, warn, info}; use crate::controls::{OrbitControls, NavState}; use crate::controls::CameraMovement::*; use crate::framebuffer::Framebuffer; use crate::importdata::ImportData; use crate::render::*; use crate::render::math::*; use crate::utils::{print_elapsed, FrameTimer, gl_check_error, print_context_info}; // TODO!: complete and pass through draw calls? or get rid of multiple shaders? // How about state ordering anyway? // struct DrawState { // current_shader: ShaderFlags, // back_face_culling_enabled: bool // } #[derive(Copy, Clone)] pub struct CameraOptions { pub index: i32, pub position: Option<Vector3>, pub target: Option<Vector3>, pub fovy: Deg<f32>, pub straight: bool, } pub struct GltfViewer { size: PhysicalSize, dpi_factor: f64, orbit_controls: OrbitControls, events_loop: Option<glutin::EventsLoop>, gl_window: Option<glutin::GlWindow>, // TODO!: get rid of scene? root: Root, scene: Scene, delta_time: f64, // seconds last_frame: Instant, render_timer: FrameTimer, } /// Note about `headless` and `visible`: True headless rendering doesn't work on /// all operating systems, but an invisible window usually works impl GltfViewer { pub fn new( source: &str, width: u32, height: u32, headless: bool, visible: bool, camera_options: CameraOptions, scene_index: usize, ) -> GltfViewer { let gl_request = GlRequest::Specific(Api::OpenGl, (3, 3)); let gl_profile = GlProfile::Core; let (events_loop, gl_window, dpi_factor, inner_size) = if headless { let headless_context = glutin::HeadlessRendererBuilder::new(width, height) //.with_gl(gl_request) //.with_gl_profile(gl_profile) .build() .unwrap(); unsafe { headless_context.make_current().unwrap() } gl::load_with(|symbol| headless_context.get_proc_address(symbol) as *const _); let framebuffer = Framebuffer::new(width, height); framebuffer.bind(); unsafe { gl::Viewport(0, 0, width as i32, height as i32); } (None, None, 1.0, PhysicalSize::new(width as f64, height as f64)) // TODO: real height (retina? (should be the same as PhysicalSize when headless?)) } else { // glutin: initialize and configure let events_loop = glutin::EventsLoop::new(); let window_size = glutin::dpi::LogicalSize::new(width as f64, height as f64); // TODO?: hints for 4.1, core profile, forward compat let window = glutin::WindowBuilder::new() .with_title("gltf-viewer") .with_dimensions(window_size) .with_visibility(visible); let context = glutin::ContextBuilder::new() .with_gl(gl_request) .with_gl_profile(gl_profile) .with_vsync(true); let gl_window = glutin::GlWindow::new(window, context, &events_loop).unwrap(); // Real dimensions might be much higher on High-DPI displays let dpi_factor = gl_window.get_hidpi_factor(); let inner_size = gl_window.get_inner_size().unwrap().to_physical(dpi_factor); unsafe { gl_window.make_current().unwrap(); } // gl: load all OpenGL function pointers gl::load_with(|symbol| gl_window.get_proc_address(symbol) as *const _); (Some(events_loop), Some(gl_window), dpi_factor, inner_size) }; let mut orbit_controls = OrbitControls::new( Point3::new(0.0, 0.0, 2.0), inner_size); orbit_controls.camera = Camera::default(); orbit_controls.camera.fovy = camera_options.fovy; orbit_controls.camera.update_aspect_ratio(inner_size.width as f32 / inner_size.height as f32); // updates projection matrix unsafe { print_context_info(); gl::ClearColor(0.0, 1.0, 0.0, 1.0); // green for debugging gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); if headless ||!visible { // transparent background for screenshots gl::ClearColor(0.0, 0.0, 0.0, 0.0); } else { gl::ClearColor(0.1, 0.2, 0.3, 1.0); } gl::Enable(gl::DEPTH_TEST); // TODO: keyboard switch? // draw in wireframe // gl::PolygonMode(gl::FRONT_AND_BACK, gl::LINE); }; let (root, scene) = Self::load(source, scene_index); let mut viewer = GltfViewer { size: inner_size, dpi_factor, orbit_controls, events_loop, gl_window, root, scene, delta_time: 0.0, // seconds last_frame: Instant::now(), render_timer: FrameTimer::new("rendering", 300), }; unsafe { gl_check_error!(); }; if camera_options.index!= 0 && camera_options.index >= viewer.root.camera_nodes.len() as i32 { error!("No camera with index {} found in glTF file (max: {})", camera_options.index, viewer.root.camera_nodes.len() as i32 - 1); process::exit(2) } if!viewer.root.camera_nodes.is_empty() && camera_options.index!= -1 { let cam_node = &viewer.root.get_camera_node(camera_options.index as usize); let cam_node_info = format!("{} ({:?})", cam_node.index, cam_node.name); let cam = cam_node.camera.as_ref().unwrap(); info!("Using camera {} on node {}", cam.description(), cam_node_info); viewer.orbit_controls.set_camera(cam, &cam_node.final_transform); if camera_options.position.is_some() || camera_options.target.is_some() { warn!("Ignoring --cam-pos / --cam-target since --cam-index is given.") } } else { info!("Determining camera view from bounding box"); viewer.set_camera_from_bounds(camera_options.straight); if let Some(p) = camera_options.position { viewer.orbit_controls.position = Point3::from_vec(p) } if let Some(target) = camera_options.target { viewer.orbit_controls.target = Point3::from_vec(target) } } viewer } pub fn load(source: &str, scene_index: usize) -> (Root, Scene) { let mut start_time = Instant::now(); // TODO!: http source // let gltf = if source.starts_with("http") { panic!("not implemented: HTTP support temporarily removed.") // let http_source = HttpSource::new(source); // let import = gltf::Import::custom(http_source, Default::default()); // let gltf = import_gltf(import); // println!(); // to end the "progress dots" // gltf } // else { let (doc, buffers, images) = match gltf::import(source) { Ok(tuple) => tuple, Err(err) => { error!("glTF import failed: {:?}", err); if let gltf::Error::Io(_) = err { error!("Hint: Are the.bin file(s) referenced by the.gltf file available?") } process::exit(1) }, }; let imp = ImportData { doc, buffers, images }; print_elapsed("Imported glTF in ", start_time); start_time = Instant::now(); // load first scene if scene_index >= imp.doc.scenes().len() { error!("Scene index too high - file has only {} scene(s)", imp.doc.scenes().len()); process::exit(3) } let base_path = Path::new(source); let mut root = Root::from_gltf(&imp, base_path); let scene = Scene::from_gltf(&imp.doc.scenes().nth(scene_index).unwrap(), &mut root); print_elapsed(&format!("Loaded scene with {} nodes, {} meshes in ", imp.doc.nodes().count(), imp.doc.meshes().len()), start_time); (root, scene) } /// determine "nice" camera perspective from bounding box. Inspired by donmccurdy/three-gltf-viewer fn set_camera_from_bounds(&mut self, straight: bool) { let bounds = &self.scene.bounds; let size = (bounds.max - bounds.min).magnitude(); let center = bounds.center(); // TODO: x,y addition optional let cam_pos = if straight { Point3::new( center.x, center.y, center.z + size * 0.75, ) } else { Point3::new( center.x + size / 2.0, center.y + size / 5.0, center.z + size / 2.0, ) }; self.orbit_controls.position = cam_pos; self.orbit_controls.target = center; self.orbit_controls.camera.znear = size / 100.0; self.orbit_controls.camera.zfar = Some(size * 20.0); self.orbit_controls.camera.update_projection_matrix(); } pub fn start_render_loop(&mut self) { loop { // per-frame time logic // NOTE: Deliberately ignoring the seconds of `elapsed()` self.delta_time = f64::from(self.last_frame.elapsed().subsec_nanos()) / 1_000_000_000.0; self.last_frame = Instant::now(); // events let keep_running = process_events( &mut self.events_loop.as_mut().unwrap(), self.gl_window.as_mut().unwrap(), &mut self.orbit_controls, &mut self.dpi_factor, &mut self.size); if!keep_running { unsafe { gl_check_error!(); } // final error check so errors don't go unnoticed break } self.orbit_controls.frame_update(self.delta_time); // keyboard navigation self.draw(); self.gl_window.as_ref().unwrap().swap_buffers().unwrap(); } } // Returns whether to keep running pub fn draw(&mut self) { // render unsafe { self.render_timer.start(); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); let cam_params = self.orbit_controls.camera_params(); self.scene.draw(&mut self.root, &cam_params); self.render_timer.end(); } } pub fn screenshot(&mut self, filename: &str) { self.draw(); let mut img = DynamicImage::new_rgba8(self.size.width as u32, self.size.height as u32); unsafe { let pixels = img.as_mut_rgba8().unwrap(); gl::PixelStorei(gl::PACK_ALIGNMENT, 1); gl::ReadPixels(0, 0, self.size.width as i32, self.size.height as i32, gl::RGBA, gl::UNSIGNED_BYTE, pixels.as_mut_ptr() as *mut c_void); gl_check_error!(); } let img = img.flipv(); if let Err(err) = img.save(filename) { error!("{}", err); } else { println!("Saved {}x{} screenshot to {}", self.size.width, self.size.height, filename); } } pub fn
(&mut self, filename: &str, count: u32) { let min_angle : f32 = 0.0 ; let max_angle : f32 = 2.0 * PI ; let increment_angle : f32 = ((max_angle - min_angle)/(count as f32)) as f32; let suffix_length = count.to_string().len(); for i in 1..=count { self.orbit_controls.rotate_object(increment_angle); let dot = filename.rfind('.').unwrap_or_else(|| filename.len()); let mut actual_name = filename.to_string(); actual_name.insert_str(dot, &format!("_{:0suffix_length$}", i, suffix_length = suffix_length)); self.screenshot(&actual_name[..]); } } } #[allow(clippy::too_many_arguments)] fn process_events( events_loop: &mut glutin::EventsLoop, gl_window: &glutin::GlWindow, mut orbit_controls: &mut OrbitControls, dpi_factor: &mut f64, size: &mut PhysicalSize) -> bool { let mut keep_running = true; #[allow(clippy::single_match)] events_loop.poll_events(|event| { match event { glutin::Event::WindowEvent{ event,.. } => match event { WindowEvent::CloseRequested => { keep_running = false; }, WindowEvent::Destroyed => { // Log and exit? panic!("WindowEvent::Destroyed, unimplemented."); }, WindowEvent::Resized(logical) => { let ph = logical.to_physical(*dpi_factor); gl_window.resize(ph); // This doesn't seem to be needed on macOS but linux X11, Wayland and Windows // do need it. unsafe { gl::Viewport(0, 0, ph.width as i32, ph.height as i32); } *size = ph; orbit_controls.camera.update_aspect_ratio((ph.width / ph.height) as f32); orbit_controls.screen_size = ph; }, WindowEvent::HiDpiFactorChanged(f) => { *dpi_factor = f; }, WindowEvent::DroppedFile(_path_buf) => { // TODO: drag file in } WindowEvent::MouseInput { button, state: Pressed,..} => { match button { MouseButton::Left => { orbit_controls.state = NavState::Rotating; }, MouseButton::Right => { orbit_controls.state = NavState::Panning; }, _ => () } }, WindowEvent::MouseInput { button, state: Released,..} => { match (button, orbit_controls.state.clone()) { (MouseButton::Left, NavState::Rotating) | (MouseButton::Right, NavState::Panning) => { orbit_controls.state = NavState::None; orbit_controls.handle_mouse_up(); }, _ => () } } WindowEvent::CursorMoved { position,.. } => { let ph = position.to_physical(*dpi_factor); orbit_controls.handle_mouse_move(ph) }, WindowEvent::MouseWheel { delta: MouseScrollDelta::PixelDelta(logical),.. } => { let ph = logical.to_physical(*dpi_factor); orbit_controls.process_mouse_scroll(ph.y as f32); } WindowEvent::MouseWheel { delta: MouseScrollDelta::LineDelta(_rows, lines),.. } => { orbit_controls.process_mouse_scroll(lines * 3.0); } WindowEvent::KeyboardInput { input,.. } => { keep_running = process_input(input, &mut orbit_controls); } _ => () }, _ => () } }); keep_running } fn process_input(input: glutin::KeyboardInput, controls: &mut OrbitControls) -> bool { let pressed = match input.state { Pressed => true, Released => false }; if let Some(code) = input.virtual_keycode { match code { VirtualKeyCode::Escape if pressed => return false, VirtualKeyCode::W | VirtualKeyCode::Up => controls.process_keyboard(FORWARD, pressed), VirtualKeyCode::S | VirtualKeyCode::Down => controls.process_keyboard(BACKWARD, pressed), VirtualKeyCode::A | VirtualKeyCode::Left => controls.process_keyboard(LEFT, pressed), VirtualKeyCode::D | VirtualKeyCode::Right => controls.process_keyboard(RIGHT, pressed), _ => () } } true }
multiscreenshot
identifier_name
viewer.rs
use std::f32::consts::PI; use std::os::raw::c_void; use std::path::Path; use std::process; use std::time::Instant; use cgmath::{ Deg, Point3 }; use collision::Aabb; use gl; use gltf; use glutin; use glutin::{ Api, MouseScrollDelta, MouseButton, GlContext, GlRequest, GlProfile, VirtualKeyCode, WindowEvent, }; use glutin::dpi::PhysicalSize; use glutin::ElementState::*; use image::{DynamicImage}; use log::{error, warn, info}; use crate::controls::{OrbitControls, NavState}; use crate::controls::CameraMovement::*; use crate::framebuffer::Framebuffer; use crate::importdata::ImportData; use crate::render::*; use crate::render::math::*; use crate::utils::{print_elapsed, FrameTimer, gl_check_error, print_context_info}; // TODO!: complete and pass through draw calls? or get rid of multiple shaders? // How about state ordering anyway? // struct DrawState { // current_shader: ShaderFlags, // back_face_culling_enabled: bool // } #[derive(Copy, Clone)] pub struct CameraOptions { pub index: i32, pub position: Option<Vector3>, pub target: Option<Vector3>, pub fovy: Deg<f32>, pub straight: bool, } pub struct GltfViewer { size: PhysicalSize, dpi_factor: f64, orbit_controls: OrbitControls, events_loop: Option<glutin::EventsLoop>, gl_window: Option<glutin::GlWindow>, // TODO!: get rid of scene? root: Root, scene: Scene, delta_time: f64, // seconds last_frame: Instant, render_timer: FrameTimer, } /// Note about `headless` and `visible`: True headless rendering doesn't work on /// all operating systems, but an invisible window usually works impl GltfViewer { pub fn new( source: &str, width: u32, height: u32, headless: bool, visible: bool, camera_options: CameraOptions, scene_index: usize, ) -> GltfViewer { let gl_request = GlRequest::Specific(Api::OpenGl, (3, 3)); let gl_profile = GlProfile::Core; let (events_loop, gl_window, dpi_factor, inner_size) = if headless { let headless_context = glutin::HeadlessRendererBuilder::new(width, height) //.with_gl(gl_request) //.with_gl_profile(gl_profile) .build() .unwrap(); unsafe { headless_context.make_current().unwrap() } gl::load_with(|symbol| headless_context.get_proc_address(symbol) as *const _); let framebuffer = Framebuffer::new(width, height); framebuffer.bind(); unsafe { gl::Viewport(0, 0, width as i32, height as i32); } (None, None, 1.0, PhysicalSize::new(width as f64, height as f64)) // TODO: real height (retina? (should be the same as PhysicalSize when headless?)) } else { // glutin: initialize and configure let events_loop = glutin::EventsLoop::new(); let window_size = glutin::dpi::LogicalSize::new(width as f64, height as f64); // TODO?: hints for 4.1, core profile, forward compat let window = glutin::WindowBuilder::new() .with_title("gltf-viewer") .with_dimensions(window_size) .with_visibility(visible); let context = glutin::ContextBuilder::new() .with_gl(gl_request) .with_gl_profile(gl_profile) .with_vsync(true); let gl_window = glutin::GlWindow::new(window, context, &events_loop).unwrap(); // Real dimensions might be much higher on High-DPI displays let dpi_factor = gl_window.get_hidpi_factor(); let inner_size = gl_window.get_inner_size().unwrap().to_physical(dpi_factor); unsafe { gl_window.make_current().unwrap(); } // gl: load all OpenGL function pointers gl::load_with(|symbol| gl_window.get_proc_address(symbol) as *const _); (Some(events_loop), Some(gl_window), dpi_factor, inner_size) }; let mut orbit_controls = OrbitControls::new( Point3::new(0.0, 0.0, 2.0), inner_size); orbit_controls.camera = Camera::default(); orbit_controls.camera.fovy = camera_options.fovy; orbit_controls.camera.update_aspect_ratio(inner_size.width as f32 / inner_size.height as f32); // updates projection matrix unsafe { print_context_info(); gl::ClearColor(0.0, 1.0, 0.0, 1.0); // green for debugging gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); if headless ||!visible { // transparent background for screenshots gl::ClearColor(0.0, 0.0, 0.0, 0.0); } else { gl::ClearColor(0.1, 0.2, 0.3, 1.0); } gl::Enable(gl::DEPTH_TEST); // TODO: keyboard switch? // draw in wireframe // gl::PolygonMode(gl::FRONT_AND_BACK, gl::LINE); }; let (root, scene) = Self::load(source, scene_index); let mut viewer = GltfViewer { size: inner_size, dpi_factor, orbit_controls, events_loop, gl_window, root, scene, delta_time: 0.0, // seconds last_frame: Instant::now(), render_timer: FrameTimer::new("rendering", 300), }; unsafe { gl_check_error!(); }; if camera_options.index!= 0 && camera_options.index >= viewer.root.camera_nodes.len() as i32 { error!("No camera with index {} found in glTF file (max: {})", camera_options.index, viewer.root.camera_nodes.len() as i32 - 1); process::exit(2) } if!viewer.root.camera_nodes.is_empty() && camera_options.index!= -1 { let cam_node = &viewer.root.get_camera_node(camera_options.index as usize); let cam_node_info = format!("{} ({:?})", cam_node.index, cam_node.name); let cam = cam_node.camera.as_ref().unwrap(); info!("Using camera {} on node {}", cam.description(), cam_node_info); viewer.orbit_controls.set_camera(cam, &cam_node.final_transform); if camera_options.position.is_some() || camera_options.target.is_some() { warn!("Ignoring --cam-pos / --cam-target since --cam-index is given.") } } else { info!("Determining camera view from bounding box"); viewer.set_camera_from_bounds(camera_options.straight); if let Some(p) = camera_options.position { viewer.orbit_controls.position = Point3::from_vec(p) } if let Some(target) = camera_options.target { viewer.orbit_controls.target = Point3::from_vec(target) } } viewer } pub fn load(source: &str, scene_index: usize) -> (Root, Scene) { let mut start_time = Instant::now(); // TODO!: http source // let gltf = if source.starts_with("http") { panic!("not implemented: HTTP support temporarily removed.") // let http_source = HttpSource::new(source); // let import = gltf::Import::custom(http_source, Default::default()); // let gltf = import_gltf(import); // println!(); // to end the "progress dots" // gltf } // else { let (doc, buffers, images) = match gltf::import(source) { Ok(tuple) => tuple, Err(err) => { error!("glTF import failed: {:?}", err); if let gltf::Error::Io(_) = err { error!("Hint: Are the.bin file(s) referenced by the.gltf file available?") } process::exit(1) }, }; let imp = ImportData { doc, buffers, images }; print_elapsed("Imported glTF in ", start_time); start_time = Instant::now(); // load first scene if scene_index >= imp.doc.scenes().len() { error!("Scene index too high - file has only {} scene(s)", imp.doc.scenes().len()); process::exit(3) } let base_path = Path::new(source); let mut root = Root::from_gltf(&imp, base_path); let scene = Scene::from_gltf(&imp.doc.scenes().nth(scene_index).unwrap(), &mut root); print_elapsed(&format!("Loaded scene with {} nodes, {} meshes in ", imp.doc.nodes().count(), imp.doc.meshes().len()), start_time); (root, scene) } /// determine "nice" camera perspective from bounding box. Inspired by donmccurdy/three-gltf-viewer fn set_camera_from_bounds(&mut self, straight: bool) { let bounds = &self.scene.bounds; let size = (bounds.max - bounds.min).magnitude(); let center = bounds.center(); // TODO: x,y addition optional let cam_pos = if straight { Point3::new( center.x, center.y, center.z + size * 0.75, ) } else { Point3::new( center.x + size / 2.0, center.y + size / 5.0, center.z + size / 2.0, ) }; self.orbit_controls.position = cam_pos; self.orbit_controls.target = center; self.orbit_controls.camera.znear = size / 100.0; self.orbit_controls.camera.zfar = Some(size * 20.0); self.orbit_controls.camera.update_projection_matrix(); } pub fn start_render_loop(&mut self) { loop { // per-frame time logic // NOTE: Deliberately ignoring the seconds of `elapsed()` self.delta_time = f64::from(self.last_frame.elapsed().subsec_nanos()) / 1_000_000_000.0; self.last_frame = Instant::now(); // events let keep_running = process_events( &mut self.events_loop.as_mut().unwrap(), self.gl_window.as_mut().unwrap(), &mut self.orbit_controls, &mut self.dpi_factor, &mut self.size); if!keep_running { unsafe { gl_check_error!(); } // final error check so errors don't go unnoticed break } self.orbit_controls.frame_update(self.delta_time); // keyboard navigation self.draw(); self.gl_window.as_ref().unwrap().swap_buffers().unwrap(); } } // Returns whether to keep running pub fn draw(&mut self) { // render unsafe { self.render_timer.start(); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); let cam_params = self.orbit_controls.camera_params(); self.scene.draw(&mut self.root, &cam_params); self.render_timer.end(); } } pub fn screenshot(&mut self, filename: &str) { self.draw(); let mut img = DynamicImage::new_rgba8(self.size.width as u32, self.size.height as u32); unsafe { let pixels = img.as_mut_rgba8().unwrap(); gl::PixelStorei(gl::PACK_ALIGNMENT, 1); gl::ReadPixels(0, 0, self.size.width as i32, self.size.height as i32, gl::RGBA, gl::UNSIGNED_BYTE, pixels.as_mut_ptr() as *mut c_void); gl_check_error!(); } let img = img.flipv(); if let Err(err) = img.save(filename) { error!("{}", err); } else { println!("Saved {}x{} screenshot to {}", self.size.width, self.size.height, filename); } } pub fn multiscreenshot(&mut self, filename: &str, count: u32) { let min_angle : f32 = 0.0 ; let max_angle : f32 = 2.0 * PI ; let increment_angle : f32 = ((max_angle - min_angle)/(count as f32)) as f32; let suffix_length = count.to_string().len(); for i in 1..=count { self.orbit_controls.rotate_object(increment_angle); let dot = filename.rfind('.').unwrap_or_else(|| filename.len()); let mut actual_name = filename.to_string(); actual_name.insert_str(dot, &format!("_{:0suffix_length$}", i, suffix_length = suffix_length)); self.screenshot(&actual_name[..]); } } } #[allow(clippy::too_many_arguments)] fn process_events( events_loop: &mut glutin::EventsLoop, gl_window: &glutin::GlWindow, mut orbit_controls: &mut OrbitControls, dpi_factor: &mut f64, size: &mut PhysicalSize) -> bool { let mut keep_running = true; #[allow(clippy::single_match)] events_loop.poll_events(|event| { match event { glutin::Event::WindowEvent{ event,.. } => match event { WindowEvent::CloseRequested => { keep_running = false; }, WindowEvent::Destroyed => { // Log and exit? panic!("WindowEvent::Destroyed, unimplemented."); }, WindowEvent::Resized(logical) => { let ph = logical.to_physical(*dpi_factor); gl_window.resize(ph); // This doesn't seem to be needed on macOS but linux X11, Wayland and Windows // do need it. unsafe { gl::Viewport(0, 0, ph.width as i32, ph.height as i32); } *size = ph; orbit_controls.camera.update_aspect_ratio((ph.width / ph.height) as f32); orbit_controls.screen_size = ph; }, WindowEvent::HiDpiFactorChanged(f) => { *dpi_factor = f; }, WindowEvent::DroppedFile(_path_buf) => { // TODO: drag file in } WindowEvent::MouseInput { button, state: Pressed,..} => { match button { MouseButton::Left => { orbit_controls.state = NavState::Rotating; }, MouseButton::Right => { orbit_controls.state = NavState::Panning; }, _ => () } }, WindowEvent::MouseInput { button, state: Released,..} => { match (button, orbit_controls.state.clone()) { (MouseButton::Left, NavState::Rotating) | (MouseButton::Right, NavState::Panning) =>
, _ => () } } WindowEvent::CursorMoved { position,.. } => { let ph = position.to_physical(*dpi_factor); orbit_controls.handle_mouse_move(ph) }, WindowEvent::MouseWheel { delta: MouseScrollDelta::PixelDelta(logical),.. } => { let ph = logical.to_physical(*dpi_factor); orbit_controls.process_mouse_scroll(ph.y as f32); } WindowEvent::MouseWheel { delta: MouseScrollDelta::LineDelta(_rows, lines),.. } => { orbit_controls.process_mouse_scroll(lines * 3.0); } WindowEvent::KeyboardInput { input,.. } => { keep_running = process_input(input, &mut orbit_controls); } _ => () }, _ => () } }); keep_running } fn process_input(input: glutin::KeyboardInput, controls: &mut OrbitControls) -> bool { let pressed = match input.state { Pressed => true, Released => false }; if let Some(code) = input.virtual_keycode { match code { VirtualKeyCode::Escape if pressed => return false, VirtualKeyCode::W | VirtualKeyCode::Up => controls.process_keyboard(FORWARD, pressed), VirtualKeyCode::S | VirtualKeyCode::Down => controls.process_keyboard(BACKWARD, pressed), VirtualKeyCode::A | VirtualKeyCode::Left => controls.process_keyboard(LEFT, pressed), VirtualKeyCode::D | VirtualKeyCode::Right => controls.process_keyboard(RIGHT, pressed), _ => () } } true }
{ orbit_controls.state = NavState::None; orbit_controls.handle_mouse_up(); }
conditional_block
xray.rs
#![cfg(feature = "xray")] extern crate rusoto_core; extern crate rusoto_xray; extern crate time; use rusoto_core::Region; use rusoto_xray::{GetServiceGraphRequest, XRay, XRayClient}; use time::OffsetDateTime; // duplicates the AWS X-Ray CLI example, which gets an (empty) service graph // for the last 600 seconds #[tokio::test] async fn
() { let client = XRayClient::new(Region::UsEast1); let time = (OffsetDateTime::now_utc().unix_timestamp() - 30) as f64; // 30 seconds in the past println!("{:?}", time); let request = GetServiceGraphRequest { start_time: time - 600.0, end_time: time, ..Default::default() }; let result = client.get_service_graph(request).await; println!("{:#?}", result); result.unwrap(); }
should_get_service_graph
identifier_name
xray.rs
#![cfg(feature = "xray")] extern crate rusoto_core; extern crate rusoto_xray; extern crate time; use rusoto_core::Region; use rusoto_xray::{GetServiceGraphRequest, XRay, XRayClient}; use time::OffsetDateTime; // duplicates the AWS X-Ray CLI example, which gets an (empty) service graph // for the last 600 seconds #[tokio::test] async fn should_get_service_graph()
{ let client = XRayClient::new(Region::UsEast1); let time = (OffsetDateTime::now_utc().unix_timestamp() - 30) as f64; // 30 seconds in the past println!("{:?}", time); let request = GetServiceGraphRequest { start_time: time - 600.0, end_time: time, ..Default::default() }; let result = client.get_service_graph(request).await; println!("{:#?}", result); result.unwrap(); }
identifier_body
xray.rs
extern crate rusoto_core; extern crate rusoto_xray; extern crate time; use rusoto_core::Region; use rusoto_xray::{GetServiceGraphRequest, XRay, XRayClient}; use time::OffsetDateTime; // duplicates the AWS X-Ray CLI example, which gets an (empty) service graph // for the last 600 seconds #[tokio::test] async fn should_get_service_graph() { let client = XRayClient::new(Region::UsEast1); let time = (OffsetDateTime::now_utc().unix_timestamp() - 30) as f64; // 30 seconds in the past println!("{:?}", time); let request = GetServiceGraphRequest { start_time: time - 600.0, end_time: time, ..Default::default() }; let result = client.get_service_graph(request).await; println!("{:#?}", result); result.unwrap(); }
#![cfg(feature = "xray")]
random_line_split
test_ls.rs
/* * Test Eio module. * * List and process all the rust source files '.rs' in the current dir. * */ extern crate libc; extern crate efl; use libc::{c_char}; use std::c_str::CString; use efl::ecore; use efl::eio; fn _filter_cb(count: &mut int, handler: &eio::EioFile, file: *c_char) -> bool
fn _main_cb(count: &mut int, handler: &eio::EioFile, file: *c_char) { let cstring = unsafe { CString::new(file, false) }; let v = match cstring.as_str() { None => "", Some(s) => s }; // Count processed files *count += 1; println!("Processing file: {} ({})", v, *count); } fn _done_cb(count: &mut int, handler: &eio::EioFile) { println!("Number of processed files: {}", *count); println!("Done!"); ecore::main_loop_quit(); } fn _error_cb(count: &mut int, handler: &eio::EioFile, error: int) { println!("Error!"); ecore::main_loop_quit(); } fn main() { ecore::init(); eio::init(); let count: int = 0; eio::file_ls(".", _filter_cb, _main_cb, _done_cb, _error_cb, &count); ecore::main_loop_begin(); eio::shutdown(); ecore::shutdown(); }
{ // Get a &str from the raw *c_char type let cstring = unsafe { CString::new(file, false) }; let f = match cstring.as_str() { None => "", Some(s) => s }; // Let's process only rust source files! if !f.ends_with(".rs") { println!("Filtering file: {}", f); return false } return true; }
identifier_body
test_ls.rs
/* * Test Eio module. * * List and process all the rust source files '.rs' in the current dir. * */ extern crate libc; extern crate efl; use libc::{c_char}; use std::c_str::CString; use efl::ecore; use efl::eio; fn _filter_cb(count: &mut int, handler: &eio::EioFile, file: *c_char) -> bool { // Get a &str from the raw *c_char type let cstring = unsafe { CString::new(file, false) }; let f = match cstring.as_str() { None => "", Some(s) => s }; // Let's process only rust source files! if!f.ends_with(".rs") { println!("Filtering file: {}", f); return false } return true; } fn _main_cb(count: &mut int, handler: &eio::EioFile, file: *c_char) { let cstring = unsafe { CString::new(file, false) }; let v = match cstring.as_str() { None => "", Some(s) => s }; // Count processed files *count += 1; println!("Processing file: {} ({})", v, *count); } fn _done_cb(count: &mut int, handler: &eio::EioFile) { println!("Number of processed files: {}", *count); println!("Done!"); ecore::main_loop_quit(); } fn
(count: &mut int, handler: &eio::EioFile, error: int) { println!("Error!"); ecore::main_loop_quit(); } fn main() { ecore::init(); eio::init(); let count: int = 0; eio::file_ls(".", _filter_cb, _main_cb, _done_cb, _error_cb, &count); ecore::main_loop_begin(); eio::shutdown(); ecore::shutdown(); }
_error_cb
identifier_name
test_ls.rs
/* * Test Eio module. * * List and process all the rust source files '.rs' in the current dir. * */ extern crate libc; extern crate efl; use libc::{c_char}; use std::c_str::CString; use efl::ecore; use efl::eio; fn _filter_cb(count: &mut int, handler: &eio::EioFile, file: *c_char) -> bool {
let f = match cstring.as_str() { None => "", Some(s) => s }; // Let's process only rust source files! if!f.ends_with(".rs") { println!("Filtering file: {}", f); return false } return true; } fn _main_cb(count: &mut int, handler: &eio::EioFile, file: *c_char) { let cstring = unsafe { CString::new(file, false) }; let v = match cstring.as_str() { None => "", Some(s) => s }; // Count processed files *count += 1; println!("Processing file: {} ({})", v, *count); } fn _done_cb(count: &mut int, handler: &eio::EioFile) { println!("Number of processed files: {}", *count); println!("Done!"); ecore::main_loop_quit(); } fn _error_cb(count: &mut int, handler: &eio::EioFile, error: int) { println!("Error!"); ecore::main_loop_quit(); } fn main() { ecore::init(); eio::init(); let count: int = 0; eio::file_ls(".", _filter_cb, _main_cb, _done_cb, _error_cb, &count); ecore::main_loop_begin(); eio::shutdown(); ecore::shutdown(); }
// Get a &str from the raw *c_char type let cstring = unsafe { CString::new(file, false) };
random_line_split
issue-61936.rs
// run-pass trait SliceExt<T: Clone> { fn array_windows_example<'a, const N: usize>(&'a self) -> ArrayWindowsExample<'a, T, N>; } impl <T: Clone> SliceExt<T> for [T] { fn array_windows_example<'a, const N: usize>(&'a self) -> ArrayWindowsExample<'a, T, N> { ArrayWindowsExample{ idx: 0, slice: &self } } } struct ArrayWindowsExample<'a, T, const N: usize> { slice: &'a [T], idx: usize, } impl <'a, T: Clone, const N: usize> Iterator for ArrayWindowsExample<'a, T, N> { type Item = [T; N]; fn next(&mut self) -> Option<Self::Item> { // Note: this is unsound for some `T` and not meant as an example // on how to implement `ArrayWindows`. let mut res = unsafe{ std::mem::zeroed() }; let mut ptr = &mut res as *mut [T; N] as *mut T; for i in 0..N { match self.slice[self.idx..].get(i) { None => return None, Some(elem) => unsafe { std::ptr::write_volatile(ptr, elem.clone())},
}; ptr = ptr.wrapping_add(1); self.idx += 1; } Some(res) } } const FOUR: usize = 4; fn main() { let v: Vec<usize> = vec![0; 100]; for array in v.as_slice().array_windows_example::<FOUR>() { assert_eq!(array, [0, 0, 0, 0]) } }
random_line_split
issue-61936.rs
// run-pass trait SliceExt<T: Clone> { fn array_windows_example<'a, const N: usize>(&'a self) -> ArrayWindowsExample<'a, T, N>; } impl <T: Clone> SliceExt<T> for [T] { fn array_windows_example<'a, const N: usize>(&'a self) -> ArrayWindowsExample<'a, T, N>
} struct ArrayWindowsExample<'a, T, const N: usize> { slice: &'a [T], idx: usize, } impl <'a, T: Clone, const N: usize> Iterator for ArrayWindowsExample<'a, T, N> { type Item = [T; N]; fn next(&mut self) -> Option<Self::Item> { // Note: this is unsound for some `T` and not meant as an example // on how to implement `ArrayWindows`. let mut res = unsafe{ std::mem::zeroed() }; let mut ptr = &mut res as *mut [T; N] as *mut T; for i in 0..N { match self.slice[self.idx..].get(i) { None => return None, Some(elem) => unsafe { std::ptr::write_volatile(ptr, elem.clone())}, }; ptr = ptr.wrapping_add(1); self.idx += 1; } Some(res) } } const FOUR: usize = 4; fn main() { let v: Vec<usize> = vec![0; 100]; for array in v.as_slice().array_windows_example::<FOUR>() { assert_eq!(array, [0, 0, 0, 0]) } }
{ ArrayWindowsExample{ idx: 0, slice: &self } }
identifier_body
issue-61936.rs
// run-pass trait SliceExt<T: Clone> { fn array_windows_example<'a, const N: usize>(&'a self) -> ArrayWindowsExample<'a, T, N>; } impl <T: Clone> SliceExt<T> for [T] { fn
<'a, const N: usize>(&'a self) -> ArrayWindowsExample<'a, T, N> { ArrayWindowsExample{ idx: 0, slice: &self } } } struct ArrayWindowsExample<'a, T, const N: usize> { slice: &'a [T], idx: usize, } impl <'a, T: Clone, const N: usize> Iterator for ArrayWindowsExample<'a, T, N> { type Item = [T; N]; fn next(&mut self) -> Option<Self::Item> { // Note: this is unsound for some `T` and not meant as an example // on how to implement `ArrayWindows`. let mut res = unsafe{ std::mem::zeroed() }; let mut ptr = &mut res as *mut [T; N] as *mut T; for i in 0..N { match self.slice[self.idx..].get(i) { None => return None, Some(elem) => unsafe { std::ptr::write_volatile(ptr, elem.clone())}, }; ptr = ptr.wrapping_add(1); self.idx += 1; } Some(res) } } const FOUR: usize = 4; fn main() { let v: Vec<usize> = vec![0; 100]; for array in v.as_slice().array_windows_example::<FOUR>() { assert_eq!(array, [0, 0, 0, 0]) } }
array_windows_example
identifier_name
endpoint.rs
/* * Copyright 2021 Google LLC * * 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. */ //! Types representing where the data is the sent. mod address; use std::sync::Arc; use serde::{Deserialize, Serialize}; pub use address::EndpointAddress; type EndpointMetadata = crate::metadata::MetadataView<Metadata>; /// A destination endpoint with any associated metadata. #[derive(Debug, Deserialize, Serialize, PartialEq, Clone, PartialOrd, Eq)] #[non_exhaustive] #[serde(deny_unknown_fields)] pub struct Endpoint { pub address: EndpointAddress, #[serde(default)] pub metadata: EndpointMetadata, } impl Endpoint { /// Creates a new [`Endpoint`] with no metadata. pub fn new(address: EndpointAddress) -> Self { Self { address, ..<_>::default() } } /// Creates a new [`Endpoint`] with the specified `metadata`. pub fn with_metadata(address: EndpointAddress, metadata: impl Into<EndpointMetadata>) -> Self { Self { address, metadata: metadata.into(), ..<_>::default() } } } impl Default for Endpoint { fn default() -> Self { Self { address: EndpointAddress::UNSPECIFIED, metadata: <_>::default(), } } } impl std::str::FromStr for Endpoint { type Err = <EndpointAddress as std::str::FromStr>::Err; fn from_str(s: &str) -> Result<Self, Self::Err>
} /// Represents the set of all known upstream endpoints. #[derive(Clone, Debug, PartialEq)] pub struct Endpoints(Arc<Vec<Endpoint>>); impl Endpoints { /// Returns an [`Endpoints`] backed by the provided list of endpoints. pub fn new(endpoints: Vec<Endpoint>) -> Option<Self> { match endpoints.is_empty() { true => None, false => Some(Self(Arc::new(endpoints))), } } } /// Provides a read-only view into the underlying endpoints. impl AsRef<Vec<Endpoint>> for Endpoints { fn as_ref(&self) -> &Vec<Endpoint> { self.0.as_ref() } } /// Metadata specific to endpoints. #[derive(Default, Debug, Deserialize, Serialize, PartialEq, Clone, PartialOrd, Eq)] #[non_exhaustive] pub struct Metadata { #[serde(with = "base64_set")] pub tokens: base64_set::Set, } /// A module for providing base64 encoding for a `BTreeSet` at the `serde` /// boundary. Accepts a list of strings representing Base64 encoded data, /// this list is then converted into its binary representation while in memory, /// and then encoded back as a list of base64 strings. mod base64_set { use serde::de::Error; pub type Set<T = Vec<u8>> = std::collections::BTreeSet<T>; pub fn serialize<S>(set: &Set, ser: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serde::Serialize::serialize(&set.iter().map(base64::encode).collect::<Vec<_>>(), ser) } pub fn deserialize<'de, D>(de: D) -> Result<Set, D::Error> where D: serde::Deserializer<'de>, { let items = <Vec<String> as serde::Deserialize>::deserialize(de)?; let set = items.iter().cloned().collect::<Set<String>>(); if set.len()!= items.len() { Err(D::Error::custom( "Found duplicate tokens in endpoint metadata.", )) } else { set.into_iter() .map(|string| base64::decode(string).map_err(D::Error::custom)) .collect() } } } #[derive(Debug, Clone, thiserror::Error)] pub enum MetadataError { #[error("Invalid bas64 encoded token: `{0}`.")] InvalidBase64(base64::DecodeError), #[error("Missing required key `{0}`.")] MissingKey(&'static str), #[error("Invalid type ({expected}) given for `{key}`.")] InvalidType { key: &'static str, expected: &'static str, }, } impl std::convert::TryFrom<prost_types::Struct> for Metadata { type Error = MetadataError; fn try_from(mut value: prost_types::Struct) -> Result<Self, Self::Error> { use prost_types::value::Kind; const TOKENS: &str = "tokens"; let tokens = if let Some(kind) = value.fields.remove(TOKENS).and_then(|v| v.kind) { if let Kind::ListValue(list) = kind { list.values .into_iter() .filter_map(|v| v.kind) .map(|kind| { if let Kind::StringValue(string) = kind { base64::decode(string).map_err(MetadataError::InvalidBase64) } else { Err(MetadataError::InvalidType { key: "quilkin.dev.tokens", expected: "base64 string", }) } }) .collect::<Result<_, _>>()? } else { return Err(MetadataError::MissingKey(TOKENS)); } } else { <_>::default() }; Ok(Self { tokens }) } } /// UpstreamEndpoints represents a set of endpoints. /// This set is guaranteed to be non-empty - any operation that would /// cause the set to be empty will return an error instead. #[derive(Debug)] pub struct UpstreamEndpoints { /// All endpoints in the initial set - this list never /// changes after initialization. endpoints: Endpoints, /// A view into the current subset of endpoints in the original set. /// It contains indices into the initial set, to form the subset. /// If unset, the initial set is the current subset. subset: Option<Vec<usize>>, } impl From<Endpoints> for UpstreamEndpoints { fn from(endpoints: Endpoints) -> Self { UpstreamEndpoints { endpoints, subset: None, } } } impl UpstreamEndpoints { /// Returns the number of endpoints in the backing set. pub fn size(&self) -> usize { self.subset .as_ref() .map(|subset| subset.len()) .unwrap_or_else(|| self.endpoints.0.len()) } /// Updates the current subset of endpoints to contain only the endpoint /// at the specified zero-indexed position, returns `None` if `index` /// is greater than the number of endpoints. pub fn keep(&mut self, index: usize) -> Option<()> { if index >= self.size() { return None; } match self.subset.as_mut() { Some(subset) => { let index = subset[index]; subset.clear(); subset.push(index); } None => { self.subset = Some(vec![index]); } } Some(()) } /// Updates the current subset of endpoints to contain only the endpoints /// which the predicate returned `true`. /// Returns an error if the predicate returns `false` for all endpoints. pub fn retain<F>(&mut self, predicate: F) -> RetainedItems where F: Fn(&Endpoint) -> bool, { let endpoints = self .subset .as_ref() .map(|s| either::Right(s.iter().map(|&index| (index, &self.endpoints.0[index])))) .unwrap_or_else(|| either::Left(self.endpoints.0.iter().enumerate())); let total_items = endpoints.clone().count(); let new_subset = endpoints .filter(|(_, ep)| predicate(ep)) .map(|(i, _)| i) .collect::<Vec<_>>(); if new_subset.is_empty() { return RetainedItems::None; } let retained_items = new_subset.len(); self.subset = Some(new_subset); if retained_items == total_items { RetainedItems::All } else { RetainedItems::Some(retained_items) } } /// Iterate over the endpoints in the current subset. pub fn iter(&self) -> UpstreamEndpointsIter { UpstreamEndpointsIter { collection: self, index: 0, } } } /// An enum representing the result of a [`UpstreamEndpoints::retain`] call, /// detailing how many (if any) of the endpoints were retained by the predicate. #[non_exhaustive] #[must_use] #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum RetainedItems { None, Some(usize), All, } impl RetainedItems { /// Returns whether `self` is [`RetainedItems::None`]. pub fn is_none(&self) -> bool { matches!(self, Self::None) } /// Returns whether `self` is [`RetainedItems::All`]. pub fn is_all(&self) -> bool { matches!(self, Self::All) } /// Returns whether `self` is [`RetainedItems::Some`]. pub fn is_some(&self) -> bool { matches!(self, Self::Some(_)) } } /// An Iterator over all endpoints in an [`UpstreamEndpoints`] pub struct UpstreamEndpointsIter<'a> { collection: &'a UpstreamEndpoints, index: usize, } impl<'a> Iterator for UpstreamEndpointsIter<'a> { type Item = &'a Endpoint; fn next(&mut self) -> Option<Self::Item> { match &self.collection.subset { Some(subset) => { self.index += 1; subset .get(self.index - 1) .and_then(|&index| self.collection.endpoints.0.get(index)) } None => { self.index += 1; self.collection.endpoints.0.get(self.index - 1) } } } } #[cfg(test)] mod tests { use super::*; fn ep(id: u8) -> Endpoint { Endpoint::new(([127, 0, 0, id], 8080u16).into()) } #[test] fn endpoint_metadata() { let metadata = Metadata { tokens: vec!["Man".into()].into_iter().collect(), }; assert_eq!( serde_json::to_value(EndpointMetadata::from(metadata)).unwrap(), serde_json::json!({ crate::metadata::KEY: { "tokens": ["TWFu"], } }) ); } #[test] fn new_endpoints() { assert!(Endpoints::new(vec![]).is_none()); assert!(Endpoints::new(vec![ep(1)]).is_some()); } #[test] fn keep() { let initial_endpoints = vec![ep(1), ep(2), ep(3)]; let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); assert!(up.keep(initial_endpoints.len() - 1).is_some()); let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); assert!(up.keep(initial_endpoints.len()).is_none()); // Limit the set to only one element. let mut up = UpstreamEndpoints::from(Endpoints::new(initial_endpoints.clone()).unwrap()); up.keep(1).unwrap(); up.keep(0).unwrap(); assert_eq!(vec![&initial_endpoints[1]], up.iter().collect::<Vec<_>>()); let mut up = UpstreamEndpoints::from(Endpoints::new(initial_endpoints).unwrap()); up.keep(1).unwrap(); assert!(up.keep(1).is_none()); } #[test] fn retain() { let initial_endpoints = vec![ep(1), ep(2), ep(3), ep(4)]; let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); let items = up.retain(|ep| ep.address!= ([127, 0, 0, 2], 8080).into()); assert!(matches!(items, RetainedItems::Some(3))); assert_eq!(up.size(), 3); assert_eq!( vec![ep(1), ep(3), ep(4)], up.iter().cloned().collect::<Vec<_>>() ); let items = up.retain(|ep| ep.address!= ([127, 0, 0, 3], 8080).into()); assert!(matches!(items, RetainedItems::Some(2))); assert_eq!(up.size(), 2); assert_eq!(vec![ep(1), ep(4)], up.iter().cloned().collect::<Vec<_>>()); // test an empty result on retain let result = up.retain(|_| false); assert!(result.is_none()); let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints).unwrap().into(); let result = up.retain(|_| false); assert!(result.is_none()); } #[test] fn upstream_len() { let mut up: UpstreamEndpoints = Endpoints::new(vec![ep(1), ep(2), ep(3)]).unwrap().into(); // starts out with all endpoints. assert_eq!(up.size(), 3); // verify that the set is now a singleton. up.keep(1).unwrap(); assert_eq!(up.size(), 1); } #[test] fn upstream_all_iter() { let initial_endpoints = vec![ep(1), ep(2), ep(3)]; let up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); let result = up.iter().cloned().collect::<Vec<_>>(); assert_eq!(initial_endpoints, result); } #[test] fn upstream_some_iter() { let mut up = UpstreamEndpoints::from(Endpoints::new(vec![ep(1), ep(2), ep(3)]).unwrap()); up.keep(1).unwrap(); assert_eq!(vec![ep(2)], up.iter().cloned().collect::<Vec<_>>()); } #[test] fn yaml_parse_endpoint_metadata() { let yaml = " user: key1: value1 quilkin.dev: tokens: - MXg3aWp5Ng== #1x7ijy6 - OGdqM3YyaQ== #8gj3v2i "; assert_eq!( serde_json::to_value(serde_yaml::from_str::<EndpointMetadata>(yaml).unwrap()).unwrap(), serde_json::json!({ "user": { "key1": "value1" }, "quilkin.dev": { "tokens": ["MXg3aWp5Ng==", "OGdqM3YyaQ=="], } }) ); } #[test] fn parse_dns_endpoints() { let localhost = "address: localhost:80"; serde_yaml::from_str::<Endpoint>(localhost).unwrap(); } #[test] fn yaml_parse_invalid_endpoint_metadata() { let not_a_list = " quilkin.dev: tokens: OGdqM3YyaQ== "; let not_a_string_value = " quilkin.dev: tokens: - map: a: b "; let not_a_base64_string = " quilkin.dev: tokens: - OGdqM3YyaQ== #8gj3v2i - iix "; for yaml in &[not_a_list, not_a_string_value, not_a_base64_string] { serde_yaml::from_str::<EndpointMetadata>(yaml).unwrap_err(); } } }
{ Ok(Self { address: s.parse()?, ..Self::default() }) }
identifier_body
endpoint.rs
/* * Copyright 2021 Google LLC * * 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. */ //! Types representing where the data is the sent. mod address; use std::sync::Arc; use serde::{Deserialize, Serialize}; pub use address::EndpointAddress; type EndpointMetadata = crate::metadata::MetadataView<Metadata>; /// A destination endpoint with any associated metadata. #[derive(Debug, Deserialize, Serialize, PartialEq, Clone, PartialOrd, Eq)] #[non_exhaustive] #[serde(deny_unknown_fields)] pub struct Endpoint { pub address: EndpointAddress, #[serde(default)] pub metadata: EndpointMetadata, } impl Endpoint { /// Creates a new [`Endpoint`] with no metadata. pub fn new(address: EndpointAddress) -> Self { Self { address, ..<_>::default() } } /// Creates a new [`Endpoint`] with the specified `metadata`. pub fn with_metadata(address: EndpointAddress, metadata: impl Into<EndpointMetadata>) -> Self { Self { address, metadata: metadata.into(), ..<_>::default() } } } impl Default for Endpoint { fn default() -> Self { Self { address: EndpointAddress::UNSPECIFIED, metadata: <_>::default(), } } } impl std::str::FromStr for Endpoint { type Err = <EndpointAddress as std::str::FromStr>::Err; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self { address: s.parse()?, ..Self::default() }) } } /// Represents the set of all known upstream endpoints. #[derive(Clone, Debug, PartialEq)] pub struct Endpoints(Arc<Vec<Endpoint>>); impl Endpoints { /// Returns an [`Endpoints`] backed by the provided list of endpoints. pub fn new(endpoints: Vec<Endpoint>) -> Option<Self> { match endpoints.is_empty() { true => None, false => Some(Self(Arc::new(endpoints))), } } } /// Provides a read-only view into the underlying endpoints. impl AsRef<Vec<Endpoint>> for Endpoints { fn as_ref(&self) -> &Vec<Endpoint> { self.0.as_ref() } } /// Metadata specific to endpoints. #[derive(Default, Debug, Deserialize, Serialize, PartialEq, Clone, PartialOrd, Eq)] #[non_exhaustive] pub struct Metadata { #[serde(with = "base64_set")] pub tokens: base64_set::Set, } /// A module for providing base64 encoding for a `BTreeSet` at the `serde` /// boundary. Accepts a list of strings representing Base64 encoded data, /// this list is then converted into its binary representation while in memory, /// and then encoded back as a list of base64 strings. mod base64_set { use serde::de::Error; pub type Set<T = Vec<u8>> = std::collections::BTreeSet<T>; pub fn serialize<S>(set: &Set, ser: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serde::Serialize::serialize(&set.iter().map(base64::encode).collect::<Vec<_>>(), ser) } pub fn
<'de, D>(de: D) -> Result<Set, D::Error> where D: serde::Deserializer<'de>, { let items = <Vec<String> as serde::Deserialize>::deserialize(de)?; let set = items.iter().cloned().collect::<Set<String>>(); if set.len()!= items.len() { Err(D::Error::custom( "Found duplicate tokens in endpoint metadata.", )) } else { set.into_iter() .map(|string| base64::decode(string).map_err(D::Error::custom)) .collect() } } } #[derive(Debug, Clone, thiserror::Error)] pub enum MetadataError { #[error("Invalid bas64 encoded token: `{0}`.")] InvalidBase64(base64::DecodeError), #[error("Missing required key `{0}`.")] MissingKey(&'static str), #[error("Invalid type ({expected}) given for `{key}`.")] InvalidType { key: &'static str, expected: &'static str, }, } impl std::convert::TryFrom<prost_types::Struct> for Metadata { type Error = MetadataError; fn try_from(mut value: prost_types::Struct) -> Result<Self, Self::Error> { use prost_types::value::Kind; const TOKENS: &str = "tokens"; let tokens = if let Some(kind) = value.fields.remove(TOKENS).and_then(|v| v.kind) { if let Kind::ListValue(list) = kind { list.values .into_iter() .filter_map(|v| v.kind) .map(|kind| { if let Kind::StringValue(string) = kind { base64::decode(string).map_err(MetadataError::InvalidBase64) } else { Err(MetadataError::InvalidType { key: "quilkin.dev.tokens", expected: "base64 string", }) } }) .collect::<Result<_, _>>()? } else { return Err(MetadataError::MissingKey(TOKENS)); } } else { <_>::default() }; Ok(Self { tokens }) } } /// UpstreamEndpoints represents a set of endpoints. /// This set is guaranteed to be non-empty - any operation that would /// cause the set to be empty will return an error instead. #[derive(Debug)] pub struct UpstreamEndpoints { /// All endpoints in the initial set - this list never /// changes after initialization. endpoints: Endpoints, /// A view into the current subset of endpoints in the original set. /// It contains indices into the initial set, to form the subset. /// If unset, the initial set is the current subset. subset: Option<Vec<usize>>, } impl From<Endpoints> for UpstreamEndpoints { fn from(endpoints: Endpoints) -> Self { UpstreamEndpoints { endpoints, subset: None, } } } impl UpstreamEndpoints { /// Returns the number of endpoints in the backing set. pub fn size(&self) -> usize { self.subset .as_ref() .map(|subset| subset.len()) .unwrap_or_else(|| self.endpoints.0.len()) } /// Updates the current subset of endpoints to contain only the endpoint /// at the specified zero-indexed position, returns `None` if `index` /// is greater than the number of endpoints. pub fn keep(&mut self, index: usize) -> Option<()> { if index >= self.size() { return None; } match self.subset.as_mut() { Some(subset) => { let index = subset[index]; subset.clear(); subset.push(index); } None => { self.subset = Some(vec![index]); } } Some(()) } /// Updates the current subset of endpoints to contain only the endpoints /// which the predicate returned `true`. /// Returns an error if the predicate returns `false` for all endpoints. pub fn retain<F>(&mut self, predicate: F) -> RetainedItems where F: Fn(&Endpoint) -> bool, { let endpoints = self .subset .as_ref() .map(|s| either::Right(s.iter().map(|&index| (index, &self.endpoints.0[index])))) .unwrap_or_else(|| either::Left(self.endpoints.0.iter().enumerate())); let total_items = endpoints.clone().count(); let new_subset = endpoints .filter(|(_, ep)| predicate(ep)) .map(|(i, _)| i) .collect::<Vec<_>>(); if new_subset.is_empty() { return RetainedItems::None; } let retained_items = new_subset.len(); self.subset = Some(new_subset); if retained_items == total_items { RetainedItems::All } else { RetainedItems::Some(retained_items) } } /// Iterate over the endpoints in the current subset. pub fn iter(&self) -> UpstreamEndpointsIter { UpstreamEndpointsIter { collection: self, index: 0, } } } /// An enum representing the result of a [`UpstreamEndpoints::retain`] call, /// detailing how many (if any) of the endpoints were retained by the predicate. #[non_exhaustive] #[must_use] #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum RetainedItems { None, Some(usize), All, } impl RetainedItems { /// Returns whether `self` is [`RetainedItems::None`]. pub fn is_none(&self) -> bool { matches!(self, Self::None) } /// Returns whether `self` is [`RetainedItems::All`]. pub fn is_all(&self) -> bool { matches!(self, Self::All) } /// Returns whether `self` is [`RetainedItems::Some`]. pub fn is_some(&self) -> bool { matches!(self, Self::Some(_)) } } /// An Iterator over all endpoints in an [`UpstreamEndpoints`] pub struct UpstreamEndpointsIter<'a> { collection: &'a UpstreamEndpoints, index: usize, } impl<'a> Iterator for UpstreamEndpointsIter<'a> { type Item = &'a Endpoint; fn next(&mut self) -> Option<Self::Item> { match &self.collection.subset { Some(subset) => { self.index += 1; subset .get(self.index - 1) .and_then(|&index| self.collection.endpoints.0.get(index)) } None => { self.index += 1; self.collection.endpoints.0.get(self.index - 1) } } } } #[cfg(test)] mod tests { use super::*; fn ep(id: u8) -> Endpoint { Endpoint::new(([127, 0, 0, id], 8080u16).into()) } #[test] fn endpoint_metadata() { let metadata = Metadata { tokens: vec!["Man".into()].into_iter().collect(), }; assert_eq!( serde_json::to_value(EndpointMetadata::from(metadata)).unwrap(), serde_json::json!({ crate::metadata::KEY: { "tokens": ["TWFu"], } }) ); } #[test] fn new_endpoints() { assert!(Endpoints::new(vec![]).is_none()); assert!(Endpoints::new(vec![ep(1)]).is_some()); } #[test] fn keep() { let initial_endpoints = vec![ep(1), ep(2), ep(3)]; let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); assert!(up.keep(initial_endpoints.len() - 1).is_some()); let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); assert!(up.keep(initial_endpoints.len()).is_none()); // Limit the set to only one element. let mut up = UpstreamEndpoints::from(Endpoints::new(initial_endpoints.clone()).unwrap()); up.keep(1).unwrap(); up.keep(0).unwrap(); assert_eq!(vec![&initial_endpoints[1]], up.iter().collect::<Vec<_>>()); let mut up = UpstreamEndpoints::from(Endpoints::new(initial_endpoints).unwrap()); up.keep(1).unwrap(); assert!(up.keep(1).is_none()); } #[test] fn retain() { let initial_endpoints = vec![ep(1), ep(2), ep(3), ep(4)]; let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); let items = up.retain(|ep| ep.address!= ([127, 0, 0, 2], 8080).into()); assert!(matches!(items, RetainedItems::Some(3))); assert_eq!(up.size(), 3); assert_eq!( vec![ep(1), ep(3), ep(4)], up.iter().cloned().collect::<Vec<_>>() ); let items = up.retain(|ep| ep.address!= ([127, 0, 0, 3], 8080).into()); assert!(matches!(items, RetainedItems::Some(2))); assert_eq!(up.size(), 2); assert_eq!(vec![ep(1), ep(4)], up.iter().cloned().collect::<Vec<_>>()); // test an empty result on retain let result = up.retain(|_| false); assert!(result.is_none()); let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints).unwrap().into(); let result = up.retain(|_| false); assert!(result.is_none()); } #[test] fn upstream_len() { let mut up: UpstreamEndpoints = Endpoints::new(vec![ep(1), ep(2), ep(3)]).unwrap().into(); // starts out with all endpoints. assert_eq!(up.size(), 3); // verify that the set is now a singleton. up.keep(1).unwrap(); assert_eq!(up.size(), 1); } #[test] fn upstream_all_iter() { let initial_endpoints = vec![ep(1), ep(2), ep(3)]; let up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); let result = up.iter().cloned().collect::<Vec<_>>(); assert_eq!(initial_endpoints, result); } #[test] fn upstream_some_iter() { let mut up = UpstreamEndpoints::from(Endpoints::new(vec![ep(1), ep(2), ep(3)]).unwrap()); up.keep(1).unwrap(); assert_eq!(vec![ep(2)], up.iter().cloned().collect::<Vec<_>>()); } #[test] fn yaml_parse_endpoint_metadata() { let yaml = " user: key1: value1 quilkin.dev: tokens: - MXg3aWp5Ng== #1x7ijy6 - OGdqM3YyaQ== #8gj3v2i "; assert_eq!( serde_json::to_value(serde_yaml::from_str::<EndpointMetadata>(yaml).unwrap()).unwrap(), serde_json::json!({ "user": { "key1": "value1" }, "quilkin.dev": { "tokens": ["MXg3aWp5Ng==", "OGdqM3YyaQ=="], } }) ); } #[test] fn parse_dns_endpoints() { let localhost = "address: localhost:80"; serde_yaml::from_str::<Endpoint>(localhost).unwrap(); } #[test] fn yaml_parse_invalid_endpoint_metadata() { let not_a_list = " quilkin.dev: tokens: OGdqM3YyaQ== "; let not_a_string_value = " quilkin.dev: tokens: - map: a: b "; let not_a_base64_string = " quilkin.dev: tokens: - OGdqM3YyaQ== #8gj3v2i - iix "; for yaml in &[not_a_list, not_a_string_value, not_a_base64_string] { serde_yaml::from_str::<EndpointMetadata>(yaml).unwrap_err(); } } }
deserialize
identifier_name
endpoint.rs
/* * Copyright 2021 Google LLC * * 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. */ //! Types representing where the data is the sent. mod address; use std::sync::Arc; use serde::{Deserialize, Serialize}; pub use address::EndpointAddress; type EndpointMetadata = crate::metadata::MetadataView<Metadata>; /// A destination endpoint with any associated metadata. #[derive(Debug, Deserialize, Serialize, PartialEq, Clone, PartialOrd, Eq)] #[non_exhaustive] #[serde(deny_unknown_fields)] pub struct Endpoint { pub address: EndpointAddress, #[serde(default)] pub metadata: EndpointMetadata, } impl Endpoint { /// Creates a new [`Endpoint`] with no metadata. pub fn new(address: EndpointAddress) -> Self { Self { address, ..<_>::default() } } /// Creates a new [`Endpoint`] with the specified `metadata`. pub fn with_metadata(address: EndpointAddress, metadata: impl Into<EndpointMetadata>) -> Self { Self { address, metadata: metadata.into(), ..<_>::default() } } } impl Default for Endpoint { fn default() -> Self { Self { address: EndpointAddress::UNSPECIFIED, metadata: <_>::default(), } } } impl std::str::FromStr for Endpoint { type Err = <EndpointAddress as std::str::FromStr>::Err; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self { address: s.parse()?, ..Self::default() }) } } /// Represents the set of all known upstream endpoints. #[derive(Clone, Debug, PartialEq)] pub struct Endpoints(Arc<Vec<Endpoint>>); impl Endpoints { /// Returns an [`Endpoints`] backed by the provided list of endpoints. pub fn new(endpoints: Vec<Endpoint>) -> Option<Self> { match endpoints.is_empty() { true => None, false => Some(Self(Arc::new(endpoints))), } } } /// Provides a read-only view into the underlying endpoints. impl AsRef<Vec<Endpoint>> for Endpoints { fn as_ref(&self) -> &Vec<Endpoint> { self.0.as_ref() } } /// Metadata specific to endpoints. #[derive(Default, Debug, Deserialize, Serialize, PartialEq, Clone, PartialOrd, Eq)] #[non_exhaustive] pub struct Metadata { #[serde(with = "base64_set")] pub tokens: base64_set::Set, } /// A module for providing base64 encoding for a `BTreeSet` at the `serde` /// boundary. Accepts a list of strings representing Base64 encoded data, /// this list is then converted into its binary representation while in memory, /// and then encoded back as a list of base64 strings. mod base64_set { use serde::de::Error; pub type Set<T = Vec<u8>> = std::collections::BTreeSet<T>; pub fn serialize<S>(set: &Set, ser: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serde::Serialize::serialize(&set.iter().map(base64::encode).collect::<Vec<_>>(), ser) } pub fn deserialize<'de, D>(de: D) -> Result<Set, D::Error> where D: serde::Deserializer<'de>, { let items = <Vec<String> as serde::Deserialize>::deserialize(de)?; let set = items.iter().cloned().collect::<Set<String>>(); if set.len()!= items.len() { Err(D::Error::custom( "Found duplicate tokens in endpoint metadata.", )) } else { set.into_iter() .map(|string| base64::decode(string).map_err(D::Error::custom)) .collect() } } } #[derive(Debug, Clone, thiserror::Error)] pub enum MetadataError { #[error("Invalid bas64 encoded token: `{0}`.")] InvalidBase64(base64::DecodeError), #[error("Missing required key `{0}`.")] MissingKey(&'static str), #[error("Invalid type ({expected}) given for `{key}`.")] InvalidType { key: &'static str, expected: &'static str, }, } impl std::convert::TryFrom<prost_types::Struct> for Metadata { type Error = MetadataError; fn try_from(mut value: prost_types::Struct) -> Result<Self, Self::Error> { use prost_types::value::Kind; const TOKENS: &str = "tokens"; let tokens = if let Some(kind) = value.fields.remove(TOKENS).and_then(|v| v.kind) { if let Kind::ListValue(list) = kind { list.values .into_iter() .filter_map(|v| v.kind) .map(|kind| { if let Kind::StringValue(string) = kind { base64::decode(string).map_err(MetadataError::InvalidBase64) } else { Err(MetadataError::InvalidType { key: "quilkin.dev.tokens", expected: "base64 string", }) } }) .collect::<Result<_, _>>()? } else { return Err(MetadataError::MissingKey(TOKENS)); } } else { <_>::default() }; Ok(Self { tokens }) } } /// UpstreamEndpoints represents a set of endpoints. /// This set is guaranteed to be non-empty - any operation that would /// cause the set to be empty will return an error instead. #[derive(Debug)] pub struct UpstreamEndpoints { /// All endpoints in the initial set - this list never /// changes after initialization. endpoints: Endpoints, /// A view into the current subset of endpoints in the original set. /// It contains indices into the initial set, to form the subset. /// If unset, the initial set is the current subset. subset: Option<Vec<usize>>, } impl From<Endpoints> for UpstreamEndpoints { fn from(endpoints: Endpoints) -> Self { UpstreamEndpoints { endpoints, subset: None, } } } impl UpstreamEndpoints { /// Returns the number of endpoints in the backing set. pub fn size(&self) -> usize { self.subset .as_ref() .map(|subset| subset.len()) .unwrap_or_else(|| self.endpoints.0.len()) } /// Updates the current subset of endpoints to contain only the endpoint /// at the specified zero-indexed position, returns `None` if `index` /// is greater than the number of endpoints. pub fn keep(&mut self, index: usize) -> Option<()> { if index >= self.size() { return None; } match self.subset.as_mut() { Some(subset) => { let index = subset[index]; subset.clear(); subset.push(index); } None => { self.subset = Some(vec![index]); } } Some(()) } /// Updates the current subset of endpoints to contain only the endpoints /// which the predicate returned `true`. /// Returns an error if the predicate returns `false` for all endpoints. pub fn retain<F>(&mut self, predicate: F) -> RetainedItems where F: Fn(&Endpoint) -> bool, { let endpoints = self .subset .as_ref() .map(|s| either::Right(s.iter().map(|&index| (index, &self.endpoints.0[index])))) .unwrap_or_else(|| either::Left(self.endpoints.0.iter().enumerate())); let total_items = endpoints.clone().count(); let new_subset = endpoints .filter(|(_, ep)| predicate(ep)) .map(|(i, _)| i) .collect::<Vec<_>>(); if new_subset.is_empty() { return RetainedItems::None; } let retained_items = new_subset.len(); self.subset = Some(new_subset); if retained_items == total_items { RetainedItems::All } else { RetainedItems::Some(retained_items) } } /// Iterate over the endpoints in the current subset. pub fn iter(&self) -> UpstreamEndpointsIter { UpstreamEndpointsIter { collection: self, index: 0, } } } /// An enum representing the result of a [`UpstreamEndpoints::retain`] call, /// detailing how many (if any) of the endpoints were retained by the predicate. #[non_exhaustive] #[must_use] #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum RetainedItems { None, Some(usize), All, } impl RetainedItems { /// Returns whether `self` is [`RetainedItems::None`]. pub fn is_none(&self) -> bool { matches!(self, Self::None) } /// Returns whether `self` is [`RetainedItems::All`]. pub fn is_all(&self) -> bool { matches!(self, Self::All) } /// Returns whether `self` is [`RetainedItems::Some`]. pub fn is_some(&self) -> bool { matches!(self, Self::Some(_)) } } /// An Iterator over all endpoints in an [`UpstreamEndpoints`] pub struct UpstreamEndpointsIter<'a> { collection: &'a UpstreamEndpoints, index: usize, } impl<'a> Iterator for UpstreamEndpointsIter<'a> { type Item = &'a Endpoint; fn next(&mut self) -> Option<Self::Item> { match &self.collection.subset { Some(subset) => { self.index += 1; subset .get(self.index - 1) .and_then(|&index| self.collection.endpoints.0.get(index)) } None => { self.index += 1; self.collection.endpoints.0.get(self.index - 1) } } } } #[cfg(test)] mod tests { use super::*; fn ep(id: u8) -> Endpoint { Endpoint::new(([127, 0, 0, id], 8080u16).into()) } #[test] fn endpoint_metadata() { let metadata = Metadata { tokens: vec!["Man".into()].into_iter().collect(), }; assert_eq!( serde_json::to_value(EndpointMetadata::from(metadata)).unwrap(), serde_json::json!({ crate::metadata::KEY: { "tokens": ["TWFu"], } }) ); } #[test] fn new_endpoints() { assert!(Endpoints::new(vec![]).is_none()); assert!(Endpoints::new(vec![ep(1)]).is_some()); } #[test] fn keep() { let initial_endpoints = vec![ep(1), ep(2), ep(3)]; let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); assert!(up.keep(initial_endpoints.len() - 1).is_some()); let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); assert!(up.keep(initial_endpoints.len()).is_none()); // Limit the set to only one element. let mut up = UpstreamEndpoints::from(Endpoints::new(initial_endpoints.clone()).unwrap()); up.keep(1).unwrap(); up.keep(0).unwrap(); assert_eq!(vec![&initial_endpoints[1]], up.iter().collect::<Vec<_>>()); let mut up = UpstreamEndpoints::from(Endpoints::new(initial_endpoints).unwrap()); up.keep(1).unwrap(); assert!(up.keep(1).is_none()); } #[test] fn retain() { let initial_endpoints = vec![ep(1), ep(2), ep(3), ep(4)]; let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); let items = up.retain(|ep| ep.address!= ([127, 0, 0, 2], 8080).into()); assert!(matches!(items, RetainedItems::Some(3))); assert_eq!(up.size(), 3); assert_eq!( vec![ep(1), ep(3), ep(4)], up.iter().cloned().collect::<Vec<_>>() ); let items = up.retain(|ep| ep.address!= ([127, 0, 0, 3], 8080).into()); assert!(matches!(items, RetainedItems::Some(2))); assert_eq!(up.size(), 2); assert_eq!(vec![ep(1), ep(4)], up.iter().cloned().collect::<Vec<_>>()); // test an empty result on retain let result = up.retain(|_| false); assert!(result.is_none()); let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints).unwrap().into(); let result = up.retain(|_| false); assert!(result.is_none()); } #[test] fn upstream_len() { let mut up: UpstreamEndpoints = Endpoints::new(vec![ep(1), ep(2), ep(3)]).unwrap().into(); // starts out with all endpoints. assert_eq!(up.size(), 3); // verify that the set is now a singleton. up.keep(1).unwrap(); assert_eq!(up.size(), 1); } #[test] fn upstream_all_iter() { let initial_endpoints = vec![ep(1), ep(2), ep(3)]; let up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); let result = up.iter().cloned().collect::<Vec<_>>(); assert_eq!(initial_endpoints, result); } #[test] fn upstream_some_iter() { let mut up = UpstreamEndpoints::from(Endpoints::new(vec![ep(1), ep(2), ep(3)]).unwrap()); up.keep(1).unwrap(); assert_eq!(vec![ep(2)], up.iter().cloned().collect::<Vec<_>>()); } #[test] fn yaml_parse_endpoint_metadata() { let yaml = " user: key1: value1 quilkin.dev: tokens: - MXg3aWp5Ng== #1x7ijy6 - OGdqM3YyaQ== #8gj3v2i "; assert_eq!( serde_json::to_value(serde_yaml::from_str::<EndpointMetadata>(yaml).unwrap()).unwrap(), serde_json::json!({ "user": { "key1": "value1" }, "quilkin.dev": { "tokens": ["MXg3aWp5Ng==", "OGdqM3YyaQ=="], } }) ); } #[test] fn parse_dns_endpoints() { let localhost = "address: localhost:80"; serde_yaml::from_str::<Endpoint>(localhost).unwrap(); } #[test] fn yaml_parse_invalid_endpoint_metadata() { let not_a_list = " quilkin.dev: tokens: OGdqM3YyaQ== "; let not_a_string_value = " quilkin.dev: tokens: - map: a: b
let not_a_base64_string = " quilkin.dev: tokens: - OGdqM3YyaQ== #8gj3v2i - iix "; for yaml in &[not_a_list, not_a_string_value, not_a_base64_string] { serde_yaml::from_str::<EndpointMetadata>(yaml).unwrap_err(); } } }
";
random_line_split
endpoint.rs
/* * Copyright 2021 Google LLC * * 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. */ //! Types representing where the data is the sent. mod address; use std::sync::Arc; use serde::{Deserialize, Serialize}; pub use address::EndpointAddress; type EndpointMetadata = crate::metadata::MetadataView<Metadata>; /// A destination endpoint with any associated metadata. #[derive(Debug, Deserialize, Serialize, PartialEq, Clone, PartialOrd, Eq)] #[non_exhaustive] #[serde(deny_unknown_fields)] pub struct Endpoint { pub address: EndpointAddress, #[serde(default)] pub metadata: EndpointMetadata, } impl Endpoint { /// Creates a new [`Endpoint`] with no metadata. pub fn new(address: EndpointAddress) -> Self { Self { address, ..<_>::default() } } /// Creates a new [`Endpoint`] with the specified `metadata`. pub fn with_metadata(address: EndpointAddress, metadata: impl Into<EndpointMetadata>) -> Self { Self { address, metadata: metadata.into(), ..<_>::default() } } } impl Default for Endpoint { fn default() -> Self { Self { address: EndpointAddress::UNSPECIFIED, metadata: <_>::default(), } } } impl std::str::FromStr for Endpoint { type Err = <EndpointAddress as std::str::FromStr>::Err; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self { address: s.parse()?, ..Self::default() }) } } /// Represents the set of all known upstream endpoints. #[derive(Clone, Debug, PartialEq)] pub struct Endpoints(Arc<Vec<Endpoint>>); impl Endpoints { /// Returns an [`Endpoints`] backed by the provided list of endpoints. pub fn new(endpoints: Vec<Endpoint>) -> Option<Self> { match endpoints.is_empty() { true => None, false => Some(Self(Arc::new(endpoints))), } } } /// Provides a read-only view into the underlying endpoints. impl AsRef<Vec<Endpoint>> for Endpoints { fn as_ref(&self) -> &Vec<Endpoint> { self.0.as_ref() } } /// Metadata specific to endpoints. #[derive(Default, Debug, Deserialize, Serialize, PartialEq, Clone, PartialOrd, Eq)] #[non_exhaustive] pub struct Metadata { #[serde(with = "base64_set")] pub tokens: base64_set::Set, } /// A module for providing base64 encoding for a `BTreeSet` at the `serde` /// boundary. Accepts a list of strings representing Base64 encoded data, /// this list is then converted into its binary representation while in memory, /// and then encoded back as a list of base64 strings. mod base64_set { use serde::de::Error; pub type Set<T = Vec<u8>> = std::collections::BTreeSet<T>; pub fn serialize<S>(set: &Set, ser: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serde::Serialize::serialize(&set.iter().map(base64::encode).collect::<Vec<_>>(), ser) } pub fn deserialize<'de, D>(de: D) -> Result<Set, D::Error> where D: serde::Deserializer<'de>, { let items = <Vec<String> as serde::Deserialize>::deserialize(de)?; let set = items.iter().cloned().collect::<Set<String>>(); if set.len()!= items.len() { Err(D::Error::custom( "Found duplicate tokens in endpoint metadata.", )) } else { set.into_iter() .map(|string| base64::decode(string).map_err(D::Error::custom)) .collect() } } } #[derive(Debug, Clone, thiserror::Error)] pub enum MetadataError { #[error("Invalid bas64 encoded token: `{0}`.")] InvalidBase64(base64::DecodeError), #[error("Missing required key `{0}`.")] MissingKey(&'static str), #[error("Invalid type ({expected}) given for `{key}`.")] InvalidType { key: &'static str, expected: &'static str, }, } impl std::convert::TryFrom<prost_types::Struct> for Metadata { type Error = MetadataError; fn try_from(mut value: prost_types::Struct) -> Result<Self, Self::Error> { use prost_types::value::Kind; const TOKENS: &str = "tokens"; let tokens = if let Some(kind) = value.fields.remove(TOKENS).and_then(|v| v.kind) { if let Kind::ListValue(list) = kind { list.values .into_iter() .filter_map(|v| v.kind) .map(|kind| { if let Kind::StringValue(string) = kind { base64::decode(string).map_err(MetadataError::InvalidBase64) } else { Err(MetadataError::InvalidType { key: "quilkin.dev.tokens", expected: "base64 string", }) } }) .collect::<Result<_, _>>()? } else { return Err(MetadataError::MissingKey(TOKENS)); } } else { <_>::default() }; Ok(Self { tokens }) } } /// UpstreamEndpoints represents a set of endpoints. /// This set is guaranteed to be non-empty - any operation that would /// cause the set to be empty will return an error instead. #[derive(Debug)] pub struct UpstreamEndpoints { /// All endpoints in the initial set - this list never /// changes after initialization. endpoints: Endpoints, /// A view into the current subset of endpoints in the original set. /// It contains indices into the initial set, to form the subset. /// If unset, the initial set is the current subset. subset: Option<Vec<usize>>, } impl From<Endpoints> for UpstreamEndpoints { fn from(endpoints: Endpoints) -> Self { UpstreamEndpoints { endpoints, subset: None, } } } impl UpstreamEndpoints { /// Returns the number of endpoints in the backing set. pub fn size(&self) -> usize { self.subset .as_ref() .map(|subset| subset.len()) .unwrap_or_else(|| self.endpoints.0.len()) } /// Updates the current subset of endpoints to contain only the endpoint /// at the specified zero-indexed position, returns `None` if `index` /// is greater than the number of endpoints. pub fn keep(&mut self, index: usize) -> Option<()> { if index >= self.size() { return None; } match self.subset.as_mut() { Some(subset) => { let index = subset[index]; subset.clear(); subset.push(index); } None => { self.subset = Some(vec![index]); } } Some(()) } /// Updates the current subset of endpoints to contain only the endpoints /// which the predicate returned `true`. /// Returns an error if the predicate returns `false` for all endpoints. pub fn retain<F>(&mut self, predicate: F) -> RetainedItems where F: Fn(&Endpoint) -> bool, { let endpoints = self .subset .as_ref() .map(|s| either::Right(s.iter().map(|&index| (index, &self.endpoints.0[index])))) .unwrap_or_else(|| either::Left(self.endpoints.0.iter().enumerate())); let total_items = endpoints.clone().count(); let new_subset = endpoints .filter(|(_, ep)| predicate(ep)) .map(|(i, _)| i) .collect::<Vec<_>>(); if new_subset.is_empty()
let retained_items = new_subset.len(); self.subset = Some(new_subset); if retained_items == total_items { RetainedItems::All } else { RetainedItems::Some(retained_items) } } /// Iterate over the endpoints in the current subset. pub fn iter(&self) -> UpstreamEndpointsIter { UpstreamEndpointsIter { collection: self, index: 0, } } } /// An enum representing the result of a [`UpstreamEndpoints::retain`] call, /// detailing how many (if any) of the endpoints were retained by the predicate. #[non_exhaustive] #[must_use] #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum RetainedItems { None, Some(usize), All, } impl RetainedItems { /// Returns whether `self` is [`RetainedItems::None`]. pub fn is_none(&self) -> bool { matches!(self, Self::None) } /// Returns whether `self` is [`RetainedItems::All`]. pub fn is_all(&self) -> bool { matches!(self, Self::All) } /// Returns whether `self` is [`RetainedItems::Some`]. pub fn is_some(&self) -> bool { matches!(self, Self::Some(_)) } } /// An Iterator over all endpoints in an [`UpstreamEndpoints`] pub struct UpstreamEndpointsIter<'a> { collection: &'a UpstreamEndpoints, index: usize, } impl<'a> Iterator for UpstreamEndpointsIter<'a> { type Item = &'a Endpoint; fn next(&mut self) -> Option<Self::Item> { match &self.collection.subset { Some(subset) => { self.index += 1; subset .get(self.index - 1) .and_then(|&index| self.collection.endpoints.0.get(index)) } None => { self.index += 1; self.collection.endpoints.0.get(self.index - 1) } } } } #[cfg(test)] mod tests { use super::*; fn ep(id: u8) -> Endpoint { Endpoint::new(([127, 0, 0, id], 8080u16).into()) } #[test] fn endpoint_metadata() { let metadata = Metadata { tokens: vec!["Man".into()].into_iter().collect(), }; assert_eq!( serde_json::to_value(EndpointMetadata::from(metadata)).unwrap(), serde_json::json!({ crate::metadata::KEY: { "tokens": ["TWFu"], } }) ); } #[test] fn new_endpoints() { assert!(Endpoints::new(vec![]).is_none()); assert!(Endpoints::new(vec![ep(1)]).is_some()); } #[test] fn keep() { let initial_endpoints = vec![ep(1), ep(2), ep(3)]; let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); assert!(up.keep(initial_endpoints.len() - 1).is_some()); let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); assert!(up.keep(initial_endpoints.len()).is_none()); // Limit the set to only one element. let mut up = UpstreamEndpoints::from(Endpoints::new(initial_endpoints.clone()).unwrap()); up.keep(1).unwrap(); up.keep(0).unwrap(); assert_eq!(vec![&initial_endpoints[1]], up.iter().collect::<Vec<_>>()); let mut up = UpstreamEndpoints::from(Endpoints::new(initial_endpoints).unwrap()); up.keep(1).unwrap(); assert!(up.keep(1).is_none()); } #[test] fn retain() { let initial_endpoints = vec![ep(1), ep(2), ep(3), ep(4)]; let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); let items = up.retain(|ep| ep.address!= ([127, 0, 0, 2], 8080).into()); assert!(matches!(items, RetainedItems::Some(3))); assert_eq!(up.size(), 3); assert_eq!( vec![ep(1), ep(3), ep(4)], up.iter().cloned().collect::<Vec<_>>() ); let items = up.retain(|ep| ep.address!= ([127, 0, 0, 3], 8080).into()); assert!(matches!(items, RetainedItems::Some(2))); assert_eq!(up.size(), 2); assert_eq!(vec![ep(1), ep(4)], up.iter().cloned().collect::<Vec<_>>()); // test an empty result on retain let result = up.retain(|_| false); assert!(result.is_none()); let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints).unwrap().into(); let result = up.retain(|_| false); assert!(result.is_none()); } #[test] fn upstream_len() { let mut up: UpstreamEndpoints = Endpoints::new(vec![ep(1), ep(2), ep(3)]).unwrap().into(); // starts out with all endpoints. assert_eq!(up.size(), 3); // verify that the set is now a singleton. up.keep(1).unwrap(); assert_eq!(up.size(), 1); } #[test] fn upstream_all_iter() { let initial_endpoints = vec![ep(1), ep(2), ep(3)]; let up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); let result = up.iter().cloned().collect::<Vec<_>>(); assert_eq!(initial_endpoints, result); } #[test] fn upstream_some_iter() { let mut up = UpstreamEndpoints::from(Endpoints::new(vec![ep(1), ep(2), ep(3)]).unwrap()); up.keep(1).unwrap(); assert_eq!(vec![ep(2)], up.iter().cloned().collect::<Vec<_>>()); } #[test] fn yaml_parse_endpoint_metadata() { let yaml = " user: key1: value1 quilkin.dev: tokens: - MXg3aWp5Ng== #1x7ijy6 - OGdqM3YyaQ== #8gj3v2i "; assert_eq!( serde_json::to_value(serde_yaml::from_str::<EndpointMetadata>(yaml).unwrap()).unwrap(), serde_json::json!({ "user": { "key1": "value1" }, "quilkin.dev": { "tokens": ["MXg3aWp5Ng==", "OGdqM3YyaQ=="], } }) ); } #[test] fn parse_dns_endpoints() { let localhost = "address: localhost:80"; serde_yaml::from_str::<Endpoint>(localhost).unwrap(); } #[test] fn yaml_parse_invalid_endpoint_metadata() { let not_a_list = " quilkin.dev: tokens: OGdqM3YyaQ== "; let not_a_string_value = " quilkin.dev: tokens: - map: a: b "; let not_a_base64_string = " quilkin.dev: tokens: - OGdqM3YyaQ== #8gj3v2i - iix "; for yaml in &[not_a_list, not_a_string_value, not_a_base64_string] { serde_yaml::from_str::<EndpointMetadata>(yaml).unwrap_err(); } } }
{ return RetainedItems::None; }
conditional_block
lib.rs
extern crate num; extern crate image; use std::str::FromStr; use num::Complex; use image::ColorType; use image::png::PNGEncoder; use std::fs::File; use std::io::Result; fn escapes(c: Complex<f64>, limit: u32) -> Option<u32> { let mut z = Complex {re: 0.0, im: 0.0}; for i in 0..limit { z = z*z + c; if z.norm_sqr() > 4.0 { return Some(i); } } return None; } pub fn render(pixels: &mut [u8], bounds: (usize, usize), upper_left: (f64, f64), lower_right: (f64, f64)) { assert!(pixels.len() == bounds.0 * bounds.1); for row in 0.. bounds.1 { for column in 0.. bounds.0 { let point = pixel_to_point(bounds, (column,row), upper_left, lower_right); pixels[row * bounds.0 + column] = match escapes(Complex {re: point.0, im: point.1}, 255) { None => 0, Some(count) => 255 - count as u8, }; } } } pub fn write_bitmap(filename: &str, pixels: &[u8], bounds: (usize, usize)) -> Result<()> { let output = try!(File::create(filename)); let encoder = PNGEncoder::new(output); try!(encoder.encode(&pixels[..], bounds.0 as u32, bounds.1 as u32, ColorType::Gray(8)));
} pub fn parse_pair<T: FromStr>(s: &str, separator: char) -> Option<(T, T)> { match s.find(separator) { None => None, Some(index) => { match (T::from_str(&s[..index]), T::from_str(&s[index+1..])) { (Ok(l), Ok(r)) => Some((l, r)), _ => None } } } } fn pixel_to_point(bounds: (usize, usize), pixel: (usize, usize), upper_left: (f64, f64), lower_right: (f64, f64)) -> (f64, f64) { let (width, height) = (lower_right.0 - upper_left.0, upper_left.1 - lower_right.1); (upper_left.0 + pixel.0 as f64 * width / bounds.0 as f64, upper_left.1 - pixel.1 as f64 * height / bounds.1 as f64) } #[cfg(test)] mod test { use super::*; #[test] fn test_parse_pair() { assert_eq!(parse_pair::<i32>("", ','), None); assert_eq!(parse_pair::<i32>("10,", ','), None); assert_eq!(parse_pair::<i32>(",10", ','), None); assert_eq!(parse_pair::<i32>("10,20", ','), Some((10, 20))); } #[test] fn test_pixel_to_point() { assert_eq!(pixel_to_point((100, 100), (25, 75), (-1.0, 1.0), (1.0, -1.0)), (-0.5, -0.5)); } }
Ok(())
random_line_split
lib.rs
extern crate num; extern crate image; use std::str::FromStr; use num::Complex; use image::ColorType; use image::png::PNGEncoder; use std::fs::File; use std::io::Result; fn escapes(c: Complex<f64>, limit: u32) -> Option<u32> { let mut z = Complex {re: 0.0, im: 0.0}; for i in 0..limit { z = z*z + c; if z.norm_sqr() > 4.0 { return Some(i); } } return None; } pub fn render(pixels: &mut [u8], bounds: (usize, usize), upper_left: (f64, f64), lower_right: (f64, f64)) { assert!(pixels.len() == bounds.0 * bounds.1); for row in 0.. bounds.1 { for column in 0.. bounds.0 { let point = pixel_to_point(bounds, (column,row), upper_left, lower_right); pixels[row * bounds.0 + column] = match escapes(Complex {re: point.0, im: point.1}, 255) { None => 0, Some(count) => 255 - count as u8, }; } } } pub fn write_bitmap(filename: &str, pixels: &[u8], bounds: (usize, usize)) -> Result<()>
pub fn parse_pair<T: FromStr>(s: &str, separator: char) -> Option<(T, T)> { match s.find(separator) { None => None, Some(index) => { match (T::from_str(&s[..index]), T::from_str(&s[index+1..])) { (Ok(l), Ok(r)) => Some((l, r)), _ => None } } } } fn pixel_to_point(bounds: (usize, usize), pixel: (usize, usize), upper_left: (f64, f64), lower_right: (f64, f64)) -> (f64, f64) { let (width, height) = (lower_right.0 - upper_left.0, upper_left.1 - lower_right.1); (upper_left.0 + pixel.0 as f64 * width / bounds.0 as f64, upper_left.1 - pixel.1 as f64 * height / bounds.1 as f64) } #[cfg(test)] mod test { use super::*; #[test] fn test_parse_pair() { assert_eq!(parse_pair::<i32>("", ','), None); assert_eq!(parse_pair::<i32>("10,", ','), None); assert_eq!(parse_pair::<i32>(",10", ','), None); assert_eq!(parse_pair::<i32>("10,20", ','), Some((10, 20))); } #[test] fn test_pixel_to_point() { assert_eq!(pixel_to_point((100, 100), (25, 75), (-1.0, 1.0), (1.0, -1.0)), (-0.5, -0.5)); } }
{ let output = try!(File::create(filename)); let encoder = PNGEncoder::new(output); try!(encoder.encode(&pixels[..], bounds.0 as u32, bounds.1 as u32, ColorType::Gray(8))); Ok(()) }
identifier_body
lib.rs
extern crate num; extern crate image; use std::str::FromStr; use num::Complex; use image::ColorType; use image::png::PNGEncoder; use std::fs::File; use std::io::Result; fn escapes(c: Complex<f64>, limit: u32) -> Option<u32> { let mut z = Complex {re: 0.0, im: 0.0}; for i in 0..limit { z = z*z + c; if z.norm_sqr() > 4.0 { return Some(i); } } return None; } pub fn
(pixels: &mut [u8], bounds: (usize, usize), upper_left: (f64, f64), lower_right: (f64, f64)) { assert!(pixels.len() == bounds.0 * bounds.1); for row in 0.. bounds.1 { for column in 0.. bounds.0 { let point = pixel_to_point(bounds, (column,row), upper_left, lower_right); pixels[row * bounds.0 + column] = match escapes(Complex {re: point.0, im: point.1}, 255) { None => 0, Some(count) => 255 - count as u8, }; } } } pub fn write_bitmap(filename: &str, pixels: &[u8], bounds: (usize, usize)) -> Result<()> { let output = try!(File::create(filename)); let encoder = PNGEncoder::new(output); try!(encoder.encode(&pixels[..], bounds.0 as u32, bounds.1 as u32, ColorType::Gray(8))); Ok(()) } pub fn parse_pair<T: FromStr>(s: &str, separator: char) -> Option<(T, T)> { match s.find(separator) { None => None, Some(index) => { match (T::from_str(&s[..index]), T::from_str(&s[index+1..])) { (Ok(l), Ok(r)) => Some((l, r)), _ => None } } } } fn pixel_to_point(bounds: (usize, usize), pixel: (usize, usize), upper_left: (f64, f64), lower_right: (f64, f64)) -> (f64, f64) { let (width, height) = (lower_right.0 - upper_left.0, upper_left.1 - lower_right.1); (upper_left.0 + pixel.0 as f64 * width / bounds.0 as f64, upper_left.1 - pixel.1 as f64 * height / bounds.1 as f64) } #[cfg(test)] mod test { use super::*; #[test] fn test_parse_pair() { assert_eq!(parse_pair::<i32>("", ','), None); assert_eq!(parse_pair::<i32>("10,", ','), None); assert_eq!(parse_pair::<i32>(",10", ','), None); assert_eq!(parse_pair::<i32>("10,20", ','), Some((10, 20))); } #[test] fn test_pixel_to_point() { assert_eq!(pixel_to_point((100, 100), (25, 75), (-1.0, 1.0), (1.0, -1.0)), (-0.5, -0.5)); } }
render
identifier_name
main.rs
#[macro_use] extern crate log; extern crate common; extern crate env_logger; extern crate game; extern crate getopts; extern crate gfx; extern crate sdl2; extern crate time; extern crate wad; use common::GeneralError; use getopts::Options; use std::path::PathBuf; use std::error::Error; use gfx::ShaderLoader; use wad::{Archive, TextureDirectory}; use gfx::Window; use game::SHADER_ROOT; use game::{Level, Game, GameConfig}; pub enum RunMode { DisplayHelp(String), Check { wad_file: PathBuf, metadata_file: PathBuf, }, ListLevelNames { wad_file: PathBuf, metadata_file: PathBuf, }, Play(GameConfig), } impl RunMode { pub fn from_args(args: &[String]) -> Result<RunMode, Box<Error>> { let mut opts = Options::new(); opts.optopt("i", "iwad", "initial WAD file to use [default='doom1.wad']", "FILE"); opts.optopt("m", "metadata", "path to TOML metadata file [default='doom.toml']", "FILE"); opts.optopt("r", "resolution", "the size of the game window [default=1280x720]", "WIDTHxHEIGHT"); opts.optopt("l", "level", "the index of the level to render [default=0]", "N"); opts.optopt("f", "fov", "horizontal field of view to please TotalBiscuit [default=65]", "FOV");
opts.optflag("h", "help", "print this help message and exit"); let matches = try!(opts.parse(&args[1..]).map_err(|e| GeneralError(e.to_string()))); if matches.opt_present("h") { return Ok(RunMode::DisplayHelp( opts.usage("rs_doom 0.0.7: A Rust Doom I/II Renderer."))) } let wad = matches.opt_str("iwad").unwrap_or("doom1.wad".to_owned()).into(); let metadata = matches.opt_str("metadata").unwrap_or("doom.toml".to_owned()).into(); Ok(if matches.opt_present("check") { RunMode::Check { wad_file: wad, metadata_file: metadata, } } else if matches.opt_present("list-levels") { RunMode::ListLevelNames { wad_file: wad, metadata_file: metadata, } } else { let size_str = matches.opt_str("resolution").unwrap_or("1280x720".to_owned()); let (width, height) = try!(size_str.find('x') .and_then(|x| { if x == 0 || x == size_str.len() - 1 { None } else { Some((&size_str[..x], &size_str[x + 1..])) } }) .map(|size| (size.0.parse::<u32>(), size.1.parse::<u32>())) .and_then(|size| match size { (Ok(width), Ok(height)) => Some((width, height)), _ => None }) .ok_or_else(|| GeneralError("invalid window size (WIDTHxHEIGHT)".to_owned()))); let fov = try!(matches.opt_str("fov").unwrap_or("65".to_owned()).parse::<f32>() .map_err(|_| GeneralError("invalid value for fov".to_owned()))); let level = try!(matches.opt_str("level").unwrap_or("0".to_owned()).parse::<usize>() .map_err(|_| GeneralError("invalid value for fov".to_owned()))); RunMode::Play(GameConfig { wad_file: wad, metadata_file: metadata, fov: fov, width: width, height: height, level_index: level, }) }) } } #[cfg(not(test))] pub fn run(args: &[String]) -> Result<(), Box<Error>> { try!(env_logger::init()); match try!(RunMode::from_args(args)) { RunMode::ListLevelNames { wad_file, metadata_file } => { let wad = try!(Archive::open(&wad_file, &metadata_file)); for i_level in 0..wad.num_levels() { println!("{:3} {:8}", i_level, wad.level_name(i_level)); } }, RunMode::Check { wad_file, metadata_file } => { let sdl = try!(sdl2::init().video().build().map_err(GeneralError)); let _win = try!(Window::new(&sdl, 128, 128)); info!("Loading all levels..."); let t0 = time::precise_time_s(); let mut wad = try!(Archive::open(&wad_file, &metadata_file)); let textures = try!(TextureDirectory::from_archive(&mut wad)); let shader_loader = ShaderLoader::new(PathBuf::from(SHADER_ROOT)); for level_index in 0.. wad.num_levels() { try!(Level::new(&shader_loader, &mut wad, &textures, level_index)); } info!("Done loading all levels in {:.4}s. Shutting down...", time::precise_time_s() - t0); }, RunMode::DisplayHelp(help) => { println!("{}", help); }, RunMode::Play(config) => { try!(Game::new(config)).run(); info!("Game main loop ended, shutting down."); } } Ok(()) } #[cfg(not(test))] fn main() { use std::io; use std::io::Write; use std::env; use std::path::Path; let args = env::args().collect::<Vec<_>>(); if let Err(error) = run(&args) { writeln!(io::stderr(), "{}: {}", Path::new(&args[0]).file_name().unwrap().to_string_lossy(), error).unwrap() }; }
opts.optflag("", "check", "load metadata and all levels in WAD, then exit"); opts.optflag("", "list-levels", "list the names and indices of all the levels in the WAD, then exit");
random_line_split
main.rs
#[macro_use] extern crate log; extern crate common; extern crate env_logger; extern crate game; extern crate getopts; extern crate gfx; extern crate sdl2; extern crate time; extern crate wad; use common::GeneralError; use getopts::Options; use std::path::PathBuf; use std::error::Error; use gfx::ShaderLoader; use wad::{Archive, TextureDirectory}; use gfx::Window; use game::SHADER_ROOT; use game::{Level, Game, GameConfig}; pub enum
{ DisplayHelp(String), Check { wad_file: PathBuf, metadata_file: PathBuf, }, ListLevelNames { wad_file: PathBuf, metadata_file: PathBuf, }, Play(GameConfig), } impl RunMode { pub fn from_args(args: &[String]) -> Result<RunMode, Box<Error>> { let mut opts = Options::new(); opts.optopt("i", "iwad", "initial WAD file to use [default='doom1.wad']", "FILE"); opts.optopt("m", "metadata", "path to TOML metadata file [default='doom.toml']", "FILE"); opts.optopt("r", "resolution", "the size of the game window [default=1280x720]", "WIDTHxHEIGHT"); opts.optopt("l", "level", "the index of the level to render [default=0]", "N"); opts.optopt("f", "fov", "horizontal field of view to please TotalBiscuit [default=65]", "FOV"); opts.optflag("", "check", "load metadata and all levels in WAD, then exit"); opts.optflag("", "list-levels", "list the names and indices of all the levels in the WAD, then exit"); opts.optflag("h", "help", "print this help message and exit"); let matches = try!(opts.parse(&args[1..]).map_err(|e| GeneralError(e.to_string()))); if matches.opt_present("h") { return Ok(RunMode::DisplayHelp( opts.usage("rs_doom 0.0.7: A Rust Doom I/II Renderer."))) } let wad = matches.opt_str("iwad").unwrap_or("doom1.wad".to_owned()).into(); let metadata = matches.opt_str("metadata").unwrap_or("doom.toml".to_owned()).into(); Ok(if matches.opt_present("check") { RunMode::Check { wad_file: wad, metadata_file: metadata, } } else if matches.opt_present("list-levels") { RunMode::ListLevelNames { wad_file: wad, metadata_file: metadata, } } else { let size_str = matches.opt_str("resolution").unwrap_or("1280x720".to_owned()); let (width, height) = try!(size_str.find('x') .and_then(|x| { if x == 0 || x == size_str.len() - 1 { None } else { Some((&size_str[..x], &size_str[x + 1..])) } }) .map(|size| (size.0.parse::<u32>(), size.1.parse::<u32>())) .and_then(|size| match size { (Ok(width), Ok(height)) => Some((width, height)), _ => None }) .ok_or_else(|| GeneralError("invalid window size (WIDTHxHEIGHT)".to_owned()))); let fov = try!(matches.opt_str("fov").unwrap_or("65".to_owned()).parse::<f32>() .map_err(|_| GeneralError("invalid value for fov".to_owned()))); let level = try!(matches.opt_str("level").unwrap_or("0".to_owned()).parse::<usize>() .map_err(|_| GeneralError("invalid value for fov".to_owned()))); RunMode::Play(GameConfig { wad_file: wad, metadata_file: metadata, fov: fov, width: width, height: height, level_index: level, }) }) } } #[cfg(not(test))] pub fn run(args: &[String]) -> Result<(), Box<Error>> { try!(env_logger::init()); match try!(RunMode::from_args(args)) { RunMode::ListLevelNames { wad_file, metadata_file } => { let wad = try!(Archive::open(&wad_file, &metadata_file)); for i_level in 0..wad.num_levels() { println!("{:3} {:8}", i_level, wad.level_name(i_level)); } }, RunMode::Check { wad_file, metadata_file } => { let sdl = try!(sdl2::init().video().build().map_err(GeneralError)); let _win = try!(Window::new(&sdl, 128, 128)); info!("Loading all levels..."); let t0 = time::precise_time_s(); let mut wad = try!(Archive::open(&wad_file, &metadata_file)); let textures = try!(TextureDirectory::from_archive(&mut wad)); let shader_loader = ShaderLoader::new(PathBuf::from(SHADER_ROOT)); for level_index in 0.. wad.num_levels() { try!(Level::new(&shader_loader, &mut wad, &textures, level_index)); } info!("Done loading all levels in {:.4}s. Shutting down...", time::precise_time_s() - t0); }, RunMode::DisplayHelp(help) => { println!("{}", help); }, RunMode::Play(config) => { try!(Game::new(config)).run(); info!("Game main loop ended, shutting down."); } } Ok(()) } #[cfg(not(test))] fn main() { use std::io; use std::io::Write; use std::env; use std::path::Path; let args = env::args().collect::<Vec<_>>(); if let Err(error) = run(&args) { writeln!(io::stderr(), "{}: {}", Path::new(&args[0]).file_name().unwrap().to_string_lossy(), error).unwrap() }; }
RunMode
identifier_name
flatten_sink.rs
use super::FlattenStreamSink; use core::pin::Pin; use futures_core::future::TryFuture; use futures_core::stream::{FusedStream, Stream, TryStream}; use futures_core::task::{Context, Poll}; use futures_sink::Sink; use pin_utils::unsafe_pinned; /// Sink for the [`flatten_sink`](super::TryFutureExt::flatten_sink) method. #[derive(Debug)] #[must_use = "sinks do nothing unless polled"] pub struct FlattenSink<Fut, Si> where Fut: TryFuture<Ok = Si>, { inner: FlattenStreamSink<Fut>, } impl<Fut, Si> FlattenSink<Fut, Si> where Fut: TryFuture<Ok = Si>, { unsafe_pinned!(inner: FlattenStreamSink<Fut>); pub(super) fn new(future: Fut) -> Self { Self { inner: FlattenStreamSink::new(future), } } } impl<Fut, S> FusedStream for FlattenSink<Fut, S> where Fut: TryFuture<Ok = S>, S: TryStream<Error = Fut::Error> + FusedStream, {
impl<Fut, S> Stream for FlattenSink<Fut, S> where Fut: TryFuture<Ok = S>, S: TryStream<Error = Fut::Error>, { type Item = Result<S::Ok, Fut::Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { self.inner().poll_next(cx) } } impl<Fut, Si, Item> Sink<Item> for FlattenSink<Fut, Si> where Fut: TryFuture<Ok = Si>, Si: Sink<Item, Error = Fut::Error>, { type Error = Fut::Error; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.inner().poll_ready(cx) } fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> { self.inner().start_send(item) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.inner().poll_flush(cx) } fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.inner().poll_close(cx) } }
fn is_terminated(&self) -> bool { self.inner.is_terminated() } }
random_line_split
flatten_sink.rs
use super::FlattenStreamSink; use core::pin::Pin; use futures_core::future::TryFuture; use futures_core::stream::{FusedStream, Stream, TryStream}; use futures_core::task::{Context, Poll}; use futures_sink::Sink; use pin_utils::unsafe_pinned; /// Sink for the [`flatten_sink`](super::TryFutureExt::flatten_sink) method. #[derive(Debug)] #[must_use = "sinks do nothing unless polled"] pub struct FlattenSink<Fut, Si> where Fut: TryFuture<Ok = Si>, { inner: FlattenStreamSink<Fut>, } impl<Fut, Si> FlattenSink<Fut, Si> where Fut: TryFuture<Ok = Si>, { unsafe_pinned!(inner: FlattenStreamSink<Fut>); pub(super) fn new(future: Fut) -> Self { Self { inner: FlattenStreamSink::new(future), } } } impl<Fut, S> FusedStream for FlattenSink<Fut, S> where Fut: TryFuture<Ok = S>, S: TryStream<Error = Fut::Error> + FusedStream, { fn is_terminated(&self) -> bool { self.inner.is_terminated() } } impl<Fut, S> Stream for FlattenSink<Fut, S> where Fut: TryFuture<Ok = S>, S: TryStream<Error = Fut::Error>, { type Item = Result<S::Ok, Fut::Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { self.inner().poll_next(cx) } } impl<Fut, Si, Item> Sink<Item> for FlattenSink<Fut, Si> where Fut: TryFuture<Ok = Si>, Si: Sink<Item, Error = Fut::Error>, { type Error = Fut::Error; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>
fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> { self.inner().start_send(item) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.inner().poll_flush(cx) } fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.inner().poll_close(cx) } }
{ self.inner().poll_ready(cx) }
identifier_body
flatten_sink.rs
use super::FlattenStreamSink; use core::pin::Pin; use futures_core::future::TryFuture; use futures_core::stream::{FusedStream, Stream, TryStream}; use futures_core::task::{Context, Poll}; use futures_sink::Sink; use pin_utils::unsafe_pinned; /// Sink for the [`flatten_sink`](super::TryFutureExt::flatten_sink) method. #[derive(Debug)] #[must_use = "sinks do nothing unless polled"] pub struct FlattenSink<Fut, Si> where Fut: TryFuture<Ok = Si>, { inner: FlattenStreamSink<Fut>, } impl<Fut, Si> FlattenSink<Fut, Si> where Fut: TryFuture<Ok = Si>, { unsafe_pinned!(inner: FlattenStreamSink<Fut>); pub(super) fn new(future: Fut) -> Self { Self { inner: FlattenStreamSink::new(future), } } } impl<Fut, S> FusedStream for FlattenSink<Fut, S> where Fut: TryFuture<Ok = S>, S: TryStream<Error = Fut::Error> + FusedStream, { fn is_terminated(&self) -> bool { self.inner.is_terminated() } } impl<Fut, S> Stream for FlattenSink<Fut, S> where Fut: TryFuture<Ok = S>, S: TryStream<Error = Fut::Error>, { type Item = Result<S::Ok, Fut::Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { self.inner().poll_next(cx) } } impl<Fut, Si, Item> Sink<Item> for FlattenSink<Fut, Si> where Fut: TryFuture<Ok = Si>, Si: Sink<Item, Error = Fut::Error>, { type Error = Fut::Error; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.inner().poll_ready(cx) } fn
(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> { self.inner().start_send(item) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.inner().poll_flush(cx) } fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.inner().poll_close(cx) } }
start_send
identifier_name