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
lib.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #![allow(clippy::large_enum_variant)] pub mod devices; pub mod udev; pub mod uevent; use std::{ cmp::Ordering, collections::BTreeSet, hash::{Hash, Hasher}, path::{Path, PathBuf}, }; #[derive(Debug, Clone, Eq, serde::Serialize, serde::Deserialize)] #[serde(transparent)] pub struct DevicePath(pub PathBuf); impl<S: Into<PathBuf>> From<S> for DevicePath { fn from(s: S) -> DevicePath { DevicePath(s.into()) } } impl<'a> From<&'a DevicePath> for &'a Path { fn from(s: &'a DevicePath) -> &'a Path { Path::new(&s.0) } } fn find_sort_slot(DevicePath(p): &DevicePath) -> usize { let o = &[ Box::new(|p: &PathBuf| p.starts_with("/dev/mapper/")) as Box<dyn Fn(&PathBuf) -> bool>, Box::new(|p| p.starts_with("/dev/disk/by-id/")), Box::new(|p| p.starts_with("/dev/disk/by-path/")), Box::new(|p| p.starts_with("/dev/")), Box::new(|_| true), ] .iter() .position(|f| f(&p)) .unwrap(); *o } pub fn get_vdev_paths(vdev: &libzfs_types::VDev) -> BTreeSet<DevicePath> { match vdev { libzfs_types::VDev::Disk { dev_id, path,.. } => { let p = dev_id .as_ref() .map(|x| format!("/dev/disk/by-id/{}", x)) .map(std::convert::Into::into) .or_else(|| { tracing::warn!( "VDev::Disk.dev_id not found, using VDev::Disk.path {:?}", path ); Some(path.clone()) }) .map(DevicePath); let mut b = BTreeSet::new(); if let Some(x) = p { b.insert(x); } b } libzfs_types::VDev::File {.. } => BTreeSet::new(), libzfs_types::VDev::Mirror { children,.. } | libzfs_types::VDev::RaidZ { children,.. } | libzfs_types::VDev::Replacing { children,.. } => { children.iter().flat_map(get_vdev_paths).collect() } libzfs_types::VDev::Root { children, spares, cache, .. } => vec![children, spares, cache] .into_iter() .flatten() .flat_map(get_vdev_paths) .collect(), } } impl Ord for DevicePath { fn cmp(&self, other: &DevicePath) -> Ordering { let a_slot = find_sort_slot(self); let b_slot = find_sort_slot(other); match a_slot.cmp(&b_slot) { Ordering::Greater => Ordering::Greater, Ordering::Less => Ordering::Less, Ordering::Equal => self.0.partial_cmp(&other.0).unwrap(), } } } impl PartialOrd for DevicePath { fn partial_cmp(&self, other: &DevicePath) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq for DevicePath { fn eq(&self, other: &DevicePath) -> bool { self.0 == other.0 } } impl Hash for DevicePath { fn hash<H: Hasher>(&self, h: &mut H) { self.0.as_path().hash(h) } } pub mod message { #[derive(Debug, serde::Serialize, serde::Deserialize)] pub enum Message { Data(String), Heartbeat, } } pub mod state { use crate::{mount, uevent}; use im::{HashMap, HashSet}; use std::path::PathBuf; pub type UEvents = HashMap<PathBuf, uevent::UEvent>; pub type ZedEvents = HashMap<u64, libzfs_types::Pool>; #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] pub struct State { pub uevents: UEvents, pub zed_events: ZedEvents, pub local_mounts: HashSet<mount::Mount>, } impl State { pub fn new() -> Self { State { uevents: HashMap::new(), zed_events: HashMap::new(), local_mounts: HashSet::new(), } } } } pub mod mount { use crate::DevicePath; use std::path::PathBuf; #[derive( Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, )] #[serde(transparent)] pub struct MountPoint(pub PathBuf); #[derive( Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, )] #[serde(transparent)] pub struct FsType(pub String); #[derive( Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, )] pub struct MountOpts(pub String); #[derive( Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, Clone, )] pub struct Mount { pub source: DevicePath, pub target: MountPoint, pub fs_type: FsType, pub opts: MountOpts, } impl Mount { pub fn new( target: MountPoint, source: DevicePath, fs_type: FsType, opts: MountOpts, ) -> Self { Mount { target, source, fs_type, opts, } } } #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum MountCommand { AddMount(MountPoint, DevicePath, FsType, MountOpts), RemoveMount(MountPoint, DevicePath, FsType, MountOpts), ReplaceMount(MountPoint, DevicePath, FsType, MountOpts, MountOpts), MoveMount(MountPoint, DevicePath, FsType, MountOpts, MountPoint), } } pub mod zed { #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum PoolCommand { AddPools(Vec<libzfs_types::Pool>), AddPool(libzfs_types::Pool), UpdatePool(libzfs_types::Pool), RemovePool(zpool::Guid), AddDataset(zpool::Guid, libzfs_types::Dataset), RemoveDataset(zpool::Guid, zfs::Name), SetZpoolProp(zpool::Guid, prop::Key, prop::Value), SetZfsProp(zpool::Guid, zfs::Name, prop::Key, prop::Value), } pub mod zpool { #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Name(pub String); #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Guid(pub String); impl From<u64> for Guid { fn from(x: u64) -> Self { Guid(format!("{:#018X}", x)) } } impl From<Guid> for Result<u64, std::num::ParseIntError> { fn from(Guid(x): Guid) -> Self { let without_prefix = x.trim_start_matches("0x"); u64::from_str_radix(without_prefix, 16) } } #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct State(pub String); impl From<State> for String { fn from(State(x): State) -> Self { x } } } pub mod zfs { #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Name(pub String); } pub mod prop { #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Key(pub String); #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Value(pub String); } #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum ZedCommand { Init, CreateZpool(zpool::Name, zpool::Guid, zpool::State), ImportZpool(zpool::Name, zpool::Guid, zpool::State), ExportZpool(zpool::Guid, zpool::State), DestroyZpool(zpool::Guid), CreateZfs(zpool::Guid, zfs::Name), DestroyZfs(zpool::Guid, zfs::Name), SetZpoolProp(zpool::Guid, prop::Key, prop::Value), SetZfsProp(zpool::Guid, zfs::Name, prop::Key, prop::Value), AddVdev(zpool::Name, zpool::Guid), } } #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum Command { Stream, GetMounts, PoolCommand(zed::PoolCommand), UdevCommand(udev::UdevCommand), MountCommand(mount::MountCommand), } #[cfg(test)] mod tests { use super::{ mount, {Command, DevicePath}, }; use im::{ordset, OrdSet}; use insta::assert_debug_snapshot; #[test] fn
() { let xs: OrdSet<DevicePath> = ordset![ "/dev/disk/by-id/dm-uuid-part1-mpath-3600140550e41a841db244a992c31e7df".into(), "/dev/mapper/mpathd1".into(), "/dev/disk/by-uuid/b4550256-cf48-4013-8363-bfee5f52da12".into(), "/dev/disk/by-partuuid/d643e32f-b6b9-4863-af8f-8950376e28da".into(), "/dev/dm-20".into(), "/dev/disk/by-id/dm-name-mpathd1".into() ]; assert_debug_snapshot!(xs); } #[test] fn test_mount_deserialize() { let s = "{\"MountCommand\":{\"AddMount\":[\"swap\",\"/dev/mapper/VolGroup00-LogVol01\",\"swap\",\"defaults\"]}}"; let result = serde_json::from_str::<Command>(s).unwrap(); assert_eq!( result, Command::MountCommand(mount::MountCommand::AddMount( mount::MountPoint("swap".into()), "/dev/mapper/VolGroup00-LogVol01".into(), mount::FsType("swap".to_string()), mount::MountOpts("defaults".to_string()) )) ) } }
test_device_path_ordering
identifier_name
lib.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #![allow(clippy::large_enum_variant)] pub mod devices; pub mod udev; pub mod uevent; use std::{ cmp::Ordering, collections::BTreeSet, hash::{Hash, Hasher}, path::{Path, PathBuf}, }; #[derive(Debug, Clone, Eq, serde::Serialize, serde::Deserialize)] #[serde(transparent)] pub struct DevicePath(pub PathBuf); impl<S: Into<PathBuf>> From<S> for DevicePath { fn from(s: S) -> DevicePath { DevicePath(s.into()) } } impl<'a> From<&'a DevicePath> for &'a Path { fn from(s: &'a DevicePath) -> &'a Path { Path::new(&s.0) } } fn find_sort_slot(DevicePath(p): &DevicePath) -> usize { let o = &[ Box::new(|p: &PathBuf| p.starts_with("/dev/mapper/")) as Box<dyn Fn(&PathBuf) -> bool>, Box::new(|p| p.starts_with("/dev/disk/by-id/")), Box::new(|p| p.starts_with("/dev/disk/by-path/")), Box::new(|p| p.starts_with("/dev/")), Box::new(|_| true), ] .iter() .position(|f| f(&p)) .unwrap(); *o } pub fn get_vdev_paths(vdev: &libzfs_types::VDev) -> BTreeSet<DevicePath> { match vdev { libzfs_types::VDev::Disk { dev_id, path,.. } => { let p = dev_id .as_ref() .map(|x| format!("/dev/disk/by-id/{}", x)) .map(std::convert::Into::into) .or_else(|| { tracing::warn!( "VDev::Disk.dev_id not found, using VDev::Disk.path {:?}", path ); Some(path.clone()) }) .map(DevicePath); let mut b = BTreeSet::new(); if let Some(x) = p { b.insert(x); } b } libzfs_types::VDev::File {.. } => BTreeSet::new(), libzfs_types::VDev::Mirror { children,.. } | libzfs_types::VDev::RaidZ { children,.. } | libzfs_types::VDev::Replacing { children,.. } =>
libzfs_types::VDev::Root { children, spares, cache, .. } => vec![children, spares, cache] .into_iter() .flatten() .flat_map(get_vdev_paths) .collect(), } } impl Ord for DevicePath { fn cmp(&self, other: &DevicePath) -> Ordering { let a_slot = find_sort_slot(self); let b_slot = find_sort_slot(other); match a_slot.cmp(&b_slot) { Ordering::Greater => Ordering::Greater, Ordering::Less => Ordering::Less, Ordering::Equal => self.0.partial_cmp(&other.0).unwrap(), } } } impl PartialOrd for DevicePath { fn partial_cmp(&self, other: &DevicePath) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq for DevicePath { fn eq(&self, other: &DevicePath) -> bool { self.0 == other.0 } } impl Hash for DevicePath { fn hash<H: Hasher>(&self, h: &mut H) { self.0.as_path().hash(h) } } pub mod message { #[derive(Debug, serde::Serialize, serde::Deserialize)] pub enum Message { Data(String), Heartbeat, } } pub mod state { use crate::{mount, uevent}; use im::{HashMap, HashSet}; use std::path::PathBuf; pub type UEvents = HashMap<PathBuf, uevent::UEvent>; pub type ZedEvents = HashMap<u64, libzfs_types::Pool>; #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] pub struct State { pub uevents: UEvents, pub zed_events: ZedEvents, pub local_mounts: HashSet<mount::Mount>, } impl State { pub fn new() -> Self { State { uevents: HashMap::new(), zed_events: HashMap::new(), local_mounts: HashSet::new(), } } } } pub mod mount { use crate::DevicePath; use std::path::PathBuf; #[derive( Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, )] #[serde(transparent)] pub struct MountPoint(pub PathBuf); #[derive( Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, )] #[serde(transparent)] pub struct FsType(pub String); #[derive( Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, )] pub struct MountOpts(pub String); #[derive( Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, Clone, )] pub struct Mount { pub source: DevicePath, pub target: MountPoint, pub fs_type: FsType, pub opts: MountOpts, } impl Mount { pub fn new( target: MountPoint, source: DevicePath, fs_type: FsType, opts: MountOpts, ) -> Self { Mount { target, source, fs_type, opts, } } } #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum MountCommand { AddMount(MountPoint, DevicePath, FsType, MountOpts), RemoveMount(MountPoint, DevicePath, FsType, MountOpts), ReplaceMount(MountPoint, DevicePath, FsType, MountOpts, MountOpts), MoveMount(MountPoint, DevicePath, FsType, MountOpts, MountPoint), } } pub mod zed { #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum PoolCommand { AddPools(Vec<libzfs_types::Pool>), AddPool(libzfs_types::Pool), UpdatePool(libzfs_types::Pool), RemovePool(zpool::Guid), AddDataset(zpool::Guid, libzfs_types::Dataset), RemoveDataset(zpool::Guid, zfs::Name), SetZpoolProp(zpool::Guid, prop::Key, prop::Value), SetZfsProp(zpool::Guid, zfs::Name, prop::Key, prop::Value), } pub mod zpool { #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Name(pub String); #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Guid(pub String); impl From<u64> for Guid { fn from(x: u64) -> Self { Guid(format!("{:#018X}", x)) } } impl From<Guid> for Result<u64, std::num::ParseIntError> { fn from(Guid(x): Guid) -> Self { let without_prefix = x.trim_start_matches("0x"); u64::from_str_radix(without_prefix, 16) } } #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct State(pub String); impl From<State> for String { fn from(State(x): State) -> Self { x } } } pub mod zfs { #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Name(pub String); } pub mod prop { #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Key(pub String); #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Value(pub String); } #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum ZedCommand { Init, CreateZpool(zpool::Name, zpool::Guid, zpool::State), ImportZpool(zpool::Name, zpool::Guid, zpool::State), ExportZpool(zpool::Guid, zpool::State), DestroyZpool(zpool::Guid), CreateZfs(zpool::Guid, zfs::Name), DestroyZfs(zpool::Guid, zfs::Name), SetZpoolProp(zpool::Guid, prop::Key, prop::Value), SetZfsProp(zpool::Guid, zfs::Name, prop::Key, prop::Value), AddVdev(zpool::Name, zpool::Guid), } } #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum Command { Stream, GetMounts, PoolCommand(zed::PoolCommand), UdevCommand(udev::UdevCommand), MountCommand(mount::MountCommand), } #[cfg(test)] mod tests { use super::{ mount, {Command, DevicePath}, }; use im::{ordset, OrdSet}; use insta::assert_debug_snapshot; #[test] fn test_device_path_ordering() { let xs: OrdSet<DevicePath> = ordset![ "/dev/disk/by-id/dm-uuid-part1-mpath-3600140550e41a841db244a992c31e7df".into(), "/dev/mapper/mpathd1".into(), "/dev/disk/by-uuid/b4550256-cf48-4013-8363-bfee5f52da12".into(), "/dev/disk/by-partuuid/d643e32f-b6b9-4863-af8f-8950376e28da".into(), "/dev/dm-20".into(), "/dev/disk/by-id/dm-name-mpathd1".into() ]; assert_debug_snapshot!(xs); } #[test] fn test_mount_deserialize() { let s = "{\"MountCommand\":{\"AddMount\":[\"swap\",\"/dev/mapper/VolGroup00-LogVol01\",\"swap\",\"defaults\"]}}"; let result = serde_json::from_str::<Command>(s).unwrap(); assert_eq!( result, Command::MountCommand(mount::MountCommand::AddMount( mount::MountPoint("swap".into()), "/dev/mapper/VolGroup00-LogVol01".into(), mount::FsType("swap".to_string()), mount::MountOpts("defaults".to_string()) )) ) } }
{ children.iter().flat_map(get_vdev_paths).collect() }
conditional_block
lib.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #![allow(clippy::large_enum_variant)] pub mod devices; pub mod udev; pub mod uevent; use std::{ cmp::Ordering, collections::BTreeSet, hash::{Hash, Hasher}, path::{Path, PathBuf}, }; #[derive(Debug, Clone, Eq, serde::Serialize, serde::Deserialize)] #[serde(transparent)] pub struct DevicePath(pub PathBuf); impl<S: Into<PathBuf>> From<S> for DevicePath { fn from(s: S) -> DevicePath { DevicePath(s.into()) } } impl<'a> From<&'a DevicePath> for &'a Path { fn from(s: &'a DevicePath) -> &'a Path { Path::new(&s.0) } } fn find_sort_slot(DevicePath(p): &DevicePath) -> usize { let o = &[ Box::new(|p: &PathBuf| p.starts_with("/dev/mapper/")) as Box<dyn Fn(&PathBuf) -> bool>, Box::new(|p| p.starts_with("/dev/disk/by-id/")), Box::new(|p| p.starts_with("/dev/disk/by-path/")), Box::new(|p| p.starts_with("/dev/")), Box::new(|_| true), ] .iter() .position(|f| f(&p)) .unwrap(); *o } pub fn get_vdev_paths(vdev: &libzfs_types::VDev) -> BTreeSet<DevicePath> { match vdev { libzfs_types::VDev::Disk { dev_id, path,.. } => { let p = dev_id .as_ref() .map(|x| format!("/dev/disk/by-id/{}", x)) .map(std::convert::Into::into) .or_else(|| { tracing::warn!( "VDev::Disk.dev_id not found, using VDev::Disk.path {:?}", path ); Some(path.clone()) }) .map(DevicePath); let mut b = BTreeSet::new(); if let Some(x) = p { b.insert(x); } b } libzfs_types::VDev::File {.. } => BTreeSet::new(), libzfs_types::VDev::Mirror { children,.. } | libzfs_types::VDev::RaidZ { children,.. } | libzfs_types::VDev::Replacing { children,.. } => { children.iter().flat_map(get_vdev_paths).collect() } libzfs_types::VDev::Root { children, spares, cache, .. } => vec![children, spares, cache] .into_iter() .flatten() .flat_map(get_vdev_paths) .collect(), } } impl Ord for DevicePath { fn cmp(&self, other: &DevicePath) -> Ordering { let a_slot = find_sort_slot(self); let b_slot = find_sort_slot(other); match a_slot.cmp(&b_slot) { Ordering::Greater => Ordering::Greater, Ordering::Less => Ordering::Less, Ordering::Equal => self.0.partial_cmp(&other.0).unwrap(), } } } impl PartialOrd for DevicePath { fn partial_cmp(&self, other: &DevicePath) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq for DevicePath { fn eq(&self, other: &DevicePath) -> bool { self.0 == other.0 } } impl Hash for DevicePath { fn hash<H: Hasher>(&self, h: &mut H) { self.0.as_path().hash(h) } } pub mod message { #[derive(Debug, serde::Serialize, serde::Deserialize)] pub enum Message { Data(String), Heartbeat, } } pub mod state { use crate::{mount, uevent}; use im::{HashMap, HashSet}; use std::path::PathBuf; pub type UEvents = HashMap<PathBuf, uevent::UEvent>; pub type ZedEvents = HashMap<u64, libzfs_types::Pool>;
pub zed_events: ZedEvents, pub local_mounts: HashSet<mount::Mount>, } impl State { pub fn new() -> Self { State { uevents: HashMap::new(), zed_events: HashMap::new(), local_mounts: HashSet::new(), } } } } pub mod mount { use crate::DevicePath; use std::path::PathBuf; #[derive( Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, )] #[serde(transparent)] pub struct MountPoint(pub PathBuf); #[derive( Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, )] #[serde(transparent)] pub struct FsType(pub String); #[derive( Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, )] pub struct MountOpts(pub String); #[derive( Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, Clone, )] pub struct Mount { pub source: DevicePath, pub target: MountPoint, pub fs_type: FsType, pub opts: MountOpts, } impl Mount { pub fn new( target: MountPoint, source: DevicePath, fs_type: FsType, opts: MountOpts, ) -> Self { Mount { target, source, fs_type, opts, } } } #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum MountCommand { AddMount(MountPoint, DevicePath, FsType, MountOpts), RemoveMount(MountPoint, DevicePath, FsType, MountOpts), ReplaceMount(MountPoint, DevicePath, FsType, MountOpts, MountOpts), MoveMount(MountPoint, DevicePath, FsType, MountOpts, MountPoint), } } pub mod zed { #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum PoolCommand { AddPools(Vec<libzfs_types::Pool>), AddPool(libzfs_types::Pool), UpdatePool(libzfs_types::Pool), RemovePool(zpool::Guid), AddDataset(zpool::Guid, libzfs_types::Dataset), RemoveDataset(zpool::Guid, zfs::Name), SetZpoolProp(zpool::Guid, prop::Key, prop::Value), SetZfsProp(zpool::Guid, zfs::Name, prop::Key, prop::Value), } pub mod zpool { #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Name(pub String); #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Guid(pub String); impl From<u64> for Guid { fn from(x: u64) -> Self { Guid(format!("{:#018X}", x)) } } impl From<Guid> for Result<u64, std::num::ParseIntError> { fn from(Guid(x): Guid) -> Self { let without_prefix = x.trim_start_matches("0x"); u64::from_str_radix(without_prefix, 16) } } #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct State(pub String); impl From<State> for String { fn from(State(x): State) -> Self { x } } } pub mod zfs { #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Name(pub String); } pub mod prop { #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Key(pub String); #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Value(pub String); } #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum ZedCommand { Init, CreateZpool(zpool::Name, zpool::Guid, zpool::State), ImportZpool(zpool::Name, zpool::Guid, zpool::State), ExportZpool(zpool::Guid, zpool::State), DestroyZpool(zpool::Guid), CreateZfs(zpool::Guid, zfs::Name), DestroyZfs(zpool::Guid, zfs::Name), SetZpoolProp(zpool::Guid, prop::Key, prop::Value), SetZfsProp(zpool::Guid, zfs::Name, prop::Key, prop::Value), AddVdev(zpool::Name, zpool::Guid), } } #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum Command { Stream, GetMounts, PoolCommand(zed::PoolCommand), UdevCommand(udev::UdevCommand), MountCommand(mount::MountCommand), } #[cfg(test)] mod tests { use super::{ mount, {Command, DevicePath}, }; use im::{ordset, OrdSet}; use insta::assert_debug_snapshot; #[test] fn test_device_path_ordering() { let xs: OrdSet<DevicePath> = ordset![ "/dev/disk/by-id/dm-uuid-part1-mpath-3600140550e41a841db244a992c31e7df".into(), "/dev/mapper/mpathd1".into(), "/dev/disk/by-uuid/b4550256-cf48-4013-8363-bfee5f52da12".into(), "/dev/disk/by-partuuid/d643e32f-b6b9-4863-af8f-8950376e28da".into(), "/dev/dm-20".into(), "/dev/disk/by-id/dm-name-mpathd1".into() ]; assert_debug_snapshot!(xs); } #[test] fn test_mount_deserialize() { let s = "{\"MountCommand\":{\"AddMount\":[\"swap\",\"/dev/mapper/VolGroup00-LogVol01\",\"swap\",\"defaults\"]}}"; let result = serde_json::from_str::<Command>(s).unwrap(); assert_eq!( result, Command::MountCommand(mount::MountCommand::AddMount( mount::MountPoint("swap".into()), "/dev/mapper/VolGroup00-LogVol01".into(), mount::FsType("swap".to_string()), mount::MountOpts("defaults".to_string()) )) ) } }
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] pub struct State { pub uevents: UEvents,
random_line_split
model_checker.rs
// Copyright 2014 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use model::*; use syntax::ptr::P; use model::AttributeModel::*; use model::AttributeLitModel::*; pub fn check_all(cx: &ExtCtxt, model: AttributeArray, attributes: Vec<Attribute>) -> AttributeArray { attributes.into_iter().fold( model, |model, attr| check(cx, model, attr) ) } pub fn check(cx: &ExtCtxt, model: AttributeArray, attr: Attribute) -> AttributeArray { let meta_item = attr.node.value; match_meta_item(cx, model, &meta_item) } fn match_meta_item(cx: &ExtCtxt, model: AttributeArray, meta_item: &P<MetaItem>) -> AttributeArray { let meta_name = meta_item_name(meta_item.node.clone()); let mut attr_exists = false; let model = model.into_iter().map(|info| if info.name == meta_name { attr_exists = true; match_model(cx, info, meta_item) } else { info } ).collect(); if!attr_exists { unknown_attribute(cx, meta_name, meta_item.span); } model } fn
(meta_item: MetaItem_) -> InternedString { match meta_item { MetaWord(name) | MetaList(name, _) | MetaNameValue(name, _) => name } } fn match_model(cx: &ExtCtxt, info: AttributeInfo, meta_item: &P<MetaItem>) -> AttributeInfo { let model = match (info.model, meta_item.node.clone()) { (UnitValue(value), MetaWord(_)) => UnitValue(match_value(cx, value, meta_item.span)), (KeyValue(mlit), MetaNameValue(_, lit)) => KeyValue(match_lit(cx, mlit, lit)), (SubAttribute(dict), MetaList(_, list)) => SubAttribute(match_sub_attributes(cx, dict, list)), (model, _) => model_mismatch(cx, model, meta_item) }; AttributeInfo { name: info.name, desc: info.desc, model: model } } fn match_value(cx: &ExtCtxt, value: AttributeValue<()>, span: Span) -> AttributeValue<()> { value.update(cx, (), span) } fn match_lit(cx: &ExtCtxt, mlit: AttributeLitModel, lit: Lit) -> AttributeLitModel { let sp = lit.span; match (mlit, lit.node.clone()) { (MLitStr(value), LitStr(s, style)) => MLitStr(value.update(cx, (s, style), sp)), (MLitBinary(value), LitBinary(val)) => MLitBinary(value.update(cx, val, sp)), (MLitByte(value), LitByte(val)) => MLitByte(value.update(cx, val, sp)), (MLitChar(value), LitChar(val)) => MLitChar(value.update(cx, val, sp)), (MLitInt(value), LitInt(val, ty)) => MLitInt(value.update(cx, (val, ty), sp)), (MLitFloat(value), LitFloat(val, ty)) => MLitFloat(value.update(cx, (val, ty), sp)), (MLitFloatUnsuffixed(value), LitFloatUnsuffixed(val)) => MLitFloatUnsuffixed(value.update(cx, val, sp)), (MLitBool(value), LitBool(val)) => MLitBool(value.update(cx, val, sp)), (mlit, _) => lit_mismatch(cx, mlit, lit) } } fn match_sub_attributes(cx: &ExtCtxt, model: AttributeArray, meta_items: Vec<P<MetaItem>>) -> AttributeArray { meta_items.iter().fold(model, |model, meta_item| match_meta_item(cx, model, meta_item)) } fn model_mismatch(cx: &ExtCtxt, model: AttributeModel, meta_item: &P<MetaItem>) -> AttributeModel { cx.span_err(meta_item.span, "Model mismatch."); model } fn lit_mismatch(cx: &ExtCtxt, mlit: AttributeLitModel, lit: Lit) -> AttributeLitModel { let mlit_printer = mlit.to_lit_printer(); let lit_printer = lit_to_lit_printer(&lit.node); cx.span_err(lit.span, format!("Expected {} literal (e.g. `key = {}`) but got {} literal (e.g. `key = {}`).", mlit_printer.type_to_str(), mlit_printer.type_example_to_str(), lit_printer.type_to_str(), lit_printer.type_example_to_str()).as_str()); mlit } fn unknown_attribute(cx: &ExtCtxt, _meta_name: InternedString, span: Span) { cx.span_err(span, "Unknown attribute."); // model.doc_approaching_results(cx, context, meta_name, span); }
meta_item_name
identifier_name
model_checker.rs
// Copyright 2014 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use model::*; use syntax::ptr::P; use model::AttributeModel::*; use model::AttributeLitModel::*; pub fn check_all(cx: &ExtCtxt, model: AttributeArray, attributes: Vec<Attribute>) -> AttributeArray { attributes.into_iter().fold( model, |model, attr| check(cx, model, attr) ) } pub fn check(cx: &ExtCtxt, model: AttributeArray, attr: Attribute) -> AttributeArray
fn match_meta_item(cx: &ExtCtxt, model: AttributeArray, meta_item: &P<MetaItem>) -> AttributeArray { let meta_name = meta_item_name(meta_item.node.clone()); let mut attr_exists = false; let model = model.into_iter().map(|info| if info.name == meta_name { attr_exists = true; match_model(cx, info, meta_item) } else { info } ).collect(); if!attr_exists { unknown_attribute(cx, meta_name, meta_item.span); } model } fn meta_item_name(meta_item: MetaItem_) -> InternedString { match meta_item { MetaWord(name) | MetaList(name, _) | MetaNameValue(name, _) => name } } fn match_model(cx: &ExtCtxt, info: AttributeInfo, meta_item: &P<MetaItem>) -> AttributeInfo { let model = match (info.model, meta_item.node.clone()) { (UnitValue(value), MetaWord(_)) => UnitValue(match_value(cx, value, meta_item.span)), (KeyValue(mlit), MetaNameValue(_, lit)) => KeyValue(match_lit(cx, mlit, lit)), (SubAttribute(dict), MetaList(_, list)) => SubAttribute(match_sub_attributes(cx, dict, list)), (model, _) => model_mismatch(cx, model, meta_item) }; AttributeInfo { name: info.name, desc: info.desc, model: model } } fn match_value(cx: &ExtCtxt, value: AttributeValue<()>, span: Span) -> AttributeValue<()> { value.update(cx, (), span) } fn match_lit(cx: &ExtCtxt, mlit: AttributeLitModel, lit: Lit) -> AttributeLitModel { let sp = lit.span; match (mlit, lit.node.clone()) { (MLitStr(value), LitStr(s, style)) => MLitStr(value.update(cx, (s, style), sp)), (MLitBinary(value), LitBinary(val)) => MLitBinary(value.update(cx, val, sp)), (MLitByte(value), LitByte(val)) => MLitByte(value.update(cx, val, sp)), (MLitChar(value), LitChar(val)) => MLitChar(value.update(cx, val, sp)), (MLitInt(value), LitInt(val, ty)) => MLitInt(value.update(cx, (val, ty), sp)), (MLitFloat(value), LitFloat(val, ty)) => MLitFloat(value.update(cx, (val, ty), sp)), (MLitFloatUnsuffixed(value), LitFloatUnsuffixed(val)) => MLitFloatUnsuffixed(value.update(cx, val, sp)), (MLitBool(value), LitBool(val)) => MLitBool(value.update(cx, val, sp)), (mlit, _) => lit_mismatch(cx, mlit, lit) } } fn match_sub_attributes(cx: &ExtCtxt, model: AttributeArray, meta_items: Vec<P<MetaItem>>) -> AttributeArray { meta_items.iter().fold(model, |model, meta_item| match_meta_item(cx, model, meta_item)) } fn model_mismatch(cx: &ExtCtxt, model: AttributeModel, meta_item: &P<MetaItem>) -> AttributeModel { cx.span_err(meta_item.span, "Model mismatch."); model } fn lit_mismatch(cx: &ExtCtxt, mlit: AttributeLitModel, lit: Lit) -> AttributeLitModel { let mlit_printer = mlit.to_lit_printer(); let lit_printer = lit_to_lit_printer(&lit.node); cx.span_err(lit.span, format!("Expected {} literal (e.g. `key = {}`) but got {} literal (e.g. `key = {}`).", mlit_printer.type_to_str(), mlit_printer.type_example_to_str(), lit_printer.type_to_str(), lit_printer.type_example_to_str()).as_str()); mlit } fn unknown_attribute(cx: &ExtCtxt, _meta_name: InternedString, span: Span) { cx.span_err(span, "Unknown attribute."); // model.doc_approaching_results(cx, context, meta_name, span); }
{ let meta_item = attr.node.value; match_meta_item(cx, model, &meta_item) }
identifier_body
model_checker.rs
// Copyright 2014 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use model::*; use syntax::ptr::P; use model::AttributeModel::*; use model::AttributeLitModel::*; pub fn check_all(cx: &ExtCtxt, model: AttributeArray, attributes: Vec<Attribute>) -> AttributeArray { attributes.into_iter().fold( model, |model, attr| check(cx, model, attr) ) } pub fn check(cx: &ExtCtxt, model: AttributeArray, attr: Attribute) -> AttributeArray { let meta_item = attr.node.value; match_meta_item(cx, model, &meta_item) } fn match_meta_item(cx: &ExtCtxt, model: AttributeArray, meta_item: &P<MetaItem>) -> AttributeArray { let meta_name = meta_item_name(meta_item.node.clone()); let mut attr_exists = false; let model = model.into_iter().map(|info| if info.name == meta_name { attr_exists = true; match_model(cx, info, meta_item) } else { info } ).collect(); if!attr_exists { unknown_attribute(cx, meta_name, meta_item.span); } model } fn meta_item_name(meta_item: MetaItem_) -> InternedString { match meta_item { MetaWord(name) | MetaList(name, _) | MetaNameValue(name, _) => name } } fn match_model(cx: &ExtCtxt, info: AttributeInfo, meta_item: &P<MetaItem>) -> AttributeInfo { let model = match (info.model, meta_item.node.clone()) { (UnitValue(value), MetaWord(_)) => UnitValue(match_value(cx, value, meta_item.span)), (KeyValue(mlit), MetaNameValue(_, lit)) => KeyValue(match_lit(cx, mlit, lit)), (SubAttribute(dict), MetaList(_, list)) => SubAttribute(match_sub_attributes(cx, dict, list)), (model, _) => model_mismatch(cx, model, meta_item)
{ value.update(cx, (), span) } fn match_lit(cx: &ExtCtxt, mlit: AttributeLitModel, lit: Lit) -> AttributeLitModel { let sp = lit.span; match (mlit, lit.node.clone()) { (MLitStr(value), LitStr(s, style)) => MLitStr(value.update(cx, (s, style), sp)), (MLitBinary(value), LitBinary(val)) => MLitBinary(value.update(cx, val, sp)), (MLitByte(value), LitByte(val)) => MLitByte(value.update(cx, val, sp)), (MLitChar(value), LitChar(val)) => MLitChar(value.update(cx, val, sp)), (MLitInt(value), LitInt(val, ty)) => MLitInt(value.update(cx, (val, ty), sp)), (MLitFloat(value), LitFloat(val, ty)) => MLitFloat(value.update(cx, (val, ty), sp)), (MLitFloatUnsuffixed(value), LitFloatUnsuffixed(val)) => MLitFloatUnsuffixed(value.update(cx, val, sp)), (MLitBool(value), LitBool(val)) => MLitBool(value.update(cx, val, sp)), (mlit, _) => lit_mismatch(cx, mlit, lit) } } fn match_sub_attributes(cx: &ExtCtxt, model: AttributeArray, meta_items: Vec<P<MetaItem>>) -> AttributeArray { meta_items.iter().fold(model, |model, meta_item| match_meta_item(cx, model, meta_item)) } fn model_mismatch(cx: &ExtCtxt, model: AttributeModel, meta_item: &P<MetaItem>) -> AttributeModel { cx.span_err(meta_item.span, "Model mismatch."); model } fn lit_mismatch(cx: &ExtCtxt, mlit: AttributeLitModel, lit: Lit) -> AttributeLitModel { let mlit_printer = mlit.to_lit_printer(); let lit_printer = lit_to_lit_printer(&lit.node); cx.span_err(lit.span, format!("Expected {} literal (e.g. `key = {}`) but got {} literal (e.g. `key = {}`).", mlit_printer.type_to_str(), mlit_printer.type_example_to_str(), lit_printer.type_to_str(), lit_printer.type_example_to_str()).as_str()); mlit } fn unknown_attribute(cx: &ExtCtxt, _meta_name: InternedString, span: Span) { cx.span_err(span, "Unknown attribute."); // model.doc_approaching_results(cx, context, meta_name, span); }
}; AttributeInfo { name: info.name, desc: info.desc, model: model } } fn match_value(cx: &ExtCtxt, value: AttributeValue<()>, span: Span) -> AttributeValue<()>
random_line_split
bookmarks.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cocoa::base::*; use cocoa::foundation::*; use objc::declare::ClassDecl; use objc::runtime::{Class, Object, Sel}; pub fn register()
_sel: Sel, _outlineview: id, _index: NSInteger, _item: id) -> id { nil } extern "C" fn is_item_expandable(_this: &Object, _sel: Sel, _outlineview: id, _item: id) -> BOOL { NO } extern "C" fn number_of_child_of_item(_this: &Object, _sel: Sel, _outlineview: id, _item: id) -> NSInteger { 0 } extern "C" fn object_value(_this: &Object, _sel: Sel, _outlineview: id, _column: id, _item: id) -> id { nil } // FIXME: Yeah! Outlets, we want to use that everywhere instead of subviews // let textfield = msg_send![view, textField]; unsafe { newclass.add_method(sel!(outlineView:child:ofItem:), child_of_item as extern "C" fn(&Object, Sel, id, NSInteger, id) -> id); newclass.add_method(sel!(outlineView:isItemExpandable:), is_item_expandable as extern "C" fn(&Object, Sel, id, id) -> BOOL); newclass.add_method(sel!(outlineView:numberOfChildrenOfItem:), number_of_child_of_item as extern "C" fn(&Object, Sel, id, id) -> NSInteger); newclass.add_method(sel!(outlineView:objectValueForTableColumn:byItem:), object_value as extern "C" fn(&Object, Sel, id, id, id) -> id); newclass.add_method(sel!(awakeFromNib), awake_from_nib as extern "C" fn(&mut Object, Sel)); } newclass.register(); } }
{ /* NShellBookmark */ { let superclass = Class::get("NSObject").unwrap(); let mut newclass = ClassDecl::new("NSShellBookmark", superclass).unwrap(); newclass.add_ivar::<id>("link"); newclass.add_ivar::<id>("name"); newclass.register(); } /* NSShellBookmarks */ { let superclass = Class::get("NSObject").unwrap(); let mut newclass = ClassDecl::new("NSShellBookmarks", superclass).unwrap(); newclass.add_ivar::<id>("bookmarks"); extern "C" fn awake_from_nib(_this: &mut Object, _sel: Sel) {} extern "C" fn child_of_item(_this: &Object,
identifier_body
bookmarks.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cocoa::base::*; use cocoa::foundation::*; use objc::declare::ClassDecl; use objc::runtime::{Class, Object, Sel}; pub fn register() { /* NShellBookmark */ { let superclass = Class::get("NSObject").unwrap(); let mut newclass = ClassDecl::new("NSShellBookmark", superclass).unwrap(); newclass.add_ivar::<id>("link"); newclass.add_ivar::<id>("name"); newclass.register(); } /* NSShellBookmarks */ { let superclass = Class::get("NSObject").unwrap(); let mut newclass = ClassDecl::new("NSShellBookmarks", superclass).unwrap(); newclass.add_ivar::<id>("bookmarks"); extern "C" fn awake_from_nib(_this: &mut Object, _sel: Sel) {} extern "C" fn child_of_item(_this: &Object, _sel: Sel, _outlineview: id, _index: NSInteger, _item: id) -> id { nil } extern "C" fn is_item_expandable(_this: &Object, _sel: Sel, _outlineview: id, _item: id) -> BOOL { NO } extern "C" fn number_of_child_of_item(_this: &Object, _sel: Sel, _outlineview: id, _item: id) -> NSInteger { 0 } extern "C" fn
(_this: &Object, _sel: Sel, _outlineview: id, _column: id, _item: id) -> id { nil } // FIXME: Yeah! Outlets, we want to use that everywhere instead of subviews // let textfield = msg_send![view, textField]; unsafe { newclass.add_method(sel!(outlineView:child:ofItem:), child_of_item as extern "C" fn(&Object, Sel, id, NSInteger, id) -> id); newclass.add_method(sel!(outlineView:isItemExpandable:), is_item_expandable as extern "C" fn(&Object, Sel, id, id) -> BOOL); newclass.add_method(sel!(outlineView:numberOfChildrenOfItem:), number_of_child_of_item as extern "C" fn(&Object, Sel, id, id) -> NSInteger); newclass.add_method(sel!(outlineView:objectValueForTableColumn:byItem:), object_value as extern "C" fn(&Object, Sel, id, id, id) -> id); newclass.add_method(sel!(awakeFromNib), awake_from_nib as extern "C" fn(&mut Object, Sel)); } newclass.register(); } }
object_value
identifier_name
bookmarks.rs
* License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cocoa::base::*; use cocoa::foundation::*; use objc::declare::ClassDecl; use objc::runtime::{Class, Object, Sel}; pub fn register() { /* NShellBookmark */ { let superclass = Class::get("NSObject").unwrap(); let mut newclass = ClassDecl::new("NSShellBookmark", superclass).unwrap(); newclass.add_ivar::<id>("link"); newclass.add_ivar::<id>("name"); newclass.register(); } /* NSShellBookmarks */ { let superclass = Class::get("NSObject").unwrap(); let mut newclass = ClassDecl::new("NSShellBookmarks", superclass).unwrap(); newclass.add_ivar::<id>("bookmarks"); extern "C" fn awake_from_nib(_this: &mut Object, _sel: Sel) {} extern "C" fn child_of_item(_this: &Object, _sel: Sel, _outlineview: id, _index: NSInteger, _item: id) -> id { nil } extern "C" fn is_item_expandable(_this: &Object, _sel: Sel, _outlineview: id, _item: id) -> BOOL { NO } extern "C" fn number_of_child_of_item(_this: &Object, _sel: Sel, _outlineview: id, _item: id) -> NSInteger { 0 } extern "C" fn object_value(_this: &Object, _sel: Sel, _outlineview: id, _column: id, _item: id) -> id { nil } // FIXME: Yeah! Outlets, we want to use that everywhere instead of subviews // let textfield = msg_send![view, textField]; unsafe { newclass.add_method(sel!(outlineView:child:ofItem:), child_of_item as extern "C" fn(&Object, Sel, id, NSInteger, id) -> id); newclass.add_method(sel!(outlineView:isItemExpandable:), is_item_expandable as extern "C" fn(&Object, Sel, id, id) -> BOOL); newclass.add_method(sel!(outlineView:numberOfChildrenOfItem:), number_of_child_of_item as extern "C" fn(&Object, Sel, id, id) -> NSInteger); newclass.add_method(sel!(outlineView:objectValueForTableColumn:byItem:), object_value as extern "C" fn(&Object, Sel, id, id, id) -> id); newclass.add_method(sel!(awakeFromNib), awake_from_nib as extern "C" fn(&mut Object, Sel)); } newclass.register(); } }
/* This Source Code Form is subject to the terms of the Mozilla Public
random_line_split
octopus.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ /// Return a DAG with cross and octopus merges. pub fn
() -> Vec<Vec<usize>> { let parents = drawdag::parse( r#" r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r00 r01 r02 r03 r04 r05 r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r02 r03 r04 r05 r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r00 r01 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r04 r05 r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r00 r01 r02 r03 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r00 r01 r02 r03 r04 r05 "#, ); (0..=32) .map(|i| { parents[&format!("r{:02}", i)] .iter() .map(|p| p.trim_start_matches('r').parse::<usize>().unwrap()) .collect() }) .collect() }
cross_octopus
identifier_name
octopus.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ /// Return a DAG with cross and octopus merges. pub fn cross_octopus() -> Vec<Vec<usize>> { let parents = drawdag::parse( r#" r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r00 r01 r02 r03 r04 r05 r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r02 r03 r04 r05 r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r00 r01 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r04 r05 r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r00 r01 r02 r03 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r00 r01 r02 r03 r04 r05
); (0..=32) .map(|i| { parents[&format!("r{:02}", i)] .iter() .map(|p| p.trim_start_matches('r').parse::<usize>().unwrap()) .collect() }) .collect() }
"#,
random_line_split
octopus.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ /// Return a DAG with cross and octopus merges. pub fn cross_octopus() -> Vec<Vec<usize>>
(0..=32) .map(|i| { parents[&format!("r{:02}", i)] .iter() .map(|p| p.trim_start_matches('r').parse::<usize>().unwrap()) .collect() }) .collect() }
{ let parents = drawdag::parse( r#" r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r00 r01 r02 r03 r04 r05 r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r02 r03 r04 r05 r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r00 r01 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r04 r05 r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r00 r01 r02 r03 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r00 r01 r02 r03 r04 r05 "#, );
identifier_body
newtype.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. struct mytype(Mytype); struct Mytype {compute: extern fn(mytype) -> int, val: int} fn compute(i: mytype) -> int { return i.val + 20; } pub fn
() { let myval = mytype(Mytype{compute: compute, val: 30}); printfln!("%d", compute(myval)); assert_eq!((myval.compute)(myval), 50); }
main
identifier_name
newtype.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. //
// except according to those terms. struct mytype(Mytype); struct Mytype {compute: extern fn(mytype) -> int, val: int} fn compute(i: mytype) -> int { return i.val + 20; } pub fn main() { let myval = mytype(Mytype{compute: compute, val: 30}); printfln!("%d", compute(myval)); assert_eq!((myval.compute)(myval), 50); }
// 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
random_line_split
ex5.rs
use std; //============================================================================== struct Complex { real : f32, imag : f32 } impl Complex { fn new(real: f32, imag: f32) -> Complex { Complex { real: real, imag: imag } } fn to_string(&self) -> String { format!("{}{:+}i", self.real, self.imag) } fn add(&self, v: Complex) -> Complex { Complex { real: self.real + v.real, imag: self.imag + v.imag } } fn times_ten(&mut self) { self.real *= 10.0; self.imag *= 10.0; } fn abs(&self) -> f32 { (self.real * self.real + self.imag * self.imag).sqrt() } } fn ex_5_1() { println!("\n========== 1 =========="); let a = Complex::new(1.0, 2.0); println!("a = {}", a.to_string()); let b = Complex::new(2.0, 4.0); println!("b = {}", b.to_string()); let mut c = a.add(b); println!("c = {}", c.to_string()); c.times_ten(); println!("c*10 = {}", c.to_string()); let d = Complex::new(-3.0, -4.0); println!("d = {}", d.to_string()); println!("abs(d) = {}", d.abs()); } //============================================================================== trait Draw { fn draw(&self); } struct S1 { val : u32 } struct S2 { val : f32 } impl Draw for S1 { fn draw(&self) { println!("*** {} ***", self.val); } } impl Draw for S2 { fn draw(&self) { println!("*** {} ***", self.val); } } fn draw_object(obj : &Draw) { obj.draw(); } fn ex_5_2() { println!("\n========== 2 =========="); let s1 = S1 { val : 10 }; draw_object(&s1); let s2 = S2 { val : 3.14 }; draw_object(&s2); } //============================================================================== // Eq, Ord, Clone, Debug, Default and Add traits for struct #[derive(Eq)] #[derive(Default)] struct Position { x : u32, y : u32 } impl PartialEq for Position { fn eq(&self, other: &Position) -> bool { self.x == other.x && self.y == other.y } } impl std::cmp::Ord for Position { fn cmp(&self, other: &Position) -> std::cmp::Ordering
} impl std::cmp::PartialOrd for Position { fn partial_cmp(&self, other: &Position) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl std::clone::Clone for Position { fn clone(&self) -> Position { Position { x : self.x, y: self.y } // Or, derive Copy at Position and return *self here. } } impl std::ops::Add for Position { type Output = Position; fn add(self, other: Position) -> Position { Position { x: self.x + other.x, y: self.y + other.y } } } impl std::fmt::Debug for Position { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Position{{ x:{}, y:{} }}", self.x, self.y) } } fn ex_5_3() { println!("\n========== 3 =========="); let pos1 = Position { x: 10, y: 20 }; let pos2 = Position { x: 10, y: 20 }; let pos3 = Position { x: 20, y: 40 }; let pos4 = Position { x: 20, y: 10 }; println!("pos1 == pos2 : {}", pos1 == pos2); println!("pos1 == pos3 : {}", pos1 == pos3); println!("pos1!= pos3 : {}", pos1!= pos3); println!("pos1 == pos4 : {}", pos1 == pos4); println!("pos1 < pos3 : {}", pos1 < pos3); println!("pos1 > pos3 : {}", pos1 > pos3); let pos5 = pos4.clone(); println!("pos4 == pos5 : {}", pos4 > pos5); println!("pos1 + pos2 : {:?}", pos1 + pos2); let pos0 : Position = Default::default(); println!("pos0 : {:?}", pos0); } //============================================================================== // Default and Debug traits for enum enum ButtonState { CLICKED, RELEASED } impl Default for ButtonState { fn default() -> ButtonState { ButtonState::CLICKED } } impl std::fmt::Debug for ButtonState { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let state = match *self { ButtonState::CLICKED => "CLICKED", ButtonState::RELEASED => "RELEASED", }; write!(f, "{}", state) } } fn ex_5_4() { println!("\n========== 4 =========="); let mut btn : ButtonState = Default::default(); println!("btn = {:?}", btn); btn = ButtonState::RELEASED; println!("btn = {:?}", btn); } //============================================================================== pub fn ex5() { println!("\n########## Example 5 ##########"); ex_5_1(); ex_5_2(); ex_5_3(); ex_5_4(); }
{ let abs = self.x * self.x + self.y * self.y; let abs_other = other.x * other.x + other.y * other.y; abs.cmp(&abs_other) }
identifier_body
ex5.rs
use std; //============================================================================== struct Complex { real : f32, imag : f32 } impl Complex { fn new(real: f32, imag: f32) -> Complex { Complex { real: real, imag: imag } }
} fn add(&self, v: Complex) -> Complex { Complex { real: self.real + v.real, imag: self.imag + v.imag } } fn times_ten(&mut self) { self.real *= 10.0; self.imag *= 10.0; } fn abs(&self) -> f32 { (self.real * self.real + self.imag * self.imag).sqrt() } } fn ex_5_1() { println!("\n========== 1 =========="); let a = Complex::new(1.0, 2.0); println!("a = {}", a.to_string()); let b = Complex::new(2.0, 4.0); println!("b = {}", b.to_string()); let mut c = a.add(b); println!("c = {}", c.to_string()); c.times_ten(); println!("c*10 = {}", c.to_string()); let d = Complex::new(-3.0, -4.0); println!("d = {}", d.to_string()); println!("abs(d) = {}", d.abs()); } //============================================================================== trait Draw { fn draw(&self); } struct S1 { val : u32 } struct S2 { val : f32 } impl Draw for S1 { fn draw(&self) { println!("*** {} ***", self.val); } } impl Draw for S2 { fn draw(&self) { println!("*** {} ***", self.val); } } fn draw_object(obj : &Draw) { obj.draw(); } fn ex_5_2() { println!("\n========== 2 =========="); let s1 = S1 { val : 10 }; draw_object(&s1); let s2 = S2 { val : 3.14 }; draw_object(&s2); } //============================================================================== // Eq, Ord, Clone, Debug, Default and Add traits for struct #[derive(Eq)] #[derive(Default)] struct Position { x : u32, y : u32 } impl PartialEq for Position { fn eq(&self, other: &Position) -> bool { self.x == other.x && self.y == other.y } } impl std::cmp::Ord for Position { fn cmp(&self, other: &Position) -> std::cmp::Ordering { let abs = self.x * self.x + self.y * self.y; let abs_other = other.x * other.x + other.y * other.y; abs.cmp(&abs_other) } } impl std::cmp::PartialOrd for Position { fn partial_cmp(&self, other: &Position) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl std::clone::Clone for Position { fn clone(&self) -> Position { Position { x : self.x, y: self.y } // Or, derive Copy at Position and return *self here. } } impl std::ops::Add for Position { type Output = Position; fn add(self, other: Position) -> Position { Position { x: self.x + other.x, y: self.y + other.y } } } impl std::fmt::Debug for Position { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Position{{ x:{}, y:{} }}", self.x, self.y) } } fn ex_5_3() { println!("\n========== 3 =========="); let pos1 = Position { x: 10, y: 20 }; let pos2 = Position { x: 10, y: 20 }; let pos3 = Position { x: 20, y: 40 }; let pos4 = Position { x: 20, y: 10 }; println!("pos1 == pos2 : {}", pos1 == pos2); println!("pos1 == pos3 : {}", pos1 == pos3); println!("pos1!= pos3 : {}", pos1!= pos3); println!("pos1 == pos4 : {}", pos1 == pos4); println!("pos1 < pos3 : {}", pos1 < pos3); println!("pos1 > pos3 : {}", pos1 > pos3); let pos5 = pos4.clone(); println!("pos4 == pos5 : {}", pos4 > pos5); println!("pos1 + pos2 : {:?}", pos1 + pos2); let pos0 : Position = Default::default(); println!("pos0 : {:?}", pos0); } //============================================================================== // Default and Debug traits for enum enum ButtonState { CLICKED, RELEASED } impl Default for ButtonState { fn default() -> ButtonState { ButtonState::CLICKED } } impl std::fmt::Debug for ButtonState { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let state = match *self { ButtonState::CLICKED => "CLICKED", ButtonState::RELEASED => "RELEASED", }; write!(f, "{}", state) } } fn ex_5_4() { println!("\n========== 4 =========="); let mut btn : ButtonState = Default::default(); println!("btn = {:?}", btn); btn = ButtonState::RELEASED; println!("btn = {:?}", btn); } //============================================================================== pub fn ex5() { println!("\n########## Example 5 ##########"); ex_5_1(); ex_5_2(); ex_5_3(); ex_5_4(); }
fn to_string(&self) -> String { format!("{}{:+}i", self.real, self.imag)
random_line_split
ex5.rs
use std; //============================================================================== struct Complex { real : f32, imag : f32 } impl Complex { fn new(real: f32, imag: f32) -> Complex { Complex { real: real, imag: imag } } fn to_string(&self) -> String { format!("{}{:+}i", self.real, self.imag) } fn add(&self, v: Complex) -> Complex { Complex { real: self.real + v.real, imag: self.imag + v.imag } } fn times_ten(&mut self) { self.real *= 10.0; self.imag *= 10.0; } fn abs(&self) -> f32 { (self.real * self.real + self.imag * self.imag).sqrt() } } fn ex_5_1() { println!("\n========== 1 =========="); let a = Complex::new(1.0, 2.0); println!("a = {}", a.to_string()); let b = Complex::new(2.0, 4.0); println!("b = {}", b.to_string()); let mut c = a.add(b); println!("c = {}", c.to_string()); c.times_ten(); println!("c*10 = {}", c.to_string()); let d = Complex::new(-3.0, -4.0); println!("d = {}", d.to_string()); println!("abs(d) = {}", d.abs()); } //============================================================================== trait Draw { fn draw(&self); } struct
{ val : u32 } struct S2 { val : f32 } impl Draw for S1 { fn draw(&self) { println!("*** {} ***", self.val); } } impl Draw for S2 { fn draw(&self) { println!("*** {} ***", self.val); } } fn draw_object(obj : &Draw) { obj.draw(); } fn ex_5_2() { println!("\n========== 2 =========="); let s1 = S1 { val : 10 }; draw_object(&s1); let s2 = S2 { val : 3.14 }; draw_object(&s2); } //============================================================================== // Eq, Ord, Clone, Debug, Default and Add traits for struct #[derive(Eq)] #[derive(Default)] struct Position { x : u32, y : u32 } impl PartialEq for Position { fn eq(&self, other: &Position) -> bool { self.x == other.x && self.y == other.y } } impl std::cmp::Ord for Position { fn cmp(&self, other: &Position) -> std::cmp::Ordering { let abs = self.x * self.x + self.y * self.y; let abs_other = other.x * other.x + other.y * other.y; abs.cmp(&abs_other) } } impl std::cmp::PartialOrd for Position { fn partial_cmp(&self, other: &Position) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl std::clone::Clone for Position { fn clone(&self) -> Position { Position { x : self.x, y: self.y } // Or, derive Copy at Position and return *self here. } } impl std::ops::Add for Position { type Output = Position; fn add(self, other: Position) -> Position { Position { x: self.x + other.x, y: self.y + other.y } } } impl std::fmt::Debug for Position { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Position{{ x:{}, y:{} }}", self.x, self.y) } } fn ex_5_3() { println!("\n========== 3 =========="); let pos1 = Position { x: 10, y: 20 }; let pos2 = Position { x: 10, y: 20 }; let pos3 = Position { x: 20, y: 40 }; let pos4 = Position { x: 20, y: 10 }; println!("pos1 == pos2 : {}", pos1 == pos2); println!("pos1 == pos3 : {}", pos1 == pos3); println!("pos1!= pos3 : {}", pos1!= pos3); println!("pos1 == pos4 : {}", pos1 == pos4); println!("pos1 < pos3 : {}", pos1 < pos3); println!("pos1 > pos3 : {}", pos1 > pos3); let pos5 = pos4.clone(); println!("pos4 == pos5 : {}", pos4 > pos5); println!("pos1 + pos2 : {:?}", pos1 + pos2); let pos0 : Position = Default::default(); println!("pos0 : {:?}", pos0); } //============================================================================== // Default and Debug traits for enum enum ButtonState { CLICKED, RELEASED } impl Default for ButtonState { fn default() -> ButtonState { ButtonState::CLICKED } } impl std::fmt::Debug for ButtonState { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let state = match *self { ButtonState::CLICKED => "CLICKED", ButtonState::RELEASED => "RELEASED", }; write!(f, "{}", state) } } fn ex_5_4() { println!("\n========== 4 =========="); let mut btn : ButtonState = Default::default(); println!("btn = {:?}", btn); btn = ButtonState::RELEASED; println!("btn = {:?}", btn); } //============================================================================== pub fn ex5() { println!("\n########## Example 5 ##########"); ex_5_1(); ex_5_2(); ex_5_3(); ex_5_4(); }
S1
identifier_name
eval_definitions.rs
use crate::helpers::{values::*, *}; use ostrov::errors::RuntimeError::*; #[test] fn define_with_one_arg()
#[test] fn define_with_two_args() { assert_eval_val("(define x 2)", unspecified()); assert_eval( "(define x 2) (= x 2)", "#t", ); assert_eval( "(define x 9) (define x 10) x", "10", ); assert_eval( "(define x 9) (define y x) y", "9", ); } #[test] fn define_with_one_arg_lambda() { assert_eval( "(define f (lambda (x) 1)) (f 9)", "1", ); } #[test] fn define_procedure_with_fixed_args() { assert_eval_val("(define (x) 3)", unspecified()); } #[test] fn define_procedure_with_varargs() { assert_eval_val("(define (x a. b) 3)", unspecified()); } #[test] fn define_procedure_with_any() { assert_eval_val("(define (x. b) 3)", unspecified()); } #[test] fn define_bad_arity() { assert_eval_err("(define)", MalformedExpression); }
{ assert_eval_val("(define x)", unspecified()); assert_eval_val( "(define x) x", unspecified(), ); }
identifier_body
eval_definitions.rs
use crate::helpers::{values::*, *}; use ostrov::errors::RuntimeError::*; #[test] fn define_with_one_arg() { assert_eval_val("(define x)", unspecified()); assert_eval_val( "(define x) x", unspecified(), ); } #[test] fn define_with_two_args() { assert_eval_val("(define x 2)", unspecified()); assert_eval( "(define x 2) (= x 2)", "#t", ); assert_eval( "(define x 9) (define x 10) x", "10", ); assert_eval( "(define x 9) (define y x) y", "9", ); } #[test] fn
() { assert_eval( "(define f (lambda (x) 1)) (f 9)", "1", ); } #[test] fn define_procedure_with_fixed_args() { assert_eval_val("(define (x) 3)", unspecified()); } #[test] fn define_procedure_with_varargs() { assert_eval_val("(define (x a. b) 3)", unspecified()); } #[test] fn define_procedure_with_any() { assert_eval_val("(define (x. b) 3)", unspecified()); } #[test] fn define_bad_arity() { assert_eval_err("(define)", MalformedExpression); }
define_with_one_arg_lambda
identifier_name
eval_definitions.rs
use crate::helpers::{values::*, *}; use ostrov::errors::RuntimeError::*; #[test] fn define_with_one_arg() { assert_eval_val("(define x)", unspecified()); assert_eval_val( "(define x) x", unspecified(), ); } #[test] fn define_with_two_args() { assert_eval_val("(define x 2)", unspecified()); assert_eval( "(define x 2)
(= x 2)", "#t", ); assert_eval( "(define x 9) (define x 10) x", "10", ); assert_eval( "(define x 9) (define y x) y", "9", ); } #[test] fn define_with_one_arg_lambda() { assert_eval( "(define f (lambda (x) 1)) (f 9)", "1", ); } #[test] fn define_procedure_with_fixed_args() { assert_eval_val("(define (x) 3)", unspecified()); } #[test] fn define_procedure_with_varargs() { assert_eval_val("(define (x a. b) 3)", unspecified()); } #[test] fn define_procedure_with_any() { assert_eval_val("(define (x. b) 3)", unspecified()); } #[test] fn define_bad_arity() { assert_eval_err("(define)", MalformedExpression); }
random_line_split
encoder.rs
extern crate getopts; extern crate lt; use std::env; use std::io::{self, Write}; use std::fs::File; use getopts::{Options, Matches}; use lt::sampler::params::LTBlockSamplerParams; use lt::encode; fn parameterize(default: LTBlockSamplerParams, matches: Matches) -> LTBlockSamplerParams { let mut params = default; // Add c to opts params = match matches.opt_str("c") { Some(c) => params.c(c.parse::<f64>().unwrap()), None => params }; // Add delta to opts params = match matches.opt_str("d") { Some(delta) => params.delta(delta.parse::<f64>().unwrap()), None => params }; // Add seed to opts params = match matches.opt_str("s") { Some(s) => params.seed(s.parse::<u32>().unwrap()), None => params }; params } fn main ()
let input_fn = matches.opt_str("f").unwrap(); let mut f = match File::open(input_fn) { Ok(file) => file, Err(e) => panic!("{}", e) }; // Parameterize LT sampler using options let num_blocks: u32 = match matches.opt_str("k").unwrap().parse() { Ok(k) => k, Err(e) => panic!("Error parsing k: {}", e) }; let params = parameterize(LTBlockSamplerParams::new(num_blocks), matches); let encoder = encode::LTEncoder::new(params, &mut f); for block in encoder.take(100) { match handle.write(block.encode().as_slice()) { Ok(_) => (), Err(e) => panic!(e) } } }
{ let args: Vec<String> = env::args().collect(); let mut options = Options::new(); options.reqopt("f", "input_file", "File to transmit", "FILE"); options.reqopt("k", "num_blocks", "Number of blocks to divide the file into for transmission", ""); options.optopt("c", "c", "C parameter to block sampler", ""); options.optopt("d", "delta", "Delta parameter to block sampler", ""); options.optopt("s", "seed", "Seed to the block sampler PRNG", ""); // Validate args let matches = match options.parse(&args[1..]) { Ok(m) => { m }, Err(f) => { panic!(f.to_string()) } }; // Get standard out to stream blocks let stdout = io::stdout(); let mut handle = stdout.lock(); // Get input file from args
identifier_body
encoder.rs
extern crate getopts; extern crate lt; use std::env; use std::io::{self, Write}; use std::fs::File; use getopts::{Options, Matches}; use lt::sampler::params::LTBlockSamplerParams; use lt::encode;
// Add c to opts params = match matches.opt_str("c") { Some(c) => params.c(c.parse::<f64>().unwrap()), None => params }; // Add delta to opts params = match matches.opt_str("d") { Some(delta) => params.delta(delta.parse::<f64>().unwrap()), None => params }; // Add seed to opts params = match matches.opt_str("s") { Some(s) => params.seed(s.parse::<u32>().unwrap()), None => params }; params } fn main () { let args: Vec<String> = env::args().collect(); let mut options = Options::new(); options.reqopt("f", "input_file", "File to transmit", "FILE"); options.reqopt("k", "num_blocks", "Number of blocks to divide the file into for transmission", ""); options.optopt("c", "c", "C parameter to block sampler", ""); options.optopt("d", "delta", "Delta parameter to block sampler", ""); options.optopt("s", "seed", "Seed to the block sampler PRNG", ""); // Validate args let matches = match options.parse(&args[1..]) { Ok(m) => { m }, Err(f) => { panic!(f.to_string()) } }; // Get standard out to stream blocks let stdout = io::stdout(); let mut handle = stdout.lock(); // Get input file from args let input_fn = matches.opt_str("f").unwrap(); let mut f = match File::open(input_fn) { Ok(file) => file, Err(e) => panic!("{}", e) }; // Parameterize LT sampler using options let num_blocks: u32 = match matches.opt_str("k").unwrap().parse() { Ok(k) => k, Err(e) => panic!("Error parsing k: {}", e) }; let params = parameterize(LTBlockSamplerParams::new(num_blocks), matches); let encoder = encode::LTEncoder::new(params, &mut f); for block in encoder.take(100) { match handle.write(block.encode().as_slice()) { Ok(_) => (), Err(e) => panic!(e) } } }
fn parameterize(default: LTBlockSamplerParams, matches: Matches) -> LTBlockSamplerParams { let mut params = default;
random_line_split
encoder.rs
extern crate getopts; extern crate lt; use std::env; use std::io::{self, Write}; use std::fs::File; use getopts::{Options, Matches}; use lt::sampler::params::LTBlockSamplerParams; use lt::encode; fn parameterize(default: LTBlockSamplerParams, matches: Matches) -> LTBlockSamplerParams { let mut params = default; // Add c to opts params = match matches.opt_str("c") { Some(c) => params.c(c.parse::<f64>().unwrap()), None => params }; // Add delta to opts params = match matches.opt_str("d") { Some(delta) => params.delta(delta.parse::<f64>().unwrap()), None => params }; // Add seed to opts params = match matches.opt_str("s") { Some(s) => params.seed(s.parse::<u32>().unwrap()), None => params }; params } fn
() { let args: Vec<String> = env::args().collect(); let mut options = Options::new(); options.reqopt("f", "input_file", "File to transmit", "FILE"); options.reqopt("k", "num_blocks", "Number of blocks to divide the file into for transmission", ""); options.optopt("c", "c", "C parameter to block sampler", ""); options.optopt("d", "delta", "Delta parameter to block sampler", ""); options.optopt("s", "seed", "Seed to the block sampler PRNG", ""); // Validate args let matches = match options.parse(&args[1..]) { Ok(m) => { m }, Err(f) => { panic!(f.to_string()) } }; // Get standard out to stream blocks let stdout = io::stdout(); let mut handle = stdout.lock(); // Get input file from args let input_fn = matches.opt_str("f").unwrap(); let mut f = match File::open(input_fn) { Ok(file) => file, Err(e) => panic!("{}", e) }; // Parameterize LT sampler using options let num_blocks: u32 = match matches.opt_str("k").unwrap().parse() { Ok(k) => k, Err(e) => panic!("Error parsing k: {}", e) }; let params = parameterize(LTBlockSamplerParams::new(num_blocks), matches); let encoder = encode::LTEncoder::new(params, &mut f); for block in encoder.take(100) { match handle.write(block.encode().as_slice()) { Ok(_) => (), Err(e) => panic!(e) } } }
main
identifier_name
linear.rs
use autograd::{Function, FuncIntf, FuncDelegate, FIWrap}; use tensor::{OptTensorKindList, TensorKindList}; impl_func!(LinearF); impl FuncIntf for LinearF { fn forward(&mut self, input_list: &mut TensorKindList) -> TensorKindList { self.save_for_backward(input_list); let (input, weight) = (input_list.remove(0), input_list.remove(0)); let mut output = input.new(()).resize_([input.size()[0], weight.size()[0]]); output.zero_().addmm_(0, 1, &input, &weight.t()); if input_list.len()!= 0 { let bias = input_list.remove(0).expand_as(&output); output.addt_(1, &bias); } vec![output] } fn backward(&mut self, grad_output_list: &mut OptTensorKindList) -> OptTensorKindList { let tensorlist = self.saved_tensors(); let grad_output_ = grad_output_list.remove(0); let needs_input_grad = self.needs_input_grad(); let grad_output = match grad_output_ { Some(f) => f, None => unreachable!(), }; let (input, weight) = (&tensorlist[0], &tensorlist[1]); let mut output: OptTensorKindList = Vec::new(); let grad_input = if needs_input_grad[0] { Some(grad_output.mm(weight)) } else { None };
}; output.push(grad_weight); if tensorlist.len() > 0 && needs_input_grad[2] { let grad_bias = grad_output.sum_reduce(0, false); output.push(Some(grad_bias)); } output } }
output.push(grad_input); let grad_weight = if needs_input_grad[1] { Some(grad_output.t().mm(input)) } else { None
random_line_split
linear.rs
use autograd::{Function, FuncIntf, FuncDelegate, FIWrap}; use tensor::{OptTensorKindList, TensorKindList}; impl_func!(LinearF); impl FuncIntf for LinearF { fn forward(&mut self, input_list: &mut TensorKindList) -> TensorKindList
fn backward(&mut self, grad_output_list: &mut OptTensorKindList) -> OptTensorKindList { let tensorlist = self.saved_tensors(); let grad_output_ = grad_output_list.remove(0); let needs_input_grad = self.needs_input_grad(); let grad_output = match grad_output_ { Some(f) => f, None => unreachable!(), }; let (input, weight) = (&tensorlist[0], &tensorlist[1]); let mut output: OptTensorKindList = Vec::new(); let grad_input = if needs_input_grad[0] { Some(grad_output.mm(weight)) } else { None }; output.push(grad_input); let grad_weight = if needs_input_grad[1] { Some(grad_output.t().mm(input)) } else { None }; output.push(grad_weight); if tensorlist.len() > 0 && needs_input_grad[2] { let grad_bias = grad_output.sum_reduce(0, false); output.push(Some(grad_bias)); } output } }
{ self.save_for_backward(input_list); let (input, weight) = (input_list.remove(0), input_list.remove(0)); let mut output = input.new(()).resize_([input.size()[0], weight.size()[0]]); output.zero_().addmm_(0, 1, &input, &weight.t()); if input_list.len() != 0 { let bias = input_list.remove(0).expand_as(&output); output.addt_(1, &bias); } vec![output] }
identifier_body
linear.rs
use autograd::{Function, FuncIntf, FuncDelegate, FIWrap}; use tensor::{OptTensorKindList, TensorKindList}; impl_func!(LinearF); impl FuncIntf for LinearF { fn forward(&mut self, input_list: &mut TensorKindList) -> TensorKindList { self.save_for_backward(input_list); let (input, weight) = (input_list.remove(0), input_list.remove(0)); let mut output = input.new(()).resize_([input.size()[0], weight.size()[0]]); output.zero_().addmm_(0, 1, &input, &weight.t()); if input_list.len()!= 0 { let bias = input_list.remove(0).expand_as(&output); output.addt_(1, &bias); } vec![output] } fn
(&mut self, grad_output_list: &mut OptTensorKindList) -> OptTensorKindList { let tensorlist = self.saved_tensors(); let grad_output_ = grad_output_list.remove(0); let needs_input_grad = self.needs_input_grad(); let grad_output = match grad_output_ { Some(f) => f, None => unreachable!(), }; let (input, weight) = (&tensorlist[0], &tensorlist[1]); let mut output: OptTensorKindList = Vec::new(); let grad_input = if needs_input_grad[0] { Some(grad_output.mm(weight)) } else { None }; output.push(grad_input); let grad_weight = if needs_input_grad[1] { Some(grad_output.t().mm(input)) } else { None }; output.push(grad_weight); if tensorlist.len() > 0 && needs_input_grad[2] { let grad_bias = grad_output.sum_reduce(0, false); output.push(Some(grad_bias)); } output } }
backward
identifier_name
linear.rs
use autograd::{Function, FuncIntf, FuncDelegate, FIWrap}; use tensor::{OptTensorKindList, TensorKindList}; impl_func!(LinearF); impl FuncIntf for LinearF { fn forward(&mut self, input_list: &mut TensorKindList) -> TensorKindList { self.save_for_backward(input_list); let (input, weight) = (input_list.remove(0), input_list.remove(0)); let mut output = input.new(()).resize_([input.size()[0], weight.size()[0]]); output.zero_().addmm_(0, 1, &input, &weight.t()); if input_list.len()!= 0 { let bias = input_list.remove(0).expand_as(&output); output.addt_(1, &bias); } vec![output] } fn backward(&mut self, grad_output_list: &mut OptTensorKindList) -> OptTensorKindList { let tensorlist = self.saved_tensors(); let grad_output_ = grad_output_list.remove(0); let needs_input_grad = self.needs_input_grad(); let grad_output = match grad_output_ { Some(f) => f, None => unreachable!(), }; let (input, weight) = (&tensorlist[0], &tensorlist[1]); let mut output: OptTensorKindList = Vec::new(); let grad_input = if needs_input_grad[0]
else { None }; output.push(grad_input); let grad_weight = if needs_input_grad[1] { Some(grad_output.t().mm(input)) } else { None }; output.push(grad_weight); if tensorlist.len() > 0 && needs_input_grad[2] { let grad_bias = grad_output.sum_reduce(0, false); output.push(Some(grad_bias)); } output } }
{ Some(grad_output.mm(weight)) }
conditional_block
mx.rs
extern crate c_ares_sys; extern crate libc; use std::ffi::CStr; use std::marker::PhantomData; use std::mem; use std::ptr; use std::slice; use std::str; use error::AresError; use utils::ares_error; /// The result of a successful MX lookup. pub struct MXResults { mx_reply: *mut c_ares_sys::Struct_ares_mx_reply, phantom: PhantomData<c_ares_sys::Struct_ares_mx_reply>, } /// The contents of a single MX record. pub struct
<'a> { mx_reply: *const c_ares_sys::Struct_ares_mx_reply, phantom: PhantomData<&'a c_ares_sys::Struct_ares_mx_reply>, } impl MXResults { /// Obtain an `MXResults` from the response to an MX lookup. pub fn parse_from(data: &[u8]) -> Result<MXResults, AresError> { let mut mx_reply: *mut c_ares_sys::Struct_ares_mx_reply = ptr::null_mut(); let parse_status = unsafe { c_ares_sys::ares_parse_mx_reply( data.as_ptr(), data.len() as libc::c_int, &mut mx_reply) }; if parse_status!= c_ares_sys::ARES_SUCCESS { Err(ares_error(parse_status)) } else { let result = MXResults::new(mx_reply); Ok(result) } } fn new(mx_reply: *mut c_ares_sys::Struct_ares_mx_reply) -> MXResults { MXResults { mx_reply: mx_reply, phantom: PhantomData, } } /// Returns an iterator over the `MXResult` values in this `MXResults`. pub fn iter(&self) -> MXResultsIterator { MXResultsIterator { next: self.mx_reply, phantom: PhantomData, } } } pub struct MXResultsIterator<'a> { next: *const c_ares_sys::Struct_ares_mx_reply, phantom: PhantomData<&'a c_ares_sys::Struct_ares_mx_reply>, } impl<'a> Iterator for MXResultsIterator<'a> { type Item = MXResult<'a>; fn next(&mut self) -> Option<Self::Item> { let mx_reply = self.next; if mx_reply.is_null() { None } else { unsafe { self.next = (*mx_reply).next; } let mx_result = MXResult { mx_reply: mx_reply, phantom: PhantomData, }; Some(mx_result) } } } impl<'a> IntoIterator for &'a MXResults { type Item = MXResult<'a>; type IntoIter = MXResultsIterator<'a>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl Drop for MXResults { fn drop(&mut self) { unsafe { c_ares_sys::ares_free_data(self.mx_reply as *mut libc::c_void); } } } unsafe impl Send for MXResults { } unsafe impl Sync for MXResults { } unsafe impl<'a> Send for MXResult<'a> { } unsafe impl<'a> Sync for MXResult<'a> { } unsafe impl<'a> Send for MXResultsIterator<'a> { } unsafe impl<'a> Sync for MXResultsIterator<'a> { } impl<'a> MXResult<'a> { /// Returns the hostname in this `MXResult`. pub fn host(&self) -> &str { unsafe { let c_str = CStr::from_ptr((*self.mx_reply).host); str::from_utf8_unchecked(c_str.to_bytes()) } } /// Returns the priority from this `MXResult`. pub fn priority(&self) -> u16 { unsafe { (*self.mx_reply).priority } } } pub unsafe extern "C" fn query_mx_callback<F>( arg: *mut libc::c_void, status: libc::c_int, _timeouts: libc::c_int, abuf: *mut libc::c_uchar, alen: libc::c_int) where F: FnOnce(Result<MXResults, AresError>) +'static { let handler: Box<F> = mem::transmute(arg); let result = if status!= c_ares_sys::ARES_SUCCESS { Err(ares_error(status)) } else { let data = slice::from_raw_parts(abuf, alen as usize); MXResults::parse_from(data) }; handler(result); }
MXResult
identifier_name
mx.rs
extern crate c_ares_sys; extern crate libc; use std::ffi::CStr; use std::marker::PhantomData; use std::mem; use std::ptr; use std::slice; use std::str; use error::AresError; use utils::ares_error; /// The result of a successful MX lookup. pub struct MXResults { mx_reply: *mut c_ares_sys::Struct_ares_mx_reply, phantom: PhantomData<c_ares_sys::Struct_ares_mx_reply>, } /// The contents of a single MX record. pub struct MXResult<'a> { mx_reply: *const c_ares_sys::Struct_ares_mx_reply, phantom: PhantomData<&'a c_ares_sys::Struct_ares_mx_reply>, } impl MXResults { /// Obtain an `MXResults` from the response to an MX lookup. pub fn parse_from(data: &[u8]) -> Result<MXResults, AresError> { let mut mx_reply: *mut c_ares_sys::Struct_ares_mx_reply = ptr::null_mut(); let parse_status = unsafe { c_ares_sys::ares_parse_mx_reply( data.as_ptr(), data.len() as libc::c_int, &mut mx_reply) }; if parse_status!= c_ares_sys::ARES_SUCCESS { Err(ares_error(parse_status)) } else { let result = MXResults::new(mx_reply); Ok(result) } } fn new(mx_reply: *mut c_ares_sys::Struct_ares_mx_reply) -> MXResults
/// Returns an iterator over the `MXResult` values in this `MXResults`. pub fn iter(&self) -> MXResultsIterator { MXResultsIterator { next: self.mx_reply, phantom: PhantomData, } } } pub struct MXResultsIterator<'a> { next: *const c_ares_sys::Struct_ares_mx_reply, phantom: PhantomData<&'a c_ares_sys::Struct_ares_mx_reply>, } impl<'a> Iterator for MXResultsIterator<'a> { type Item = MXResult<'a>; fn next(&mut self) -> Option<Self::Item> { let mx_reply = self.next; if mx_reply.is_null() { None } else { unsafe { self.next = (*mx_reply).next; } let mx_result = MXResult { mx_reply: mx_reply, phantom: PhantomData, }; Some(mx_result) } } } impl<'a> IntoIterator for &'a MXResults { type Item = MXResult<'a>; type IntoIter = MXResultsIterator<'a>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl Drop for MXResults { fn drop(&mut self) { unsafe { c_ares_sys::ares_free_data(self.mx_reply as *mut libc::c_void); } } } unsafe impl Send for MXResults { } unsafe impl Sync for MXResults { } unsafe impl<'a> Send for MXResult<'a> { } unsafe impl<'a> Sync for MXResult<'a> { } unsafe impl<'a> Send for MXResultsIterator<'a> { } unsafe impl<'a> Sync for MXResultsIterator<'a> { } impl<'a> MXResult<'a> { /// Returns the hostname in this `MXResult`. pub fn host(&self) -> &str { unsafe { let c_str = CStr::from_ptr((*self.mx_reply).host); str::from_utf8_unchecked(c_str.to_bytes()) } } /// Returns the priority from this `MXResult`. pub fn priority(&self) -> u16 { unsafe { (*self.mx_reply).priority } } } pub unsafe extern "C" fn query_mx_callback<F>( arg: *mut libc::c_void, status: libc::c_int, _timeouts: libc::c_int, abuf: *mut libc::c_uchar, alen: libc::c_int) where F: FnOnce(Result<MXResults, AresError>) +'static { let handler: Box<F> = mem::transmute(arg); let result = if status!= c_ares_sys::ARES_SUCCESS { Err(ares_error(status)) } else { let data = slice::from_raw_parts(abuf, alen as usize); MXResults::parse_from(data) }; handler(result); }
{ MXResults { mx_reply: mx_reply, phantom: PhantomData, } }
identifier_body
mx.rs
extern crate c_ares_sys; extern crate libc; use std::ffi::CStr; use std::marker::PhantomData; use std::mem; use std::ptr; use std::slice; use std::str; use error::AresError; use utils::ares_error; /// The result of a successful MX lookup. pub struct MXResults { mx_reply: *mut c_ares_sys::Struct_ares_mx_reply, phantom: PhantomData<c_ares_sys::Struct_ares_mx_reply>, } /// The contents of a single MX record. pub struct MXResult<'a> { mx_reply: *const c_ares_sys::Struct_ares_mx_reply, phantom: PhantomData<&'a c_ares_sys::Struct_ares_mx_reply>, } impl MXResults { /// Obtain an `MXResults` from the response to an MX lookup. pub fn parse_from(data: &[u8]) -> Result<MXResults, AresError> { let mut mx_reply: *mut c_ares_sys::Struct_ares_mx_reply = ptr::null_mut(); let parse_status = unsafe { c_ares_sys::ares_parse_mx_reply( data.as_ptr(), data.len() as libc::c_int, &mut mx_reply) }; if parse_status!= c_ares_sys::ARES_SUCCESS { Err(ares_error(parse_status)) } else { let result = MXResults::new(mx_reply); Ok(result) } } fn new(mx_reply: *mut c_ares_sys::Struct_ares_mx_reply) -> MXResults { MXResults { mx_reply: mx_reply, phantom: PhantomData, } } /// Returns an iterator over the `MXResult` values in this `MXResults`. pub fn iter(&self) -> MXResultsIterator { MXResultsIterator { next: self.mx_reply, phantom: PhantomData, } } } pub struct MXResultsIterator<'a> { next: *const c_ares_sys::Struct_ares_mx_reply, phantom: PhantomData<&'a c_ares_sys::Struct_ares_mx_reply>, } impl<'a> Iterator for MXResultsIterator<'a> { type Item = MXResult<'a>; fn next(&mut self) -> Option<Self::Item> { let mx_reply = self.next; if mx_reply.is_null() { None } else { unsafe { self.next = (*mx_reply).next; } let mx_result = MXResult { mx_reply: mx_reply, phantom: PhantomData, }; Some(mx_result) } } } impl<'a> IntoIterator for &'a MXResults { type Item = MXResult<'a>; type IntoIter = MXResultsIterator<'a>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl Drop for MXResults { fn drop(&mut self) { unsafe { c_ares_sys::ares_free_data(self.mx_reply as *mut libc::c_void); } } } unsafe impl Send for MXResults { } unsafe impl Sync for MXResults { } unsafe impl<'a> Send for MXResult<'a> { } unsafe impl<'a> Sync for MXResult<'a> { } unsafe impl<'a> Send for MXResultsIterator<'a> { } unsafe impl<'a> Sync for MXResultsIterator<'a> { } impl<'a> MXResult<'a> { /// Returns the hostname in this `MXResult`. pub fn host(&self) -> &str { unsafe { let c_str = CStr::from_ptr((*self.mx_reply).host); str::from_utf8_unchecked(c_str.to_bytes()) } } /// Returns the priority from this `MXResult`. pub fn priority(&self) -> u16 { unsafe { (*self.mx_reply).priority } } } pub unsafe extern "C" fn query_mx_callback<F>( arg: *mut libc::c_void, status: libc::c_int, _timeouts: libc::c_int, abuf: *mut libc::c_uchar, alen: libc::c_int) where F: FnOnce(Result<MXResults, AresError>) +'static {
Err(ares_error(status)) } else { let data = slice::from_raw_parts(abuf, alen as usize); MXResults::parse_from(data) }; handler(result); }
let handler: Box<F> = mem::transmute(arg); let result = if status != c_ares_sys::ARES_SUCCESS {
random_line_split
mx.rs
extern crate c_ares_sys; extern crate libc; use std::ffi::CStr; use std::marker::PhantomData; use std::mem; use std::ptr; use std::slice; use std::str; use error::AresError; use utils::ares_error; /// The result of a successful MX lookup. pub struct MXResults { mx_reply: *mut c_ares_sys::Struct_ares_mx_reply, phantom: PhantomData<c_ares_sys::Struct_ares_mx_reply>, } /// The contents of a single MX record. pub struct MXResult<'a> { mx_reply: *const c_ares_sys::Struct_ares_mx_reply, phantom: PhantomData<&'a c_ares_sys::Struct_ares_mx_reply>, } impl MXResults { /// Obtain an `MXResults` from the response to an MX lookup. pub fn parse_from(data: &[u8]) -> Result<MXResults, AresError> { let mut mx_reply: *mut c_ares_sys::Struct_ares_mx_reply = ptr::null_mut(); let parse_status = unsafe { c_ares_sys::ares_parse_mx_reply( data.as_ptr(), data.len() as libc::c_int, &mut mx_reply) }; if parse_status!= c_ares_sys::ARES_SUCCESS { Err(ares_error(parse_status)) } else { let result = MXResults::new(mx_reply); Ok(result) } } fn new(mx_reply: *mut c_ares_sys::Struct_ares_mx_reply) -> MXResults { MXResults { mx_reply: mx_reply, phantom: PhantomData, } } /// Returns an iterator over the `MXResult` values in this `MXResults`. pub fn iter(&self) -> MXResultsIterator { MXResultsIterator { next: self.mx_reply, phantom: PhantomData, } } } pub struct MXResultsIterator<'a> { next: *const c_ares_sys::Struct_ares_mx_reply, phantom: PhantomData<&'a c_ares_sys::Struct_ares_mx_reply>, } impl<'a> Iterator for MXResultsIterator<'a> { type Item = MXResult<'a>; fn next(&mut self) -> Option<Self::Item> { let mx_reply = self.next; if mx_reply.is_null() { None } else { unsafe { self.next = (*mx_reply).next; } let mx_result = MXResult { mx_reply: mx_reply, phantom: PhantomData, }; Some(mx_result) } } } impl<'a> IntoIterator for &'a MXResults { type Item = MXResult<'a>; type IntoIter = MXResultsIterator<'a>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl Drop for MXResults { fn drop(&mut self) { unsafe { c_ares_sys::ares_free_data(self.mx_reply as *mut libc::c_void); } } } unsafe impl Send for MXResults { } unsafe impl Sync for MXResults { } unsafe impl<'a> Send for MXResult<'a> { } unsafe impl<'a> Sync for MXResult<'a> { } unsafe impl<'a> Send for MXResultsIterator<'a> { } unsafe impl<'a> Sync for MXResultsIterator<'a> { } impl<'a> MXResult<'a> { /// Returns the hostname in this `MXResult`. pub fn host(&self) -> &str { unsafe { let c_str = CStr::from_ptr((*self.mx_reply).host); str::from_utf8_unchecked(c_str.to_bytes()) } } /// Returns the priority from this `MXResult`. pub fn priority(&self) -> u16 { unsafe { (*self.mx_reply).priority } } } pub unsafe extern "C" fn query_mx_callback<F>( arg: *mut libc::c_void, status: libc::c_int, _timeouts: libc::c_int, abuf: *mut libc::c_uchar, alen: libc::c_int) where F: FnOnce(Result<MXResults, AresError>) +'static { let handler: Box<F> = mem::transmute(arg); let result = if status!= c_ares_sys::ARES_SUCCESS
else { let data = slice::from_raw_parts(abuf, alen as usize); MXResults::parse_from(data) }; handler(result); }
{ Err(ares_error(status)) }
conditional_block
lib.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/. */ #![feature(append)] #![feature(arc_unique)] #![feature(box_str)] #![feature(box_syntax)] #![feature(cell_extras)] #![feature(custom_derive)] #![feature(filling_drop)] #![feature(hashmap_hasher)] #![feature(heap_api)] #![feature(mpsc_select)] #![feature(plugin)] #![feature(raw)] #![feature(step_by)] #![feature(str_char)] #![feature(unsafe_no_drop_flag)] #![deny(unsafe_code)]
#[macro_use] extern crate log; #[macro_use] extern crate bitflags; #[macro_use] #[no_link] extern crate plugins as servo_plugins; extern crate net_traits; #[macro_use] extern crate profile_traits; #[macro_use] extern crate util; extern crate azure; extern crate canvas_traits; extern crate clock_ticks; extern crate cssparser; extern crate encoding; extern crate fnv; extern crate euclid; extern crate gfx; extern crate gfx_traits; extern crate ipc_channel; extern crate layout_traits; extern crate libc; extern crate msg; extern crate rustc_serialize; extern crate script; extern crate script_traits; extern crate selectors; extern crate serde; extern crate serde_json; extern crate smallvec; extern crate string_cache; extern crate style; extern crate unicode_bidi; extern crate url; // Listed first because of macro definitions pub mod layout_debug; pub mod animation; pub mod block; pub mod construct; pub mod context; pub mod data; pub mod display_list_builder; pub mod floats; pub mod flow; pub mod flow_list; pub mod flow_ref; pub mod fragment; pub mod generated_content; pub mod layout_task; pub mod incremental; pub mod inline; pub mod list_item; pub mod model; pub mod multicol; pub mod opaque_node; pub mod parallel; pub mod query; pub mod sequential; pub mod table_wrapper; pub mod table; pub mod table_caption; pub mod table_colgroup; pub mod table_rowgroup; pub mod table_row; pub mod table_cell; pub mod text; pub mod traversal; pub mod wrapper; pub mod css { pub mod matching; }
#![plugin(string_cache_plugin)] #![plugin(plugins)]
random_line_split
drawevent.rs
/// Event log for a drawing session /// Menu selections must pass through here to ensure they can be referenced /// Motion events can be shoved in wherever, though /// TODO: replay /// use timestamps on point events, rather than Frame events, so writing can be done from one /// thread /// think about how to make shaders handle accelerated time /// // TODO: remove all this duplication use core::prelude::*; use core::borrow::ToOwned; //use collections::vec::Vec; use point::PointEntry; use glstore::{DrawObjectIndex, DrawObjectList}; use glstore::{ShaderInitValues, BrushInitValues, LuaInitValues}; use glstore::{BrushUnfilledValues, LuaUnfilledValues}; //use glstore::MaybeInitFromCache; // FIXME separate out get_source() use gltexture::{BrushTexture, PixelFormat}; use pointshader::PointShader; use copyshader::CopyShader; use luascript::LuaScript; use paintlayer::PaintLayer; use glcommon::{GLResult, MString, UsingDefaults}; use drawevent::event_stream::EventState; //use collections::slice::CloneSliceExt; // can't use Copy, wtf #[derive(Clone)] enum DrawEvent { UseAnimShader(DrawObjectIndex<CopyShader>), UseCopyShader(DrawObjectIndex<CopyShader>), UsePointShader(DrawObjectIndex<PointShader>), UseBrush(DrawObjectIndex<BrushTexture>), UseInterpolator(DrawObjectIndex<LuaScript>), Point(PointEntry), AddLayer(Option<DrawObjectIndex<CopyShader>>, Option<DrawObjectIndex<PointShader>>, i32), ClearLayers, Frame, } pub struct Events<'a> { //eventlist: Vec<DrawEvent>, pointshaders: DrawObjectList<'a, PointShader, ShaderInitValues>, copyshaders: DrawObjectList<'a, CopyShader, ShaderInitValues>, textures: DrawObjectList<'a, BrushTexture, BrushInitValues>, luascripts: DrawObjectList<'a, LuaScript, LuaInitValues>, } impl<'a> Events<'a> { pub fn new() -> Events<'a> { Events { //eventlist: Vec::new(), pointshaders: DrawObjectList::new(), copyshaders: DrawObjectList::new(), textures: DrawObjectList::new(), luascripts: DrawObjectList::new(), } } // FIXME: let glstore deal with optionalness pub fn load_copyshader(&mut self, vert: Option<MString>, frag: Option<MString>) -> GLResult<DrawObjectIndex<CopyShader>> { let initargs = (vert, frag); self.copyshaders.push_object(initargs) } pub fn use_copyshader(&mut self, idx: DrawObjectIndex<CopyShader>) -> GLResult<&'a CopyShader> { //self.eventlist.push(DrawEvent::UseCopyShader(idx.clone())); self.copyshaders.maybe_get_object(idx) } pub fn use_animshader(&mut self, idx: DrawObjectIndex<CopyShader>) -> GLResult<&'a CopyShader> { //self.eventlist.push(DrawEvent::UseAnimShader(idx.clone())); self.copyshaders.maybe_get_object(idx) } pub fn load_pointshader(&mut self, vert: Option<MString>, frag: Option<MString>) -> GLResult<DrawObjectIndex<PointShader>> { let initargs = (vert, frag); self.pointshaders.push_object(initargs) } pub fn use_pointshader(&mut self, idx: DrawObjectIndex<PointShader>) -> GLResult<&'a PointShader> { //self.eventlist.push(DrawEvent::UsePointShader(idx.clone())); self.pointshaders.maybe_get_object(idx) } pub fn load_brush(&mut self, w: i32, h: i32, pixels: &[u8], format: PixelFormat) -> DrawObjectIndex<BrushTexture> { let ownedpixels = pixels.to_owned(); let init: BrushUnfilledValues = (format, (w, h), ownedpixels); self.textures.safe_push_object(init) } pub fn use_brush(&mut self, idx: DrawObjectIndex<BrushTexture>) -> GLResult<&'a BrushTexture> { //self.eventlist.push(DrawEvent::UseBrush(idx.clone())); self.textures.maybe_get_object(idx) } pub fn load_interpolator(&mut self, script: Option<MString>) -> GLResult<DrawObjectIndex<LuaScript>> { let initopt: LuaUnfilledValues = script; self.luascripts.push_object(initopt) } pub fn use_interpolator(&mut self, idx: DrawObjectIndex<LuaScript>) -> GLResult<&'a LuaScript> { //self.eventlist.push(DrawEvent::UseInterpolator(idx.clone())); self.luascripts.maybe_get_object(idx) } pub fn add_layer(&mut self, dimensions: (i32, i32) , copyshader: Option<DrawObjectIndex<CopyShader>>, pointshader: Option<DrawObjectIndex<PointShader>> , pointidx: i32) -> PaintLayer<'a> { //self.eventlist.push(DrawEvent::AddLayer(copyshader.clone(), pointshader.clone(), pointidx)); let copyshader = match copyshader { Some(x) => Some(self.copyshaders.get_object(x)), None => None }; let pointshader = match pointshader { Some(x) => Some(self.pointshaders.get_object(x)), None => None }; PaintLayer::new(dimensions, copyshader, pointshader, pointidx) } pub fn clear_layers(&mut self) { //self.eventlist.push(DrawEvent::ClearLayers); } pub fn get_pointshader_source(&mut self, pointshader: DrawObjectIndex<PointShader>) -> &(MString, MString) { self.pointshaders.get_object(pointshader).get_source() } pub fn get_copyshader_source(&mut self, copyshader: DrawObjectIndex<CopyShader>) -> &(MString, MString) { self.copyshaders.get_object(copyshader).get_source() } pub fn get_luascript_source(&mut self, luascript: DrawObjectIndex<LuaScript>) -> &MString { self.luascripts.get_object(luascript).get_source() } #[allow(unused_variables)] pub fn pushpoint(&mut self, event: PointEntry) { //self.eventlist.push(DrawEvent::Point(event)); } pub fn pushframe(&mut self) { //self.eventlist.push(DrawEvent::Frame); } pub fn clear(&mut self)
//fn get_event(&self, idx: usize) -> Option<&DrawEvent> { //self.eventlist.as_slice().get(idx) //} } #[inline] #[allow(unused)] pub fn handle_event<'a>(gl: &mut ::glinit::GLInit<'a>, events: &mut Events<'a>, queue: &mut ::point::PointProducer, eventidx: i32) -> event_stream::EventState { // FIXME do this without exposing Events or GLInit internal details /* match events.get_event(eventidx as usize) { Some(event) => match event.clone() { DrawEvent::UseAnimShader(idx) => gl.set_anim_shader(events.copyshaders.get_object(idx)), DrawEvent::UseCopyShader(idx) => gl.set_copy_shader(events.copyshaders.get_object(idx)), DrawEvent::UsePointShader(idx) => gl.set_point_shader(events.pointshaders.get_object(idx)), DrawEvent::UseBrush(idx) => gl.set_brush_texture(&events.textures.get_object(idx).texture), DrawEvent::UseInterpolator(idx) => gl.set_interpolator(events.luascripts.get_object(idx)), DrawEvent::Point(p) => queue.send(p), DrawEvent::AddLayer(copyshader, pointshader, pointidx) => { let copyshader = match copyshader { Some(x) => Some(events.copyshaders.get_object(x)), None => None }; let pointshader = match pointshader { Some(x) => Some(events.pointshaders.get_object(x)), None => None }; let layer = PaintLayer::new(gl.dimensions, copyshader, pointshader, pointidx); gl.add_layer(layer); }, DrawEvent::ClearLayers => gl.clear_layers(), DrawEvent::Frame => return EventState::Frame, }, None => return EventState::Done, } */ return EventState::NoFrame; } pub mod event_stream { use core::prelude::*; use drawevent::{Events, handle_event}; #[derive(Copy)] pub enum EventState { Done, Frame, NoFrame, } pub struct EventStream { position: i32, pub consumer: ::glpoint::MotionEventConsumer, producer: ::glpoint::MotionEventProducer, } impl EventStream { pub fn new() -> EventStream { let (consumer, producer) = ::glpoint::create_motion_event_handler(0); EventStream { position: 0, producer: producer, consumer: consumer } } pub fn advance_frame<'a>(&mut self, init: &mut ::glinit::GLInit<'a>, events: &mut Events<'a>) -> bool { loop { match handle_event(init, events, &mut self.producer.producer, self.position) { EventState::Done => return true, EventState::Frame => return false, EventState::NoFrame => { }, } } } } }
{ //self.eventlist.clear(); }
identifier_body
drawevent.rs
/// Event log for a drawing session /// Menu selections must pass through here to ensure they can be referenced /// Motion events can be shoved in wherever, though /// TODO: replay /// use timestamps on point events, rather than Frame events, so writing can be done from one /// thread /// think about how to make shaders handle accelerated time /// // TODO: remove all this duplication use core::prelude::*; use core::borrow::ToOwned; //use collections::vec::Vec; use point::PointEntry; use glstore::{DrawObjectIndex, DrawObjectList}; use glstore::{ShaderInitValues, BrushInitValues, LuaInitValues}; use glstore::{BrushUnfilledValues, LuaUnfilledValues}; //use glstore::MaybeInitFromCache; // FIXME separate out get_source() use gltexture::{BrushTexture, PixelFormat}; use pointshader::PointShader; use copyshader::CopyShader; use luascript::LuaScript; use paintlayer::PaintLayer; use glcommon::{GLResult, MString, UsingDefaults}; use drawevent::event_stream::EventState; //use collections::slice::CloneSliceExt; // can't use Copy, wtf #[derive(Clone)] enum DrawEvent { UseAnimShader(DrawObjectIndex<CopyShader>), UseCopyShader(DrawObjectIndex<CopyShader>), UsePointShader(DrawObjectIndex<PointShader>), UseBrush(DrawObjectIndex<BrushTexture>), UseInterpolator(DrawObjectIndex<LuaScript>), Point(PointEntry), AddLayer(Option<DrawObjectIndex<CopyShader>>, Option<DrawObjectIndex<PointShader>>, i32), ClearLayers, Frame, } pub struct Events<'a> { //eventlist: Vec<DrawEvent>, pointshaders: DrawObjectList<'a, PointShader, ShaderInitValues>, copyshaders: DrawObjectList<'a, CopyShader, ShaderInitValues>, textures: DrawObjectList<'a, BrushTexture, BrushInitValues>, luascripts: DrawObjectList<'a, LuaScript, LuaInitValues>, } impl<'a> Events<'a> { pub fn new() -> Events<'a> { Events { //eventlist: Vec::new(), pointshaders: DrawObjectList::new(), copyshaders: DrawObjectList::new(), textures: DrawObjectList::new(), luascripts: DrawObjectList::new(), } } // FIXME: let glstore deal with optionalness pub fn load_copyshader(&mut self, vert: Option<MString>, frag: Option<MString>) -> GLResult<DrawObjectIndex<CopyShader>> { let initargs = (vert, frag); self.copyshaders.push_object(initargs) } pub fn use_copyshader(&mut self, idx: DrawObjectIndex<CopyShader>) -> GLResult<&'a CopyShader> { //self.eventlist.push(DrawEvent::UseCopyShader(idx.clone())); self.copyshaders.maybe_get_object(idx) } pub fn use_animshader(&mut self, idx: DrawObjectIndex<CopyShader>) -> GLResult<&'a CopyShader> { //self.eventlist.push(DrawEvent::UseAnimShader(idx.clone())); self.copyshaders.maybe_get_object(idx) } pub fn load_pointshader(&mut self, vert: Option<MString>, frag: Option<MString>) -> GLResult<DrawObjectIndex<PointShader>> { let initargs = (vert, frag); self.pointshaders.push_object(initargs) } pub fn use_pointshader(&mut self, idx: DrawObjectIndex<PointShader>) -> GLResult<&'a PointShader> { //self.eventlist.push(DrawEvent::UsePointShader(idx.clone())); self.pointshaders.maybe_get_object(idx) } pub fn load_brush(&mut self, w: i32, h: i32, pixels: &[u8], format: PixelFormat) -> DrawObjectIndex<BrushTexture> { let ownedpixels = pixels.to_owned(); let init: BrushUnfilledValues = (format, (w, h), ownedpixels); self.textures.safe_push_object(init) } pub fn use_brush(&mut self, idx: DrawObjectIndex<BrushTexture>) -> GLResult<&'a BrushTexture> { //self.eventlist.push(DrawEvent::UseBrush(idx.clone())); self.textures.maybe_get_object(idx) } pub fn load_interpolator(&mut self, script: Option<MString>) -> GLResult<DrawObjectIndex<LuaScript>> { let initopt: LuaUnfilledValues = script; self.luascripts.push_object(initopt) } pub fn use_interpolator(&mut self, idx: DrawObjectIndex<LuaScript>) -> GLResult<&'a LuaScript> { //self.eventlist.push(DrawEvent::UseInterpolator(idx.clone())); self.luascripts.maybe_get_object(idx) } pub fn add_layer(&mut self, dimensions: (i32, i32) , copyshader: Option<DrawObjectIndex<CopyShader>>, pointshader: Option<DrawObjectIndex<PointShader>> , pointidx: i32) -> PaintLayer<'a> { //self.eventlist.push(DrawEvent::AddLayer(copyshader.clone(), pointshader.clone(), pointidx)); let copyshader = match copyshader { Some(x) => Some(self.copyshaders.get_object(x)), None => None }; let pointshader = match pointshader { Some(x) => Some(self.pointshaders.get_object(x)), None => None }; PaintLayer::new(dimensions, copyshader, pointshader, pointidx) } pub fn clear_layers(&mut self) { //self.eventlist.push(DrawEvent::ClearLayers); } pub fn get_pointshader_source(&mut self, pointshader: DrawObjectIndex<PointShader>) -> &(MString, MString) { self.pointshaders.get_object(pointshader).get_source() } pub fn get_copyshader_source(&mut self, copyshader: DrawObjectIndex<CopyShader>) -> &(MString, MString) { self.copyshaders.get_object(copyshader).get_source() } pub fn get_luascript_source(&mut self, luascript: DrawObjectIndex<LuaScript>) -> &MString { self.luascripts.get_object(luascript).get_source() } #[allow(unused_variables)] pub fn pushpoint(&mut self, event: PointEntry) { //self.eventlist.push(DrawEvent::Point(event)); } pub fn pushframe(&mut self) { //self.eventlist.push(DrawEvent::Frame); } pub fn clear(&mut self) { //self.eventlist.clear(); } //fn get_event(&self, idx: usize) -> Option<&DrawEvent> { //self.eventlist.as_slice().get(idx) //} } #[inline] #[allow(unused)] pub fn handle_event<'a>(gl: &mut ::glinit::GLInit<'a>, events: &mut Events<'a>, queue: &mut ::point::PointProducer, eventidx: i32) -> event_stream::EventState { // FIXME do this without exposing Events or GLInit internal details /* match events.get_event(eventidx as usize) { Some(event) => match event.clone() { DrawEvent::UseAnimShader(idx) => gl.set_anim_shader(events.copyshaders.get_object(idx)), DrawEvent::UseCopyShader(idx) => gl.set_copy_shader(events.copyshaders.get_object(idx)), DrawEvent::UsePointShader(idx) => gl.set_point_shader(events.pointshaders.get_object(idx)), DrawEvent::UseBrush(idx) => gl.set_brush_texture(&events.textures.get_object(idx).texture), DrawEvent::UseInterpolator(idx) => gl.set_interpolator(events.luascripts.get_object(idx)), DrawEvent::Point(p) => queue.send(p), DrawEvent::AddLayer(copyshader, pointshader, pointidx) => { let copyshader = match copyshader { Some(x) => Some(events.copyshaders.get_object(x)), None => None }; let pointshader = match pointshader { Some(x) => Some(events.pointshaders.get_object(x)), None => None }; let layer = PaintLayer::new(gl.dimensions, copyshader, pointshader, pointidx); gl.add_layer(layer); }, DrawEvent::ClearLayers => gl.clear_layers(), DrawEvent::Frame => return EventState::Frame, }, None => return EventState::Done, } */ return EventState::NoFrame; } pub mod event_stream {
Done, Frame, NoFrame, } pub struct EventStream { position: i32, pub consumer: ::glpoint::MotionEventConsumer, producer: ::glpoint::MotionEventProducer, } impl EventStream { pub fn new() -> EventStream { let (consumer, producer) = ::glpoint::create_motion_event_handler(0); EventStream { position: 0, producer: producer, consumer: consumer } } pub fn advance_frame<'a>(&mut self, init: &mut ::glinit::GLInit<'a>, events: &mut Events<'a>) -> bool { loop { match handle_event(init, events, &mut self.producer.producer, self.position) { EventState::Done => return true, EventState::Frame => return false, EventState::NoFrame => { }, } } } } }
use core::prelude::*; use drawevent::{Events, handle_event}; #[derive(Copy)] pub enum EventState {
random_line_split
drawevent.rs
/// Event log for a drawing session /// Menu selections must pass through here to ensure they can be referenced /// Motion events can be shoved in wherever, though /// TODO: replay /// use timestamps on point events, rather than Frame events, so writing can be done from one /// thread /// think about how to make shaders handle accelerated time /// // TODO: remove all this duplication use core::prelude::*; use core::borrow::ToOwned; //use collections::vec::Vec; use point::PointEntry; use glstore::{DrawObjectIndex, DrawObjectList}; use glstore::{ShaderInitValues, BrushInitValues, LuaInitValues}; use glstore::{BrushUnfilledValues, LuaUnfilledValues}; //use glstore::MaybeInitFromCache; // FIXME separate out get_source() use gltexture::{BrushTexture, PixelFormat}; use pointshader::PointShader; use copyshader::CopyShader; use luascript::LuaScript; use paintlayer::PaintLayer; use glcommon::{GLResult, MString, UsingDefaults}; use drawevent::event_stream::EventState; //use collections::slice::CloneSliceExt; // can't use Copy, wtf #[derive(Clone)] enum DrawEvent { UseAnimShader(DrawObjectIndex<CopyShader>), UseCopyShader(DrawObjectIndex<CopyShader>), UsePointShader(DrawObjectIndex<PointShader>), UseBrush(DrawObjectIndex<BrushTexture>), UseInterpolator(DrawObjectIndex<LuaScript>), Point(PointEntry), AddLayer(Option<DrawObjectIndex<CopyShader>>, Option<DrawObjectIndex<PointShader>>, i32), ClearLayers, Frame, } pub struct Events<'a> { //eventlist: Vec<DrawEvent>, pointshaders: DrawObjectList<'a, PointShader, ShaderInitValues>, copyshaders: DrawObjectList<'a, CopyShader, ShaderInitValues>, textures: DrawObjectList<'a, BrushTexture, BrushInitValues>, luascripts: DrawObjectList<'a, LuaScript, LuaInitValues>, } impl<'a> Events<'a> { pub fn new() -> Events<'a> { Events { //eventlist: Vec::new(), pointshaders: DrawObjectList::new(), copyshaders: DrawObjectList::new(), textures: DrawObjectList::new(), luascripts: DrawObjectList::new(), } } // FIXME: let glstore deal with optionalness pub fn load_copyshader(&mut self, vert: Option<MString>, frag: Option<MString>) -> GLResult<DrawObjectIndex<CopyShader>> { let initargs = (vert, frag); self.copyshaders.push_object(initargs) } pub fn use_copyshader(&mut self, idx: DrawObjectIndex<CopyShader>) -> GLResult<&'a CopyShader> { //self.eventlist.push(DrawEvent::UseCopyShader(idx.clone())); self.copyshaders.maybe_get_object(idx) } pub fn use_animshader(&mut self, idx: DrawObjectIndex<CopyShader>) -> GLResult<&'a CopyShader> { //self.eventlist.push(DrawEvent::UseAnimShader(idx.clone())); self.copyshaders.maybe_get_object(idx) } pub fn load_pointshader(&mut self, vert: Option<MString>, frag: Option<MString>) -> GLResult<DrawObjectIndex<PointShader>> { let initargs = (vert, frag); self.pointshaders.push_object(initargs) } pub fn use_pointshader(&mut self, idx: DrawObjectIndex<PointShader>) -> GLResult<&'a PointShader> { //self.eventlist.push(DrawEvent::UsePointShader(idx.clone())); self.pointshaders.maybe_get_object(idx) } pub fn load_brush(&mut self, w: i32, h: i32, pixels: &[u8], format: PixelFormat) -> DrawObjectIndex<BrushTexture> { let ownedpixels = pixels.to_owned(); let init: BrushUnfilledValues = (format, (w, h), ownedpixels); self.textures.safe_push_object(init) } pub fn use_brush(&mut self, idx: DrawObjectIndex<BrushTexture>) -> GLResult<&'a BrushTexture> { //self.eventlist.push(DrawEvent::UseBrush(idx.clone())); self.textures.maybe_get_object(idx) } pub fn
(&mut self, script: Option<MString>) -> GLResult<DrawObjectIndex<LuaScript>> { let initopt: LuaUnfilledValues = script; self.luascripts.push_object(initopt) } pub fn use_interpolator(&mut self, idx: DrawObjectIndex<LuaScript>) -> GLResult<&'a LuaScript> { //self.eventlist.push(DrawEvent::UseInterpolator(idx.clone())); self.luascripts.maybe_get_object(idx) } pub fn add_layer(&mut self, dimensions: (i32, i32) , copyshader: Option<DrawObjectIndex<CopyShader>>, pointshader: Option<DrawObjectIndex<PointShader>> , pointidx: i32) -> PaintLayer<'a> { //self.eventlist.push(DrawEvent::AddLayer(copyshader.clone(), pointshader.clone(), pointidx)); let copyshader = match copyshader { Some(x) => Some(self.copyshaders.get_object(x)), None => None }; let pointshader = match pointshader { Some(x) => Some(self.pointshaders.get_object(x)), None => None }; PaintLayer::new(dimensions, copyshader, pointshader, pointidx) } pub fn clear_layers(&mut self) { //self.eventlist.push(DrawEvent::ClearLayers); } pub fn get_pointshader_source(&mut self, pointshader: DrawObjectIndex<PointShader>) -> &(MString, MString) { self.pointshaders.get_object(pointshader).get_source() } pub fn get_copyshader_source(&mut self, copyshader: DrawObjectIndex<CopyShader>) -> &(MString, MString) { self.copyshaders.get_object(copyshader).get_source() } pub fn get_luascript_source(&mut self, luascript: DrawObjectIndex<LuaScript>) -> &MString { self.luascripts.get_object(luascript).get_source() } #[allow(unused_variables)] pub fn pushpoint(&mut self, event: PointEntry) { //self.eventlist.push(DrawEvent::Point(event)); } pub fn pushframe(&mut self) { //self.eventlist.push(DrawEvent::Frame); } pub fn clear(&mut self) { //self.eventlist.clear(); } //fn get_event(&self, idx: usize) -> Option<&DrawEvent> { //self.eventlist.as_slice().get(idx) //} } #[inline] #[allow(unused)] pub fn handle_event<'a>(gl: &mut ::glinit::GLInit<'a>, events: &mut Events<'a>, queue: &mut ::point::PointProducer, eventidx: i32) -> event_stream::EventState { // FIXME do this without exposing Events or GLInit internal details /* match events.get_event(eventidx as usize) { Some(event) => match event.clone() { DrawEvent::UseAnimShader(idx) => gl.set_anim_shader(events.copyshaders.get_object(idx)), DrawEvent::UseCopyShader(idx) => gl.set_copy_shader(events.copyshaders.get_object(idx)), DrawEvent::UsePointShader(idx) => gl.set_point_shader(events.pointshaders.get_object(idx)), DrawEvent::UseBrush(idx) => gl.set_brush_texture(&events.textures.get_object(idx).texture), DrawEvent::UseInterpolator(idx) => gl.set_interpolator(events.luascripts.get_object(idx)), DrawEvent::Point(p) => queue.send(p), DrawEvent::AddLayer(copyshader, pointshader, pointidx) => { let copyshader = match copyshader { Some(x) => Some(events.copyshaders.get_object(x)), None => None }; let pointshader = match pointshader { Some(x) => Some(events.pointshaders.get_object(x)), None => None }; let layer = PaintLayer::new(gl.dimensions, copyshader, pointshader, pointidx); gl.add_layer(layer); }, DrawEvent::ClearLayers => gl.clear_layers(), DrawEvent::Frame => return EventState::Frame, }, None => return EventState::Done, } */ return EventState::NoFrame; } pub mod event_stream { use core::prelude::*; use drawevent::{Events, handle_event}; #[derive(Copy)] pub enum EventState { Done, Frame, NoFrame, } pub struct EventStream { position: i32, pub consumer: ::glpoint::MotionEventConsumer, producer: ::glpoint::MotionEventProducer, } impl EventStream { pub fn new() -> EventStream { let (consumer, producer) = ::glpoint::create_motion_event_handler(0); EventStream { position: 0, producer: producer, consumer: consumer } } pub fn advance_frame<'a>(&mut self, init: &mut ::glinit::GLInit<'a>, events: &mut Events<'a>) -> bool { loop { match handle_event(init, events, &mut self.producer.producer, self.position) { EventState::Done => return true, EventState::Frame => return false, EventState::NoFrame => { }, } } } } }
load_interpolator
identifier_name
etcd_result.rs
use super::etcd_node::EtcdNode; use rustc_serialize::json; #[allow(dead_code)] #[derive(Debug)] pub struct EtcdResult { /// action: the action of the request that was just made. pub action: String, /// the node upon which the request was made pub node: Option<EtcdNode>, /// the previous node if there was one pub previous_node: Option<EtcdNode>, /// X-Etcd-Index is the current etcd index as explained above. pub x_etcd_index: i64, /// X-Raft-Index is similar to the etcd index but is for the underlying raft protocol pub x_raft_index: i64, /// X-Raft-Term is an integer that will increase whenever an etcd master election happens in the cluster. /// If this number is increasing rapidly, you may need to tune the election timeout. pub x_raft_term: i64, } impl EtcdResult { pub fn from_json(obj: &json::Object) -> EtcdResult
fn node_from_json(key: &'static str, result_obj: &json::Object) -> Option<EtcdNode> { // get the json for the node let node_obj: &json::Json = match result_obj.get(key) { Some(o) => o, None => return None, }; // extract the node return match node_obj.as_object() { Some(o) => Some(EtcdNode::from_json(o)), None => None, } } } #[cfg(test)] mod tests { use rustc_serialize::json; use super::EtcdResult; use etcd::etcd_node::EtcdNode; static RESULT_JSON: &'static str = "{ \"action\": \"expire\", \"node\": { \"createdIndex\": 8, \"key\": \"/dir\", \"dir\":true, \"modifiedIndex\": 15 }, \"prevNode\": { \"createdIndex\": 8, \"key\": \"/dir\", \"dir\":true, \"modifiedIndex\": 17, \"expiration\": \"2013-12-11T10:39:35.689275857-08:00\" } }"; #[test] fn decode_result_json_test() { let json_tree = json::Json::from_str(RESULT_JSON).unwrap(); let etcd_result = EtcdResult::from_json(json_tree.as_object().unwrap()); assert_eq!(etcd_result.action, "expire".to_string()); let etcd_node = etcd_result.node.as_ref().unwrap(); assert_eq!(etcd_node.key, "/dir".to_string()); assert_eq!(etcd_node.dir, true); assert_eq!(etcd_node.created_index, 8); assert_eq!(etcd_node.modified_index, 15); let etcd_prev_node = etcd_result.previous_node.as_ref().unwrap(); assert_eq!(etcd_prev_node.key, "/dir".to_string()); assert_eq!(etcd_prev_node.dir, true); assert_eq!(etcd_prev_node.created_index, 8); assert_eq!(etcd_prev_node.modified_index, 17); assert_eq!(*etcd_prev_node.expiration.as_ref().unwrap(), "2013-12-11T10:39:35.689275857-08:00".to_string()); } }
{ let node = EtcdResult::node_from_json("node", obj); let prev_node = EtcdResult::node_from_json("prevNode", obj); let result_action: Option<&json::Json> = obj.get("action"); return EtcdResult{ action: result_action.unwrap().as_string().unwrap().to_string(), node: node, previous_node: prev_node, x_etcd_index: 0, // from headers... x_raft_index: 0, x_raft_term: 0, } }
identifier_body
etcd_result.rs
use super::etcd_node::EtcdNode; use rustc_serialize::json; #[allow(dead_code)] #[derive(Debug)] pub struct EtcdResult { /// action: the action of the request that was just made.
/// the node upon which the request was made pub node: Option<EtcdNode>, /// the previous node if there was one pub previous_node: Option<EtcdNode>, /// X-Etcd-Index is the current etcd index as explained above. pub x_etcd_index: i64, /// X-Raft-Index is similar to the etcd index but is for the underlying raft protocol pub x_raft_index: i64, /// X-Raft-Term is an integer that will increase whenever an etcd master election happens in the cluster. /// If this number is increasing rapidly, you may need to tune the election timeout. pub x_raft_term: i64, } impl EtcdResult { pub fn from_json(obj: &json::Object) -> EtcdResult { let node = EtcdResult::node_from_json("node", obj); let prev_node = EtcdResult::node_from_json("prevNode", obj); let result_action: Option<&json::Json> = obj.get("action"); return EtcdResult{ action: result_action.unwrap().as_string().unwrap().to_string(), node: node, previous_node: prev_node, x_etcd_index: 0, // from headers... x_raft_index: 0, x_raft_term: 0, } } fn node_from_json(key: &'static str, result_obj: &json::Object) -> Option<EtcdNode> { // get the json for the node let node_obj: &json::Json = match result_obj.get(key) { Some(o) => o, None => return None, }; // extract the node return match node_obj.as_object() { Some(o) => Some(EtcdNode::from_json(o)), None => None, } } } #[cfg(test)] mod tests { use rustc_serialize::json; use super::EtcdResult; use etcd::etcd_node::EtcdNode; static RESULT_JSON: &'static str = "{ \"action\": \"expire\", \"node\": { \"createdIndex\": 8, \"key\": \"/dir\", \"dir\":true, \"modifiedIndex\": 15 }, \"prevNode\": { \"createdIndex\": 8, \"key\": \"/dir\", \"dir\":true, \"modifiedIndex\": 17, \"expiration\": \"2013-12-11T10:39:35.689275857-08:00\" } }"; #[test] fn decode_result_json_test() { let json_tree = json::Json::from_str(RESULT_JSON).unwrap(); let etcd_result = EtcdResult::from_json(json_tree.as_object().unwrap()); assert_eq!(etcd_result.action, "expire".to_string()); let etcd_node = etcd_result.node.as_ref().unwrap(); assert_eq!(etcd_node.key, "/dir".to_string()); assert_eq!(etcd_node.dir, true); assert_eq!(etcd_node.created_index, 8); assert_eq!(etcd_node.modified_index, 15); let etcd_prev_node = etcd_result.previous_node.as_ref().unwrap(); assert_eq!(etcd_prev_node.key, "/dir".to_string()); assert_eq!(etcd_prev_node.dir, true); assert_eq!(etcd_prev_node.created_index, 8); assert_eq!(etcd_prev_node.modified_index, 17); assert_eq!(*etcd_prev_node.expiration.as_ref().unwrap(), "2013-12-11T10:39:35.689275857-08:00".to_string()); } }
pub action: String,
random_line_split
etcd_result.rs
use super::etcd_node::EtcdNode; use rustc_serialize::json; #[allow(dead_code)] #[derive(Debug)] pub struct EtcdResult { /// action: the action of the request that was just made. pub action: String, /// the node upon which the request was made pub node: Option<EtcdNode>, /// the previous node if there was one pub previous_node: Option<EtcdNode>, /// X-Etcd-Index is the current etcd index as explained above. pub x_etcd_index: i64, /// X-Raft-Index is similar to the etcd index but is for the underlying raft protocol pub x_raft_index: i64, /// X-Raft-Term is an integer that will increase whenever an etcd master election happens in the cluster. /// If this number is increasing rapidly, you may need to tune the election timeout. pub x_raft_term: i64, } impl EtcdResult { pub fn from_json(obj: &json::Object) -> EtcdResult { let node = EtcdResult::node_from_json("node", obj); let prev_node = EtcdResult::node_from_json("prevNode", obj); let result_action: Option<&json::Json> = obj.get("action"); return EtcdResult{ action: result_action.unwrap().as_string().unwrap().to_string(), node: node, previous_node: prev_node, x_etcd_index: 0, // from headers... x_raft_index: 0, x_raft_term: 0, } } fn
(key: &'static str, result_obj: &json::Object) -> Option<EtcdNode> { // get the json for the node let node_obj: &json::Json = match result_obj.get(key) { Some(o) => o, None => return None, }; // extract the node return match node_obj.as_object() { Some(o) => Some(EtcdNode::from_json(o)), None => None, } } } #[cfg(test)] mod tests { use rustc_serialize::json; use super::EtcdResult; use etcd::etcd_node::EtcdNode; static RESULT_JSON: &'static str = "{ \"action\": \"expire\", \"node\": { \"createdIndex\": 8, \"key\": \"/dir\", \"dir\":true, \"modifiedIndex\": 15 }, \"prevNode\": { \"createdIndex\": 8, \"key\": \"/dir\", \"dir\":true, \"modifiedIndex\": 17, \"expiration\": \"2013-12-11T10:39:35.689275857-08:00\" } }"; #[test] fn decode_result_json_test() { let json_tree = json::Json::from_str(RESULT_JSON).unwrap(); let etcd_result = EtcdResult::from_json(json_tree.as_object().unwrap()); assert_eq!(etcd_result.action, "expire".to_string()); let etcd_node = etcd_result.node.as_ref().unwrap(); assert_eq!(etcd_node.key, "/dir".to_string()); assert_eq!(etcd_node.dir, true); assert_eq!(etcd_node.created_index, 8); assert_eq!(etcd_node.modified_index, 15); let etcd_prev_node = etcd_result.previous_node.as_ref().unwrap(); assert_eq!(etcd_prev_node.key, "/dir".to_string()); assert_eq!(etcd_prev_node.dir, true); assert_eq!(etcd_prev_node.created_index, 8); assert_eq!(etcd_prev_node.modified_index, 17); assert_eq!(*etcd_prev_node.expiration.as_ref().unwrap(), "2013-12-11T10:39:35.689275857-08:00".to_string()); } }
node_from_json
identifier_name
numeric_literal.rs
use rustc_ast::ast::{Lit, LitFloatType, LitIntType, LitKind}; use std::iter; #[derive(Debug, PartialEq, Copy, Clone)] pub enum Radix { Binary, Octal, Decimal, Hexadecimal, } impl Radix { /// Returns a reasonable digit group size for this radix. #[must_use] fn suggest_grouping(self) -> usize { match self { Self::Binary | Self::Hexadecimal => 4, Self::Octal | Self::Decimal => 3, } } } /// A helper method to format numeric literals with digit grouping. /// `lit` must be a valid numeric literal without suffix. pub fn format(lit: &str, type_suffix: Option<&str>, float: bool) -> String
#[derive(Debug)] pub struct NumericLiteral<'a> { /// Which radix the literal was represented in. pub radix: Radix, /// The radix prefix, if present. pub prefix: Option<&'a str>, /// The integer part of the number. pub integer: &'a str, /// The fraction part of the number. pub fraction: Option<&'a str>, /// The exponent separator (b'e' or b'E') including preceding underscore if present /// and the exponent part. pub exponent: Option<(&'a str, &'a str)>, /// The type suffix, including preceding underscore if present. pub suffix: Option<&'a str>, } impl<'a> NumericLiteral<'a> { pub fn from_lit(src: &'a str, lit: &Lit) -> Option<NumericLiteral<'a>> { NumericLiteral::from_lit_kind(src, &lit.kind) } pub fn from_lit_kind(src: &'a str, lit_kind: &LitKind) -> Option<NumericLiteral<'a>> { if lit_kind.is_numeric() && src.chars().next().map_or(false, |c| c.is_digit(10)) { let (unsuffixed, suffix) = split_suffix(src, lit_kind); let float = matches!(lit_kind, LitKind::Float(..)); Some(NumericLiteral::new(unsuffixed, suffix, float)) } else { None } } #[must_use] pub fn new(lit: &'a str, suffix: Option<&'a str>, float: bool) -> Self { // Determine delimiter for radix prefix, if present, and radix. let radix = if lit.starts_with("0x") { Radix::Hexadecimal } else if lit.starts_with("0b") { Radix::Binary } else if lit.starts_with("0o") { Radix::Octal } else { Radix::Decimal }; // Grab part of the literal after prefix, if present. let (prefix, mut sans_prefix) = if radix == Radix::Decimal { (None, lit) } else { let (p, s) = lit.split_at(2); (Some(p), s) }; if suffix.is_some() && sans_prefix.ends_with('_') { // The '_' before the suffix isn't part of the digits sans_prefix = &sans_prefix[..sans_prefix.len() - 1]; } let (integer, fraction, exponent) = Self::split_digit_parts(sans_prefix, float); Self { radix, prefix, integer, fraction, exponent, suffix, } } pub fn is_decimal(&self) -> bool { self.radix == Radix::Decimal } pub fn split_digit_parts(digits: &str, float: bool) -> (&str, Option<&str>, Option<(&str, &str)>) { let mut integer = digits; let mut fraction = None; let mut exponent = None; if float { for (i, c) in digits.char_indices() { match c { '.' => { integer = &digits[..i]; fraction = Some(&digits[i + 1..]); }, 'e' | 'E' => { let exp_start = if digits[..i].ends_with('_') { i - 1 } else { i }; if integer.len() > exp_start { integer = &digits[..exp_start]; } else { fraction = Some(&digits[integer.len() + 1..exp_start]); }; exponent = Some((&digits[exp_start..=i], &digits[i + 1..])); break; }, _ => {}, } } } (integer, fraction, exponent) } /// Returns literal formatted in a sensible way. pub fn format(&self) -> String { let mut output = String::new(); if let Some(prefix) = self.prefix { output.push_str(prefix); } let group_size = self.radix.suggest_grouping(); Self::group_digits( &mut output, self.integer, group_size, true, self.radix == Radix::Hexadecimal, ); if let Some(fraction) = self.fraction { output.push('.'); Self::group_digits(&mut output, fraction, group_size, false, false); } if let Some((separator, exponent)) = self.exponent { if exponent!= "0" { output.push_str(separator); Self::group_digits(&mut output, exponent, group_size, true, false); } } if let Some(suffix) = self.suffix { if output.ends_with('.') { output.push('0'); } output.push('_'); output.push_str(suffix); } output } pub fn group_digits(output: &mut String, input: &str, group_size: usize, partial_group_first: bool, pad: bool) { debug_assert!(group_size > 0); let mut digits = input.chars().filter(|&c| c!= '_'); // The exponent may have a sign, output it early, otherwise it will be // treated as a digit if digits.clone().next() == Some('-') { let _ = digits.next(); output.push('-'); } let first_group_size; if partial_group_first { first_group_size = (digits.clone().count() - 1) % group_size + 1; if pad { for _ in 0..group_size - first_group_size { output.push('0'); } } } else { first_group_size = group_size; } for _ in 0..first_group_size { if let Some(digit) = digits.next() { output.push(digit); } } for (c, i) in iter::zip(digits, (0..group_size).cycle()) { if i == 0 { output.push('_'); } output.push(c); } } } fn split_suffix<'a>(src: &'a str, lit_kind: &LitKind) -> (&'a str, Option<&'a str>) { debug_assert!(lit_kind.is_numeric()); lit_suffix_length(lit_kind).map_or((src, None), |suffix_length| { let (unsuffixed, suffix) = src.split_at(src.len() - suffix_length); (unsuffixed, Some(suffix)) }) } fn lit_suffix_length(lit_kind: &LitKind) -> Option<usize> { debug_assert!(lit_kind.is_numeric()); let suffix = match lit_kind { LitKind::Int(_, int_lit_kind) => match int_lit_kind { LitIntType::Signed(int_ty) => Some(int_ty.name_str()), LitIntType::Unsigned(uint_ty) => Some(uint_ty.name_str()), LitIntType::Unsuffixed => None, }, LitKind::Float(_, float_lit_kind) => match float_lit_kind { LitFloatType::Suffixed(float_ty) => Some(float_ty.name_str()), LitFloatType::Unsuffixed => None, }, _ => None, }; suffix.map(str::len) }
{ NumericLiteral::new(lit, type_suffix, float).format() }
identifier_body
numeric_literal.rs
use rustc_ast::ast::{Lit, LitFloatType, LitIntType, LitKind}; use std::iter; #[derive(Debug, PartialEq, Copy, Clone)] pub enum Radix { Binary, Octal, Decimal, Hexadecimal, } impl Radix { /// Returns a reasonable digit group size for this radix. #[must_use] fn suggest_grouping(self) -> usize { match self { Self::Binary | Self::Hexadecimal => 4, Self::Octal | Self::Decimal => 3, } } } /// A helper method to format numeric literals with digit grouping. /// `lit` must be a valid numeric literal without suffix. pub fn format(lit: &str, type_suffix: Option<&str>, float: bool) -> String { NumericLiteral::new(lit, type_suffix, float).format() } #[derive(Debug)] pub struct NumericLiteral<'a> { /// Which radix the literal was represented in. pub radix: Radix, /// The radix prefix, if present. pub prefix: Option<&'a str>, /// The integer part of the number. pub integer: &'a str, /// The fraction part of the number. pub fraction: Option<&'a str>, /// The exponent separator (b'e' or b'E') including preceding underscore if present /// and the exponent part. pub exponent: Option<(&'a str, &'a str)>, /// The type suffix, including preceding underscore if present. pub suffix: Option<&'a str>, } impl<'a> NumericLiteral<'a> { pub fn from_lit(src: &'a str, lit: &Lit) -> Option<NumericLiteral<'a>> { NumericLiteral::from_lit_kind(src, &lit.kind) } pub fn from_lit_kind(src: &'a str, lit_kind: &LitKind) -> Option<NumericLiteral<'a>> { if lit_kind.is_numeric() && src.chars().next().map_or(false, |c| c.is_digit(10)) { let (unsuffixed, suffix) = split_suffix(src, lit_kind); let float = matches!(lit_kind, LitKind::Float(..)); Some(NumericLiteral::new(unsuffixed, suffix, float)) } else { None } } #[must_use] pub fn new(lit: &'a str, suffix: Option<&'a str>, float: bool) -> Self { // Determine delimiter for radix prefix, if present, and radix. let radix = if lit.starts_with("0x") { Radix::Hexadecimal } else if lit.starts_with("0b") { Radix::Binary } else if lit.starts_with("0o") { Radix::Octal } else { Radix::Decimal }; // Grab part of the literal after prefix, if present. let (prefix, mut sans_prefix) = if radix == Radix::Decimal { (None, lit) } else { let (p, s) = lit.split_at(2); (Some(p), s) }; if suffix.is_some() && sans_prefix.ends_with('_') { // The '_' before the suffix isn't part of the digits sans_prefix = &sans_prefix[..sans_prefix.len() - 1]; } let (integer, fraction, exponent) = Self::split_digit_parts(sans_prefix, float); Self { radix, prefix, integer, fraction, exponent, suffix, } } pub fn is_decimal(&self) -> bool { self.radix == Radix::Decimal } pub fn split_digit_parts(digits: &str, float: bool) -> (&str, Option<&str>, Option<(&str, &str)>) { let mut integer = digits; let mut fraction = None;
if float { for (i, c) in digits.char_indices() { match c { '.' => { integer = &digits[..i]; fraction = Some(&digits[i + 1..]); }, 'e' | 'E' => { let exp_start = if digits[..i].ends_with('_') { i - 1 } else { i }; if integer.len() > exp_start { integer = &digits[..exp_start]; } else { fraction = Some(&digits[integer.len() + 1..exp_start]); }; exponent = Some((&digits[exp_start..=i], &digits[i + 1..])); break; }, _ => {}, } } } (integer, fraction, exponent) } /// Returns literal formatted in a sensible way. pub fn format(&self) -> String { let mut output = String::new(); if let Some(prefix) = self.prefix { output.push_str(prefix); } let group_size = self.radix.suggest_grouping(); Self::group_digits( &mut output, self.integer, group_size, true, self.radix == Radix::Hexadecimal, ); if let Some(fraction) = self.fraction { output.push('.'); Self::group_digits(&mut output, fraction, group_size, false, false); } if let Some((separator, exponent)) = self.exponent { if exponent!= "0" { output.push_str(separator); Self::group_digits(&mut output, exponent, group_size, true, false); } } if let Some(suffix) = self.suffix { if output.ends_with('.') { output.push('0'); } output.push('_'); output.push_str(suffix); } output } pub fn group_digits(output: &mut String, input: &str, group_size: usize, partial_group_first: bool, pad: bool) { debug_assert!(group_size > 0); let mut digits = input.chars().filter(|&c| c!= '_'); // The exponent may have a sign, output it early, otherwise it will be // treated as a digit if digits.clone().next() == Some('-') { let _ = digits.next(); output.push('-'); } let first_group_size; if partial_group_first { first_group_size = (digits.clone().count() - 1) % group_size + 1; if pad { for _ in 0..group_size - first_group_size { output.push('0'); } } } else { first_group_size = group_size; } for _ in 0..first_group_size { if let Some(digit) = digits.next() { output.push(digit); } } for (c, i) in iter::zip(digits, (0..group_size).cycle()) { if i == 0 { output.push('_'); } output.push(c); } } } fn split_suffix<'a>(src: &'a str, lit_kind: &LitKind) -> (&'a str, Option<&'a str>) { debug_assert!(lit_kind.is_numeric()); lit_suffix_length(lit_kind).map_or((src, None), |suffix_length| { let (unsuffixed, suffix) = src.split_at(src.len() - suffix_length); (unsuffixed, Some(suffix)) }) } fn lit_suffix_length(lit_kind: &LitKind) -> Option<usize> { debug_assert!(lit_kind.is_numeric()); let suffix = match lit_kind { LitKind::Int(_, int_lit_kind) => match int_lit_kind { LitIntType::Signed(int_ty) => Some(int_ty.name_str()), LitIntType::Unsigned(uint_ty) => Some(uint_ty.name_str()), LitIntType::Unsuffixed => None, }, LitKind::Float(_, float_lit_kind) => match float_lit_kind { LitFloatType::Suffixed(float_ty) => Some(float_ty.name_str()), LitFloatType::Unsuffixed => None, }, _ => None, }; suffix.map(str::len) }
let mut exponent = None;
random_line_split
numeric_literal.rs
use rustc_ast::ast::{Lit, LitFloatType, LitIntType, LitKind}; use std::iter; #[derive(Debug, PartialEq, Copy, Clone)] pub enum Radix { Binary, Octal, Decimal, Hexadecimal, } impl Radix { /// Returns a reasonable digit group size for this radix. #[must_use] fn suggest_grouping(self) -> usize { match self { Self::Binary | Self::Hexadecimal => 4, Self::Octal | Self::Decimal => 3, } } } /// A helper method to format numeric literals with digit grouping. /// `lit` must be a valid numeric literal without suffix. pub fn format(lit: &str, type_suffix: Option<&str>, float: bool) -> String { NumericLiteral::new(lit, type_suffix, float).format() } #[derive(Debug)] pub struct NumericLiteral<'a> { /// Which radix the literal was represented in. pub radix: Radix, /// The radix prefix, if present. pub prefix: Option<&'a str>, /// The integer part of the number. pub integer: &'a str, /// The fraction part of the number. pub fraction: Option<&'a str>, /// The exponent separator (b'e' or b'E') including preceding underscore if present /// and the exponent part. pub exponent: Option<(&'a str, &'a str)>, /// The type suffix, including preceding underscore if present. pub suffix: Option<&'a str>, } impl<'a> NumericLiteral<'a> { pub fn from_lit(src: &'a str, lit: &Lit) -> Option<NumericLiteral<'a>> { NumericLiteral::from_lit_kind(src, &lit.kind) } pub fn from_lit_kind(src: &'a str, lit_kind: &LitKind) -> Option<NumericLiteral<'a>> { if lit_kind.is_numeric() && src.chars().next().map_or(false, |c| c.is_digit(10)) { let (unsuffixed, suffix) = split_suffix(src, lit_kind); let float = matches!(lit_kind, LitKind::Float(..)); Some(NumericLiteral::new(unsuffixed, suffix, float)) } else { None } } #[must_use] pub fn new(lit: &'a str, suffix: Option<&'a str>, float: bool) -> Self { // Determine delimiter for radix prefix, if present, and radix. let radix = if lit.starts_with("0x") { Radix::Hexadecimal } else if lit.starts_with("0b") { Radix::Binary } else if lit.starts_with("0o") { Radix::Octal } else { Radix::Decimal }; // Grab part of the literal after prefix, if present. let (prefix, mut sans_prefix) = if radix == Radix::Decimal { (None, lit) } else { let (p, s) = lit.split_at(2); (Some(p), s) }; if suffix.is_some() && sans_prefix.ends_with('_') { // The '_' before the suffix isn't part of the digits sans_prefix = &sans_prefix[..sans_prefix.len() - 1]; } let (integer, fraction, exponent) = Self::split_digit_parts(sans_prefix, float); Self { radix, prefix, integer, fraction, exponent, suffix, } } pub fn
(&self) -> bool { self.radix == Radix::Decimal } pub fn split_digit_parts(digits: &str, float: bool) -> (&str, Option<&str>, Option<(&str, &str)>) { let mut integer = digits; let mut fraction = None; let mut exponent = None; if float { for (i, c) in digits.char_indices() { match c { '.' => { integer = &digits[..i]; fraction = Some(&digits[i + 1..]); }, 'e' | 'E' => { let exp_start = if digits[..i].ends_with('_') { i - 1 } else { i }; if integer.len() > exp_start { integer = &digits[..exp_start]; } else { fraction = Some(&digits[integer.len() + 1..exp_start]); }; exponent = Some((&digits[exp_start..=i], &digits[i + 1..])); break; }, _ => {}, } } } (integer, fraction, exponent) } /// Returns literal formatted in a sensible way. pub fn format(&self) -> String { let mut output = String::new(); if let Some(prefix) = self.prefix { output.push_str(prefix); } let group_size = self.radix.suggest_grouping(); Self::group_digits( &mut output, self.integer, group_size, true, self.radix == Radix::Hexadecimal, ); if let Some(fraction) = self.fraction { output.push('.'); Self::group_digits(&mut output, fraction, group_size, false, false); } if let Some((separator, exponent)) = self.exponent { if exponent!= "0" { output.push_str(separator); Self::group_digits(&mut output, exponent, group_size, true, false); } } if let Some(suffix) = self.suffix { if output.ends_with('.') { output.push('0'); } output.push('_'); output.push_str(suffix); } output } pub fn group_digits(output: &mut String, input: &str, group_size: usize, partial_group_first: bool, pad: bool) { debug_assert!(group_size > 0); let mut digits = input.chars().filter(|&c| c!= '_'); // The exponent may have a sign, output it early, otherwise it will be // treated as a digit if digits.clone().next() == Some('-') { let _ = digits.next(); output.push('-'); } let first_group_size; if partial_group_first { first_group_size = (digits.clone().count() - 1) % group_size + 1; if pad { for _ in 0..group_size - first_group_size { output.push('0'); } } } else { first_group_size = group_size; } for _ in 0..first_group_size { if let Some(digit) = digits.next() { output.push(digit); } } for (c, i) in iter::zip(digits, (0..group_size).cycle()) { if i == 0 { output.push('_'); } output.push(c); } } } fn split_suffix<'a>(src: &'a str, lit_kind: &LitKind) -> (&'a str, Option<&'a str>) { debug_assert!(lit_kind.is_numeric()); lit_suffix_length(lit_kind).map_or((src, None), |suffix_length| { let (unsuffixed, suffix) = src.split_at(src.len() - suffix_length); (unsuffixed, Some(suffix)) }) } fn lit_suffix_length(lit_kind: &LitKind) -> Option<usize> { debug_assert!(lit_kind.is_numeric()); let suffix = match lit_kind { LitKind::Int(_, int_lit_kind) => match int_lit_kind { LitIntType::Signed(int_ty) => Some(int_ty.name_str()), LitIntType::Unsigned(uint_ty) => Some(uint_ty.name_str()), LitIntType::Unsuffixed => None, }, LitKind::Float(_, float_lit_kind) => match float_lit_kind { LitFloatType::Suffixed(float_ty) => Some(float_ty.name_str()), LitFloatType::Unsuffixed => None, }, _ => None, }; suffix.map(str::len) }
is_decimal
identifier_name
io.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use file::reader::ParquetReader; use std::{cmp, fs::File, io::*, sync::Mutex}; // ---------------------------------------------------------------------- // Read/Write wrappers for `File`. /// Position trait returns the current position in the stream. /// Should be viewed as a lighter version of `Seek` that does not allow seek operations, /// and does not require mutable reference for the current position. pub trait Position { /// Returns position in the stream. fn pos(&self) -> u64; } /// Struct that represents a slice of a file data with independent start position and /// length. Internally clones provided file handle, wraps with BufReader and resets /// position before any read. /// /// This is workaround and alternative for `file.try_clone()` method. It clones `File` /// while preserving independent position, which is not available with `try_clone()`. /// /// Designed after `arrow::io::RandomAccessFile`. pub struct FileSource<R: ParquetReader> { reader: Mutex<BufReader<R>>, start: u64, // start position in a file end: u64, // end position in a file } impl<R: ParquetReader> FileSource<R> { /// Creates new file reader with start and length from a file handle pub fn new(fd: &R, start: u64, length: usize) -> Self { Self { reader: Mutex::new(BufReader::new(fd.try_clone().unwrap())), start, end: start + length as u64, } } } impl<R: ParquetReader> Read for FileSource<R> { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let mut reader = self .reader .lock() .map_err(|err| Error::new(ErrorKind::Other, err.to_string()))?; let bytes_to_read = cmp::min(buf.len(), (self.end - self.start) as usize); let buf = &mut buf[0..bytes_to_read]; reader.seek(SeekFrom::Start(self.start as u64))?; let res = reader.read(buf); if let Ok(bytes_read) = res { self.start += bytes_read as u64; } res } } impl<R: ParquetReader> Position for FileSource<R> { fn pos(&self) -> u64 { self.start } } /// Struct that represents `File` output stream with position tracking. /// Used as a sink in file writer. pub struct
{ buf: BufWriter<File>, // This is not necessarily position in the underlying file, // but rather current position in the sink. pos: u64, } impl FileSink { /// Creates new file sink. /// Position is set to whatever position file has. pub fn new(file: &File) -> Self { let mut owned_file = file.try_clone().unwrap(); let pos = owned_file.seek(SeekFrom::Current(0)).unwrap(); Self { buf: BufWriter::new(owned_file), pos, } } } impl Write for FileSink { fn write(&mut self, buf: &[u8]) -> Result<usize> { let num_bytes = self.buf.write(buf)?; self.pos += num_bytes as u64; Ok(num_bytes) } fn flush(&mut self) -> Result<()> { self.buf.flush() } } impl Position for FileSink { fn pos(&self) -> u64 { self.pos } } // Position implementation for Cursor to use in various tests. impl<'a> Position for Cursor<&'a mut Vec<u8>> { fn pos(&self) -> u64 { self.position() } } #[cfg(test)] mod tests { use super::*; use util::test_common::{get_temp_file, get_test_file}; #[test] fn test_io_read_fully() { let mut buf = vec![0; 8]; let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); let bytes_read = src.read(&mut buf[..]).unwrap(); assert_eq!(bytes_read, 4); assert_eq!(buf, vec![b'P', b'A', b'R', b'1', 0, 0, 0, 0]); } #[test] fn test_io_read_in_chunks() { let mut buf = vec![0; 4]; let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); let bytes_read = src.read(&mut buf[0..2]).unwrap(); assert_eq!(bytes_read, 2); let bytes_read = src.read(&mut buf[2..]).unwrap(); assert_eq!(bytes_read, 2); assert_eq!(buf, vec![b'P', b'A', b'R', b'1']); } #[test] fn test_io_read_pos() { let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); src.read(&mut vec![0; 1]).unwrap(); assert_eq!(src.pos(), 1); src.read(&mut vec![0; 4]).unwrap(); assert_eq!(src.pos(), 4); } #[test] fn test_io_read_over_limit() { let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); // Read all bytes from source src.read(&mut vec![0; 128]).unwrap(); assert_eq!(src.pos(), 4); // Try reading again, should return 0 bytes. let bytes_read = src.read(&mut vec![0; 128]).unwrap(); assert_eq!(bytes_read, 0); assert_eq!(src.pos(), 4); } #[test] fn test_io_seek_switch() { let mut buf = vec![0; 4]; let mut file = get_test_file("alltypes_plain.parquet"); let mut src = FileSource::new(&file, 0, 4); file .seek(SeekFrom::Start(5 as u64)) .expect("File seek to a position"); let bytes_read = src.read(&mut buf[..]).unwrap(); assert_eq!(bytes_read, 4); assert_eq!(buf, vec![b'P', b'A', b'R', b'1']); } #[test] fn test_io_write_with_pos() { let mut file = get_temp_file("file_sink_test", &[b'a', b'b', b'c']); file.seek(SeekFrom::Current(3)).unwrap(); // Write into sink let mut sink = FileSink::new(&file); assert_eq!(sink.pos(), 3); sink.write(&[b'd', b'e', b'f', b'g']).unwrap(); assert_eq!(sink.pos(), 7); sink.flush().unwrap(); assert_eq!(sink.pos(), file.seek(SeekFrom::Current(0)).unwrap()); // Read data using file chunk let mut res = vec![0u8; 7]; let mut chunk = FileSource::new(&file, 0, file.metadata().unwrap().len() as usize); chunk.read(&mut res[..]).unwrap(); assert_eq!(res, vec![b'a', b'b', b'c', b'd', b'e', b'f', b'g']); } }
FileSink
identifier_name
io.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use file::reader::ParquetReader; use std::{cmp, fs::File, io::*, sync::Mutex}; // ---------------------------------------------------------------------- // Read/Write wrappers for `File`. /// Position trait returns the current position in the stream. /// Should be viewed as a lighter version of `Seek` that does not allow seek operations, /// and does not require mutable reference for the current position. pub trait Position { /// Returns position in the stream. fn pos(&self) -> u64; } /// Struct that represents a slice of a file data with independent start position and /// length. Internally clones provided file handle, wraps with BufReader and resets /// position before any read. /// /// This is workaround and alternative for `file.try_clone()` method. It clones `File` /// while preserving independent position, which is not available with `try_clone()`. /// /// Designed after `arrow::io::RandomAccessFile`. pub struct FileSource<R: ParquetReader> { reader: Mutex<BufReader<R>>, start: u64, // start position in a file end: u64, // end position in a file } impl<R: ParquetReader> FileSource<R> { /// Creates new file reader with start and length from a file handle pub fn new(fd: &R, start: u64, length: usize) -> Self { Self { reader: Mutex::new(BufReader::new(fd.try_clone().unwrap())), start, end: start + length as u64, } } } impl<R: ParquetReader> Read for FileSource<R> { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let mut reader = self .reader .lock() .map_err(|err| Error::new(ErrorKind::Other, err.to_string()))?; let bytes_to_read = cmp::min(buf.len(), (self.end - self.start) as usize); let buf = &mut buf[0..bytes_to_read]; reader.seek(SeekFrom::Start(self.start as u64))?; let res = reader.read(buf); if let Ok(bytes_read) = res { self.start += bytes_read as u64; } res } } impl<R: ParquetReader> Position for FileSource<R> { fn pos(&self) -> u64 { self.start } } /// Struct that represents `File` output stream with position tracking. /// Used as a sink in file writer. pub struct FileSink { buf: BufWriter<File>, // This is not necessarily position in the underlying file, // but rather current position in the sink. pos: u64, } impl FileSink { /// Creates new file sink. /// Position is set to whatever position file has. pub fn new(file: &File) -> Self { let mut owned_file = file.try_clone().unwrap(); let pos = owned_file.seek(SeekFrom::Current(0)).unwrap(); Self { buf: BufWriter::new(owned_file), pos, } } } impl Write for FileSink { fn write(&mut self, buf: &[u8]) -> Result<usize> { let num_bytes = self.buf.write(buf)?; self.pos += num_bytes as u64; Ok(num_bytes) } fn flush(&mut self) -> Result<()> { self.buf.flush() } } impl Position for FileSink { fn pos(&self) -> u64 { self.pos } } // Position implementation for Cursor to use in various tests. impl<'a> Position for Cursor<&'a mut Vec<u8>> { fn pos(&self) -> u64 { self.position() } } #[cfg(test)] mod tests { use super::*; use util::test_common::{get_temp_file, get_test_file}; #[test] fn test_io_read_fully() { let mut buf = vec![0; 8]; let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); let bytes_read = src.read(&mut buf[..]).unwrap(); assert_eq!(bytes_read, 4); assert_eq!(buf, vec![b'P', b'A', b'R', b'1', 0, 0, 0, 0]); } #[test] fn test_io_read_in_chunks() { let mut buf = vec![0; 4]; let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); let bytes_read = src.read(&mut buf[0..2]).unwrap(); assert_eq!(bytes_read, 2); let bytes_read = src.read(&mut buf[2..]).unwrap(); assert_eq!(bytes_read, 2); assert_eq!(buf, vec![b'P', b'A', b'R', b'1']); } #[test] fn test_io_read_pos()
#[test] fn test_io_read_over_limit() { let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); // Read all bytes from source src.read(&mut vec![0; 128]).unwrap(); assert_eq!(src.pos(), 4); // Try reading again, should return 0 bytes. let bytes_read = src.read(&mut vec![0; 128]).unwrap(); assert_eq!(bytes_read, 0); assert_eq!(src.pos(), 4); } #[test] fn test_io_seek_switch() { let mut buf = vec![0; 4]; let mut file = get_test_file("alltypes_plain.parquet"); let mut src = FileSource::new(&file, 0, 4); file .seek(SeekFrom::Start(5 as u64)) .expect("File seek to a position"); let bytes_read = src.read(&mut buf[..]).unwrap(); assert_eq!(bytes_read, 4); assert_eq!(buf, vec![b'P', b'A', b'R', b'1']); } #[test] fn test_io_write_with_pos() { let mut file = get_temp_file("file_sink_test", &[b'a', b'b', b'c']); file.seek(SeekFrom::Current(3)).unwrap(); // Write into sink let mut sink = FileSink::new(&file); assert_eq!(sink.pos(), 3); sink.write(&[b'd', b'e', b'f', b'g']).unwrap(); assert_eq!(sink.pos(), 7); sink.flush().unwrap(); assert_eq!(sink.pos(), file.seek(SeekFrom::Current(0)).unwrap()); // Read data using file chunk let mut res = vec![0u8; 7]; let mut chunk = FileSource::new(&file, 0, file.metadata().unwrap().len() as usize); chunk.read(&mut res[..]).unwrap(); assert_eq!(res, vec![b'a', b'b', b'c', b'd', b'e', b'f', b'g']); } }
{ let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); src.read(&mut vec![0; 1]).unwrap(); assert_eq!(src.pos(), 1); src.read(&mut vec![0; 4]).unwrap(); assert_eq!(src.pos(), 4); }
identifier_body
io.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use file::reader::ParquetReader; use std::{cmp, fs::File, io::*, sync::Mutex}; // ---------------------------------------------------------------------- // Read/Write wrappers for `File`. /// Position trait returns the current position in the stream. /// Should be viewed as a lighter version of `Seek` that does not allow seek operations, /// and does not require mutable reference for the current position. pub trait Position { /// Returns position in the stream. fn pos(&self) -> u64; } /// Struct that represents a slice of a file data with independent start position and /// length. Internally clones provided file handle, wraps with BufReader and resets /// position before any read. /// /// This is workaround and alternative for `file.try_clone()` method. It clones `File` /// while preserving independent position, which is not available with `try_clone()`. /// /// Designed after `arrow::io::RandomAccessFile`. pub struct FileSource<R: ParquetReader> { reader: Mutex<BufReader<R>>, start: u64, // start position in a file end: u64, // end position in a file } impl<R: ParquetReader> FileSource<R> { /// Creates new file reader with start and length from a file handle pub fn new(fd: &R, start: u64, length: usize) -> Self { Self { reader: Mutex::new(BufReader::new(fd.try_clone().unwrap())), start, end: start + length as u64, } } } impl<R: ParquetReader> Read for FileSource<R> { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let mut reader = self .reader .lock() .map_err(|err| Error::new(ErrorKind::Other, err.to_string()))?; let bytes_to_read = cmp::min(buf.len(), (self.end - self.start) as usize); let buf = &mut buf[0..bytes_to_read]; reader.seek(SeekFrom::Start(self.start as u64))?; let res = reader.read(buf); if let Ok(bytes_read) = res
res } } impl<R: ParquetReader> Position for FileSource<R> { fn pos(&self) -> u64 { self.start } } /// Struct that represents `File` output stream with position tracking. /// Used as a sink in file writer. pub struct FileSink { buf: BufWriter<File>, // This is not necessarily position in the underlying file, // but rather current position in the sink. pos: u64, } impl FileSink { /// Creates new file sink. /// Position is set to whatever position file has. pub fn new(file: &File) -> Self { let mut owned_file = file.try_clone().unwrap(); let pos = owned_file.seek(SeekFrom::Current(0)).unwrap(); Self { buf: BufWriter::new(owned_file), pos, } } } impl Write for FileSink { fn write(&mut self, buf: &[u8]) -> Result<usize> { let num_bytes = self.buf.write(buf)?; self.pos += num_bytes as u64; Ok(num_bytes) } fn flush(&mut self) -> Result<()> { self.buf.flush() } } impl Position for FileSink { fn pos(&self) -> u64 { self.pos } } // Position implementation for Cursor to use in various tests. impl<'a> Position for Cursor<&'a mut Vec<u8>> { fn pos(&self) -> u64 { self.position() } } #[cfg(test)] mod tests { use super::*; use util::test_common::{get_temp_file, get_test_file}; #[test] fn test_io_read_fully() { let mut buf = vec![0; 8]; let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); let bytes_read = src.read(&mut buf[..]).unwrap(); assert_eq!(bytes_read, 4); assert_eq!(buf, vec![b'P', b'A', b'R', b'1', 0, 0, 0, 0]); } #[test] fn test_io_read_in_chunks() { let mut buf = vec![0; 4]; let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); let bytes_read = src.read(&mut buf[0..2]).unwrap(); assert_eq!(bytes_read, 2); let bytes_read = src.read(&mut buf[2..]).unwrap(); assert_eq!(bytes_read, 2); assert_eq!(buf, vec![b'P', b'A', b'R', b'1']); } #[test] fn test_io_read_pos() { let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); src.read(&mut vec![0; 1]).unwrap(); assert_eq!(src.pos(), 1); src.read(&mut vec![0; 4]).unwrap(); assert_eq!(src.pos(), 4); } #[test] fn test_io_read_over_limit() { let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); // Read all bytes from source src.read(&mut vec![0; 128]).unwrap(); assert_eq!(src.pos(), 4); // Try reading again, should return 0 bytes. let bytes_read = src.read(&mut vec![0; 128]).unwrap(); assert_eq!(bytes_read, 0); assert_eq!(src.pos(), 4); } #[test] fn test_io_seek_switch() { let mut buf = vec![0; 4]; let mut file = get_test_file("alltypes_plain.parquet"); let mut src = FileSource::new(&file, 0, 4); file .seek(SeekFrom::Start(5 as u64)) .expect("File seek to a position"); let bytes_read = src.read(&mut buf[..]).unwrap(); assert_eq!(bytes_read, 4); assert_eq!(buf, vec![b'P', b'A', b'R', b'1']); } #[test] fn test_io_write_with_pos() { let mut file = get_temp_file("file_sink_test", &[b'a', b'b', b'c']); file.seek(SeekFrom::Current(3)).unwrap(); // Write into sink let mut sink = FileSink::new(&file); assert_eq!(sink.pos(), 3); sink.write(&[b'd', b'e', b'f', b'g']).unwrap(); assert_eq!(sink.pos(), 7); sink.flush().unwrap(); assert_eq!(sink.pos(), file.seek(SeekFrom::Current(0)).unwrap()); // Read data using file chunk let mut res = vec![0u8; 7]; let mut chunk = FileSource::new(&file, 0, file.metadata().unwrap().len() as usize); chunk.read(&mut res[..]).unwrap(); assert_eq!(res, vec![b'a', b'b', b'c', b'd', b'e', b'f', b'g']); } }
{ self.start += bytes_read as u64; }
conditional_block
io.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use file::reader::ParquetReader; use std::{cmp, fs::File, io::*, sync::Mutex}; // ---------------------------------------------------------------------- // Read/Write wrappers for `File`. /// Position trait returns the current position in the stream. /// Should be viewed as a lighter version of `Seek` that does not allow seek operations, /// and does not require mutable reference for the current position. pub trait Position { /// Returns position in the stream. fn pos(&self) -> u64; } /// Struct that represents a slice of a file data with independent start position and /// length. Internally clones provided file handle, wraps with BufReader and resets
/// position before any read. /// /// This is workaround and alternative for `file.try_clone()` method. It clones `File` /// while preserving independent position, which is not available with `try_clone()`. /// /// Designed after `arrow::io::RandomAccessFile`. pub struct FileSource<R: ParquetReader> { reader: Mutex<BufReader<R>>, start: u64, // start position in a file end: u64, // end position in a file } impl<R: ParquetReader> FileSource<R> { /// Creates new file reader with start and length from a file handle pub fn new(fd: &R, start: u64, length: usize) -> Self { Self { reader: Mutex::new(BufReader::new(fd.try_clone().unwrap())), start, end: start + length as u64, } } } impl<R: ParquetReader> Read for FileSource<R> { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let mut reader = self .reader .lock() .map_err(|err| Error::new(ErrorKind::Other, err.to_string()))?; let bytes_to_read = cmp::min(buf.len(), (self.end - self.start) as usize); let buf = &mut buf[0..bytes_to_read]; reader.seek(SeekFrom::Start(self.start as u64))?; let res = reader.read(buf); if let Ok(bytes_read) = res { self.start += bytes_read as u64; } res } } impl<R: ParquetReader> Position for FileSource<R> { fn pos(&self) -> u64 { self.start } } /// Struct that represents `File` output stream with position tracking. /// Used as a sink in file writer. pub struct FileSink { buf: BufWriter<File>, // This is not necessarily position in the underlying file, // but rather current position in the sink. pos: u64, } impl FileSink { /// Creates new file sink. /// Position is set to whatever position file has. pub fn new(file: &File) -> Self { let mut owned_file = file.try_clone().unwrap(); let pos = owned_file.seek(SeekFrom::Current(0)).unwrap(); Self { buf: BufWriter::new(owned_file), pos, } } } impl Write for FileSink { fn write(&mut self, buf: &[u8]) -> Result<usize> { let num_bytes = self.buf.write(buf)?; self.pos += num_bytes as u64; Ok(num_bytes) } fn flush(&mut self) -> Result<()> { self.buf.flush() } } impl Position for FileSink { fn pos(&self) -> u64 { self.pos } } // Position implementation for Cursor to use in various tests. impl<'a> Position for Cursor<&'a mut Vec<u8>> { fn pos(&self) -> u64 { self.position() } } #[cfg(test)] mod tests { use super::*; use util::test_common::{get_temp_file, get_test_file}; #[test] fn test_io_read_fully() { let mut buf = vec![0; 8]; let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); let bytes_read = src.read(&mut buf[..]).unwrap(); assert_eq!(bytes_read, 4); assert_eq!(buf, vec![b'P', b'A', b'R', b'1', 0, 0, 0, 0]); } #[test] fn test_io_read_in_chunks() { let mut buf = vec![0; 4]; let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); let bytes_read = src.read(&mut buf[0..2]).unwrap(); assert_eq!(bytes_read, 2); let bytes_read = src.read(&mut buf[2..]).unwrap(); assert_eq!(bytes_read, 2); assert_eq!(buf, vec![b'P', b'A', b'R', b'1']); } #[test] fn test_io_read_pos() { let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); src.read(&mut vec![0; 1]).unwrap(); assert_eq!(src.pos(), 1); src.read(&mut vec![0; 4]).unwrap(); assert_eq!(src.pos(), 4); } #[test] fn test_io_read_over_limit() { let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); // Read all bytes from source src.read(&mut vec![0; 128]).unwrap(); assert_eq!(src.pos(), 4); // Try reading again, should return 0 bytes. let bytes_read = src.read(&mut vec![0; 128]).unwrap(); assert_eq!(bytes_read, 0); assert_eq!(src.pos(), 4); } #[test] fn test_io_seek_switch() { let mut buf = vec![0; 4]; let mut file = get_test_file("alltypes_plain.parquet"); let mut src = FileSource::new(&file, 0, 4); file .seek(SeekFrom::Start(5 as u64)) .expect("File seek to a position"); let bytes_read = src.read(&mut buf[..]).unwrap(); assert_eq!(bytes_read, 4); assert_eq!(buf, vec![b'P', b'A', b'R', b'1']); } #[test] fn test_io_write_with_pos() { let mut file = get_temp_file("file_sink_test", &[b'a', b'b', b'c']); file.seek(SeekFrom::Current(3)).unwrap(); // Write into sink let mut sink = FileSink::new(&file); assert_eq!(sink.pos(), 3); sink.write(&[b'd', b'e', b'f', b'g']).unwrap(); assert_eq!(sink.pos(), 7); sink.flush().unwrap(); assert_eq!(sink.pos(), file.seek(SeekFrom::Current(0)).unwrap()); // Read data using file chunk let mut res = vec![0u8; 7]; let mut chunk = FileSource::new(&file, 0, file.metadata().unwrap().len() as usize); chunk.read(&mut res[..]).unwrap(); assert_eq!(res, vec![b'a', b'b', b'c', b'd', b'e', b'f', b'g']); } }
random_line_split
entry.rs
use arch::mm::phys::Frame; use arch::mm::MappedAddr; use arch::mm::PhysAddr; use kernel::mm::*; bitflags! { pub struct Entry: usize { const PRESENT = 1 << 0; const WRITABLE = 1 << 1; const USER = 1 << 2; const WRT_THROUGH = 1 << 3; const NO_CACHE = 1 << 4; const ACCESSED = 1 << 5; const DIRTY = 1 << 6; const HUGE_PAGE = 1 << 7; const GLOBAL = 1 << 8; const NO_EXECUTE = 1 << 63; } } impl Entry { pub fn new_empty() -> Entry { Entry { bits: 0 } } pub fn from_kernel_flags(flags: virt::PageFlags) -> Entry { let mut res: Entry = Entry::new_empty(); if flags.contains(virt::PageFlags::NO_EXECUTE) { res.insert(Entry::NO_EXECUTE); } if flags.contains(virt::PageFlags::USER) { res.insert(Entry::USER); } if flags.contains(virt::PageFlags::WRITABLE) { res.insert(Entry::WRITABLE); } return res; } pub unsafe fn from_addr(addr: MappedAddr) -> Entry
pub fn clear(&mut self) { self.bits = 0; } pub fn raw(&self) -> usize { self.bits } pub fn set_raw(&mut self, bits: usize) { self.bits = bits; } pub fn is_unused(&self) -> bool { self.bits == 0 } pub fn address(&self) -> PhysAddr { PhysAddr(self.bits) & PhysAddr(0x000fffff_fffff000) } pub fn frame(&self) -> Option<Frame> { if self.contains(Entry::PRESENT) { Some(Frame::new(self.address())) } else { None } } pub fn set_frame_flags(&mut self, frame: &Frame, flags: Entry) { self.bits = frame.address().0; self.insert(flags | Entry::USER); } pub fn set_frame(&mut self, frame: &Frame) { self.bits = frame.address().0; } pub fn set_flags(&mut self, flags: Entry) { self.insert(flags | Entry::USER); } }
{ Entry { bits: addr.read::<usize>(), } }
identifier_body
entry.rs
use arch::mm::phys::Frame; use arch::mm::MappedAddr; use arch::mm::PhysAddr; use kernel::mm::*; bitflags! { pub struct Entry: usize { const PRESENT = 1 << 0; const WRITABLE = 1 << 1; const USER = 1 << 2; const WRT_THROUGH = 1 << 3; const NO_CACHE = 1 << 4; const ACCESSED = 1 << 5; const DIRTY = 1 << 6; const HUGE_PAGE = 1 << 7; const GLOBAL = 1 << 8; const NO_EXECUTE = 1 << 63; } } impl Entry { pub fn new_empty() -> Entry { Entry { bits: 0 } } pub fn from_kernel_flags(flags: virt::PageFlags) -> Entry { let mut res: Entry = Entry::new_empty(); if flags.contains(virt::PageFlags::NO_EXECUTE) { res.insert(Entry::NO_EXECUTE); } if flags.contains(virt::PageFlags::USER) { res.insert(Entry::USER); } if flags.contains(virt::PageFlags::WRITABLE) { res.insert(Entry::WRITABLE); } return res; } pub unsafe fn from_addr(addr: MappedAddr) -> Entry { Entry { bits: addr.read::<usize>(), } } pub fn clear(&mut self) { self.bits = 0; } pub fn raw(&self) -> usize { self.bits } pub fn
(&mut self, bits: usize) { self.bits = bits; } pub fn is_unused(&self) -> bool { self.bits == 0 } pub fn address(&self) -> PhysAddr { PhysAddr(self.bits) & PhysAddr(0x000fffff_fffff000) } pub fn frame(&self) -> Option<Frame> { if self.contains(Entry::PRESENT) { Some(Frame::new(self.address())) } else { None } } pub fn set_frame_flags(&mut self, frame: &Frame, flags: Entry) { self.bits = frame.address().0; self.insert(flags | Entry::USER); } pub fn set_frame(&mut self, frame: &Frame) { self.bits = frame.address().0; } pub fn set_flags(&mut self, flags: Entry) { self.insert(flags | Entry::USER); } }
set_raw
identifier_name
entry.rs
use arch::mm::phys::Frame; use arch::mm::MappedAddr; use arch::mm::PhysAddr; use kernel::mm::*; bitflags! { pub struct Entry: usize { const PRESENT = 1 << 0; const WRITABLE = 1 << 1; const USER = 1 << 2; const WRT_THROUGH = 1 << 3; const NO_CACHE = 1 << 4; const ACCESSED = 1 << 5; const DIRTY = 1 << 6; const HUGE_PAGE = 1 << 7; const GLOBAL = 1 << 8; const NO_EXECUTE = 1 << 63; } } impl Entry { pub fn new_empty() -> Entry { Entry { bits: 0 } } pub fn from_kernel_flags(flags: virt::PageFlags) -> Entry { let mut res: Entry = Entry::new_empty(); if flags.contains(virt::PageFlags::NO_EXECUTE) { res.insert(Entry::NO_EXECUTE); } if flags.contains(virt::PageFlags::USER) { res.insert(Entry::USER); } if flags.contains(virt::PageFlags::WRITABLE) { res.insert(Entry::WRITABLE); } return res; } pub unsafe fn from_addr(addr: MappedAddr) -> Entry { Entry { bits: addr.read::<usize>(), } } pub fn clear(&mut self) { self.bits = 0; } pub fn raw(&self) -> usize { self.bits } pub fn set_raw(&mut self, bits: usize) { self.bits = bits; } pub fn is_unused(&self) -> bool { self.bits == 0 } pub fn address(&self) -> PhysAddr { PhysAddr(self.bits) & PhysAddr(0x000fffff_fffff000) } pub fn frame(&self) -> Option<Frame> { if self.contains(Entry::PRESENT) { Some(Frame::new(self.address())) } else { None } } pub fn set_frame_flags(&mut self, frame: &Frame, flags: Entry) { self.bits = frame.address().0; self.insert(flags | Entry::USER); }
self.bits = frame.address().0; } pub fn set_flags(&mut self, flags: Entry) { self.insert(flags | Entry::USER); } }
pub fn set_frame(&mut self, frame: &Frame) {
random_line_split
entry.rs
use arch::mm::phys::Frame; use arch::mm::MappedAddr; use arch::mm::PhysAddr; use kernel::mm::*; bitflags! { pub struct Entry: usize { const PRESENT = 1 << 0; const WRITABLE = 1 << 1; const USER = 1 << 2; const WRT_THROUGH = 1 << 3; const NO_CACHE = 1 << 4; const ACCESSED = 1 << 5; const DIRTY = 1 << 6; const HUGE_PAGE = 1 << 7; const GLOBAL = 1 << 8; const NO_EXECUTE = 1 << 63; } } impl Entry { pub fn new_empty() -> Entry { Entry { bits: 0 } } pub fn from_kernel_flags(flags: virt::PageFlags) -> Entry { let mut res: Entry = Entry::new_empty(); if flags.contains(virt::PageFlags::NO_EXECUTE) { res.insert(Entry::NO_EXECUTE); } if flags.contains(virt::PageFlags::USER)
if flags.contains(virt::PageFlags::WRITABLE) { res.insert(Entry::WRITABLE); } return res; } pub unsafe fn from_addr(addr: MappedAddr) -> Entry { Entry { bits: addr.read::<usize>(), } } pub fn clear(&mut self) { self.bits = 0; } pub fn raw(&self) -> usize { self.bits } pub fn set_raw(&mut self, bits: usize) { self.bits = bits; } pub fn is_unused(&self) -> bool { self.bits == 0 } pub fn address(&self) -> PhysAddr { PhysAddr(self.bits) & PhysAddr(0x000fffff_fffff000) } pub fn frame(&self) -> Option<Frame> { if self.contains(Entry::PRESENT) { Some(Frame::new(self.address())) } else { None } } pub fn set_frame_flags(&mut self, frame: &Frame, flags: Entry) { self.bits = frame.address().0; self.insert(flags | Entry::USER); } pub fn set_frame(&mut self, frame: &Frame) { self.bits = frame.address().0; } pub fn set_flags(&mut self, flags: Entry) { self.insert(flags | Entry::USER); } }
{ res.insert(Entry::USER); }
conditional_block
int.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. //! Operations and constants for `int` pub use self::inst::pow; mod inst { use num::{Primitive, BitCount}; pub type T = int; pub static bits: uint = ::uint::bits; impl Primitive for int { #[cfg(target_word_size = "32")] #[inline(always)] fn bits() -> uint { 32 } #[cfg(target_word_size = "64")] #[inline(always)] fn bits() -> uint { 64 } #[inline(always)] fn bytes() -> uint { Primitive::bits::<int>() / 8 } } #[cfg(target_word_size = "32")] #[inline(always)] impl BitCount for int { /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. #[inline(always)] fn population_count(&self) -> int { (*self as i32).population_count() as int } /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. #[inline(always)] fn leading_zeros(&self) -> int { (*self as i32).leading_zeros() as int } /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. #[inline(always)] fn trailing_zeros(&self) -> int { (*self as i32).trailing_zeros() as int } } #[cfg(target_word_size = "64")] #[inline(always)] impl BitCount for int { /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. #[inline(always)] fn population_count(&self) -> int { (*self as i64).population_count() as int } /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. #[inline(always)] fn leading_zeros(&self) -> int { (*self as i64).leading_zeros() as int } /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. #[inline(always)] fn trailing_zeros(&self) -> int { (*self as i64).trailing_zeros() as int } } /// Returns `base` raised to the power of `exponent` pub fn pow(base: int, exponent: uint) -> int { if exponent == 0u
if base == 0 { return 0; } let mut my_pow = exponent; let mut acc = 1; let mut multiplier = base; while(my_pow > 0u) { if my_pow % 2u == 1u { acc *= multiplier; } my_pow /= 2u; multiplier *= multiplier; } return acc; } #[test] fn test_pow() { assert!((pow(0, 0u) == 1)); assert!((pow(0, 1u) == 0)); assert!((pow(0, 2u) == 0)); assert!((pow(-1, 0u) == 1)); assert!((pow(1, 0u) == 1)); assert!((pow(-3, 2u) == 9)); assert!((pow(-3, 3u) == -27)); assert!((pow(4, 9u) == 262144)); } #[test] fn test_overflows() { assert!((::int::max_value > 0)); assert!((::int::min_value <= 0)); assert!((::int::min_value + ::int::max_value + 1 == 0)); } }
{ //Not mathemtically true if ~[base == 0] return 1; }
conditional_block
int.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. //! Operations and constants for `int` pub use self::inst::pow; mod inst { use num::{Primitive, BitCount}; pub type T = int; pub static bits: uint = ::uint::bits; impl Primitive for int { #[cfg(target_word_size = "32")] #[inline(always)] fn bits() -> uint { 32 } #[cfg(target_word_size = "64")] #[inline(always)] fn bits() -> uint { 64 } #[inline(always)] fn bytes() -> uint { Primitive::bits::<int>() / 8 } } #[cfg(target_word_size = "32")] #[inline(always)] impl BitCount for int { /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. #[inline(always)] fn population_count(&self) -> int { (*self as i32).population_count() as int } /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. #[inline(always)] fn leading_zeros(&self) -> int { (*self as i32).leading_zeros() as int } /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. #[inline(always)] fn trailing_zeros(&self) -> int { (*self as i32).trailing_zeros() as int } } #[cfg(target_word_size = "64")] #[inline(always)] impl BitCount for int { /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. #[inline(always)] fn population_count(&self) -> int { (*self as i64).population_count() as int } /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. #[inline(always)] fn leading_zeros(&self) -> int { (*self as i64).leading_zeros() as int } /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. #[inline(always)] fn trailing_zeros(&self) -> int { (*self as i64).trailing_zeros() as int } } /// Returns `base` raised to the power of `exponent` pub fn pow(base: int, exponent: uint) -> int { if exponent == 0u { //Not mathemtically true if ~[base == 0] return 1; } if base == 0 { return 0; } let mut my_pow = exponent; let mut acc = 1; let mut multiplier = base; while(my_pow > 0u) { if my_pow % 2u == 1u { acc *= multiplier; } my_pow /= 2u; multiplier *= multiplier; } return acc; } #[test] fn test_pow() { assert!((pow(0, 0u) == 1)); assert!((pow(0, 1u) == 0)); assert!((pow(0, 2u) == 0)); assert!((pow(-1, 0u) == 1)); assert!((pow(1, 0u) == 1)); assert!((pow(-3, 2u) == 9)); assert!((pow(-3, 3u) == -27)); assert!((pow(4, 9u) == 262144)); } #[test] fn test_overflows() { assert!((::int::max_value > 0)); assert!((::int::min_value <= 0)); assert!((::int::min_value + ::int::max_value + 1 == 0)); } }
random_line_split
int.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. //! Operations and constants for `int` pub use self::inst::pow; mod inst { use num::{Primitive, BitCount}; pub type T = int; pub static bits: uint = ::uint::bits; impl Primitive for int { #[cfg(target_word_size = "32")] #[inline(always)] fn bits() -> uint { 32 } #[cfg(target_word_size = "64")] #[inline(always)] fn bits() -> uint { 64 } #[inline(always)] fn bytes() -> uint { Primitive::bits::<int>() / 8 } } #[cfg(target_word_size = "32")] #[inline(always)] impl BitCount for int { /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. #[inline(always)] fn population_count(&self) -> int { (*self as i32).population_count() as int } /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. #[inline(always)] fn leading_zeros(&self) -> int { (*self as i32).leading_zeros() as int } /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. #[inline(always)] fn trailing_zeros(&self) -> int { (*self as i32).trailing_zeros() as int } } #[cfg(target_word_size = "64")] #[inline(always)] impl BitCount for int { /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. #[inline(always)] fn population_count(&self) -> int { (*self as i64).population_count() as int } /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. #[inline(always)] fn leading_zeros(&self) -> int { (*self as i64).leading_zeros() as int } /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. #[inline(always)] fn
(&self) -> int { (*self as i64).trailing_zeros() as int } } /// Returns `base` raised to the power of `exponent` pub fn pow(base: int, exponent: uint) -> int { if exponent == 0u { //Not mathemtically true if ~[base == 0] return 1; } if base == 0 { return 0; } let mut my_pow = exponent; let mut acc = 1; let mut multiplier = base; while(my_pow > 0u) { if my_pow % 2u == 1u { acc *= multiplier; } my_pow /= 2u; multiplier *= multiplier; } return acc; } #[test] fn test_pow() { assert!((pow(0, 0u) == 1)); assert!((pow(0, 1u) == 0)); assert!((pow(0, 2u) == 0)); assert!((pow(-1, 0u) == 1)); assert!((pow(1, 0u) == 1)); assert!((pow(-3, 2u) == 9)); assert!((pow(-3, 3u) == -27)); assert!((pow(4, 9u) == 262144)); } #[test] fn test_overflows() { assert!((::int::max_value > 0)); assert!((::int::min_value <= 0)); assert!((::int::min_value + ::int::max_value + 1 == 0)); } }
trailing_zeros
identifier_name
int.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. //! Operations and constants for `int` pub use self::inst::pow; mod inst { use num::{Primitive, BitCount}; pub type T = int; pub static bits: uint = ::uint::bits; impl Primitive for int { #[cfg(target_word_size = "32")] #[inline(always)] fn bits() -> uint { 32 } #[cfg(target_word_size = "64")] #[inline(always)] fn bits() -> uint { 64 } #[inline(always)] fn bytes() -> uint { Primitive::bits::<int>() / 8 } } #[cfg(target_word_size = "32")] #[inline(always)] impl BitCount for int { /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. #[inline(always)] fn population_count(&self) -> int { (*self as i32).population_count() as int } /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. #[inline(always)] fn leading_zeros(&self) -> int { (*self as i32).leading_zeros() as int } /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. #[inline(always)] fn trailing_zeros(&self) -> int { (*self as i32).trailing_zeros() as int } } #[cfg(target_word_size = "64")] #[inline(always)] impl BitCount for int { /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. #[inline(always)] fn population_count(&self) -> int { (*self as i64).population_count() as int } /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. #[inline(always)] fn leading_zeros(&self) -> int { (*self as i64).leading_zeros() as int } /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. #[inline(always)] fn trailing_zeros(&self) -> int { (*self as i64).trailing_zeros() as int } } /// Returns `base` raised to the power of `exponent` pub fn pow(base: int, exponent: uint) -> int { if exponent == 0u { //Not mathemtically true if ~[base == 0] return 1; } if base == 0 { return 0; } let mut my_pow = exponent; let mut acc = 1; let mut multiplier = base; while(my_pow > 0u) { if my_pow % 2u == 1u { acc *= multiplier; } my_pow /= 2u; multiplier *= multiplier; } return acc; } #[test] fn test_pow()
#[test] fn test_overflows() { assert!((::int::max_value > 0)); assert!((::int::min_value <= 0)); assert!((::int::min_value + ::int::max_value + 1 == 0)); } }
{ assert!((pow(0, 0u) == 1)); assert!((pow(0, 1u) == 0)); assert!((pow(0, 2u) == 0)); assert!((pow(-1, 0u) == 1)); assert!((pow(1, 0u) == 1)); assert!((pow(-3, 2u) == 9)); assert!((pow(-3, 3u) == -27)); assert!((pow(4, 9u) == 262144)); }
identifier_body
custom_entities.rs
//! This example demonstrate how custom entities can be extracted from the DOCTYPE!, //! and later use to decode text and attribute values. //! //! NB: this example is deliberately kept simple:
//! * it only handles internal entities; //! * the regex in this example is simple but brittle; //! * it does not support the use of entities in entity declaration. extern crate quick_xml; extern crate regex; use quick_xml::events::Event; use quick_xml::Reader; use regex::bytes::Regex; use std::collections::HashMap; const DATA: &str = r#" <?xml version="1.0"?> <!DOCTYPE test [ <!ENTITY msg "hello world" > ]> <test label="&msg;">&msg;</test> "#; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut reader = Reader::from_str(DATA); reader.trim_text(true); let mut buf = Vec::new(); let mut custom_entities = HashMap::new(); let entity_re = Regex::new(r#"<!ENTITY\s+([^ \t\r\n]+)\s+"([^"]*)"\s*>"#)?; loop { match reader.read_event(&mut buf) { Ok(Event::DocType(ref e)) => { for cap in entity_re.captures_iter(&e) { custom_entities.insert(cap[1].to_vec(), cap[2].to_vec()); } } Ok(Event::Start(ref e)) => match e.name() { b"test" => println!( "attributes values: {:?}", e.attributes() .map(|a| a .unwrap() .unescape_and_decode_value_with_custom_entities( &reader, &custom_entities ) .unwrap()) .collect::<Vec<_>>() ), _ => (), }, Ok(Event::Text(ref e)) => { println!( "text value: {}", e.unescape_and_decode_with_custom_entities(&reader, &custom_entities) .unwrap() ); } Ok(Event::Eof) => break, Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e), _ => (), } } Ok(()) }
//! * it assumes that the XML file is UTF-8 encoded (custom_entities must only contain UTF-8 data)
random_line_split
custom_entities.rs
//! This example demonstrate how custom entities can be extracted from the DOCTYPE!, //! and later use to decode text and attribute values. //! //! NB: this example is deliberately kept simple: //! * it assumes that the XML file is UTF-8 encoded (custom_entities must only contain UTF-8 data) //! * it only handles internal entities; //! * the regex in this example is simple but brittle; //! * it does not support the use of entities in entity declaration. extern crate quick_xml; extern crate regex; use quick_xml::events::Event; use quick_xml::Reader; use regex::bytes::Regex; use std::collections::HashMap; const DATA: &str = r#" <?xml version="1.0"?> <!DOCTYPE test [ <!ENTITY msg "hello world" > ]> <test label="&msg;">&msg;</test> "#; fn
() -> Result<(), Box<dyn std::error::Error>> { let mut reader = Reader::from_str(DATA); reader.trim_text(true); let mut buf = Vec::new(); let mut custom_entities = HashMap::new(); let entity_re = Regex::new(r#"<!ENTITY\s+([^ \t\r\n]+)\s+"([^"]*)"\s*>"#)?; loop { match reader.read_event(&mut buf) { Ok(Event::DocType(ref e)) => { for cap in entity_re.captures_iter(&e) { custom_entities.insert(cap[1].to_vec(), cap[2].to_vec()); } } Ok(Event::Start(ref e)) => match e.name() { b"test" => println!( "attributes values: {:?}", e.attributes() .map(|a| a .unwrap() .unescape_and_decode_value_with_custom_entities( &reader, &custom_entities ) .unwrap()) .collect::<Vec<_>>() ), _ => (), }, Ok(Event::Text(ref e)) => { println!( "text value: {}", e.unescape_and_decode_with_custom_entities(&reader, &custom_entities) .unwrap() ); } Ok(Event::Eof) => break, Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e), _ => (), } } Ok(()) }
main
identifier_name
custom_entities.rs
//! This example demonstrate how custom entities can be extracted from the DOCTYPE!, //! and later use to decode text and attribute values. //! //! NB: this example is deliberately kept simple: //! * it assumes that the XML file is UTF-8 encoded (custom_entities must only contain UTF-8 data) //! * it only handles internal entities; //! * the regex in this example is simple but brittle; //! * it does not support the use of entities in entity declaration. extern crate quick_xml; extern crate regex; use quick_xml::events::Event; use quick_xml::Reader; use regex::bytes::Regex; use std::collections::HashMap; const DATA: &str = r#" <?xml version="1.0"?> <!DOCTYPE test [ <!ENTITY msg "hello world" > ]> <test label="&msg;">&msg;</test> "#; fn main() -> Result<(), Box<dyn std::error::Error>>
.unwrap() .unescape_and_decode_value_with_custom_entities( &reader, &custom_entities ) .unwrap()) .collect::<Vec<_>>() ), _ => (), }, Ok(Event::Text(ref e)) => { println!( "text value: {}", e.unescape_and_decode_with_custom_entities(&reader, &custom_entities) .unwrap() ); } Ok(Event::Eof) => break, Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e), _ => (), } } Ok(()) }
{ let mut reader = Reader::from_str(DATA); reader.trim_text(true); let mut buf = Vec::new(); let mut custom_entities = HashMap::new(); let entity_re = Regex::new(r#"<!ENTITY\s+([^ \t\r\n]+)\s+"([^"]*)"\s*>"#)?; loop { match reader.read_event(&mut buf) { Ok(Event::DocType(ref e)) => { for cap in entity_re.captures_iter(&e) { custom_entities.insert(cap[1].to_vec(), cap[2].to_vec()); } } Ok(Event::Start(ref e)) => match e.name() { b"test" => println!( "attributes values: {:?}", e.attributes() .map(|a| a
identifier_body
lib.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/. */ #![cfg_attr(not(target_os = "windows"), feature(alloc_jemalloc))] #![feature(box_syntax)] #![feature(iter_arith)] #![feature(plugin)] #![plugin(plugins)] #![feature(custom_derive)] #![plugin(serde_macros)] #![deny(unsafe_code)] #[allow(unused_extern_crates)] #[cfg(not(target_os = "windows"))] extern crate alloc_jemalloc; extern crate hbs_pow; extern crate ipc_channel; #[cfg(not(target_os = "windows"))] extern crate libc; #[macro_use] extern crate log; #[macro_use] extern crate profile_traits; #[cfg(target_os = "linux")] extern crate regex; extern crate serde; extern crate serde_json; #[cfg(target_os = "macos")] extern crate task_info; extern crate time as std_time; extern crate util; #[allow(unsafe_code)] mod heartbeats; #[allow(unsafe_code)] pub mod mem;
pub mod time; pub mod trace_dump;
random_line_split
context.rs
dump statistics about the style system. pub dump_style_statistics: bool, /// The minimum number of elements that must be traversed to trigger a dump /// of style statistics. pub style_statistics_threshold: usize, } #[cfg(feature = "gecko")] fn get_env_bool(name: &str) -> bool { use std::env; match env::var(name) { Ok(s) =>!s.is_empty(), Err(_) => false, } } const DEFAULT_STATISTICS_THRESHOLD: usize = 50; #[cfg(feature = "gecko")] fn get_env_usize(name: &str) -> Option<usize> { use std::env; env::var(name).ok().map(|s| { s.parse::<usize>() .expect("Couldn't parse environmental variable as usize") }) } impl Default for StyleSystemOptions { #[cfg(feature = "servo")] fn default() -> Self { use servo_config::opts; StyleSystemOptions { disable_style_sharing_cache: opts::get().disable_share_style_cache, dump_style_statistics: opts::get().style_sharing_stats, style_statistics_threshold: DEFAULT_STATISTICS_THRESHOLD, } } #[cfg(feature = "gecko")] fn default() -> Self { StyleSystemOptions { disable_style_sharing_cache: get_env_bool("DISABLE_STYLE_SHARING_CACHE"), dump_style_statistics: get_env_bool("DUMP_STYLE_STATISTICS"), style_statistics_threshold: get_env_usize("STYLE_STATISTICS_THRESHOLD") .unwrap_or(DEFAULT_STATISTICS_THRESHOLD), } } } impl StyleSystemOptions { #[cfg(feature = "servo")] /// On Gecko's nightly build? pub fn is_nightly(&self) -> bool { false } #[cfg(feature = "gecko")] /// On Gecko's nightly build? #[inline] pub fn is_nightly(&self) -> bool { structs::GECKO_IS_NIGHTLY } } /// A shared style context. /// /// There's exactly one of these during a given restyle traversal, and it's /// shared among the worker threads. pub struct SharedStyleContext<'a> { /// The CSS selector stylist. pub stylist: &'a Stylist, /// Whether visited styles are enabled. /// /// They may be disabled when Gecko's pref layout.css.visited_links_enabled /// is false, or when in private browsing mode. pub visited_styles_enabled: bool, /// Configuration options. pub options: StyleSystemOptions, /// Guards for pre-acquired locks pub guards: StylesheetGuards<'a>, /// The current timer for transitions and animations. This is needed to test /// them.
/// A map with our snapshots in order to handle restyle hints. pub snapshot_map: &'a SnapshotMap, /// The animations that are currently running. #[cfg(feature = "servo")] pub running_animations: Arc<RwLock<FxHashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. #[cfg(feature = "servo")] pub expired_animations: Arc<RwLock<FxHashMap<OpaqueNode, Vec<Animation>>>>, /// Paint worklets #[cfg(feature = "servo")] pub registered_speculative_painters: &'a RegisteredSpeculativePainters, /// Data needed to create the thread-local style context from the shared one. #[cfg(feature = "servo")] pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>, } impl<'a> SharedStyleContext<'a> { /// Return a suitable viewport size in order to be used for viewport units. pub fn viewport_size(&self) -> Size2D<Au> { self.stylist.device().au_viewport_size() } /// The device pixel ratio pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel> { self.stylist.device().device_pixel_ratio() } /// The quirks mode of the document. pub fn quirks_mode(&self) -> QuirksMode { self.stylist.quirks_mode() } } /// The structure holds various intermediate inputs that are eventually used by /// by the cascade. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Debug, Default)] pub struct CascadeInputs { /// The rule node representing the ordered list of rules matched for this /// node. pub rules: Option<StrongRuleNode>, /// The rule node representing the ordered list of rules matched for this /// node if visited, only computed if there's a relevant link for this /// element. A element's "relevant link" is the element being matched if it /// is a link or the nearest ancestor link. pub visited_rules: Option<StrongRuleNode>, } impl CascadeInputs { /// Construct inputs from previous cascade results, if any. pub fn new_from_style(style: &ComputedValues) -> Self { CascadeInputs { rules: style.rules.clone(), visited_rules: style.visited_style().and_then(|v| v.rules.clone()), } } } /// A list of cascade inputs for eagerly-cascaded pseudo-elements. /// The list is stored inline. #[derive(Debug)] pub struct EagerPseudoCascadeInputs(Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]>); // Manually implement `Clone` here because the derived impl of `Clone` for // array types assumes the value inside is `Copy`. impl Clone for EagerPseudoCascadeInputs { fn clone(&self) -> Self { if self.0.is_none() { return EagerPseudoCascadeInputs(None); } let self_inputs = self.0.as_ref().unwrap(); let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = self_inputs[i].clone(); } EagerPseudoCascadeInputs(Some(inputs)) } } impl EagerPseudoCascadeInputs { /// Construct inputs from previous cascade results, if any. fn new_from_style(styles: &EagerPseudoStyles) -> Self { EagerPseudoCascadeInputs(styles.as_optional_array().map(|styles| { let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = styles[i].as_ref().map(|s| CascadeInputs::new_from_style(s)); } inputs })) } /// Returns the list of rules, if they exist. pub fn into_array(self) -> Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]> { self.0 } } /// The cascade inputs associated with a node, including those for any /// pseudo-elements. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Debug)] pub struct ElementCascadeInputs { /// The element's cascade inputs. pub primary: CascadeInputs, /// A list of the inputs for the element's eagerly-cascaded pseudo-elements. pub pseudos: EagerPseudoCascadeInputs, } impl ElementCascadeInputs { /// Construct inputs from previous cascade results, if any. #[inline] pub fn new_from_element_data(data: &ElementData) -> Self { debug_assert!(data.has_styles()); ElementCascadeInputs { primary: CascadeInputs::new_from_style(data.styles.primary()), pseudos: EagerPseudoCascadeInputs::new_from_style(&data.styles.pseudos), } } } /// Statistics gathered during the traversal. We gather statistics on each /// thread and then combine them after the threads join via the Add /// implementation below. #[derive(AddAssign, Clone, Default)] pub struct PerThreadTraversalStatistics { /// The total number of elements traversed. pub elements_traversed: u32, /// The number of elements where has_styles() went from false to true. pub elements_styled: u32, /// The number of elements for which we performed selector matching. pub elements_matched: u32, /// The number of cache hits from the StyleSharingCache. pub styles_shared: u32, /// The number of styles reused via rule node comparison from the /// StyleSharingCache. pub styles_reused: u32, } /// Statistics gathered during the traversal plus some information from /// other sources including stylist. #[derive(Default)] pub struct TraversalStatistics { /// Aggregated statistics gathered during the traversal. pub aggregated: PerThreadTraversalStatistics, /// The number of selectors in the stylist. pub selectors: u32, /// The number of revalidation selectors. pub revalidation_selectors: u32, /// The number of state/attr dependencies in the dependency set. pub dependency_selectors: u32, /// The number of declarations in the stylist. pub declarations: u32, /// The number of times the stylist was rebuilt. pub stylist_rebuilds: u32, /// Time spent in the traversal, in milliseconds. pub traversal_time_ms: f64, /// Whether this was a parallel traversal. pub is_parallel: bool, /// Whether this is a "large" traversal. pub is_large: bool, } /// Format the statistics in a way that the performance test harness understands. /// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2 impl fmt::Display for TraversalStatistics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { debug_assert!( self.traversal_time_ms!= 0.0, "should have set traversal time" ); writeln!(f, "[PERF] perf block start")?; writeln!( f, "[PERF],traversal,{}", if self.is_parallel { "parallel" } else { "sequential" } )?; writeln!( f, "[PERF],elements_traversed,{}", self.aggregated.elements_traversed )?; writeln!( f, "[PERF],elements_styled,{}", self.aggregated.elements_styled )?; writeln!( f, "[PERF],elements_matched,{}", self.aggregated.elements_matched )?; writeln!(f, "[PERF],styles_shared,{}", self.aggregated.styles_shared)?; writeln!(f, "[PERF],styles_reused,{}", self.aggregated.styles_reused)?; writeln!(f, "[PERF],selectors,{}", self.selectors)?; writeln!( f, "[PERF],revalidation_selectors,{}", self.revalidation_selectors )?; writeln!( f, "[PERF],dependency_selectors,{}", self.dependency_selectors )?; writeln!(f, "[PERF],declarations,{}", self.declarations)?; writeln!(f, "[PERF],stylist_rebuilds,{}", self.stylist_rebuilds)?; writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms)?; writeln!(f, "[PERF] perf block end") } } impl TraversalStatistics { /// Generate complete traversal statistics. /// /// The traversal time is computed given the start time in seconds. pub fn new<E, D>( aggregated: PerThreadTraversalStatistics, traversal: &D, parallel: bool, start: f64, ) -> TraversalStatistics where E: TElement, D: DomTraversal<E>, { let threshold = traversal .shared_context() .options .style_statistics_threshold; let stylist = traversal.shared_context().stylist; let is_large = aggregated.elements_traversed as usize >= threshold; TraversalStatistics { aggregated, selectors: stylist.num_selectors() as u32, revalidation_selectors: stylist.num_revalidation_selectors() as u32, dependency_selectors: stylist.num_invalidations() as u32, declarations: stylist.num_declarations() as u32, stylist_rebuilds: stylist.num_rebuilds() as u32, traversal_time_ms: (time::precise_time_s() - start) * 1000.0, is_parallel: parallel, is_large, } } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask of /// UpdateAnimations which is a result of normal restyle. pub struct UpdateAnimationsTasks: u8 { /// Update CSS Animations. const CSS_ANIMATIONS = structs::UpdateAnimationsTasks_CSSAnimations; /// Update CSS Transitions. const CSS_TRANSITIONS = structs::UpdateAnimationsTasks_CSSTransitions; /// Update effect properties. const EFFECT_PROPERTIES = structs::UpdateAnimationsTasks_EffectProperties; /// Update animation cacade results for animations running on the compositor. const CASCADE_RESULTS = structs::UpdateAnimationsTasks_CascadeResults; /// Display property was changed from none. /// Script animations keep alive on display:none elements, so we need to trigger /// the second animation restyles for the script animations in the case where /// the display property was changed from 'none' to others. const DISPLAY_CHANGED_FROM_NONE = structs::UpdateAnimationsTasks_DisplayChangedFromNone; } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask as a result of /// animation-only restyle. pub struct PostAnimationTasks: u8 { /// Display property was changed from none in animation-only restyle so /// that we need to resolve styles for descendants in a subsequent /// normal restyle. const DISPLAY_CHANGED_FROM_NONE_FOR_SMIL = 0x01; } } /// A task to be run in sequential mode on the parent (non-worker) thread. This /// is used by the style system to queue up work which is not safe to do during /// the parallel traversal. pub enum SequentialTask<E: TElement> { /// Entry to avoid an unused type parameter error on servo. Unused(SendElement<E>), /// Performs one of a number of possible tasks related to updating /// animations based on the |tasks| field. These include updating CSS /// animations/transitions that changed as part of the non-animation style /// traversal, and updating the computed effect properties. #[cfg(feature = "gecko")] UpdateAnimations { /// The target element or pseudo-element. el: SendElement<E>, /// The before-change style for transitions. We use before-change style /// as the initial value of its Keyframe. Required if |tasks| includes /// CSSTransitions. before_change_style: Option<Arc<ComputedValues>>, /// The tasks which are performed in this SequentialTask. tasks: UpdateAnimationsTasks, }, /// Performs one of a number of possible tasks as a result of animation-only /// restyle. /// /// Currently we do only process for resolving descendant elements that were /// display:none subtree for SMIL animation. #[cfg(feature = "gecko")] PostAnimation { /// The target element. el: SendElement<E>, /// The tasks which are performed in this SequentialTask. tasks: PostAnimationTasks, }, } impl<E: TElement> SequentialTask<E> { /// Executes this task. pub fn execute(self) { use self::SequentialTask::*; debug_assert_eq!(thread_state::get(), ThreadState::LAYOUT); match self { Unused(_) => unreachable!(), #[cfg(feature = "gecko")] UpdateAnimations { el, before_change_style, tasks, } => { el.update_animations(before_change_style, tasks); }, #[cfg(feature = "gecko")] PostAnimation { el, tasks } => { el.process_post_animation(tasks); }, } } /// Creates a task to update various animation-related state on a given /// (pseudo-)element. #[cfg(feature = "gecko")] pub fn update_animations( el: E, before_change_style: Option<Arc<ComputedValues>>, tasks: UpdateAnimationsTasks, ) -> Self { use self::SequentialTask::*; UpdateAnimations { el: unsafe { SendElement::new(el) }, before_change_style, tasks, } } /// Creates a task to do post-process for a given element as a result of /// animation-only restyle. #[cfg(feature = "gecko")] pub fn process_post_animation(el: E, tasks: PostAnimationTasks) -> Self { use self::SequentialTask::*; PostAnimation { el: unsafe { SendElement::new(el) }, tasks, } } } type CacheItem<E> = (SendElement<E>, ElementSelectorFlags); /// Map from Elements to ElementSelectorFlags. Used to defer applying selector /// flags until after the traversal. pub struct SelectorFlagsMap<E: TElement> { /// The hashmap storing the flags to apply. map: FxHashMap<SendElement<E>, ElementSelectorFlags>, /// An LRU cache to avoid hashmap lookups, which can be slow if the map /// gets big. cache: LRUCache<[Entry<CacheItem<E>>; 4 + 1]>, } #[cfg(debug_assertions)] impl<E: TElement> Drop for SelectorFlagsMap<E> { fn drop(&mut self) { debug_assert!(self.map.is_empty()); } } impl<E: TElement> SelectorFlagsMap<E> { /// Creates a new empty SelectorFlagsMap. pub fn new() -> Self { SelectorFlagsMap { map: FxHashMap::default(), cache: LRUCache::default(), } } /// Inserts some flags into the map for a given element. pub fn insert_flags(&mut self, element: E, flags: ElementSelectorFlags) { let el = unsafe { SendElement::new(element) }; // Check the cache. If the flags have already been noted, we're done. if let Some(item) = self.cache.find(|x| x.0 == el) { if!item.1.contains(flags) { item.1.insert(flags); self.map.get_mut(&el).unwrap().insert(flags); } return; } let f = self.map.entry(el).or_insert(ElementSelectorFlags::empty()); *f |= flags; self.cache .insert((unsafe { SendElement::new(element) }, *f)) } /// Applies the flags. Must be called on the main thread. fn apply_flags(&mut self) { debug_assert_eq!(thread_state::get(), ThreadState::LAYOUT); self.cache.evict_all(); for (el, flags) in self.map.drain() { unsafe { el.set_selector_flags(flags); } } } } /// A list of SequentialTasks that get executed on Drop. pub struct SequentialTaskList<E>(Vec<SequentialTask<E>>) where E: TElement; impl<E> ops::Deref for SequentialTaskList<E> where E: TElement, { type Target = Vec<SequentialTask<E>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<E> ops::DerefMut for SequentialTaskList<E> where E: TElement, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<E> Drop for SequentialTaskList<E> where E: TElement, { fn drop(&mut self) { debug_assert_eq!(thread_state::get(), ThreadState::LAYOUT); for task in self.0.drain(..) { task.execute() } } } /// A helper type for stack limit checking. This assumes that stacks grow /// down, which is true for all non-ancient CPU architectures. pub struct StackLimitChecker { lower_limit: usize, } impl StackLimitChecker { /// Create a new limit checker, for this thread, allowing further use /// of up to |stack_size| bytes beyond (below) the current stack pointer. #[inline(never)] pub fn new(stack_size_limit: usize) -> Self { StackLimitChecker { lower_limit: StackLimitChecker::get_sp() - stack_size_limit, } } /// Checks whether the previously stored stack limit has now been exceeded. #[inline(never)] pub fn limit_exceeded(&self) -> bool { let curr_sp = StackLimitChecker::get_sp(); // Do some sanity-checking to ensure that our invariants hold, even in // the case where we've exceeded the soft limit. // // The correctness of depends on the assumption that no stack wraps // around the end of the address space. if cfg!(debug_assertions) { // Compute the actual bottom of the stack by subtracting our safety // margin from our soft limit. Note that this will be slightly below // the actual bottom of the stack, because there are a few initial // frames on the stack before we do the measurement that computes // the limit. let stack_bottom = self.lower_limit - STACK_SAFETY_MARGIN_KB * 1024; // The bottom of the stack should be below the current sp. If it // isn't, that means we've either waited too long to check the limit // and burned through our safety margin (in which case we probably // would have segfaulted by now), or we're using a limit computed for // a different thread. debug_assert!(stack_bottom < curr_sp); // Compute the distance between the current sp and the bottom of // the stack, and compare it against the current stack. It should be // no further from us than the total stack size. We allow some slop // to handle the fact that stack_bottom is a bit further than the // bottom of the stack, as discussed above. let distance_to_stack_bottom = curr_sp - stack_bottom; let max_allowable_distance = (STYLE_THREAD_STACK_SIZE_KB + 10) * 1024; debug_assert!(distance_to_stack_bottom <= max_allowable_distance); } // The actual bounds check. curr_sp <= self.lower_limit } // Technically, rustc can optimize this away, but shouldn't for now. // We should fix this once black_
pub timer: Timer, /// Flags controlling how we traverse the tree. pub traversal_flags: TraversalFlags,
random_line_split
context.rs
statistics about the style system. pub dump_style_statistics: bool, /// The minimum number of elements that must be traversed to trigger a dump /// of style statistics. pub style_statistics_threshold: usize, } #[cfg(feature = "gecko")] fn get_env_bool(name: &str) -> bool { use std::env; match env::var(name) { Ok(s) =>!s.is_empty(), Err(_) => false, } } const DEFAULT_STATISTICS_THRESHOLD: usize = 50; #[cfg(feature = "gecko")] fn get_env_usize(name: &str) -> Option<usize> { use std::env; env::var(name).ok().map(|s| { s.parse::<usize>() .expect("Couldn't parse environmental variable as usize") }) } impl Default for StyleSystemOptions { #[cfg(feature = "servo")] fn default() -> Self { use servo_config::opts; StyleSystemOptions { disable_style_sharing_cache: opts::get().disable_share_style_cache, dump_style_statistics: opts::get().style_sharing_stats, style_statistics_threshold: DEFAULT_STATISTICS_THRESHOLD, } } #[cfg(feature = "gecko")] fn default() -> Self { StyleSystemOptions { disable_style_sharing_cache: get_env_bool("DISABLE_STYLE_SHARING_CACHE"), dump_style_statistics: get_env_bool("DUMP_STYLE_STATISTICS"), style_statistics_threshold: get_env_usize("STYLE_STATISTICS_THRESHOLD") .unwrap_or(DEFAULT_STATISTICS_THRESHOLD), } } } impl StyleSystemOptions { #[cfg(feature = "servo")] /// On Gecko's nightly build? pub fn is_nightly(&self) -> bool { false } #[cfg(feature = "gecko")] /// On Gecko's nightly build? #[inline] pub fn is_nightly(&self) -> bool { structs::GECKO_IS_NIGHTLY } } /// A shared style context. /// /// There's exactly one of these during a given restyle traversal, and it's /// shared among the worker threads. pub struct SharedStyleContext<'a> { /// The CSS selector stylist. pub stylist: &'a Stylist, /// Whether visited styles are enabled. /// /// They may be disabled when Gecko's pref layout.css.visited_links_enabled /// is false, or when in private browsing mode. pub visited_styles_enabled: bool, /// Configuration options. pub options: StyleSystemOptions, /// Guards for pre-acquired locks pub guards: StylesheetGuards<'a>, /// The current timer for transitions and animations. This is needed to test /// them. pub timer: Timer, /// Flags controlling how we traverse the tree. pub traversal_flags: TraversalFlags, /// A map with our snapshots in order to handle restyle hints. pub snapshot_map: &'a SnapshotMap, /// The animations that are currently running. #[cfg(feature = "servo")] pub running_animations: Arc<RwLock<FxHashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. #[cfg(feature = "servo")] pub expired_animations: Arc<RwLock<FxHashMap<OpaqueNode, Vec<Animation>>>>, /// Paint worklets #[cfg(feature = "servo")] pub registered_speculative_painters: &'a RegisteredSpeculativePainters, /// Data needed to create the thread-local style context from the shared one. #[cfg(feature = "servo")] pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>, } impl<'a> SharedStyleContext<'a> { /// Return a suitable viewport size in order to be used for viewport units. pub fn viewport_size(&self) -> Size2D<Au> { self.stylist.device().au_viewport_size() } /// The device pixel ratio pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel> { self.stylist.device().device_pixel_ratio() } /// The quirks mode of the document. pub fn quirks_mode(&self) -> QuirksMode { self.stylist.quirks_mode() } } /// The structure holds various intermediate inputs that are eventually used by /// by the cascade. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Debug, Default)] pub struct CascadeInputs { /// The rule node representing the ordered list of rules matched for this /// node. pub rules: Option<StrongRuleNode>, /// The rule node representing the ordered list of rules matched for this /// node if visited, only computed if there's a relevant link for this /// element. A element's "relevant link" is the element being matched if it /// is a link or the nearest ancestor link. pub visited_rules: Option<StrongRuleNode>, } impl CascadeInputs { /// Construct inputs from previous cascade results, if any. pub fn new_from_style(style: &ComputedValues) -> Self { CascadeInputs { rules: style.rules.clone(), visited_rules: style.visited_style().and_then(|v| v.rules.clone()), } } } /// A list of cascade inputs for eagerly-cascaded pseudo-elements. /// The list is stored inline. #[derive(Debug)] pub struct EagerPseudoCascadeInputs(Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]>); // Manually implement `Clone` here because the derived impl of `Clone` for // array types assumes the value inside is `Copy`. impl Clone for EagerPseudoCascadeInputs { fn clone(&self) -> Self { if self.0.is_none() { return EagerPseudoCascadeInputs(None); } let self_inputs = self.0.as_ref().unwrap(); let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = self_inputs[i].clone(); } EagerPseudoCascadeInputs(Some(inputs)) } } impl EagerPseudoCascadeInputs { /// Construct inputs from previous cascade results, if any. fn new_from_style(styles: &EagerPseudoStyles) -> Self { EagerPseudoCascadeInputs(styles.as_optional_array().map(|styles| { let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = styles[i].as_ref().map(|s| CascadeInputs::new_from_style(s)); } inputs })) } /// Returns the list of rules, if they exist. pub fn into_array(self) -> Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]> { self.0 } } /// The cascade inputs associated with a node, including those for any /// pseudo-elements. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Debug)] pub struct ElementCascadeInputs { /// The element's cascade inputs. pub primary: CascadeInputs, /// A list of the inputs for the element's eagerly-cascaded pseudo-elements. pub pseudos: EagerPseudoCascadeInputs, } impl ElementCascadeInputs { /// Construct inputs from previous cascade results, if any. #[inline] pub fn new_from_element_data(data: &ElementData) -> Self { debug_assert!(data.has_styles()); ElementCascadeInputs { primary: CascadeInputs::new_from_style(data.styles.primary()), pseudos: EagerPseudoCascadeInputs::new_from_style(&data.styles.pseudos), } } } /// Statistics gathered during the traversal. We gather statistics on each /// thread and then combine them after the threads join via the Add /// implementation below. #[derive(AddAssign, Clone, Default)] pub struct PerThreadTraversalStatistics { /// The total number of elements traversed. pub elements_traversed: u32, /// The number of elements where has_styles() went from false to true. pub elements_styled: u32, /// The number of elements for which we performed selector matching. pub elements_matched: u32, /// The number of cache hits from the StyleSharingCache. pub styles_shared: u32, /// The number of styles reused via rule node comparison from the /// StyleSharingCache. pub styles_reused: u32, } /// Statistics gathered during the traversal plus some information from /// other sources including stylist. #[derive(Default)] pub struct TraversalStatistics { /// Aggregated statistics gathered during the traversal. pub aggregated: PerThreadTraversalStatistics, /// The number of selectors in the stylist. pub selectors: u32, /// The number of revalidation selectors. pub revalidation_selectors: u32, /// The number of state/attr dependencies in the dependency set. pub dependency_selectors: u32, /// The number of declarations in the stylist. pub declarations: u32, /// The number of times the stylist was rebuilt. pub stylist_rebuilds: u32, /// Time spent in the traversal, in milliseconds. pub traversal_time_ms: f64, /// Whether this was a parallel traversal. pub is_parallel: bool, /// Whether this is a "large" traversal. pub is_large: bool, } /// Format the statistics in a way that the performance test harness understands. /// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2 impl fmt::Display for TraversalStatistics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { debug_assert!( self.traversal_time_ms!= 0.0, "should have set traversal time" ); writeln!(f, "[PERF] perf block start")?; writeln!( f, "[PERF],traversal,{}", if self.is_parallel { "parallel" } else { "sequential" } )?; writeln!( f, "[PERF],elements_traversed,{}", self.aggregated.elements_traversed )?; writeln!( f, "[PERF],elements_styled,{}", self.aggregated.elements_styled )?; writeln!( f, "[PERF],elements_matched,{}", self.aggregated.elements_matched )?; writeln!(f, "[PERF],styles_shared,{}", self.aggregated.styles_shared)?; writeln!(f, "[PERF],styles_reused,{}", self.aggregated.styles_reused)?; writeln!(f, "[PERF],selectors,{}", self.selectors)?; writeln!( f, "[PERF],revalidation_selectors,{}", self.revalidation_selectors )?; writeln!( f, "[PERF],dependency_selectors,{}", self.dependency_selectors )?; writeln!(f, "[PERF],declarations,{}", self.declarations)?; writeln!(f, "[PERF],stylist_rebuilds,{}", self.stylist_rebuilds)?; writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms)?; writeln!(f, "[PERF] perf block end") } } impl TraversalStatistics { /// Generate complete traversal statistics. /// /// The traversal time is computed given the start time in seconds. pub fn new<E, D>( aggregated: PerThreadTraversalStatistics, traversal: &D, parallel: bool, start: f64, ) -> TraversalStatistics where E: TElement, D: DomTraversal<E>, { let threshold = traversal .shared_context() .options .style_statistics_threshold; let stylist = traversal.shared_context().stylist; let is_large = aggregated.elements_traversed as usize >= threshold; TraversalStatistics { aggregated, selectors: stylist.num_selectors() as u32, revalidation_selectors: stylist.num_revalidation_selectors() as u32, dependency_selectors: stylist.num_invalidations() as u32, declarations: stylist.num_declarations() as u32, stylist_rebuilds: stylist.num_rebuilds() as u32, traversal_time_ms: (time::precise_time_s() - start) * 1000.0, is_parallel: parallel, is_large, } } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask of /// UpdateAnimations which is a result of normal restyle. pub struct UpdateAnimationsTasks: u8 { /// Update CSS Animations. const CSS_ANIMATIONS = structs::UpdateAnimationsTasks_CSSAnimations; /// Update CSS Transitions. const CSS_TRANSITIONS = structs::UpdateAnimationsTasks_CSSTransitions; /// Update effect properties. const EFFECT_PROPERTIES = structs::UpdateAnimationsTasks_EffectProperties; /// Update animation cacade results for animations running on the compositor. const CASCADE_RESULTS = structs::UpdateAnimationsTasks_CascadeResults; /// Display property was changed from none. /// Script animations keep alive on display:none elements, so we need to trigger /// the second animation restyles for the script animations in the case where /// the display property was changed from 'none' to others. const DISPLAY_CHANGED_FROM_NONE = structs::UpdateAnimationsTasks_DisplayChangedFromNone; } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask as a result of /// animation-only restyle. pub struct PostAnimationTasks: u8 { /// Display property was changed from none in animation-only restyle so /// that we need to resolve styles for descendants in a subsequent /// normal restyle. const DISPLAY_CHANGED_FROM_NONE_FOR_SMIL = 0x01; } } /// A task to be run in sequential mode on the parent (non-worker) thread. This /// is used by the style system to queue up work which is not safe to do during /// the parallel traversal. pub enum SequentialTask<E: TElement> { /// Entry to avoid an unused type parameter error on servo. Unused(SendElement<E>), /// Performs one of a number of possible tasks related to updating /// animations based on the |tasks| field. These include updating CSS /// animations/transitions that changed as part of the non-animation style /// traversal, and updating the computed effect properties. #[cfg(feature = "gecko")] UpdateAnimations { /// The target element or pseudo-element. el: SendElement<E>, /// The before-change style for transitions. We use before-change style /// as the initial value of its Keyframe. Required if |tasks| includes /// CSSTransitions. before_change_style: Option<Arc<ComputedValues>>, /// The tasks which are performed in this SequentialTask. tasks: UpdateAnimationsTasks, }, /// Performs one of a number of possible tasks as a result of animation-only /// restyle. /// /// Currently we do only process for resolving descendant elements that were /// display:none subtree for SMIL animation. #[cfg(feature = "gecko")] PostAnimation { /// The target element. el: SendElement<E>, /// The tasks which are performed in this SequentialTask. tasks: PostAnimationTasks, }, } impl<E: TElement> SequentialTask<E> { /// Executes this task. pub fn execute(self) { use self::SequentialTask::*; debug_assert_eq!(thread_state::get(), ThreadState::LAYOUT); match self { Unused(_) => unreachable!(), #[cfg(feature = "gecko")] UpdateAnimations { el, before_change_style, tasks, } => { el.update_animations(before_change_style, tasks); }, #[cfg(feature = "gecko")] PostAnimation { el, tasks } => { el.process_post_animation(tasks); }, } } /// Creates a task to update various animation-related state on a given /// (pseudo-)element. #[cfg(feature = "gecko")] pub fn update_animations( el: E, before_change_style: Option<Arc<ComputedValues>>, tasks: UpdateAnimationsTasks, ) -> Self { use self::SequentialTask::*; UpdateAnimations { el: unsafe { SendElement::new(el) }, before_change_style, tasks, } } /// Creates a task to do post-process for a given element as a result of /// animation-only restyle. #[cfg(feature = "gecko")] pub fn process_post_animation(el: E, tasks: PostAnimationTasks) -> Self { use self::SequentialTask::*; PostAnimation { el: unsafe { SendElement::new(el) }, tasks, } } } type CacheItem<E> = (SendElement<E>, ElementSelectorFlags); /// Map from Elements to ElementSelectorFlags. Used to defer applying selector /// flags until after the traversal. pub struct SelectorFlagsMap<E: TElement> { /// The hashmap storing the flags to apply. map: FxHashMap<SendElement<E>, ElementSelectorFlags>, /// An LRU cache to avoid hashmap lookups, which can be slow if the map /// gets big. cache: LRUCache<[Entry<CacheItem<E>>; 4 + 1]>, } #[cfg(debug_assertions)] impl<E: TElement> Drop for SelectorFlagsMap<E> { fn drop(&mut self) { debug_assert!(self.map.is_empty()); } } impl<E: TElement> SelectorFlagsMap<E> { /// Creates a new empty SelectorFlagsMap. pub fn new() -> Self { SelectorFlagsMap { map: FxHashMap::default(), cache: LRUCache::default(), } } /// Inserts some flags into the map for a given element. pub fn insert_flags(&mut self, element: E, flags: ElementSelectorFlags) { let el = unsafe { SendElement::new(element) }; // Check the cache. If the flags have already been noted, we're done. if let Some(item) = self.cache.find(|x| x.0 == el) { if!item.1.contains(flags) { item.1.insert(flags); self.map.get_mut(&el).unwrap().insert(flags); } return; } let f = self.map.entry(el).or_insert(ElementSelectorFlags::empty()); *f |= flags; self.cache .insert((unsafe { SendElement::new(element) }, *f)) } /// Applies the flags. Must be called on the main thread. fn apply_flags(&mut self) { debug_assert_eq!(thread_state::get(), ThreadState::LAYOUT); self.cache.evict_all(); for (el, flags) in self.map.drain() { unsafe { el.set_selector_flags(flags); } } } } /// A list of SequentialTasks that get executed on Drop. pub struct SequentialTaskList<E>(Vec<SequentialTask<E>>) where E: TElement; impl<E> ops::Deref for SequentialTaskList<E> where E: TElement, { type Target = Vec<SequentialTask<E>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<E> ops::DerefMut for SequentialTaskList<E> where E: TElement, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<E> Drop for SequentialTaskList<E> where E: TElement, { fn drop(&mut self) { debug_assert_eq!(thread_state::get(), ThreadState::LAYOUT); for task in self.0.drain(..) { task.execute() } } } /// A helper type for stack limit checking. This assumes that stacks grow /// down, which is true for all non-ancient CPU architectures. pub struct StackLimitChecker { lower_limit: usize, } impl StackLimitChecker { /// Create a new limit checker, for this thread, allowing further use /// of up to |stack_size| bytes beyond (below) the current stack pointer. #[inline(never)] pub fn
(stack_size_limit: usize) -> Self { StackLimitChecker { lower_limit: StackLimitChecker::get_sp() - stack_size_limit, } } /// Checks whether the previously stored stack limit has now been exceeded. #[inline(never)] pub fn limit_exceeded(&self) -> bool { let curr_sp = StackLimitChecker::get_sp(); // Do some sanity-checking to ensure that our invariants hold, even in // the case where we've exceeded the soft limit. // // The correctness of depends on the assumption that no stack wraps // around the end of the address space. if cfg!(debug_assertions) { // Compute the actual bottom of the stack by subtracting our safety // margin from our soft limit. Note that this will be slightly below // the actual bottom of the stack, because there are a few initial // frames on the stack before we do the measurement that computes // the limit. let stack_bottom = self.lower_limit - STACK_SAFETY_MARGIN_KB * 1024; // The bottom of the stack should be below the current sp. If it // isn't, that means we've either waited too long to check the limit // and burned through our safety margin (in which case we probably // would have segfaulted by now), or we're using a limit computed for // a different thread. debug_assert!(stack_bottom < curr_sp); // Compute the distance between the current sp and the bottom of // the stack, and compare it against the current stack. It should be // no further from us than the total stack size. We allow some slop // to handle the fact that stack_bottom is a bit further than the // bottom of the stack, as discussed above. let distance_to_stack_bottom = curr_sp - stack_bottom; let max_allowable_distance = (STYLE_THREAD_STACK_SIZE_KB + 10) * 1024; debug_assert!(distance_to_stack_bottom <= max_allowable_distance); } // The actual bounds check. curr_sp <= self.lower_limit } // Technically, rustc can optimize this away, but shouldn't for now. // We should fix this once
new
identifier_name
context.rs
statistics about the style system. pub dump_style_statistics: bool, /// The minimum number of elements that must be traversed to trigger a dump /// of style statistics. pub style_statistics_threshold: usize, } #[cfg(feature = "gecko")] fn get_env_bool(name: &str) -> bool { use std::env; match env::var(name) { Ok(s) =>!s.is_empty(), Err(_) => false, } } const DEFAULT_STATISTICS_THRESHOLD: usize = 50; #[cfg(feature = "gecko")] fn get_env_usize(name: &str) -> Option<usize> { use std::env; env::var(name).ok().map(|s| { s.parse::<usize>() .expect("Couldn't parse environmental variable as usize") }) } impl Default for StyleSystemOptions { #[cfg(feature = "servo")] fn default() -> Self { use servo_config::opts; StyleSystemOptions { disable_style_sharing_cache: opts::get().disable_share_style_cache, dump_style_statistics: opts::get().style_sharing_stats, style_statistics_threshold: DEFAULT_STATISTICS_THRESHOLD, } } #[cfg(feature = "gecko")] fn default() -> Self { StyleSystemOptions { disable_style_sharing_cache: get_env_bool("DISABLE_STYLE_SHARING_CACHE"), dump_style_statistics: get_env_bool("DUMP_STYLE_STATISTICS"), style_statistics_threshold: get_env_usize("STYLE_STATISTICS_THRESHOLD") .unwrap_or(DEFAULT_STATISTICS_THRESHOLD), } } } impl StyleSystemOptions { #[cfg(feature = "servo")] /// On Gecko's nightly build? pub fn is_nightly(&self) -> bool { false } #[cfg(feature = "gecko")] /// On Gecko's nightly build? #[inline] pub fn is_nightly(&self) -> bool { structs::GECKO_IS_NIGHTLY } } /// A shared style context. /// /// There's exactly one of these during a given restyle traversal, and it's /// shared among the worker threads. pub struct SharedStyleContext<'a> { /// The CSS selector stylist. pub stylist: &'a Stylist, /// Whether visited styles are enabled. /// /// They may be disabled when Gecko's pref layout.css.visited_links_enabled /// is false, or when in private browsing mode. pub visited_styles_enabled: bool, /// Configuration options. pub options: StyleSystemOptions, /// Guards for pre-acquired locks pub guards: StylesheetGuards<'a>, /// The current timer for transitions and animations. This is needed to test /// them. pub timer: Timer, /// Flags controlling how we traverse the tree. pub traversal_flags: TraversalFlags, /// A map with our snapshots in order to handle restyle hints. pub snapshot_map: &'a SnapshotMap, /// The animations that are currently running. #[cfg(feature = "servo")] pub running_animations: Arc<RwLock<FxHashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. #[cfg(feature = "servo")] pub expired_animations: Arc<RwLock<FxHashMap<OpaqueNode, Vec<Animation>>>>, /// Paint worklets #[cfg(feature = "servo")] pub registered_speculative_painters: &'a RegisteredSpeculativePainters, /// Data needed to create the thread-local style context from the shared one. #[cfg(feature = "servo")] pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>, } impl<'a> SharedStyleContext<'a> { /// Return a suitable viewport size in order to be used for viewport units. pub fn viewport_size(&self) -> Size2D<Au> { self.stylist.device().au_viewport_size() } /// The device pixel ratio pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel> { self.stylist.device().device_pixel_ratio() } /// The quirks mode of the document. pub fn quirks_mode(&self) -> QuirksMode { self.stylist.quirks_mode() } } /// The structure holds various intermediate inputs that are eventually used by /// by the cascade. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Debug, Default)] pub struct CascadeInputs { /// The rule node representing the ordered list of rules matched for this /// node. pub rules: Option<StrongRuleNode>, /// The rule node representing the ordered list of rules matched for this /// node if visited, only computed if there's a relevant link for this /// element. A element's "relevant link" is the element being matched if it /// is a link or the nearest ancestor link. pub visited_rules: Option<StrongRuleNode>, } impl CascadeInputs { /// Construct inputs from previous cascade results, if any. pub fn new_from_style(style: &ComputedValues) -> Self { CascadeInputs { rules: style.rules.clone(), visited_rules: style.visited_style().and_then(|v| v.rules.clone()), } } } /// A list of cascade inputs for eagerly-cascaded pseudo-elements. /// The list is stored inline. #[derive(Debug)] pub struct EagerPseudoCascadeInputs(Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]>); // Manually implement `Clone` here because the derived impl of `Clone` for // array types assumes the value inside is `Copy`. impl Clone for EagerPseudoCascadeInputs { fn clone(&self) -> Self { if self.0.is_none() { return EagerPseudoCascadeInputs(None); } let self_inputs = self.0.as_ref().unwrap(); let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = self_inputs[i].clone(); } EagerPseudoCascadeInputs(Some(inputs)) } } impl EagerPseudoCascadeInputs { /// Construct inputs from previous cascade results, if any. fn new_from_style(styles: &EagerPseudoStyles) -> Self { EagerPseudoCascadeInputs(styles.as_optional_array().map(|styles| { let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = styles[i].as_ref().map(|s| CascadeInputs::new_from_style(s)); } inputs })) } /// Returns the list of rules, if they exist. pub fn into_array(self) -> Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]> { self.0 } } /// The cascade inputs associated with a node, including those for any /// pseudo-elements. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Debug)] pub struct ElementCascadeInputs { /// The element's cascade inputs. pub primary: CascadeInputs, /// A list of the inputs for the element's eagerly-cascaded pseudo-elements. pub pseudos: EagerPseudoCascadeInputs, } impl ElementCascadeInputs { /// Construct inputs from previous cascade results, if any. #[inline] pub fn new_from_element_data(data: &ElementData) -> Self { debug_assert!(data.has_styles()); ElementCascadeInputs { primary: CascadeInputs::new_from_style(data.styles.primary()), pseudos: EagerPseudoCascadeInputs::new_from_style(&data.styles.pseudos), } } } /// Statistics gathered during the traversal. We gather statistics on each /// thread and then combine them after the threads join via the Add /// implementation below. #[derive(AddAssign, Clone, Default)] pub struct PerThreadTraversalStatistics { /// The total number of elements traversed. pub elements_traversed: u32, /// The number of elements where has_styles() went from false to true. pub elements_styled: u32, /// The number of elements for which we performed selector matching. pub elements_matched: u32, /// The number of cache hits from the StyleSharingCache. pub styles_shared: u32, /// The number of styles reused via rule node comparison from the /// StyleSharingCache. pub styles_reused: u32, } /// Statistics gathered during the traversal plus some information from /// other sources including stylist. #[derive(Default)] pub struct TraversalStatistics { /// Aggregated statistics gathered during the traversal. pub aggregated: PerThreadTraversalStatistics, /// The number of selectors in the stylist. pub selectors: u32, /// The number of revalidation selectors. pub revalidation_selectors: u32, /// The number of state/attr dependencies in the dependency set. pub dependency_selectors: u32, /// The number of declarations in the stylist. pub declarations: u32, /// The number of times the stylist was rebuilt. pub stylist_rebuilds: u32, /// Time spent in the traversal, in milliseconds. pub traversal_time_ms: f64, /// Whether this was a parallel traversal. pub is_parallel: bool, /// Whether this is a "large" traversal. pub is_large: bool, } /// Format the statistics in a way that the performance test harness understands. /// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2 impl fmt::Display for TraversalStatistics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { debug_assert!( self.traversal_time_ms!= 0.0, "should have set traversal time" ); writeln!(f, "[PERF] perf block start")?; writeln!( f, "[PERF],traversal,{}", if self.is_parallel { "parallel" } else { "sequential" } )?; writeln!( f, "[PERF],elements_traversed,{}", self.aggregated.elements_traversed )?; writeln!( f, "[PERF],elements_styled,{}", self.aggregated.elements_styled )?; writeln!( f, "[PERF],elements_matched,{}", self.aggregated.elements_matched )?; writeln!(f, "[PERF],styles_shared,{}", self.aggregated.styles_shared)?; writeln!(f, "[PERF],styles_reused,{}", self.aggregated.styles_reused)?; writeln!(f, "[PERF],selectors,{}", self.selectors)?; writeln!( f, "[PERF],revalidation_selectors,{}", self.revalidation_selectors )?; writeln!( f, "[PERF],dependency_selectors,{}", self.dependency_selectors )?; writeln!(f, "[PERF],declarations,{}", self.declarations)?; writeln!(f, "[PERF],stylist_rebuilds,{}", self.stylist_rebuilds)?; writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms)?; writeln!(f, "[PERF] perf block end") } } impl TraversalStatistics { /// Generate complete traversal statistics. /// /// The traversal time is computed given the start time in seconds. pub fn new<E, D>( aggregated: PerThreadTraversalStatistics, traversal: &D, parallel: bool, start: f64, ) -> TraversalStatistics where E: TElement, D: DomTraversal<E>, { let threshold = traversal .shared_context() .options .style_statistics_threshold; let stylist = traversal.shared_context().stylist; let is_large = aggregated.elements_traversed as usize >= threshold; TraversalStatistics { aggregated, selectors: stylist.num_selectors() as u32, revalidation_selectors: stylist.num_revalidation_selectors() as u32, dependency_selectors: stylist.num_invalidations() as u32, declarations: stylist.num_declarations() as u32, stylist_rebuilds: stylist.num_rebuilds() as u32, traversal_time_ms: (time::precise_time_s() - start) * 1000.0, is_parallel: parallel, is_large, } } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask of /// UpdateAnimations which is a result of normal restyle. pub struct UpdateAnimationsTasks: u8 { /// Update CSS Animations. const CSS_ANIMATIONS = structs::UpdateAnimationsTasks_CSSAnimations; /// Update CSS Transitions. const CSS_TRANSITIONS = structs::UpdateAnimationsTasks_CSSTransitions; /// Update effect properties. const EFFECT_PROPERTIES = structs::UpdateAnimationsTasks_EffectProperties; /// Update animation cacade results for animations running on the compositor. const CASCADE_RESULTS = structs::UpdateAnimationsTasks_CascadeResults; /// Display property was changed from none. /// Script animations keep alive on display:none elements, so we need to trigger /// the second animation restyles for the script animations in the case where /// the display property was changed from 'none' to others. const DISPLAY_CHANGED_FROM_NONE = structs::UpdateAnimationsTasks_DisplayChangedFromNone; } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask as a result of /// animation-only restyle. pub struct PostAnimationTasks: u8 { /// Display property was changed from none in animation-only restyle so /// that we need to resolve styles for descendants in a subsequent /// normal restyle. const DISPLAY_CHANGED_FROM_NONE_FOR_SMIL = 0x01; } } /// A task to be run in sequential mode on the parent (non-worker) thread. This /// is used by the style system to queue up work which is not safe to do during /// the parallel traversal. pub enum SequentialTask<E: TElement> { /// Entry to avoid an unused type parameter error on servo. Unused(SendElement<E>), /// Performs one of a number of possible tasks related to updating /// animations based on the |tasks| field. These include updating CSS /// animations/transitions that changed as part of the non-animation style /// traversal, and updating the computed effect properties. #[cfg(feature = "gecko")] UpdateAnimations { /// The target element or pseudo-element. el: SendElement<E>, /// The before-change style for transitions. We use before-change style /// as the initial value of its Keyframe. Required if |tasks| includes /// CSSTransitions. before_change_style: Option<Arc<ComputedValues>>, /// The tasks which are performed in this SequentialTask. tasks: UpdateAnimationsTasks, }, /// Performs one of a number of possible tasks as a result of animation-only /// restyle. /// /// Currently we do only process for resolving descendant elements that were /// display:none subtree for SMIL animation. #[cfg(feature = "gecko")] PostAnimation { /// The target element. el: SendElement<E>, /// The tasks which are performed in this SequentialTask. tasks: PostAnimationTasks, }, } impl<E: TElement> SequentialTask<E> { /// Executes this task. pub fn execute(self) { use self::SequentialTask::*; debug_assert_eq!(thread_state::get(), ThreadState::LAYOUT); match self { Unused(_) => unreachable!(), #[cfg(feature = "gecko")] UpdateAnimations { el, before_change_style, tasks, } =>
, #[cfg(feature = "gecko")] PostAnimation { el, tasks } => { el.process_post_animation(tasks); }, } } /// Creates a task to update various animation-related state on a given /// (pseudo-)element. #[cfg(feature = "gecko")] pub fn update_animations( el: E, before_change_style: Option<Arc<ComputedValues>>, tasks: UpdateAnimationsTasks, ) -> Self { use self::SequentialTask::*; UpdateAnimations { el: unsafe { SendElement::new(el) }, before_change_style, tasks, } } /// Creates a task to do post-process for a given element as a result of /// animation-only restyle. #[cfg(feature = "gecko")] pub fn process_post_animation(el: E, tasks: PostAnimationTasks) -> Self { use self::SequentialTask::*; PostAnimation { el: unsafe { SendElement::new(el) }, tasks, } } } type CacheItem<E> = (SendElement<E>, ElementSelectorFlags); /// Map from Elements to ElementSelectorFlags. Used to defer applying selector /// flags until after the traversal. pub struct SelectorFlagsMap<E: TElement> { /// The hashmap storing the flags to apply. map: FxHashMap<SendElement<E>, ElementSelectorFlags>, /// An LRU cache to avoid hashmap lookups, which can be slow if the map /// gets big. cache: LRUCache<[Entry<CacheItem<E>>; 4 + 1]>, } #[cfg(debug_assertions)] impl<E: TElement> Drop for SelectorFlagsMap<E> { fn drop(&mut self) { debug_assert!(self.map.is_empty()); } } impl<E: TElement> SelectorFlagsMap<E> { /// Creates a new empty SelectorFlagsMap. pub fn new() -> Self { SelectorFlagsMap { map: FxHashMap::default(), cache: LRUCache::default(), } } /// Inserts some flags into the map for a given element. pub fn insert_flags(&mut self, element: E, flags: ElementSelectorFlags) { let el = unsafe { SendElement::new(element) }; // Check the cache. If the flags have already been noted, we're done. if let Some(item) = self.cache.find(|x| x.0 == el) { if!item.1.contains(flags) { item.1.insert(flags); self.map.get_mut(&el).unwrap().insert(flags); } return; } let f = self.map.entry(el).or_insert(ElementSelectorFlags::empty()); *f |= flags; self.cache .insert((unsafe { SendElement::new(element) }, *f)) } /// Applies the flags. Must be called on the main thread. fn apply_flags(&mut self) { debug_assert_eq!(thread_state::get(), ThreadState::LAYOUT); self.cache.evict_all(); for (el, flags) in self.map.drain() { unsafe { el.set_selector_flags(flags); } } } } /// A list of SequentialTasks that get executed on Drop. pub struct SequentialTaskList<E>(Vec<SequentialTask<E>>) where E: TElement; impl<E> ops::Deref for SequentialTaskList<E> where E: TElement, { type Target = Vec<SequentialTask<E>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<E> ops::DerefMut for SequentialTaskList<E> where E: TElement, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<E> Drop for SequentialTaskList<E> where E: TElement, { fn drop(&mut self) { debug_assert_eq!(thread_state::get(), ThreadState::LAYOUT); for task in self.0.drain(..) { task.execute() } } } /// A helper type for stack limit checking. This assumes that stacks grow /// down, which is true for all non-ancient CPU architectures. pub struct StackLimitChecker { lower_limit: usize, } impl StackLimitChecker { /// Create a new limit checker, for this thread, allowing further use /// of up to |stack_size| bytes beyond (below) the current stack pointer. #[inline(never)] pub fn new(stack_size_limit: usize) -> Self { StackLimitChecker { lower_limit: StackLimitChecker::get_sp() - stack_size_limit, } } /// Checks whether the previously stored stack limit has now been exceeded. #[inline(never)] pub fn limit_exceeded(&self) -> bool { let curr_sp = StackLimitChecker::get_sp(); // Do some sanity-checking to ensure that our invariants hold, even in // the case where we've exceeded the soft limit. // // The correctness of depends on the assumption that no stack wraps // around the end of the address space. if cfg!(debug_assertions) { // Compute the actual bottom of the stack by subtracting our safety // margin from our soft limit. Note that this will be slightly below // the actual bottom of the stack, because there are a few initial // frames on the stack before we do the measurement that computes // the limit. let stack_bottom = self.lower_limit - STACK_SAFETY_MARGIN_KB * 1024; // The bottom of the stack should be below the current sp. If it // isn't, that means we've either waited too long to check the limit // and burned through our safety margin (in which case we probably // would have segfaulted by now), or we're using a limit computed for // a different thread. debug_assert!(stack_bottom < curr_sp); // Compute the distance between the current sp and the bottom of // the stack, and compare it against the current stack. It should be // no further from us than the total stack size. We allow some slop // to handle the fact that stack_bottom is a bit further than the // bottom of the stack, as discussed above. let distance_to_stack_bottom = curr_sp - stack_bottom; let max_allowable_distance = (STYLE_THREAD_STACK_SIZE_KB + 10) * 1024; debug_assert!(distance_to_stack_bottom <= max_allowable_distance); } // The actual bounds check. curr_sp <= self.lower_limit } // Technically, rustc can optimize this away, but shouldn't for now. // We should fix this
{ el.update_animations(before_change_style, tasks); }
conditional_block
cards.rs
//! This module represents a basic, rule-agnostic 32-cards system. use rand::{thread_rng, IsaacRng, Rng, SeedableRng}; use std::num::Wrapping; use std::str::FromStr; use std::string::ToString; /// One of the four Suits: Heart, Spade, Diamond, Club. #[derive(PartialEq, Clone, Copy, Debug, Serialize, Deserialize)] #[repr(u32)] pub enum Suit { /// The suit of hearts. Heart = 1, /// The suit of spades. Spade = 1 << 8, /// The suit of diamonds. Diamond = 1 << 16, /// The suit of clubs. Club = 1 << 24, } impl Suit { /// Returns the suit corresponding to the number: /// /// * `0` -> Heart /// * `1` -> Spade /// * `2` -> Diamond /// * `3` -> Club /// /// # Panics /// /// If `n >= 4`. pub fn from_n(n: u32) -> Self { match n { 0 => Suit::Heart, 1 => Suit::Spade, 2 => Suit::Diamond, 3 => Suit::Club, other => panic!("bad suit number: {}", other), } } /// Returns a UTF-8 character representing the suit (♥, ♠, ♦ or ♣). pub fn to_string(self) -> String { match self { Suit::Heart => "♥", Suit::Spade => "♠", Suit::Diamond => "♦", Suit::Club => "♣", }.to_owned() } } impl FromStr for Suit { type Err = String; fn from_str(s: &str) -> Result<Self, String> { match s { "H" | "h" | "heart" | "Suit::Heart" | "Heart" => Ok(Suit::Heart), "C" | "c" | "club" | "Suit::Club" | "Club" => Ok(Suit::Club), "S" | "s" | "spade" | "Suit::Spade" | "Spade" => Ok(Suit::Spade), "D" | "d" | "diamond" | "Suit::Diamond" | "Diamond" => Ok(Suit::Diamond), _ => Err(format!("invalid suit: {}", s)), } } } /// Rank of a card in a suit. #[derive(PartialEq, Clone, Copy, Debug)] #[repr(u32)] pub enum Rank { /// 7 Rank7 = 1, /// 8 Rank8 = 1 << 1, /// 9 Rank9 = 1 << 2, /// Jack RankJ = 1 << 3, /// Queen RankQ = 1 << 4, /// King RankK = 1 << 5, /// 10 RankX = 1 << 6, /// Ace RankA = 1 << 7, } /// Bit RANK_MASK over all ranks. const RANK_MASK: u32 = 255; impl Rank { /// Returns the rank corresponding to the given number: /// /// * `0` -> 7 /// * `1` -> 8 /// * `2` -> 9 /// * `3` -> Jack /// * `4` -> Queen /// * `5` -> King /// * `6` -> 10 /// * `7` -> Ace /// /// # Panics /// /// If `n >= 8`. pub fn from_n(n: u32) -> Self { match n { 0 => Rank::Rank7, 1 => Rank::Rank8, 2 => Rank::Rank9, 3 => Rank::RankJ, 4 => Rank::RankQ, 5 => Rank::RankK, 6 => Rank::RankX, 7 => Rank::RankA, other => panic!("invalid rank number: {}", other), } } // Return the enum by its discriminant. fn from_discriminant(rank: u32) -> Self { match rank { 1 => Rank::Rank7, 2 => Rank::Rank8, 4 => Rank::Rank9, 8 => Rank::RankJ, 16 => Rank::RankQ, 32 => Rank::RankK, 64 => Rank::RankX, 128 => Rank::RankA, other => panic!("invalid rank discrimant: {}", other), } } /// Returns a character representing the given rank. pub fn to_string(self) -> String { match self { Rank::Rank7 => "7", Rank::Rank8 => "8", Rank::Rank9 => "9", Rank::RankJ => "J", Rank::RankQ => "Q", Rank::RankK => "K", Rank::RankX => "X", Rank::RankA => "A", }.to_owned() } } /// Represents a single card. #[derive(PartialEq, Clone, Copy, Debug, Serialize, Deserialize)] pub struct Card(u32); // TODO: Add card constants? (8 of heart, Queen of spades,...?) // (As associated constants when it's stable?) impl Card { /// Returns the card id (from 0 to 31). pub fn id(self) -> u32 { let mut i = 0; let Card(mut v) = self; while v!= 0 { i += 1; v >>= 1; } i - 1 } /// Returns the card corresponding to the given id. /// /// # Panics /// /// If `id >= 32` pub fn from_id(id: u32) -> Self { if id > 31 { panic!("invalid card id"); } Card(1 << id) } /// Returns the card's rank. pub fn rank(self) -> Rank { let suit = self.suit(); let Card(v) = self; Rank::from_discriminant(v / suit as u32) } /// Returns the card's suit. pub fn suit(self) -> Suit { let Card(n) = self; if n < Suit::Spade as u32 { Suit::Heart } else if n < Suit::Diamond as u32 { Suit::Spade } else if n < Suit::Club as u32 { Suit::Diamond } else { Suit::Club } } /// Returns a string representation of the card (ex: "7♦"). pub fn to_string(self) -> String { let r = self.rank(); let s = self.suit(); r.to_string() + &s.to_string() } /// Creates a card from the given suit and rank. pub fn new(suit: Suit, rank: Rank) -> Self { Card(suit as u32 * rank as u32) } } /// Represents an unordered set of cards. #[derive(PartialEq, Clone, Copy, Debug, Serialize, Deserialize, Default)] pub struct Hand(u32); impl Hand { /// Returns an empty hand. pub fn new() -> Self { Hand(0) } /// Add `card` to `self`. /// /// No effect if `self` already contains `card`. pub fn add(&mut self, card: Card) -> &mut Hand { self.0 |
`card` from `self`. /// /// No effect if `self` does not contains `card`. pub fn remove(&mut self, card: Card) { self.0 &=!card.0; } /// Remove all cards from `self`. pub fn clean(&mut self) { *self = Hand::new(); } /// Returns `true` if `self` contains `card`. pub fn has(self, card: Card) -> bool { (self.0 & card.0)!= 0 } /// Returns `true` if the hand contains any card of the given suit. pub fn has_any(self, suit: Suit) -> bool { (self.0 & (RANK_MASK * suit as u32))!= 0 } /// Returns `true` if `self` contains no card. pub fn is_empty(self) -> bool { self.0 == 0 } /// Returns a card from `self`. /// /// Returns an invalid card if `self` is empty. pub fn get_card(self) -> Card { if self.is_empty() { return Card(0); } let Hand(h) = self; // Finds the rightmost bit, shifted to the left by 1. // let n = 1 << (h.trailing_zeroes()); let n = Wrapping(h ^ (h - 1)) + Wrapping(1); if n.0 == 0 { // We got an overflow. This means the desired bit it the leftmost one. Card::from_id(31) } else { // We just need to shift it back. Card(n.0 >> 1) } } /// Returns the cards contained in `self` as a `Vec`. pub fn list(self) -> Vec<Card> { let mut cards = Vec::new(); let mut h = self; while!h.is_empty() { let c = h.get_card(); h.remove(c); cards.push(c); } cards } /// Returns the number of cards in `self`. pub fn size(self) -> usize { self.list().len() } } impl ToString for Hand { /// Returns a string representation of `self`. fn to_string(&self) -> String { let mut s = "[".to_owned(); for c in &(*self).list() { s += &c.to_string(); s += ","; } s + "]" } } /// A deck of cards. pub struct Deck { cards: Vec<Card>, } impl Default for Deck { fn default() -> Self { Deck::new() } } impl Deck { /// Returns a full, sorted deck of 32 cards. pub fn new() -> Self { let mut d = Deck { cards: Vec::with_capacity(32), }; for i in 0..32 { d.cards.push(Card::from_id(i)); } d } /// Shuffle this deck. pub fn shuffle(&mut self) { self.shuffle_from(thread_rng()); } /// Shuffle this deck with the given random seed. /// /// Result is determined by the seed. pub fn shuffle_seeded(&mut self, seed: [u8; 32]) { let rng = IsaacRng::from_seed(seed); self.shuffle_from(rng); } fn shuffle_from<RNG: Rng>(&mut self, mut rng: RNG) { rng.shuffle(&mut self.cards[..]); } /// Draw the top card from the deck. /// /// # Panics /// If `self` is empty. pub fn draw(&mut self) -> Card { self.cards.pop().expect("deck is empty") } /// Returns `true` if this deck is empty. pub fn is_empty(&self) -> bool { self.cards.is_empty() } /// Returns the number of cards left in this deck. pub fn len(&self) -> usize { self.cards.len() } /// Deal `n` cards to each hand. /// /// # Panics /// If `self.len() < 4 * n` pub fn deal_each(&mut self, hands: &mut [Hand; 4], n: usize) { if self.len() < 4 * n { panic!("Deck has too few cards!"); } for hand in hands.iter_mut() { for _ in 0..n { hand.add(self.draw()); } } } } impl ToString for Deck { fn to_string(&self) -> String { let mut s = "[".to_owned(); for c in &self.cards { s += &c.to_string(); s += ","; } s + "]" } } #[cfg(test)] mod tests { use super::*; #[test] fn test_cards() { for i in 0..32 { let card = Card::from_id(i); assert!(i == card.id()); } for s in 0..4 { let suit = Suit::from_n(s); for r in 0..8 { let rank = Rank::from_n(r); let card = Card::new(suit, rank); assert!(card.rank() == rank); assert!(card.suit() == suit); } } } #[test] fn test_hand() { let mut hand = Hand::new(); let cards: Vec<Card> = vec![ Card::new(Suit::Heart, Rank::Rank7), Card::new(Suit::Heart, Rank::Rank8), Card::new(Suit::Spade, Rank::Rank9), Card::new(Suit::Spade, Rank::RankJ), Card::new(Suit::Club, Rank::RankQ), Card::new(Suit::Club, Rank::RankK), Card::new(Suit::Diamond, Rank::RankX), Card::new(Suit::Diamond, Rank::RankA), ]; assert!(hand.is_empty()); for card in cards.iter() { assert!(!hand.has(*card)); hand.add(*card); assert!(hand.has(*card)); } assert!(hand.size() == cards.len()); for card in cards.iter() { assert!(hand.has(*card)); hand.remove(*card); assert!(!hand.has(*card)); } } #[test] fn test_deck() { let mut deck = Deck::new(); deck.shuffle(); assert!(deck.len() == 32); let mut count = [0; 32]; while!deck.is_empty() { let card = deck.draw(); count[card.id() as usize] += 1; } for c in count.iter() { assert!(*c == 1); } } } #[cfg(feature = "use_bench")] mod benchs { use deal_seeded_hands; use test::Bencher; #[bench] fn bench_deal(b: &mut Bencher) { let seed = &[1, 2, 3, 4, 5]; b.iter(|| { deal_seeded_hands(seed); }); } #[bench] fn bench_list_hand(b: &mut Bencher) { let seed = &[1, 2, 3, 4, 5]; let hands = deal_seeded_hands(seed); b.iter(|| { for hand in hands.iter() { hand.list().len(); } }); } #[bench] fn bench_del_add_check(b: &mut Bencher) { let seed = &[1, 2, 3, 4, 5]; let hands = deal_seeded_hands(seed); let cards: Vec<_> = hands.iter().map(|h| h.list()).collect(); b.iter(|| { let mut hands = hands.clone(); for (hand, cards) in hands.iter_mut().zip(cards.iter()) { for c in cards.iter() { hand.remove(*c); } } for (hand, cards) in hands.iter_mut().zip(cards.iter()) { for c in cards.iter() { hand.add(*c); } } for (hand, cards) in hands.iter_mut().zip(cards.iter()) { for c in cards.iter() { if!hand.has(*c) { panic!("Error!"); } } } }); } }
= card.0; self } /// Removes
identifier_body
cards.rs
//! This module represents a basic, rule-agnostic 32-cards system. use rand::{thread_rng, IsaacRng, Rng, SeedableRng}; use std::num::Wrapping; use std::str::FromStr; use std::string::ToString; /// One of the four Suits: Heart, Spade, Diamond, Club. #[derive(PartialEq, Clone, Copy, Debug, Serialize, Deserialize)] #[repr(u32)] pub enum Suit { /// The suit of hearts. Heart = 1, /// The suit of spades. Spade = 1 << 8, /// The suit of diamonds. Diamond = 1 << 16, /// The suit of clubs. Club = 1 << 24, } impl Suit { /// Returns the suit corresponding to the number: /// /// * `0` -> Heart /// * `1` -> Spade /// * `2` -> Diamond /// * `3` -> Club /// /// # Panics /// /// If `n >= 4`. pub fn from_n(n: u32) -> Self { match n { 0 => Suit::Heart, 1 => Suit::Spade, 2 => Suit::Diamond, 3 => Suit::Club, other => panic!("bad suit number: {}", other), } } /// Returns a UTF-8 character representing the suit (♥, ♠, ♦ or ♣). pub fn to_string(self) -> String { match self { Suit::Heart => "♥", Suit::Spade => "♠", Suit::Diamond => "♦", Suit::Club => "♣", }.to_owned() } } impl FromStr for Suit { type Err = String; fn from_str(s: &str) -> Result<Self, String> { match s { "H" | "h" | "heart" | "Suit::Heart" | "Heart" => Ok(Suit::Heart), "C" | "c" | "club" | "Suit::Club" | "Club" => Ok(Suit::Club), "S" | "s" | "spade" | "Suit::Spade" | "Spade" => Ok(Suit::Spade), "D" | "d" | "diamond" | "Suit::Diamond" | "Diamond" => Ok(Suit::Diamond), _ => Err(format!("invalid suit: {}", s)), } } } /// Rank of a card in a suit. #[derive(PartialEq, Clone, Copy, Debug)] #[repr(u32)] pub enum Rank { /// 7 Rank7 = 1, /// 8 Rank8 = 1 << 1, /// 9 Rank9 = 1 << 2, /// Jack RankJ = 1 << 3, /// Queen RankQ = 1 << 4, /// King RankK = 1 << 5, /// 10 RankX = 1 << 6, /// Ace RankA = 1 << 7, } /// Bit RANK_MASK over all ranks. const RANK_MASK: u32 = 255; impl Rank { /// Returns the rank corresponding to the given number: /// /// * `0` -> 7 /// * `1` -> 8 /// * `2` -> 9 /// * `3` -> Jack /// * `4` -> Queen /// * `5` -> King /// * `6` -> 10 /// * `7` -> Ace /// /// # Panics /// /// If `n >= 8`. pub fn from_n(n: u32) -> Self { match n { 0 => Rank::Rank7, 1 => Rank::Rank8, 2 => Rank::Rank9, 3 => Rank::RankJ, 4 => Rank::RankQ, 5 => Rank::RankK, 6 => Rank::RankX, 7 => Rank::RankA, other => panic!("invalid rank number: {}", other), } } // Return the enum by its discriminant. fn from_discriminant(rank: u32) -> Self { match rank { 1 => Rank::Rank7, 2 => Rank::Rank8, 4 => Rank::Rank9, 8 => Rank::RankJ, 16 => Rank::RankQ, 32 => Rank::RankK, 64 => Rank::RankX, 128 => Rank::RankA, other => panic!("invalid rank discrimant: {}", other), } } /// Returns a character representing the given rank. pub fn to_string(self) -> String { match self { Rank::Rank7 => "7", Rank::Rank8 => "8", Rank::Rank9 => "9", Rank::RankJ => "J", Rank::RankQ => "Q", Rank::RankK => "K", Rank::RankX => "X", Rank::RankA => "A", }.to_owned() } } /// Represents a single card. #[derive(PartialEq, Clone, Copy, Debug, Serialize, Deserialize)] pub struct Card(u32); // TODO: Add card constants? (8 of heart, Queen of spades,...?) // (As associated constants when it's stable?) impl Card { /// Returns the card id (from 0 to 31). pub fn id(self) -> u32 { let mut i = 0; let Card(mut v) = self; while v!= 0 { i += 1; v >>= 1; } i - 1 } /// Returns the card corresponding to the given id. /// /// # Panics /// /// If `id >= 32` pub fn from_id(id: u32) -> Self { if id > 31 { panic!("invalid card id"); } Card(1 << id) } /// Returns the card's rank. pub fn rank(self) -> Rank { let suit = self.suit(); let Card(v) = self; Rank::from_discriminant(v / suit as u32) } /// Returns the card's suit. pub fn suit(self) -> Suit { let Card(n) = self; if n < Suit::Spade as u32 { Suit::Heart } else if n < Suit::Diamond as u32 { Suit::Spade } else if n < Suit::Club as u32 { Suit::Diamond } else { Suit::Club } } /// Returns a string representation of the card (ex: "7♦"). pub fn to_string(self) -> String { let r = self.rank(); let s = self.suit(); r.to_string() + &s.to_string() } /// Creates a card from the given suit and rank. pub fn new(suit: Suit, rank: Rank) -> Self { Card(suit as u32 * rank as u32) } } /// Represents an unordered set of cards. #[derive(PartialEq, Clone, Copy, Debug, Serialize, Deserialize, Default)] pub struct Hand(u32); impl Hand { /// Returns an empty hand. pub fn new() -> Self { Hand(0) } /// Add `card` to `self`. /// /// No effect if `self` already contains `card`. pub fn add(&mut self, card: Card) -> &mut Hand { self.0 |= card.0; self } /// Removes `card` from `self`. /// /// No effect if `self` does not contains `card`. pub fn remove(&mut self, card: Card) { self.0 &=!card.0; } /// Remove all cards from `self`. pub fn clean(&mut self) { *self = Hand::new(); } /// Returns `true` if `self` contains `card`. pub fn has(self, card: Card) -> bool { (self.0 & card.0)!= 0 } /// Returns `true` if the hand contains any card of the given suit. pub fn has_any(self, suit: Suit) -> bool { (self.0 & (RANK_MASK * suit as u32))!= 0 } /// Returns `true` if `self` contains no card. pub fn is_empty(self) -> bool { self.0 == 0 } /// Returns a card from `self`. /// /// Returns an invalid card if `self` is empty. pub fn get_card(self) -> Card { if self.is_empty() { return Card(0); } let Hand(h) = self; // Finds the rightmost bit, shifted to the left by 1. // let n = 1 << (h.trailing_zeroes()); let n = Wrapping(h ^ (h - 1)) + Wrapping(1); if n.0 == 0 { // We got an overflow. This means the desired bit it the leftmost one. Card::from_id(31) } else { // We just need to shift it back. Card(n.0 >> 1) } } /// Returns the cards contained in `self` as a `Vec`. pub fn list(self) -> Vec<Card> { let mut cards = Vec::new(); let mut h = self; while!h.is_empty() { let c = h.get_card(); h.remove(c); cards.push(c); } cards } /// Returns the number of cards in `self`. pub fn size(self) -> usize { self.list().len() } } impl ToString for Hand { /// Returns a string representation of `self`. fn to_string(&self) -> String { let mut s = "[".to_owned(); for c in &(*self).list() { s += &c.to_string(); s += ","; } s + "]" } } /// A deck of cards. pub struct Deck { cards: Vec<Card>, } impl Default for Deck { fn default() -> Self { Deck::new() } } impl Deck { /// Returns a full, sorted deck of 32 cards. pub fn new() -> Self { let mut d = Deck { cards: Vec::with_capacity(32), }; for i in 0..32 { d.cards.push(Card::from_id(i)); } d } /// Shuffle this deck. pub fn shuffle(&mut self) { self.shuffle_from(thread_rng()); } /// Shuffle this deck with the given random seed. /// /// Result is determined by the seed. pub fn shuffle_seeded(&mut self, seed: [u8; 32]) { let rng = IsaacRng::from_seed(seed); self.shuffle_from(rng); } fn shuffle_from<RNG: Rng>(&mut self, mut rng: RNG) { rng.shuffle(&mut self.cards[..]); } /// Draw the top card from the deck. /// /// # Panics /// If `self` is empty. pub fn draw(&mut self) -> Card { self.cards.pop().expect("deck is empty") } /// Returns `true` if this deck is empty. pub fn is_empty(&self) -> bool { self.cards.is_empty() } /// Returns the number of cards left in this deck. pub fn len(&self) -> usize { self.cards.len() } /// Deal `n` cards to each hand. /// /// # Panics /// If `self.len() < 4 * n` pub fn deal_each(&mut self, hands: &mut [Hand; 4], n: usize) { if self.len() < 4 * n { panic!("Deck has too few cards!"); } for hand in hands.iter_mut() { for _ in 0..n { hand.add(self.draw()); }
} } impl ToString for Deck { fn to_string(&self) -> String { let mut s = "[".to_owned(); for c in &self.cards { s += &c.to_string(); s += ","; } s + "]" } } #[cfg(test)] mod tests { use super::*; #[test] fn test_cards() { for i in 0..32 { let card = Card::from_id(i); assert!(i == card.id()); } for s in 0..4 { let suit = Suit::from_n(s); for r in 0..8 { let rank = Rank::from_n(r); let card = Card::new(suit, rank); assert!(card.rank() == rank); assert!(card.suit() == suit); } } } #[test] fn test_hand() { let mut hand = Hand::new(); let cards: Vec<Card> = vec![ Card::new(Suit::Heart, Rank::Rank7), Card::new(Suit::Heart, Rank::Rank8), Card::new(Suit::Spade, Rank::Rank9), Card::new(Suit::Spade, Rank::RankJ), Card::new(Suit::Club, Rank::RankQ), Card::new(Suit::Club, Rank::RankK), Card::new(Suit::Diamond, Rank::RankX), Card::new(Suit::Diamond, Rank::RankA), ]; assert!(hand.is_empty()); for card in cards.iter() { assert!(!hand.has(*card)); hand.add(*card); assert!(hand.has(*card)); } assert!(hand.size() == cards.len()); for card in cards.iter() { assert!(hand.has(*card)); hand.remove(*card); assert!(!hand.has(*card)); } } #[test] fn test_deck() { let mut deck = Deck::new(); deck.shuffle(); assert!(deck.len() == 32); let mut count = [0; 32]; while!deck.is_empty() { let card = deck.draw(); count[card.id() as usize] += 1; } for c in count.iter() { assert!(*c == 1); } } } #[cfg(feature = "use_bench")] mod benchs { use deal_seeded_hands; use test::Bencher; #[bench] fn bench_deal(b: &mut Bencher) { let seed = &[1, 2, 3, 4, 5]; b.iter(|| { deal_seeded_hands(seed); }); } #[bench] fn bench_list_hand(b: &mut Bencher) { let seed = &[1, 2, 3, 4, 5]; let hands = deal_seeded_hands(seed); b.iter(|| { for hand in hands.iter() { hand.list().len(); } }); } #[bench] fn bench_del_add_check(b: &mut Bencher) { let seed = &[1, 2, 3, 4, 5]; let hands = deal_seeded_hands(seed); let cards: Vec<_> = hands.iter().map(|h| h.list()).collect(); b.iter(|| { let mut hands = hands.clone(); for (hand, cards) in hands.iter_mut().zip(cards.iter()) { for c in cards.iter() { hand.remove(*c); } } for (hand, cards) in hands.iter_mut().zip(cards.iter()) { for c in cards.iter() { hand.add(*c); } } for (hand, cards) in hands.iter_mut().zip(cards.iter()) { for c in cards.iter() { if!hand.has(*c) { panic!("Error!"); } } } }); } }
}
random_line_split
cards.rs
//! This module represents a basic, rule-agnostic 32-cards system. use rand::{thread_rng, IsaacRng, Rng, SeedableRng}; use std::num::Wrapping; use std::str::FromStr; use std::string::ToString; /// One of the four Suits: Heart, Spade, Diamond, Club. #[derive(PartialEq, Clone, Copy, Debug, Serialize, Deserialize)] #[repr(u32)] pub enum Suit { /// The suit of hearts. Heart = 1, /// The suit of spades. Spade = 1 << 8, /// The suit of diamonds. Diamond = 1 << 16, /// The suit of clubs. Club = 1 << 24, } impl Suit { /// Returns the suit corresponding to the number: /// /// * `0` -> Heart /// * `1` -> Spade /// * `2` -> Diamond /// * `3` -> Club /// /// # Panics /// /// If `n >= 4`. pub fn from_n(n: u32) -> Self { match n { 0 => Suit::Heart, 1 => Suit::Spade, 2 => Suit::Diamond, 3 => Suit::Club, other => panic!("bad suit number: {}", other), } } /// Returns a UTF-8 character representing the suit (♥, ♠, ♦ or ♣). pub fn to_string(self) -> String { match self { Suit::Heart => "♥", Suit::Spade => "♠", Suit::Diamond => "♦", Suit::Club => "♣", }.to_owned() } } impl FromStr for Suit { type Err = String; fn from_str(s: &str) -> Result<Self, String> { match s { "H" | "h" | "heart" | "Suit::Heart" | "Heart" => Ok(Suit::Heart), "C" | "c" | "club" | "Suit::Club" | "Club" => Ok(Suit::Club), "S" | "s" | "spade" | "Suit::Spade" | "Spade" => Ok(Suit::Spade), "D" | "d" | "diamond" | "Suit::Diamond" | "Diamond" => Ok(Suit::Diamond), _ => Err(format!("invalid suit: {}", s)), } } } /// Rank of a card in a suit. #[derive(PartialEq, Clone, Copy, Debug)] #[repr(u32)] pub enum Rank { /// 7 Rank7 = 1, /// 8 Rank8 = 1 << 1, /// 9 Rank9 = 1 << 2, /// Jack RankJ = 1 << 3, /// Queen RankQ = 1 << 4, /// King RankK = 1 << 5, /// 10 RankX = 1 << 6, /// Ace RankA = 1 << 7, } /// Bit RANK_MASK over all ranks. const RANK_MASK: u32 = 255; impl Rank { /// Returns the rank corresponding to the given number: /// /// * `0` -> 7 /// * `1` -> 8 /// * `2` -> 9 /// * `3` -> Jack /// * `4` -> Queen /// * `5` -> King /// * `6` -> 10 /// * `7` -> Ace /// /// # Panics /// /// If `n >= 8`. pub fn from_n(n: u32) -> Self { match n { 0 => Rank::Rank7, 1 => Rank::Rank8, 2 => Rank::Rank9, 3 => Rank::RankJ, 4 => Rank::RankQ, 5 => Rank::RankK, 6 => Rank::RankX, 7 => Rank::RankA, other => panic!("invalid rank number: {}", other), } } // Return the enum by its discriminant. fn from_discriminant(rank: u32) -> Self { match rank { 1 => Rank::Rank7, 2 => Rank::Rank8, 4 => Rank::Rank9, 8 => Rank::RankJ, 16 => Rank::RankQ, 32 => Rank::RankK, 64 => Rank::RankX, 128 => Rank::RankA, other => panic!("invalid rank discrimant: {}", other), } } /// Returns a character representing the given rank. pub fn to_string(self) -> String { match self { Rank::Rank7 => "7", Rank::Rank8 => "8", Rank::Rank9 => "9", Rank::RankJ => "J", Rank::RankQ => "Q", Rank::RankK => "K", Rank::RankX => "X", Rank::RankA => "A", }.to_owned() } } /// Represents a single card. #[derive(PartialEq, Clone, Copy, Debug, Serialize, Deserialize)] pub struct Card(u32); // TODO: Add card constants? (8 of heart, Queen of spades,...?) // (As associated constants when it's stable?) impl Card { /// Returns the card id (from 0 to 31). pub fn id(self) -> u32 { let mut i = 0; let Card(mut v) = self; while v!= 0 { i += 1; v >>= 1; } i - 1 } /// Returns the card corresponding to the given id. /// /// # Panics /// /// If `id >= 32` pub fn from_id(id: u32) -> Self { if id > 31 { panic!("invalid card id"); } Card(1 << id) } /// Returns the card's rank. pub fn rank(self) -> Rank { let suit = self.suit(); let Card(v) = self; Rank::from_discriminant(v / suit as u32) } /// Returns the card's suit. pub fn suit(self) -> Suit { let Card(n) = self; if n < Suit::Spade as u32 { Suit::Heart } else if n < Suit::Diamond as u32 { Suit::Spade } else if n < Suit::Club as u32 { Suit::Diamond } else { Suit::Club } } /// Returns a string representation of the card (ex: "7♦"). pub fn to_string(self) -> String { let r = self.rank(); let s = self.suit(); r.to_string() + &s.to_string() } /// Creates a card from the given suit and rank. pub fn new(suit: Suit, rank: Rank) -> Self { Card(suit as u32 * rank as u32) } } /// Represents an unordered set of cards. #[derive(PartialEq, Clone, Copy, Debug, Serialize, Deserialize, Default)] pub struct Hand(u32); impl Hand { /// Returns an empty hand. pub fn new() -> Self { Hand(0) } /// Add `card` to `self`. /// /// No effect if `self` already contains `card`. pub fn add(&mut self, card: Card) -> &mut Hand { self.0 |= card.0; self } /// Removes `card` from `self`. /// /// No effect if `self` does not contains `card`. pub fn remove(&mut self, card: Card) { self.0 &=!card.0; } /// Remove all cards from `self`. pub fn clean(&mut self) { *self = Hand::new(); } /// Returns `true` if `self` contains `card`. pub fn has(self, card: Card) -> bool { (self.0 & card.0)!= 0 } /// Returns `true` if the hand contains any card of the given suit. pub fn has_any(self, suit: Suit) -> bool { (self.0 & (RANK_MASK * suit as u32))!= 0 } /// Returns `true` if `self` contains no card. pub fn is_empty(self) -> bool { self.0 == 0 } /// Returns a card from `self`. /// /// Returns an invalid card if `self` is empty. pub fn get_card(self) -> Card { if self.is_empty() { return Card(0); } let Hand(h) = self; // Finds the rightmost bit, shifted to the left by 1. // let n = 1 << (h.trailing_zeroes()); let n = Wrapping(h ^ (h - 1)) + Wrapping(1); if n.0 == 0 { // We got an overflow. This means the desired bit it the leftmost one. Card::from_id(31) } else { // We just need to shift it back. Card(n.0 >> 1) } } /// Returns the cards contained in `self` as a `Vec`. pub fn list(self) -> Vec<Card> { let mut cards = Vec::new(); let mut h = self; while!h.is_empty() { let c = h.get_card(); h.remove(c); cards.push(c); } cards } /// Returns the number of cards in `self`. pub fn size(self) -> usize { self.list().len() } } impl ToString for Hand { /// Returns a string representation of `self`. fn to_string(&self) -
{ let mut s = "[".to_owned(); for c in &(*self).list() { s += &c.to_string(); s += ","; } s + "]" } } /// A deck of cards. pub struct Deck { cards: Vec<Card>, } impl Default for Deck { fn default() -> Self { Deck::new() } } impl Deck { /// Returns a full, sorted deck of 32 cards. pub fn new() -> Self { let mut d = Deck { cards: Vec::with_capacity(32), }; for i in 0..32 { d.cards.push(Card::from_id(i)); } d } /// Shuffle this deck. pub fn shuffle(&mut self) { self.shuffle_from(thread_rng()); } /// Shuffle this deck with the given random seed. /// /// Result is determined by the seed. pub fn shuffle_seeded(&mut self, seed: [u8; 32]) { let rng = IsaacRng::from_seed(seed); self.shuffle_from(rng); } fn shuffle_from<RNG: Rng>(&mut self, mut rng: RNG) { rng.shuffle(&mut self.cards[..]); } /// Draw the top card from the deck. /// /// # Panics /// If `self` is empty. pub fn draw(&mut self) -> Card { self.cards.pop().expect("deck is empty") } /// Returns `true` if this deck is empty. pub fn is_empty(&self) -> bool { self.cards.is_empty() } /// Returns the number of cards left in this deck. pub fn len(&self) -> usize { self.cards.len() } /// Deal `n` cards to each hand. /// /// # Panics /// If `self.len() < 4 * n` pub fn deal_each(&mut self, hands: &mut [Hand; 4], n: usize) { if self.len() < 4 * n { panic!("Deck has too few cards!"); } for hand in hands.iter_mut() { for _ in 0..n { hand.add(self.draw()); } } } } impl ToString for Deck { fn to_string(&self) -> String { let mut s = "[".to_owned(); for c in &self.cards { s += &c.to_string(); s += ","; } s + "]" } } #[cfg(test)] mod tests { use super::*; #[test] fn test_cards() { for i in 0..32 { let card = Card::from_id(i); assert!(i == card.id()); } for s in 0..4 { let suit = Suit::from_n(s); for r in 0..8 { let rank = Rank::from_n(r); let card = Card::new(suit, rank); assert!(card.rank() == rank); assert!(card.suit() == suit); } } } #[test] fn test_hand() { let mut hand = Hand::new(); let cards: Vec<Card> = vec![ Card::new(Suit::Heart, Rank::Rank7), Card::new(Suit::Heart, Rank::Rank8), Card::new(Suit::Spade, Rank::Rank9), Card::new(Suit::Spade, Rank::RankJ), Card::new(Suit::Club, Rank::RankQ), Card::new(Suit::Club, Rank::RankK), Card::new(Suit::Diamond, Rank::RankX), Card::new(Suit::Diamond, Rank::RankA), ]; assert!(hand.is_empty()); for card in cards.iter() { assert!(!hand.has(*card)); hand.add(*card); assert!(hand.has(*card)); } assert!(hand.size() == cards.len()); for card in cards.iter() { assert!(hand.has(*card)); hand.remove(*card); assert!(!hand.has(*card)); } } #[test] fn test_deck() { let mut deck = Deck::new(); deck.shuffle(); assert!(deck.len() == 32); let mut count = [0; 32]; while!deck.is_empty() { let card = deck.draw(); count[card.id() as usize] += 1; } for c in count.iter() { assert!(*c == 1); } } } #[cfg(feature = "use_bench")] mod benchs { use deal_seeded_hands; use test::Bencher; #[bench] fn bench_deal(b: &mut Bencher) { let seed = &[1, 2, 3, 4, 5]; b.iter(|| { deal_seeded_hands(seed); }); } #[bench] fn bench_list_hand(b: &mut Bencher) { let seed = &[1, 2, 3, 4, 5]; let hands = deal_seeded_hands(seed); b.iter(|| { for hand in hands.iter() { hand.list().len(); } }); } #[bench] fn bench_del_add_check(b: &mut Bencher) { let seed = &[1, 2, 3, 4, 5]; let hands = deal_seeded_hands(seed); let cards: Vec<_> = hands.iter().map(|h| h.list()).collect(); b.iter(|| { let mut hands = hands.clone(); for (hand, cards) in hands.iter_mut().zip(cards.iter()) { for c in cards.iter() { hand.remove(*c); } } for (hand, cards) in hands.iter_mut().zip(cards.iter()) { for c in cards.iter() { hand.add(*c); } } for (hand, cards) in hands.iter_mut().zip(cards.iter()) { for c in cards.iter() { if!hand.has(*c) { panic!("Error!"); } } } }); } }
> String
identifier_name
integration_tests.rs
use std::env; use std::process::Command; use std::str; pub fn bin_dir() -> String { let mut path = env::current_exe().unwrap(); path.pop(); if path.ends_with("deps") { path.pop(); } path.join("gb-rust-frontend").to_str().unwrap().to_string() } pub fn gekkio_test_rom(name: &str, timeout: usize) { let test_rom = "tests/gekkio/".to_owned() + name + ".gb"; let output = Command::new(bin_dir()) .args(&[&test_rom, "--headless", "--timeout", &timeout.to_string()]) .output() .unwrap(); // Gekkio's tests output this magin number on success, // a failure will be 42, 42, 42, 42, 42 assert_eq!( str::from_utf8(&output.stdout[..]).unwrap_or(""), "\u{3}\u{5}\u{8}\r\u{15}\"" ); } pub fn blargg_test_rom_with_address(name: &str, expected: &str, address: u16, timeout: usize) { let test_rom = "tests/blargg/".to_owned() + name + ".gb"; let output = Command::new(bin_dir()) .args(&[ &test_rom, "--headless", "--timeout", &timeout.to_string(), "--result", &format!("{:04X}", address), ]) .output() .unwrap(); assert_eq!(str::from_utf8(&output.stdout[..]).unwrap(), expected); } pub fn blargg_test_rom(name: &str, expected: &str, timeout: usize) { let test_rom = "tests/blargg/".to_owned() + name + ".gb"; let output = Command::new(bin_dir()) .args(&[&test_rom, "--headless", "--timeout", &timeout.to_string()]) .output() .unwrap(); assert_eq!(str::from_utf8(&output.stdout[..]).unwrap(), expected); } #[test] pub fn blargg_instr_timing() { blargg_test_rom("instr_timing", "instr_timing\n\n\nPassed\n", 1); } #[test] pub fn blargg_mem_timing_2() { blargg_test_rom_with_address( "mem_timing", "mem_timing\n\n01:ok 02:ok 03:ok \n\nPassed\n",
} #[test] pub fn blargg_cpu_instrs() { blargg_test_rom( "cpu_instrs", "cpu_instrs\n\n01:ok 02:ok 03:ok 04:ok 05:ok 06:ok 07:ok 08:ok \ 09:ok 10:ok 11:ok \n\nPassed all tests\n", 30, ); } #[test] pub fn blargg_halt_bug() { // TODO: blargg_test_rom_with_address( "halt_bug", "halt bug\n\nIE IF IF DE\n01 10 F1 0C04 \n01 00 E1 0C04 \n01 \ 01 E1 0C04 \n11 00 E1 0C04 \n11 10 F1 0C04 \n11 11 F1 0C04 \n\ E1 00 E1 0C04 \nE1 E0 E1 0C04 \nE1 E1 E1 0C04 \n2A6CE34B \n\ Failed\n", 0xA004, 2, ); } #[test] pub fn blargg_interrupt_time() { // TODO: blargg_test_rom_with_address( "interrupt_time", "interrupt time\n\n00 00 00 \n00 08 0D \n00 00 00 \n00 08 0D \n\ 7F8F4AAF \nFailed\n", 0xA004, 1, ); } #[test] pub fn blargg_dmg_sound() { // TODO: Fix test 9, 10, 12 failures blargg_test_rom_with_address( "dmg_sound", "dmg_sound\n\n01:ok 02:ok 03:ok 04:ok 05:ok 06:ok 07:ok 08:ok \ 09:01 10:01 11:ok 12:01 \n\nRun failed tests\nindividually for\nmore \ details.\n\nFailed #9\n", 0xA004, 30, ); } #[test] pub fn gekkio_acceptance_ei_sequence() { gekkio_test_rom("acceptance/ei_sequence", 1); } #[test] pub fn gekkio_acceptance_ei_timing() { gekkio_test_rom("acceptance/ei_timing", 1); } #[test] pub fn gekkio_acceptance_div_timing() { gekkio_test_rom("acceptance/div_timing", 1); } #[test] pub fn gekkio_acceptance_interrupts_ie_push() { gekkio_test_rom("acceptance/interrupts/ie_push", 1); } #[test] pub fn gekkio_acceptance_intr_timing() { gekkio_test_rom("acceptance/intr_timing", 1); } #[test] pub fn gekkio_acceptance_di_timing_gs() { gekkio_test_rom("acceptance/di_timing-GS", 1); }
0xA004, 2, );
random_line_split
integration_tests.rs
use std::env; use std::process::Command; use std::str; pub fn bin_dir() -> String { let mut path = env::current_exe().unwrap(); path.pop(); if path.ends_with("deps") { path.pop(); } path.join("gb-rust-frontend").to_str().unwrap().to_string() } pub fn gekkio_test_rom(name: &str, timeout: usize) { let test_rom = "tests/gekkio/".to_owned() + name + ".gb"; let output = Command::new(bin_dir()) .args(&[&test_rom, "--headless", "--timeout", &timeout.to_string()]) .output() .unwrap(); // Gekkio's tests output this magin number on success, // a failure will be 42, 42, 42, 42, 42 assert_eq!( str::from_utf8(&output.stdout[..]).unwrap_or(""), "\u{3}\u{5}\u{8}\r\u{15}\"" ); } pub fn blargg_test_rom_with_address(name: &str, expected: &str, address: u16, timeout: usize) { let test_rom = "tests/blargg/".to_owned() + name + ".gb"; let output = Command::new(bin_dir()) .args(&[ &test_rom, "--headless", "--timeout", &timeout.to_string(), "--result", &format!("{:04X}", address), ]) .output() .unwrap(); assert_eq!(str::from_utf8(&output.stdout[..]).unwrap(), expected); } pub fn blargg_test_rom(name: &str, expected: &str, timeout: usize) { let test_rom = "tests/blargg/".to_owned() + name + ".gb"; let output = Command::new(bin_dir()) .args(&[&test_rom, "--headless", "--timeout", &timeout.to_string()]) .output() .unwrap(); assert_eq!(str::from_utf8(&output.stdout[..]).unwrap(), expected); } #[test] pub fn blargg_instr_timing() { blargg_test_rom("instr_timing", "instr_timing\n\n\nPassed\n", 1); } #[test] pub fn
() { blargg_test_rom_with_address( "mem_timing", "mem_timing\n\n01:ok 02:ok 03:ok \n\nPassed\n", 0xA004, 2, ); } #[test] pub fn blargg_cpu_instrs() { blargg_test_rom( "cpu_instrs", "cpu_instrs\n\n01:ok 02:ok 03:ok 04:ok 05:ok 06:ok 07:ok 08:ok \ 09:ok 10:ok 11:ok \n\nPassed all tests\n", 30, ); } #[test] pub fn blargg_halt_bug() { // TODO: blargg_test_rom_with_address( "halt_bug", "halt bug\n\nIE IF IF DE\n01 10 F1 0C04 \n01 00 E1 0C04 \n01 \ 01 E1 0C04 \n11 00 E1 0C04 \n11 10 F1 0C04 \n11 11 F1 0C04 \n\ E1 00 E1 0C04 \nE1 E0 E1 0C04 \nE1 E1 E1 0C04 \n2A6CE34B \n\ Failed\n", 0xA004, 2, ); } #[test] pub fn blargg_interrupt_time() { // TODO: blargg_test_rom_with_address( "interrupt_time", "interrupt time\n\n00 00 00 \n00 08 0D \n00 00 00 \n00 08 0D \n\ 7F8F4AAF \nFailed\n", 0xA004, 1, ); } #[test] pub fn blargg_dmg_sound() { // TODO: Fix test 9, 10, 12 failures blargg_test_rom_with_address( "dmg_sound", "dmg_sound\n\n01:ok 02:ok 03:ok 04:ok 05:ok 06:ok 07:ok 08:ok \ 09:01 10:01 11:ok 12:01 \n\nRun failed tests\nindividually for\nmore \ details.\n\nFailed #9\n", 0xA004, 30, ); } #[test] pub fn gekkio_acceptance_ei_sequence() { gekkio_test_rom("acceptance/ei_sequence", 1); } #[test] pub fn gekkio_acceptance_ei_timing() { gekkio_test_rom("acceptance/ei_timing", 1); } #[test] pub fn gekkio_acceptance_div_timing() { gekkio_test_rom("acceptance/div_timing", 1); } #[test] pub fn gekkio_acceptance_interrupts_ie_push() { gekkio_test_rom("acceptance/interrupts/ie_push", 1); } #[test] pub fn gekkio_acceptance_intr_timing() { gekkio_test_rom("acceptance/intr_timing", 1); } #[test] pub fn gekkio_acceptance_di_timing_gs() { gekkio_test_rom("acceptance/di_timing-GS", 1); }
blargg_mem_timing_2
identifier_name
integration_tests.rs
use std::env; use std::process::Command; use std::str; pub fn bin_dir() -> String { let mut path = env::current_exe().unwrap(); path.pop(); if path.ends_with("deps")
path.join("gb-rust-frontend").to_str().unwrap().to_string() } pub fn gekkio_test_rom(name: &str, timeout: usize) { let test_rom = "tests/gekkio/".to_owned() + name + ".gb"; let output = Command::new(bin_dir()) .args(&[&test_rom, "--headless", "--timeout", &timeout.to_string()]) .output() .unwrap(); // Gekkio's tests output this magin number on success, // a failure will be 42, 42, 42, 42, 42 assert_eq!( str::from_utf8(&output.stdout[..]).unwrap_or(""), "\u{3}\u{5}\u{8}\r\u{15}\"" ); } pub fn blargg_test_rom_with_address(name: &str, expected: &str, address: u16, timeout: usize) { let test_rom = "tests/blargg/".to_owned() + name + ".gb"; let output = Command::new(bin_dir()) .args(&[ &test_rom, "--headless", "--timeout", &timeout.to_string(), "--result", &format!("{:04X}", address), ]) .output() .unwrap(); assert_eq!(str::from_utf8(&output.stdout[..]).unwrap(), expected); } pub fn blargg_test_rom(name: &str, expected: &str, timeout: usize) { let test_rom = "tests/blargg/".to_owned() + name + ".gb"; let output = Command::new(bin_dir()) .args(&[&test_rom, "--headless", "--timeout", &timeout.to_string()]) .output() .unwrap(); assert_eq!(str::from_utf8(&output.stdout[..]).unwrap(), expected); } #[test] pub fn blargg_instr_timing() { blargg_test_rom("instr_timing", "instr_timing\n\n\nPassed\n", 1); } #[test] pub fn blargg_mem_timing_2() { blargg_test_rom_with_address( "mem_timing", "mem_timing\n\n01:ok 02:ok 03:ok \n\nPassed\n", 0xA004, 2, ); } #[test] pub fn blargg_cpu_instrs() { blargg_test_rom( "cpu_instrs", "cpu_instrs\n\n01:ok 02:ok 03:ok 04:ok 05:ok 06:ok 07:ok 08:ok \ 09:ok 10:ok 11:ok \n\nPassed all tests\n", 30, ); } #[test] pub fn blargg_halt_bug() { // TODO: blargg_test_rom_with_address( "halt_bug", "halt bug\n\nIE IF IF DE\n01 10 F1 0C04 \n01 00 E1 0C04 \n01 \ 01 E1 0C04 \n11 00 E1 0C04 \n11 10 F1 0C04 \n11 11 F1 0C04 \n\ E1 00 E1 0C04 \nE1 E0 E1 0C04 \nE1 E1 E1 0C04 \n2A6CE34B \n\ Failed\n", 0xA004, 2, ); } #[test] pub fn blargg_interrupt_time() { // TODO: blargg_test_rom_with_address( "interrupt_time", "interrupt time\n\n00 00 00 \n00 08 0D \n00 00 00 \n00 08 0D \n\ 7F8F4AAF \nFailed\n", 0xA004, 1, ); } #[test] pub fn blargg_dmg_sound() { // TODO: Fix test 9, 10, 12 failures blargg_test_rom_with_address( "dmg_sound", "dmg_sound\n\n01:ok 02:ok 03:ok 04:ok 05:ok 06:ok 07:ok 08:ok \ 09:01 10:01 11:ok 12:01 \n\nRun failed tests\nindividually for\nmore \ details.\n\nFailed #9\n", 0xA004, 30, ); } #[test] pub fn gekkio_acceptance_ei_sequence() { gekkio_test_rom("acceptance/ei_sequence", 1); } #[test] pub fn gekkio_acceptance_ei_timing() { gekkio_test_rom("acceptance/ei_timing", 1); } #[test] pub fn gekkio_acceptance_div_timing() { gekkio_test_rom("acceptance/div_timing", 1); } #[test] pub fn gekkio_acceptance_interrupts_ie_push() { gekkio_test_rom("acceptance/interrupts/ie_push", 1); } #[test] pub fn gekkio_acceptance_intr_timing() { gekkio_test_rom("acceptance/intr_timing", 1); } #[test] pub fn gekkio_acceptance_di_timing_gs() { gekkio_test_rom("acceptance/di_timing-GS", 1); }
{ path.pop(); }
conditional_block
integration_tests.rs
use std::env; use std::process::Command; use std::str; pub fn bin_dir() -> String { let mut path = env::current_exe().unwrap(); path.pop(); if path.ends_with("deps") { path.pop(); } path.join("gb-rust-frontend").to_str().unwrap().to_string() } pub fn gekkio_test_rom(name: &str, timeout: usize) { let test_rom = "tests/gekkio/".to_owned() + name + ".gb"; let output = Command::new(bin_dir()) .args(&[&test_rom, "--headless", "--timeout", &timeout.to_string()]) .output() .unwrap(); // Gekkio's tests output this magin number on success, // a failure will be 42, 42, 42, 42, 42 assert_eq!( str::from_utf8(&output.stdout[..]).unwrap_or(""), "\u{3}\u{5}\u{8}\r\u{15}\"" ); } pub fn blargg_test_rom_with_address(name: &str, expected: &str, address: u16, timeout: usize) { let test_rom = "tests/blargg/".to_owned() + name + ".gb"; let output = Command::new(bin_dir()) .args(&[ &test_rom, "--headless", "--timeout", &timeout.to_string(), "--result", &format!("{:04X}", address), ]) .output() .unwrap(); assert_eq!(str::from_utf8(&output.stdout[..]).unwrap(), expected); } pub fn blargg_test_rom(name: &str, expected: &str, timeout: usize) { let test_rom = "tests/blargg/".to_owned() + name + ".gb"; let output = Command::new(bin_dir()) .args(&[&test_rom, "--headless", "--timeout", &timeout.to_string()]) .output() .unwrap(); assert_eq!(str::from_utf8(&output.stdout[..]).unwrap(), expected); } #[test] pub fn blargg_instr_timing() { blargg_test_rom("instr_timing", "instr_timing\n\n\nPassed\n", 1); } #[test] pub fn blargg_mem_timing_2() { blargg_test_rom_with_address( "mem_timing", "mem_timing\n\n01:ok 02:ok 03:ok \n\nPassed\n", 0xA004, 2, ); } #[test] pub fn blargg_cpu_instrs() { blargg_test_rom( "cpu_instrs", "cpu_instrs\n\n01:ok 02:ok 03:ok 04:ok 05:ok 06:ok 07:ok 08:ok \ 09:ok 10:ok 11:ok \n\nPassed all tests\n", 30, ); } #[test] pub fn blargg_halt_bug() { // TODO: blargg_test_rom_with_address( "halt_bug", "halt bug\n\nIE IF IF DE\n01 10 F1 0C04 \n01 00 E1 0C04 \n01 \ 01 E1 0C04 \n11 00 E1 0C04 \n11 10 F1 0C04 \n11 11 F1 0C04 \n\ E1 00 E1 0C04 \nE1 E0 E1 0C04 \nE1 E1 E1 0C04 \n2A6CE34B \n\ Failed\n", 0xA004, 2, ); } #[test] pub fn blargg_interrupt_time() { // TODO: blargg_test_rom_with_address( "interrupt_time", "interrupt time\n\n00 00 00 \n00 08 0D \n00 00 00 \n00 08 0D \n\ 7F8F4AAF \nFailed\n", 0xA004, 1, ); } #[test] pub fn blargg_dmg_sound() { // TODO: Fix test 9, 10, 12 failures blargg_test_rom_with_address( "dmg_sound", "dmg_sound\n\n01:ok 02:ok 03:ok 04:ok 05:ok 06:ok 07:ok 08:ok \ 09:01 10:01 11:ok 12:01 \n\nRun failed tests\nindividually for\nmore \ details.\n\nFailed #9\n", 0xA004, 30, ); } #[test] pub fn gekkio_acceptance_ei_sequence() { gekkio_test_rom("acceptance/ei_sequence", 1); } #[test] pub fn gekkio_acceptance_ei_timing() { gekkio_test_rom("acceptance/ei_timing", 1); } #[test] pub fn gekkio_acceptance_div_timing() { gekkio_test_rom("acceptance/div_timing", 1); } #[test] pub fn gekkio_acceptance_interrupts_ie_push() { gekkio_test_rom("acceptance/interrupts/ie_push", 1); } #[test] pub fn gekkio_acceptance_intr_timing() { gekkio_test_rom("acceptance/intr_timing", 1); } #[test] pub fn gekkio_acceptance_di_timing_gs()
{ gekkio_test_rom("acceptance/di_timing-GS", 1); }
identifier_body
check.rs
use std::error::Error; use std::fmt::{self, Debug, Display}; use futures::future::BoxFuture; use crate::client::Context; use crate::framework::standard::{Args, CommandOptions}; use crate::model::channel::Message; /// This type describes why a check has failed. /// /// **Note**: /// The bot-developer is supposed to process this `enum` as the framework is not. /// It solely serves as a way to inform a user about why a check /// has failed and for the developer to log given failure (e.g. bugs or statistics) /// occurring in [`Check`]s. #[derive(Clone, Debug)] #[non_exhaustive] pub enum Reason { /// No information on the failure. Unknown, /// Information dedicated to the user. User(String), /// Information purely for logging purposes. Log(String), /// Information for the user but also for logging purposes. UserAndLog { user: String, log: String }, } impl Error for Reason {} pub type CheckFunction = for<'fut> fn( &'fut Context, &'fut Message, &'fut mut Args, &'fut CommandOptions, ) -> BoxFuture<'fut, Result<(), Reason>>; /// A check can be part of a command or group and will be executed to /// determine whether a user is permitted to use related item. /// /// Additionally, a check may hold additional settings. pub struct Check { /// Name listed in help-system. pub name: &'static str, /// Function that will be executed. pub function: CheckFunction, /// Whether a check should be evaluated in the help-system. /// `false` will ignore check and won't fail execution. pub check_in_help: bool, /// Whether a check shall be listed in the help-system. /// `false` won't affect whether the check will be evaluated help, /// solely [`Self::check_in_help`] sets this. pub display_in_help: bool, } impl Debug for Check { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Check") .field("name", &self.name) .field("function", &"<fn>") .field("check_in_help", &self.check_in_help) .field("display_in_help", &self.display_in_help) .finish() } } impl Display for Reason { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Unknown => f.write_str("Unknown"), Self::User(reason) => write!(f, "User {}", reason), Self::Log(reason) => write!(f, "Log {}", reason), Self::UserAndLog { user, log, } => { write!(f, "UserAndLog {{user: {}, log: {}}}", user, log)
} impl PartialEq for Check { fn eq(&self, other: &Self) -> bool { self.name == other.name } }
}, } }
random_line_split
check.rs
use std::error::Error; use std::fmt::{self, Debug, Display}; use futures::future::BoxFuture; use crate::client::Context; use crate::framework::standard::{Args, CommandOptions}; use crate::model::channel::Message; /// This type describes why a check has failed. /// /// **Note**: /// The bot-developer is supposed to process this `enum` as the framework is not. /// It solely serves as a way to inform a user about why a check /// has failed and for the developer to log given failure (e.g. bugs or statistics) /// occurring in [`Check`]s. #[derive(Clone, Debug)] #[non_exhaustive] pub enum
{ /// No information on the failure. Unknown, /// Information dedicated to the user. User(String), /// Information purely for logging purposes. Log(String), /// Information for the user but also for logging purposes. UserAndLog { user: String, log: String }, } impl Error for Reason {} pub type CheckFunction = for<'fut> fn( &'fut Context, &'fut Message, &'fut mut Args, &'fut CommandOptions, ) -> BoxFuture<'fut, Result<(), Reason>>; /// A check can be part of a command or group and will be executed to /// determine whether a user is permitted to use related item. /// /// Additionally, a check may hold additional settings. pub struct Check { /// Name listed in help-system. pub name: &'static str, /// Function that will be executed. pub function: CheckFunction, /// Whether a check should be evaluated in the help-system. /// `false` will ignore check and won't fail execution. pub check_in_help: bool, /// Whether a check shall be listed in the help-system. /// `false` won't affect whether the check will be evaluated help, /// solely [`Self::check_in_help`] sets this. pub display_in_help: bool, } impl Debug for Check { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Check") .field("name", &self.name) .field("function", &"<fn>") .field("check_in_help", &self.check_in_help) .field("display_in_help", &self.display_in_help) .finish() } } impl Display for Reason { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Unknown => f.write_str("Unknown"), Self::User(reason) => write!(f, "User {}", reason), Self::Log(reason) => write!(f, "Log {}", reason), Self::UserAndLog { user, log, } => { write!(f, "UserAndLog {{user: {}, log: {}}}", user, log) }, } } } impl PartialEq for Check { fn eq(&self, other: &Self) -> bool { self.name == other.name } }
Reason
identifier_name
check.rs
use std::error::Error; use std::fmt::{self, Debug, Display}; use futures::future::BoxFuture; use crate::client::Context; use crate::framework::standard::{Args, CommandOptions}; use crate::model::channel::Message; /// This type describes why a check has failed. /// /// **Note**: /// The bot-developer is supposed to process this `enum` as the framework is not. /// It solely serves as a way to inform a user about why a check /// has failed and for the developer to log given failure (e.g. bugs or statistics) /// occurring in [`Check`]s. #[derive(Clone, Debug)] #[non_exhaustive] pub enum Reason { /// No information on the failure. Unknown, /// Information dedicated to the user. User(String), /// Information purely for logging purposes. Log(String), /// Information for the user but also for logging purposes. UserAndLog { user: String, log: String }, } impl Error for Reason {} pub type CheckFunction = for<'fut> fn( &'fut Context, &'fut Message, &'fut mut Args, &'fut CommandOptions, ) -> BoxFuture<'fut, Result<(), Reason>>; /// A check can be part of a command or group and will be executed to /// determine whether a user is permitted to use related item. /// /// Additionally, a check may hold additional settings. pub struct Check { /// Name listed in help-system. pub name: &'static str, /// Function that will be executed. pub function: CheckFunction, /// Whether a check should be evaluated in the help-system. /// `false` will ignore check and won't fail execution. pub check_in_help: bool, /// Whether a check shall be listed in the help-system. /// `false` won't affect whether the check will be evaluated help, /// solely [`Self::check_in_help`] sets this. pub display_in_help: bool, } impl Debug for Check { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Check") .field("name", &self.name) .field("function", &"<fn>") .field("check_in_help", &self.check_in_help) .field("display_in_help", &self.display_in_help) .finish() } } impl Display for Reason { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Unknown => f.write_str("Unknown"), Self::User(reason) => write!(f, "User {}", reason), Self::Log(reason) => write!(f, "Log {}", reason), Self::UserAndLog { user, log, } =>
, } } } impl PartialEq for Check { fn eq(&self, other: &Self) -> bool { self.name == other.name } }
{ write!(f, "UserAndLog {{user: {}, log: {}}}", user, log) }
conditional_block
blockdev.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/. // Code to handle a single block device. use std::fs::OpenOptions; use std::path::PathBuf; use chrono::{DateTime, TimeZone, Utc}; use devicemapper::{Device, Sectors}; use crate::engine::{BlockDev, BlockDevState, DevUuid, EngineEvent, MaybeDbusPath, PoolUuid}; use crate::stratis::StratisResult; use crate::engine::event::get_engine_listener_list; use crate::engine::strat_engine::serde_structs::{BaseBlockDevSave, Recordable}; use crate::engine::strat_engine::backstore::metadata::BDA; use crate::engine::strat_engine::backstore::range_alloc::RangeAllocator;
#[derive(Debug)] pub struct StratBlockDev { dev: Device, pub(super) devnode: PathBuf, bda: BDA, used: RangeAllocator, user_info: Option<String>, hardware_info: Option<String>, dbus_path: MaybeDbusPath, } impl StratBlockDev { /// Make a new BlockDev from the parameters. /// Allocate space for the Stratis metadata on the device. /// - dev: the device, identified by number /// - devnode: the device node /// - bda: the device's BDA /// - other_segments: segments claimed for non-Stratis metadata use /// - user_info: user settable identifying information /// - hardware_info: identifying information in the hardware /// Returns an error if it is impossible to allocate all segments on the /// device. /// NOTE: It is possible that the actual device size is greater than /// the recorded device size. In that case, the additional space available /// on the device is simply invisible to the blockdev. Consequently, it /// is invisible to the engine, and is not part of the total size value /// reported on the D-Bus. #[allow(clippy::new_ret_no_self)] pub fn new( dev: Device, devnode: PathBuf, bda: BDA, upper_segments: &[(Sectors, Sectors)], user_info: Option<String>, hardware_info: Option<String>, ) -> StratisResult<StratBlockDev> { let mut segments = vec![(Sectors(0), bda.size())]; segments.extend(upper_segments); let allocator = RangeAllocator::new(bda.dev_size(), &segments)?; Ok(StratBlockDev { dev, devnode, bda, used: allocator, user_info, hardware_info, dbus_path: MaybeDbusPath(None), }) } /// Returns the blockdev's Device pub fn device(&self) -> &Device { &self.dev } pub fn wipe_metadata(&self) -> StratisResult<()> { let mut f = OpenOptions::new().write(true).open(&self.devnode)?; BDA::wipe(&mut f) } pub fn save_state(&mut self, time: &DateTime<Utc>, metadata: &[u8]) -> StratisResult<()> { let mut f = OpenOptions::new().write(true).open(&self.devnode)?; self.bda.save_state(time, metadata, &mut f) } /// The device's UUID. pub fn uuid(&self) -> DevUuid { self.bda.dev_uuid() } /// The device's pool's UUID. #[allow(dead_code)] pub fn pool_uuid(&self) -> PoolUuid { self.bda.pool_uuid() } /// Last time metadata was written to this device. #[allow(dead_code)] pub fn last_update_time(&self) -> Option<&DateTime<Utc>> { self.bda.last_update_time() } /// Find some sector ranges that could be allocated. If more /// sectors are needed than are available, return partial results. /// If all sectors are desired, use available() method to get all. pub fn request_space(&mut self, size: Sectors) -> (Sectors, Vec<(Sectors, Sectors)>) { let prev_state = self.state(); let result = self.used.request(size); if result.0 > Sectors(0) && prev_state!= BlockDevState::InUse { get_engine_listener_list().notify(&EngineEvent::BlockdevStateChanged { dbus_path: self.get_dbus_path(), state: BlockDevState::InUse, }); } result } // ALL SIZE METHODS (except size(), which is in BlockDev impl.) /// The number of Sectors on this device used by Stratis for metadata pub fn metadata_size(&self) -> Sectors { self.bda.size() } /// The number of Sectors on this device not allocated for any purpose. /// self.size() - self.metadata_size() >= self.available() pub fn available(&self) -> Sectors { self.used.available() } /// The maximum size of variable length metadata that can be accommodated. /// self.max_metadata_size() < self.metadata_size() pub fn max_metadata_size(&self) -> Sectors { self.bda.max_data_size() } /// Set the user info on this blockdev. /// The user_info may be None, which unsets user info. /// Returns true if the user info was changed, otherwise false. pub fn set_user_info(&mut self, user_info: Option<&str>) -> bool { set_blockdev_user_info!(self; user_info) } } impl BlockDev for StratBlockDev { fn devnode(&self) -> PathBuf { self.devnode.clone() } fn user_info(&self) -> Option<&str> { self.user_info.as_ref().map(|x| &**x) } fn hardware_info(&self) -> Option<&str> { self.hardware_info.as_ref().map(|x| &**x) } fn initialization_time(&self) -> DateTime<Utc> { // This cast will result in an incorrect, negative value starting in // the year 292,277,026,596. :-) Utc.timestamp(self.bda.initialization_time() as i64, 0) } fn size(&self) -> Sectors { let size = self.used.size(); assert_eq!(self.bda.dev_size(), size); size } fn state(&self) -> BlockDevState { // TODO: Implement support for other BlockDevStates if self.used.used() > self.bda.size() { BlockDevState::InUse } else { BlockDevState::NotInUse } } fn set_dbus_path(&mut self, path: MaybeDbusPath) { self.dbus_path = path } fn get_dbus_path(&self) -> &MaybeDbusPath { &self.dbus_path } } impl Recordable<BaseBlockDevSave> for StratBlockDev { fn record(&self) -> BaseBlockDevSave { BaseBlockDevSave { uuid: self.uuid(), user_info: self.user_info.clone(), hardware_info: self.hardware_info.clone(), } } }
random_line_split
blockdev.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/. // Code to handle a single block device. use std::fs::OpenOptions; use std::path::PathBuf; use chrono::{DateTime, TimeZone, Utc}; use devicemapper::{Device, Sectors}; use crate::engine::{BlockDev, BlockDevState, DevUuid, EngineEvent, MaybeDbusPath, PoolUuid}; use crate::stratis::StratisResult; use crate::engine::event::get_engine_listener_list; use crate::engine::strat_engine::serde_structs::{BaseBlockDevSave, Recordable}; use crate::engine::strat_engine::backstore::metadata::BDA; use crate::engine::strat_engine::backstore::range_alloc::RangeAllocator; #[derive(Debug)] pub struct StratBlockDev { dev: Device, pub(super) devnode: PathBuf, bda: BDA, used: RangeAllocator, user_info: Option<String>, hardware_info: Option<String>, dbus_path: MaybeDbusPath, } impl StratBlockDev { /// Make a new BlockDev from the parameters. /// Allocate space for the Stratis metadata on the device. /// - dev: the device, identified by number /// - devnode: the device node /// - bda: the device's BDA /// - other_segments: segments claimed for non-Stratis metadata use /// - user_info: user settable identifying information /// - hardware_info: identifying information in the hardware /// Returns an error if it is impossible to allocate all segments on the /// device. /// NOTE: It is possible that the actual device size is greater than /// the recorded device size. In that case, the additional space available /// on the device is simply invisible to the blockdev. Consequently, it /// is invisible to the engine, and is not part of the total size value /// reported on the D-Bus. #[allow(clippy::new_ret_no_self)] pub fn new( dev: Device, devnode: PathBuf, bda: BDA, upper_segments: &[(Sectors, Sectors)], user_info: Option<String>, hardware_info: Option<String>, ) -> StratisResult<StratBlockDev> { let mut segments = vec![(Sectors(0), bda.size())]; segments.extend(upper_segments); let allocator = RangeAllocator::new(bda.dev_size(), &segments)?; Ok(StratBlockDev { dev, devnode, bda, used: allocator, user_info, hardware_info, dbus_path: MaybeDbusPath(None), }) } /// Returns the blockdev's Device pub fn device(&self) -> &Device { &self.dev } pub fn wipe_metadata(&self) -> StratisResult<()> { let mut f = OpenOptions::new().write(true).open(&self.devnode)?; BDA::wipe(&mut f) } pub fn save_state(&mut self, time: &DateTime<Utc>, metadata: &[u8]) -> StratisResult<()> { let mut f = OpenOptions::new().write(true).open(&self.devnode)?; self.bda.save_state(time, metadata, &mut f) } /// The device's UUID. pub fn uuid(&self) -> DevUuid
/// The device's pool's UUID. #[allow(dead_code)] pub fn pool_uuid(&self) -> PoolUuid { self.bda.pool_uuid() } /// Last time metadata was written to this device. #[allow(dead_code)] pub fn last_update_time(&self) -> Option<&DateTime<Utc>> { self.bda.last_update_time() } /// Find some sector ranges that could be allocated. If more /// sectors are needed than are available, return partial results. /// If all sectors are desired, use available() method to get all. pub fn request_space(&mut self, size: Sectors) -> (Sectors, Vec<(Sectors, Sectors)>) { let prev_state = self.state(); let result = self.used.request(size); if result.0 > Sectors(0) && prev_state!= BlockDevState::InUse { get_engine_listener_list().notify(&EngineEvent::BlockdevStateChanged { dbus_path: self.get_dbus_path(), state: BlockDevState::InUse, }); } result } // ALL SIZE METHODS (except size(), which is in BlockDev impl.) /// The number of Sectors on this device used by Stratis for metadata pub fn metadata_size(&self) -> Sectors { self.bda.size() } /// The number of Sectors on this device not allocated for any purpose. /// self.size() - self.metadata_size() >= self.available() pub fn available(&self) -> Sectors { self.used.available() } /// The maximum size of variable length metadata that can be accommodated. /// self.max_metadata_size() < self.metadata_size() pub fn max_metadata_size(&self) -> Sectors { self.bda.max_data_size() } /// Set the user info on this blockdev. /// The user_info may be None, which unsets user info. /// Returns true if the user info was changed, otherwise false. pub fn set_user_info(&mut self, user_info: Option<&str>) -> bool { set_blockdev_user_info!(self; user_info) } } impl BlockDev for StratBlockDev { fn devnode(&self) -> PathBuf { self.devnode.clone() } fn user_info(&self) -> Option<&str> { self.user_info.as_ref().map(|x| &**x) } fn hardware_info(&self) -> Option<&str> { self.hardware_info.as_ref().map(|x| &**x) } fn initialization_time(&self) -> DateTime<Utc> { // This cast will result in an incorrect, negative value starting in // the year 292,277,026,596. :-) Utc.timestamp(self.bda.initialization_time() as i64, 0) } fn size(&self) -> Sectors { let size = self.used.size(); assert_eq!(self.bda.dev_size(), size); size } fn state(&self) -> BlockDevState { // TODO: Implement support for other BlockDevStates if self.used.used() > self.bda.size() { BlockDevState::InUse } else { BlockDevState::NotInUse } } fn set_dbus_path(&mut self, path: MaybeDbusPath) { self.dbus_path = path } fn get_dbus_path(&self) -> &MaybeDbusPath { &self.dbus_path } } impl Recordable<BaseBlockDevSave> for StratBlockDev { fn record(&self) -> BaseBlockDevSave { BaseBlockDevSave { uuid: self.uuid(), user_info: self.user_info.clone(), hardware_info: self.hardware_info.clone(), } } }
{ self.bda.dev_uuid() }
identifier_body
blockdev.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/. // Code to handle a single block device. use std::fs::OpenOptions; use std::path::PathBuf; use chrono::{DateTime, TimeZone, Utc}; use devicemapper::{Device, Sectors}; use crate::engine::{BlockDev, BlockDevState, DevUuid, EngineEvent, MaybeDbusPath, PoolUuid}; use crate::stratis::StratisResult; use crate::engine::event::get_engine_listener_list; use crate::engine::strat_engine::serde_structs::{BaseBlockDevSave, Recordable}; use crate::engine::strat_engine::backstore::metadata::BDA; use crate::engine::strat_engine::backstore::range_alloc::RangeAllocator; #[derive(Debug)] pub struct StratBlockDev { dev: Device, pub(super) devnode: PathBuf, bda: BDA, used: RangeAllocator, user_info: Option<String>, hardware_info: Option<String>, dbus_path: MaybeDbusPath, } impl StratBlockDev { /// Make a new BlockDev from the parameters. /// Allocate space for the Stratis metadata on the device. /// - dev: the device, identified by number /// - devnode: the device node /// - bda: the device's BDA /// - other_segments: segments claimed for non-Stratis metadata use /// - user_info: user settable identifying information /// - hardware_info: identifying information in the hardware /// Returns an error if it is impossible to allocate all segments on the /// device. /// NOTE: It is possible that the actual device size is greater than /// the recorded device size. In that case, the additional space available /// on the device is simply invisible to the blockdev. Consequently, it /// is invisible to the engine, and is not part of the total size value /// reported on the D-Bus. #[allow(clippy::new_ret_no_self)] pub fn new( dev: Device, devnode: PathBuf, bda: BDA, upper_segments: &[(Sectors, Sectors)], user_info: Option<String>, hardware_info: Option<String>, ) -> StratisResult<StratBlockDev> { let mut segments = vec![(Sectors(0), bda.size())]; segments.extend(upper_segments); let allocator = RangeAllocator::new(bda.dev_size(), &segments)?; Ok(StratBlockDev { dev, devnode, bda, used: allocator, user_info, hardware_info, dbus_path: MaybeDbusPath(None), }) } /// Returns the blockdev's Device pub fn device(&self) -> &Device { &self.dev } pub fn wipe_metadata(&self) -> StratisResult<()> { let mut f = OpenOptions::new().write(true).open(&self.devnode)?; BDA::wipe(&mut f) } pub fn save_state(&mut self, time: &DateTime<Utc>, metadata: &[u8]) -> StratisResult<()> { let mut f = OpenOptions::new().write(true).open(&self.devnode)?; self.bda.save_state(time, metadata, &mut f) } /// The device's UUID. pub fn uuid(&self) -> DevUuid { self.bda.dev_uuid() } /// The device's pool's UUID. #[allow(dead_code)] pub fn pool_uuid(&self) -> PoolUuid { self.bda.pool_uuid() } /// Last time metadata was written to this device. #[allow(dead_code)] pub fn last_update_time(&self) -> Option<&DateTime<Utc>> { self.bda.last_update_time() } /// Find some sector ranges that could be allocated. If more /// sectors are needed than are available, return partial results. /// If all sectors are desired, use available() method to get all. pub fn request_space(&mut self, size: Sectors) -> (Sectors, Vec<(Sectors, Sectors)>) { let prev_state = self.state(); let result = self.used.request(size); if result.0 > Sectors(0) && prev_state!= BlockDevState::InUse { get_engine_listener_list().notify(&EngineEvent::BlockdevStateChanged { dbus_path: self.get_dbus_path(), state: BlockDevState::InUse, }); } result } // ALL SIZE METHODS (except size(), which is in BlockDev impl.) /// The number of Sectors on this device used by Stratis for metadata pub fn metadata_size(&self) -> Sectors { self.bda.size() } /// The number of Sectors on this device not allocated for any purpose. /// self.size() - self.metadata_size() >= self.available() pub fn
(&self) -> Sectors { self.used.available() } /// The maximum size of variable length metadata that can be accommodated. /// self.max_metadata_size() < self.metadata_size() pub fn max_metadata_size(&self) -> Sectors { self.bda.max_data_size() } /// Set the user info on this blockdev. /// The user_info may be None, which unsets user info. /// Returns true if the user info was changed, otherwise false. pub fn set_user_info(&mut self, user_info: Option<&str>) -> bool { set_blockdev_user_info!(self; user_info) } } impl BlockDev for StratBlockDev { fn devnode(&self) -> PathBuf { self.devnode.clone() } fn user_info(&self) -> Option<&str> { self.user_info.as_ref().map(|x| &**x) } fn hardware_info(&self) -> Option<&str> { self.hardware_info.as_ref().map(|x| &**x) } fn initialization_time(&self) -> DateTime<Utc> { // This cast will result in an incorrect, negative value starting in // the year 292,277,026,596. :-) Utc.timestamp(self.bda.initialization_time() as i64, 0) } fn size(&self) -> Sectors { let size = self.used.size(); assert_eq!(self.bda.dev_size(), size); size } fn state(&self) -> BlockDevState { // TODO: Implement support for other BlockDevStates if self.used.used() > self.bda.size() { BlockDevState::InUse } else { BlockDevState::NotInUse } } fn set_dbus_path(&mut self, path: MaybeDbusPath) { self.dbus_path = path } fn get_dbus_path(&self) -> &MaybeDbusPath { &self.dbus_path } } impl Recordable<BaseBlockDevSave> for StratBlockDev { fn record(&self) -> BaseBlockDevSave { BaseBlockDevSave { uuid: self.uuid(), user_info: self.user_info.clone(), hardware_info: self.hardware_info.clone(), } } }
available
identifier_name
blockdev.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/. // Code to handle a single block device. use std::fs::OpenOptions; use std::path::PathBuf; use chrono::{DateTime, TimeZone, Utc}; use devicemapper::{Device, Sectors}; use crate::engine::{BlockDev, BlockDevState, DevUuid, EngineEvent, MaybeDbusPath, PoolUuid}; use crate::stratis::StratisResult; use crate::engine::event::get_engine_listener_list; use crate::engine::strat_engine::serde_structs::{BaseBlockDevSave, Recordable}; use crate::engine::strat_engine::backstore::metadata::BDA; use crate::engine::strat_engine::backstore::range_alloc::RangeAllocator; #[derive(Debug)] pub struct StratBlockDev { dev: Device, pub(super) devnode: PathBuf, bda: BDA, used: RangeAllocator, user_info: Option<String>, hardware_info: Option<String>, dbus_path: MaybeDbusPath, } impl StratBlockDev { /// Make a new BlockDev from the parameters. /// Allocate space for the Stratis metadata on the device. /// - dev: the device, identified by number /// - devnode: the device node /// - bda: the device's BDA /// - other_segments: segments claimed for non-Stratis metadata use /// - user_info: user settable identifying information /// - hardware_info: identifying information in the hardware /// Returns an error if it is impossible to allocate all segments on the /// device. /// NOTE: It is possible that the actual device size is greater than /// the recorded device size. In that case, the additional space available /// on the device is simply invisible to the blockdev. Consequently, it /// is invisible to the engine, and is not part of the total size value /// reported on the D-Bus. #[allow(clippy::new_ret_no_self)] pub fn new( dev: Device, devnode: PathBuf, bda: BDA, upper_segments: &[(Sectors, Sectors)], user_info: Option<String>, hardware_info: Option<String>, ) -> StratisResult<StratBlockDev> { let mut segments = vec![(Sectors(0), bda.size())]; segments.extend(upper_segments); let allocator = RangeAllocator::new(bda.dev_size(), &segments)?; Ok(StratBlockDev { dev, devnode, bda, used: allocator, user_info, hardware_info, dbus_path: MaybeDbusPath(None), }) } /// Returns the blockdev's Device pub fn device(&self) -> &Device { &self.dev } pub fn wipe_metadata(&self) -> StratisResult<()> { let mut f = OpenOptions::new().write(true).open(&self.devnode)?; BDA::wipe(&mut f) } pub fn save_state(&mut self, time: &DateTime<Utc>, metadata: &[u8]) -> StratisResult<()> { let mut f = OpenOptions::new().write(true).open(&self.devnode)?; self.bda.save_state(time, metadata, &mut f) } /// The device's UUID. pub fn uuid(&self) -> DevUuid { self.bda.dev_uuid() } /// The device's pool's UUID. #[allow(dead_code)] pub fn pool_uuid(&self) -> PoolUuid { self.bda.pool_uuid() } /// Last time metadata was written to this device. #[allow(dead_code)] pub fn last_update_time(&self) -> Option<&DateTime<Utc>> { self.bda.last_update_time() } /// Find some sector ranges that could be allocated. If more /// sectors are needed than are available, return partial results. /// If all sectors are desired, use available() method to get all. pub fn request_space(&mut self, size: Sectors) -> (Sectors, Vec<(Sectors, Sectors)>) { let prev_state = self.state(); let result = self.used.request(size); if result.0 > Sectors(0) && prev_state!= BlockDevState::InUse { get_engine_listener_list().notify(&EngineEvent::BlockdevStateChanged { dbus_path: self.get_dbus_path(), state: BlockDevState::InUse, }); } result } // ALL SIZE METHODS (except size(), which is in BlockDev impl.) /// The number of Sectors on this device used by Stratis for metadata pub fn metadata_size(&self) -> Sectors { self.bda.size() } /// The number of Sectors on this device not allocated for any purpose. /// self.size() - self.metadata_size() >= self.available() pub fn available(&self) -> Sectors { self.used.available() } /// The maximum size of variable length metadata that can be accommodated. /// self.max_metadata_size() < self.metadata_size() pub fn max_metadata_size(&self) -> Sectors { self.bda.max_data_size() } /// Set the user info on this blockdev. /// The user_info may be None, which unsets user info. /// Returns true if the user info was changed, otherwise false. pub fn set_user_info(&mut self, user_info: Option<&str>) -> bool { set_blockdev_user_info!(self; user_info) } } impl BlockDev for StratBlockDev { fn devnode(&self) -> PathBuf { self.devnode.clone() } fn user_info(&self) -> Option<&str> { self.user_info.as_ref().map(|x| &**x) } fn hardware_info(&self) -> Option<&str> { self.hardware_info.as_ref().map(|x| &**x) } fn initialization_time(&self) -> DateTime<Utc> { // This cast will result in an incorrect, negative value starting in // the year 292,277,026,596. :-) Utc.timestamp(self.bda.initialization_time() as i64, 0) } fn size(&self) -> Sectors { let size = self.used.size(); assert_eq!(self.bda.dev_size(), size); size } fn state(&self) -> BlockDevState { // TODO: Implement support for other BlockDevStates if self.used.used() > self.bda.size()
else { BlockDevState::NotInUse } } fn set_dbus_path(&mut self, path: MaybeDbusPath) { self.dbus_path = path } fn get_dbus_path(&self) -> &MaybeDbusPath { &self.dbus_path } } impl Recordable<BaseBlockDevSave> for StratBlockDev { fn record(&self) -> BaseBlockDevSave { BaseBlockDevSave { uuid: self.uuid(), user_info: self.user_info.clone(), hardware_info: self.hardware_info.clone(), } } }
{ BlockDevState::InUse }
conditional_block
ancient_import.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Helper for ancient block import. use std::sync::Arc; use blockchain::BlockChain; use engines::{EthEngine, EpochVerifier}; use header::Header; use machine::EthereumMachine; use rand::Rng; use parking_lot::RwLock; // do "heavy" verification on ~1/50 blocks, randomly sampled. const HEAVY_VERIFY_RATE: f32 = 0.02; /// Ancient block verifier: import an ancient sequence of blocks in order from a starting /// epoch. pub struct AncientVerifier { cur_verifier: RwLock<Box<EpochVerifier<EthereumMachine>>>, engine: Arc<EthEngine>, } impl AncientVerifier { /// Create a new ancient block verifier with the given engine and initial verifier. pub fn
(engine: Arc<EthEngine>, start_verifier: Box<EpochVerifier<EthereumMachine>>) -> Self { AncientVerifier { cur_verifier: RwLock::new(start_verifier), engine: engine, } } /// Verify the next block header, randomly choosing whether to do heavy or light /// verification. If the block is the end of an epoch, updates the epoch verifier. pub fn verify<R: Rng>( &self, rng: &mut R, header: &Header, chain: &BlockChain, ) -> Result<(), ::error::Error> { match rng.gen::<f32>() <= HEAVY_VERIFY_RATE { true => self.cur_verifier.read().verify_heavy(header)?, false => self.cur_verifier.read().verify_light(header)?, } // ancient import will only use transitions obtained from the snapshot. if let Some(transition) = chain.epoch_transition(header.number(), header.hash()) { let v = self.engine.epoch_verifier(&header, &transition.proof).known_confirmed()?; *self.cur_verifier.write() = v; } Ok(()) } }
new
identifier_name
ancient_import.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Helper for ancient block import. use std::sync::Arc; use blockchain::BlockChain; use engines::{EthEngine, EpochVerifier}; use header::Header; use machine::EthereumMachine; use rand::Rng; use parking_lot::RwLock; // do "heavy" verification on ~1/50 blocks, randomly sampled. const HEAVY_VERIFY_RATE: f32 = 0.02; /// Ancient block verifier: import an ancient sequence of blocks in order from a starting /// epoch. pub struct AncientVerifier { cur_verifier: RwLock<Box<EpochVerifier<EthereumMachine>>>, engine: Arc<EthEngine>, } impl AncientVerifier { /// Create a new ancient block verifier with the given engine and initial verifier. pub fn new(engine: Arc<EthEngine>, start_verifier: Box<EpochVerifier<EthereumMachine>>) -> Self
/// Verify the next block header, randomly choosing whether to do heavy or light /// verification. If the block is the end of an epoch, updates the epoch verifier. pub fn verify<R: Rng>( &self, rng: &mut R, header: &Header, chain: &BlockChain, ) -> Result<(), ::error::Error> { match rng.gen::<f32>() <= HEAVY_VERIFY_RATE { true => self.cur_verifier.read().verify_heavy(header)?, false => self.cur_verifier.read().verify_light(header)?, } // ancient import will only use transitions obtained from the snapshot. if let Some(transition) = chain.epoch_transition(header.number(), header.hash()) { let v = self.engine.epoch_verifier(&header, &transition.proof).known_confirmed()?; *self.cur_verifier.write() = v; } Ok(()) } }
{ AncientVerifier { cur_verifier: RwLock::new(start_verifier), engine: engine, } }
identifier_body
ancient_import.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Helper for ancient block import. use std::sync::Arc; use blockchain::BlockChain; use engines::{EthEngine, EpochVerifier}; use header::Header; use machine::EthereumMachine; use rand::Rng; use parking_lot::RwLock; // do "heavy" verification on ~1/50 blocks, randomly sampled. const HEAVY_VERIFY_RATE: f32 = 0.02; /// Ancient block verifier: import an ancient sequence of blocks in order from a starting /// epoch. pub struct AncientVerifier { cur_verifier: RwLock<Box<EpochVerifier<EthereumMachine>>>, engine: Arc<EthEngine>, } impl AncientVerifier { /// Create a new ancient block verifier with the given engine and initial verifier. pub fn new(engine: Arc<EthEngine>, start_verifier: Box<EpochVerifier<EthereumMachine>>) -> Self { AncientVerifier { cur_verifier: RwLock::new(start_verifier), engine: engine, } } /// Verify the next block header, randomly choosing whether to do heavy or light /// verification. If the block is the end of an epoch, updates the epoch verifier.
header: &Header, chain: &BlockChain, ) -> Result<(), ::error::Error> { match rng.gen::<f32>() <= HEAVY_VERIFY_RATE { true => self.cur_verifier.read().verify_heavy(header)?, false => self.cur_verifier.read().verify_light(header)?, } // ancient import will only use transitions obtained from the snapshot. if let Some(transition) = chain.epoch_transition(header.number(), header.hash()) { let v = self.engine.epoch_verifier(&header, &transition.proof).known_confirmed()?; *self.cur_verifier.write() = v; } Ok(()) } }
pub fn verify<R: Rng>( &self, rng: &mut R,
random_line_split
ancient_import.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Helper for ancient block import. use std::sync::Arc; use blockchain::BlockChain; use engines::{EthEngine, EpochVerifier}; use header::Header; use machine::EthereumMachine; use rand::Rng; use parking_lot::RwLock; // do "heavy" verification on ~1/50 blocks, randomly sampled. const HEAVY_VERIFY_RATE: f32 = 0.02; /// Ancient block verifier: import an ancient sequence of blocks in order from a starting /// epoch. pub struct AncientVerifier { cur_verifier: RwLock<Box<EpochVerifier<EthereumMachine>>>, engine: Arc<EthEngine>, } impl AncientVerifier { /// Create a new ancient block verifier with the given engine and initial verifier. pub fn new(engine: Arc<EthEngine>, start_verifier: Box<EpochVerifier<EthereumMachine>>) -> Self { AncientVerifier { cur_verifier: RwLock::new(start_verifier), engine: engine, } } /// Verify the next block header, randomly choosing whether to do heavy or light /// verification. If the block is the end of an epoch, updates the epoch verifier. pub fn verify<R: Rng>( &self, rng: &mut R, header: &Header, chain: &BlockChain, ) -> Result<(), ::error::Error> { match rng.gen::<f32>() <= HEAVY_VERIFY_RATE { true => self.cur_verifier.read().verify_heavy(header)?, false => self.cur_verifier.read().verify_light(header)?, } // ancient import will only use transitions obtained from the snapshot. if let Some(transition) = chain.epoch_transition(header.number(), header.hash())
Ok(()) } }
{ let v = self.engine.epoch_verifier(&header, &transition.proof).known_confirmed()?; *self.cur_verifier.write() = v; }
conditional_block
http_ece.rs
use ece::encrypt; use crate::error::WebPushError; use crate::message::WebPushPayload; use crate::vapid::VapidSignature; /// Content encoding profiles. pub enum ContentEncoding { //Make sure this enum remains exhaustive as that allows for easier migrations to new versions. Aes128Gcm, } /// Struct for handling payload encryption. pub struct HttpEce<'a> { peer_public_key: &'a [u8], peer_secret: &'a [u8], encoding: ContentEncoding, vapid_signature: Option<VapidSignature>, } impl<'a> HttpEce<'a> { /// Create a new encryptor. /// /// `peer_public_key` is the `p256dh` and `peer_secret` the `auth` from /// browser subscription info. pub fn new( encoding: ContentEncoding, peer_public_key: &'a [u8], peer_secret: &'a [u8], vapid_signature: Option<VapidSignature>, ) -> HttpEce<'a> { HttpEce { peer_public_key, peer_secret, encoding, vapid_signature, } } /// Encrypts a payload. The maximum length for the payload is 3800 /// characters, which is the largest that works with Google's and Mozilla's /// push servers. pub fn encrypt(&self, content: &'a [u8]) -> Result<WebPushPayload, WebPushError> { if content.len() > 3052
//Add more encoding standards to this match as they are created. match self.encoding { ContentEncoding::Aes128Gcm => { let result = encrypt(self.peer_public_key, self.peer_secret, content); let mut headers = Vec::new(); //VAPID uses a special Authorisation header, which contains a ecdhsa key and a jwt. if let Some(signature) = &self.vapid_signature { headers.push(( "Authorization", format!( "vapid t={}, k={}", signature.auth_t, base64::encode_config(&signature.auth_k, base64::URL_SAFE_NO_PAD) ), )); } match result { Ok(data) => Ok(WebPushPayload { content: data, crypto_headers: headers, content_encoding: "aes128gcm", }), _ => Err(WebPushError::InvalidCryptoKeys), } } } } } #[cfg(test)] mod tests { use base64::{self, URL_SAFE}; use regex::Regex; use crate::error::WebPushError; use crate::http_ece::{ContentEncoding, HttpEce}; use crate::VapidSignature; use crate::WebPushPayload; #[test] fn test_payload_too_big() { let p256dh = base64::decode_config( "BLMaF9ffKBiWQLCKvTHb6LO8Nb6dcUh6TItC455vu2kElga6PQvUmaFyCdykxY2nOSSL3yKgfbmFLRTUaGv4yV8", URL_SAFE, ) .unwrap(); let auth = base64::decode_config("xS03Fj5ErfTNH_l9WHE9Ig", URL_SAFE).unwrap(); let http_ece = HttpEce::new(ContentEncoding::Aes128Gcm, &p256dh, &auth, None); //This content is one above limit. let content = [0u8; 3801]; assert_eq!(Err(WebPushError::PayloadTooLarge), http_ece.encrypt(&content)); } /// Tests that the content encryption is properly reversible while using aes128gcm. #[test] fn test_payload_encrypts_128() { let (key, auth) = ece::generate_keypair_and_auth_secret().unwrap(); let p_key = key.raw_components().unwrap(); let p_key = p_key.public_key(); let http_ece = HttpEce::new(ContentEncoding::Aes128Gcm, p_key, &auth, None); let plaintext = "Hello world!"; let ciphertext = http_ece.encrypt(plaintext.as_bytes()).unwrap(); assert_ne!(plaintext.as_bytes(), ciphertext.content); assert_eq!( String::from_utf8(ece::decrypt(&key.raw_components().unwrap(), &auth, &ciphertext.content).unwrap()) .unwrap(), plaintext ) } fn setup_payload(vapid_signature: Option<VapidSignature>, encoding: ContentEncoding) -> WebPushPayload { let p256dh = base64::decode_config( "BLMbF9ffKBiWQLCKvTHb6LO8Nb6dcUh6TItC455vu2kElga6PQvUmaFyCdykxY2nOSSL3yKgfbmFLRTUaGv4yV8", URL_SAFE, ) .unwrap(); let auth = base64::decode_config("xS03Fi5ErfTNH_l9WHE9Ig", URL_SAFE).unwrap(); let http_ece = HttpEce::new(encoding, &p256dh, &auth, vapid_signature); let content = "Hello, world!".as_bytes(); http_ece.encrypt(content).unwrap() } #[test] fn test_aes128gcm_headers_no_vapid() { let wp_payload = setup_payload(None, ContentEncoding::Aes128Gcm); assert_eq!(wp_payload.crypto_headers.len(), 0); } #[test] fn test_aes128gcm_headers_vapid() { let auth_re = Regex::new(r"vapid t=(?P<sig_t>[^,]*), k=(?P<sig_k>[^,]*)").unwrap(); let vapid_signature = VapidSignature { auth_t: String::from("foo"), auth_k: String::from("bar").into_bytes(), }; let wp_payload = setup_payload(Some(vapid_signature), ContentEncoding::Aes128Gcm); assert_eq!(wp_payload.crypto_headers.len(), 1); let auth = wp_payload.crypto_headers[0].clone(); assert_eq!(auth.0, "Authorization"); assert!(auth_re.captures(&auth.1).is_some()); } }
{ return Err(WebPushError::PayloadTooLarge); }
conditional_block
http_ece.rs
use ece::encrypt; use crate::error::WebPushError; use crate::message::WebPushPayload; use crate::vapid::VapidSignature; /// Content encoding profiles. pub enum ContentEncoding { //Make sure this enum remains exhaustive as that allows for easier migrations to new versions. Aes128Gcm, } /// Struct for handling payload encryption. pub struct HttpEce<'a> { peer_public_key: &'a [u8], peer_secret: &'a [u8], encoding: ContentEncoding, vapid_signature: Option<VapidSignature>, } impl<'a> HttpEce<'a> { /// Create a new encryptor. /// /// `peer_public_key` is the `p256dh` and `peer_secret` the `auth` from /// browser subscription info. pub fn new( encoding: ContentEncoding, peer_public_key: &'a [u8], peer_secret: &'a [u8], vapid_signature: Option<VapidSignature>, ) -> HttpEce<'a> { HttpEce { peer_public_key, peer_secret, encoding, vapid_signature, } } /// Encrypts a payload. The maximum length for the payload is 3800 /// characters, which is the largest that works with Google's and Mozilla's /// push servers. pub fn encrypt(&self, content: &'a [u8]) -> Result<WebPushPayload, WebPushError> { if content.len() > 3052 { return Err(WebPushError::PayloadTooLarge); } //Add more encoding standards to this match as they are created. match self.encoding { ContentEncoding::Aes128Gcm => { let result = encrypt(self.peer_public_key, self.peer_secret, content); let mut headers = Vec::new(); //VAPID uses a special Authorisation header, which contains a ecdhsa key and a jwt. if let Some(signature) = &self.vapid_signature { headers.push(( "Authorization", format!( "vapid t={}, k={}", signature.auth_t, base64::encode_config(&signature.auth_k, base64::URL_SAFE_NO_PAD) ), )); } match result { Ok(data) => Ok(WebPushPayload { content: data, crypto_headers: headers, content_encoding: "aes128gcm", }), _ => Err(WebPushError::InvalidCryptoKeys), } } } } } #[cfg(test)] mod tests { use base64::{self, URL_SAFE}; use regex::Regex; use crate::error::WebPushError; use crate::http_ece::{ContentEncoding, HttpEce}; use crate::VapidSignature; use crate::WebPushPayload; #[test] fn test_payload_too_big() { let p256dh = base64::decode_config( "BLMaF9ffKBiWQLCKvTHb6LO8Nb6dcUh6TItC455vu2kElga6PQvUmaFyCdykxY2nOSSL3yKgfbmFLRTUaGv4yV8", URL_SAFE, ) .unwrap(); let auth = base64::decode_config("xS03Fj5ErfTNH_l9WHE9Ig", URL_SAFE).unwrap(); let http_ece = HttpEce::new(ContentEncoding::Aes128Gcm, &p256dh, &auth, None); //This content is one above limit. let content = [0u8; 3801]; assert_eq!(Err(WebPushError::PayloadTooLarge), http_ece.encrypt(&content)); } /// Tests that the content encryption is properly reversible while using aes128gcm. #[test] fn test_payload_encrypts_128() { let (key, auth) = ece::generate_keypair_and_auth_secret().unwrap(); let p_key = key.raw_components().unwrap(); let p_key = p_key.public_key(); let http_ece = HttpEce::new(ContentEncoding::Aes128Gcm, p_key, &auth, None); let plaintext = "Hello world!"; let ciphertext = http_ece.encrypt(plaintext.as_bytes()).unwrap(); assert_ne!(plaintext.as_bytes(), ciphertext.content); assert_eq!( String::from_utf8(ece::decrypt(&key.raw_components().unwrap(), &auth, &ciphertext.content).unwrap()) .unwrap(), plaintext ) } fn
(vapid_signature: Option<VapidSignature>, encoding: ContentEncoding) -> WebPushPayload { let p256dh = base64::decode_config( "BLMbF9ffKBiWQLCKvTHb6LO8Nb6dcUh6TItC455vu2kElga6PQvUmaFyCdykxY2nOSSL3yKgfbmFLRTUaGv4yV8", URL_SAFE, ) .unwrap(); let auth = base64::decode_config("xS03Fi5ErfTNH_l9WHE9Ig", URL_SAFE).unwrap(); let http_ece = HttpEce::new(encoding, &p256dh, &auth, vapid_signature); let content = "Hello, world!".as_bytes(); http_ece.encrypt(content).unwrap() } #[test] fn test_aes128gcm_headers_no_vapid() { let wp_payload = setup_payload(None, ContentEncoding::Aes128Gcm); assert_eq!(wp_payload.crypto_headers.len(), 0); } #[test] fn test_aes128gcm_headers_vapid() { let auth_re = Regex::new(r"vapid t=(?P<sig_t>[^,]*), k=(?P<sig_k>[^,]*)").unwrap(); let vapid_signature = VapidSignature { auth_t: String::from("foo"), auth_k: String::from("bar").into_bytes(), }; let wp_payload = setup_payload(Some(vapid_signature), ContentEncoding::Aes128Gcm); assert_eq!(wp_payload.crypto_headers.len(), 1); let auth = wp_payload.crypto_headers[0].clone(); assert_eq!(auth.0, "Authorization"); assert!(auth_re.captures(&auth.1).is_some()); } }
setup_payload
identifier_name
http_ece.rs
use ece::encrypt; use crate::error::WebPushError; use crate::message::WebPushPayload; use crate::vapid::VapidSignature; /// Content encoding profiles. pub enum ContentEncoding { //Make sure this enum remains exhaustive as that allows for easier migrations to new versions. Aes128Gcm, } /// Struct for handling payload encryption. pub struct HttpEce<'a> { peer_public_key: &'a [u8], peer_secret: &'a [u8], encoding: ContentEncoding, vapid_signature: Option<VapidSignature>, } impl<'a> HttpEce<'a> { /// Create a new encryptor. /// /// `peer_public_key` is the `p256dh` and `peer_secret` the `auth` from /// browser subscription info. pub fn new( encoding: ContentEncoding, peer_public_key: &'a [u8], peer_secret: &'a [u8], vapid_signature: Option<VapidSignature>, ) -> HttpEce<'a> { HttpEce { peer_public_key, peer_secret, encoding, vapid_signature, } } /// Encrypts a payload. The maximum length for the payload is 3800 /// characters, which is the largest that works with Google's and Mozilla's /// push servers. pub fn encrypt(&self, content: &'a [u8]) -> Result<WebPushPayload, WebPushError> { if content.len() > 3052 { return Err(WebPushError::PayloadTooLarge); } //Add more encoding standards to this match as they are created. match self.encoding { ContentEncoding::Aes128Gcm => { let result = encrypt(self.peer_public_key, self.peer_secret, content); let mut headers = Vec::new(); //VAPID uses a special Authorisation header, which contains a ecdhsa key and a jwt. if let Some(signature) = &self.vapid_signature { headers.push(( "Authorization", format!( "vapid t={}, k={}", signature.auth_t, base64::encode_config(&signature.auth_k, base64::URL_SAFE_NO_PAD) ), )); } match result { Ok(data) => Ok(WebPushPayload { content: data, crypto_headers: headers, content_encoding: "aes128gcm", }), _ => Err(WebPushError::InvalidCryptoKeys), } } } } } #[cfg(test)] mod tests { use base64::{self, URL_SAFE}; use regex::Regex; use crate::error::WebPushError; use crate::http_ece::{ContentEncoding, HttpEce}; use crate::VapidSignature; use crate::WebPushPayload; #[test] fn test_payload_too_big() { let p256dh = base64::decode_config( "BLMaF9ffKBiWQLCKvTHb6LO8Nb6dcUh6TItC455vu2kElga6PQvUmaFyCdykxY2nOSSL3yKgfbmFLRTUaGv4yV8", URL_SAFE, ) .unwrap(); let auth = base64::decode_config("xS03Fj5ErfTNH_l9WHE9Ig", URL_SAFE).unwrap(); let http_ece = HttpEce::new(ContentEncoding::Aes128Gcm, &p256dh, &auth, None); //This content is one above limit. let content = [0u8; 3801]; assert_eq!(Err(WebPushError::PayloadTooLarge), http_ece.encrypt(&content)); } /// Tests that the content encryption is properly reversible while using aes128gcm. #[test] fn test_payload_encrypts_128() { let (key, auth) = ece::generate_keypair_and_auth_secret().unwrap(); let p_key = key.raw_components().unwrap(); let p_key = p_key.public_key(); let http_ece = HttpEce::new(ContentEncoding::Aes128Gcm, p_key, &auth, None); let plaintext = "Hello world!"; let ciphertext = http_ece.encrypt(plaintext.as_bytes()).unwrap(); assert_ne!(plaintext.as_bytes(), ciphertext.content); assert_eq!( String::from_utf8(ece::decrypt(&key.raw_components().unwrap(), &auth, &ciphertext.content).unwrap()) .unwrap(), plaintext ) } fn setup_payload(vapid_signature: Option<VapidSignature>, encoding: ContentEncoding) -> WebPushPayload
#[test] fn test_aes128gcm_headers_no_vapid() { let wp_payload = setup_payload(None, ContentEncoding::Aes128Gcm); assert_eq!(wp_payload.crypto_headers.len(), 0); } #[test] fn test_aes128gcm_headers_vapid() { let auth_re = Regex::new(r"vapid t=(?P<sig_t>[^,]*), k=(?P<sig_k>[^,]*)").unwrap(); let vapid_signature = VapidSignature { auth_t: String::from("foo"), auth_k: String::from("bar").into_bytes(), }; let wp_payload = setup_payload(Some(vapid_signature), ContentEncoding::Aes128Gcm); assert_eq!(wp_payload.crypto_headers.len(), 1); let auth = wp_payload.crypto_headers[0].clone(); assert_eq!(auth.0, "Authorization"); assert!(auth_re.captures(&auth.1).is_some()); } }
{ let p256dh = base64::decode_config( "BLMbF9ffKBiWQLCKvTHb6LO8Nb6dcUh6TItC455vu2kElga6PQvUmaFyCdykxY2nOSSL3yKgfbmFLRTUaGv4yV8", URL_SAFE, ) .unwrap(); let auth = base64::decode_config("xS03Fi5ErfTNH_l9WHE9Ig", URL_SAFE).unwrap(); let http_ece = HttpEce::new(encoding, &p256dh, &auth, vapid_signature); let content = "Hello, world!".as_bytes(); http_ece.encrypt(content).unwrap() }
identifier_body
http_ece.rs
use ece::encrypt; use crate::error::WebPushError; use crate::message::WebPushPayload; use crate::vapid::VapidSignature; /// Content encoding profiles. pub enum ContentEncoding { //Make sure this enum remains exhaustive as that allows for easier migrations to new versions. Aes128Gcm, } /// Struct for handling payload encryption. pub struct HttpEce<'a> { peer_public_key: &'a [u8], peer_secret: &'a [u8], encoding: ContentEncoding, vapid_signature: Option<VapidSignature>, } impl<'a> HttpEce<'a> { /// Create a new encryptor. /// /// `peer_public_key` is the `p256dh` and `peer_secret` the `auth` from /// browser subscription info. pub fn new( encoding: ContentEncoding, peer_public_key: &'a [u8], peer_secret: &'a [u8], vapid_signature: Option<VapidSignature>, ) -> HttpEce<'a> { HttpEce { peer_public_key, peer_secret, encoding, vapid_signature, } } /// Encrypts a payload. The maximum length for the payload is 3800 /// characters, which is the largest that works with Google's and Mozilla's /// push servers. pub fn encrypt(&self, content: &'a [u8]) -> Result<WebPushPayload, WebPushError> {
match self.encoding { ContentEncoding::Aes128Gcm => { let result = encrypt(self.peer_public_key, self.peer_secret, content); let mut headers = Vec::new(); //VAPID uses a special Authorisation header, which contains a ecdhsa key and a jwt. if let Some(signature) = &self.vapid_signature { headers.push(( "Authorization", format!( "vapid t={}, k={}", signature.auth_t, base64::encode_config(&signature.auth_k, base64::URL_SAFE_NO_PAD) ), )); } match result { Ok(data) => Ok(WebPushPayload { content: data, crypto_headers: headers, content_encoding: "aes128gcm", }), _ => Err(WebPushError::InvalidCryptoKeys), } } } } } #[cfg(test)] mod tests { use base64::{self, URL_SAFE}; use regex::Regex; use crate::error::WebPushError; use crate::http_ece::{ContentEncoding, HttpEce}; use crate::VapidSignature; use crate::WebPushPayload; #[test] fn test_payload_too_big() { let p256dh = base64::decode_config( "BLMaF9ffKBiWQLCKvTHb6LO8Nb6dcUh6TItC455vu2kElga6PQvUmaFyCdykxY2nOSSL3yKgfbmFLRTUaGv4yV8", URL_SAFE, ) .unwrap(); let auth = base64::decode_config("xS03Fj5ErfTNH_l9WHE9Ig", URL_SAFE).unwrap(); let http_ece = HttpEce::new(ContentEncoding::Aes128Gcm, &p256dh, &auth, None); //This content is one above limit. let content = [0u8; 3801]; assert_eq!(Err(WebPushError::PayloadTooLarge), http_ece.encrypt(&content)); } /// Tests that the content encryption is properly reversible while using aes128gcm. #[test] fn test_payload_encrypts_128() { let (key, auth) = ece::generate_keypair_and_auth_secret().unwrap(); let p_key = key.raw_components().unwrap(); let p_key = p_key.public_key(); let http_ece = HttpEce::new(ContentEncoding::Aes128Gcm, p_key, &auth, None); let plaintext = "Hello world!"; let ciphertext = http_ece.encrypt(plaintext.as_bytes()).unwrap(); assert_ne!(plaintext.as_bytes(), ciphertext.content); assert_eq!( String::from_utf8(ece::decrypt(&key.raw_components().unwrap(), &auth, &ciphertext.content).unwrap()) .unwrap(), plaintext ) } fn setup_payload(vapid_signature: Option<VapidSignature>, encoding: ContentEncoding) -> WebPushPayload { let p256dh = base64::decode_config( "BLMbF9ffKBiWQLCKvTHb6LO8Nb6dcUh6TItC455vu2kElga6PQvUmaFyCdykxY2nOSSL3yKgfbmFLRTUaGv4yV8", URL_SAFE, ) .unwrap(); let auth = base64::decode_config("xS03Fi5ErfTNH_l9WHE9Ig", URL_SAFE).unwrap(); let http_ece = HttpEce::new(encoding, &p256dh, &auth, vapid_signature); let content = "Hello, world!".as_bytes(); http_ece.encrypt(content).unwrap() } #[test] fn test_aes128gcm_headers_no_vapid() { let wp_payload = setup_payload(None, ContentEncoding::Aes128Gcm); assert_eq!(wp_payload.crypto_headers.len(), 0); } #[test] fn test_aes128gcm_headers_vapid() { let auth_re = Regex::new(r"vapid t=(?P<sig_t>[^,]*), k=(?P<sig_k>[^,]*)").unwrap(); let vapid_signature = VapidSignature { auth_t: String::from("foo"), auth_k: String::from("bar").into_bytes(), }; let wp_payload = setup_payload(Some(vapid_signature), ContentEncoding::Aes128Gcm); assert_eq!(wp_payload.crypto_headers.len(), 1); let auth = wp_payload.crypto_headers[0].clone(); assert_eq!(auth.0, "Authorization"); assert!(auth_re.captures(&auth.1).is_some()); } }
if content.len() > 3052 { return Err(WebPushError::PayloadTooLarge); } //Add more encoding standards to this match as they are created.
random_line_split
char.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. //! Character manipulation. //! //! For more details, see ::rustc_unicode::char (a.k.a. std::char) #![allow(non_snake_case)] #![stable(feature = "core_char", since = "1.2.0")] use iter::Iterator; use mem::transmute; use option::Option::{None, Some}; use option::Option; use slice::SliceExt; // UTF-8 ranges and tags for encoding characters const TAG_CONT: u8 = 0b1000_0000; const TAG_TWO_B: u8 = 0b1100_0000; const TAG_THREE_B: u8 = 0b1110_0000; const TAG_FOUR_B: u8 = 0b1111_0000; const MAX_ONE_B: u32 = 0x80; const MAX_TWO_B: u32 = 0x800; const MAX_THREE_B: u32 = 0x10000; /* Lu Uppercase_Letter an uppercase letter Ll Lowercase_Letter a lowercase letter Lt Titlecase_Letter a digraphic character, with first part uppercase Lm Modifier_Letter a modifier letter Lo Other_Letter other letters, including syllables and ideographs Mn Nonspacing_Mark a nonspacing combining mark (zero advance width) Mc Spacing_Mark a spacing combining mark (positive advance width) Me Enclosing_Mark an enclosing combining mark Nd Decimal_Number a decimal digit Nl Letter_Number a letterlike numeric character No Other_Number a numeric character of other type Pc Connector_Punctuation a connecting punctuation mark, like a tie Pd Dash_Punctuation a dash or hyphen punctuation mark Ps Open_Punctuation an opening punctuation mark (of a pair) Pe Close_Punctuation a closing punctuation mark (of a pair) Pi Initial_Punctuation an initial quotation mark Pf Final_Punctuation a final quotation mark Po Other_Punctuation a punctuation mark of other type Sm Math_Symbol a symbol of primarily mathematical use Sc Currency_Symbol a currency sign Sk Modifier_Symbol a non-letterlike modifier symbol So Other_Symbol a symbol of other type Zs Space_Separator a space character (of various non-zero widths) Zl Line_Separator U+2028 LINE SEPARATOR only Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only Cc Control a C0 or C1 control code Cf Format a format control character Cs Surrogate a surrogate code point Co Private_Use a private-use character Cn Unassigned a reserved unassigned code point or a noncharacter */ /// The highest valid code point #[stable(feature = "rust1", since = "1.0.0")] pub const MAX: char = '\u{10ffff}'; /// Converts a `u32` to an `Option<char>`. /// /// # Examples /// /// ``` /// use std::char; /// /// assert_eq!(char::from_u32(0x2764), Some('❤')); /// assert_eq!(char::from_u32(0x110000), None); // invalid character /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn from_u32(i: u32) -> Option<char> { // catch out-of-bounds and surrogates if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) { None } else { Some(unsafe { from_u32_unchecked(i) }) } } /// Converts a `u32` to an `char`, not checking whether it is a valid unicode /// codepoint. #[inline] #[stable(feature = "char_from_unchecked", since = "1.5.0")] pub unsafe fn from_u32_unchecked(i: u32) -> char { transmute(i) } /// Converts a number to the character representing it. /// /// # Return value /// /// Returns `Some(char)` if `num` represents one digit under `radix`, /// using one character of `0-9` or `a-z`, or `None` if it doesn't. /// /// # Panics /// /// Panics if given an `radix` > 36. /// /// # Examples /// /// ``` /// use std::char; /// /// let c = char::from_digit(4, 10); /// /// assert_eq!(c, Some('4')); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn from_digit(num: u32, radix: u32) -> Option<char> { if radix > 36 { panic!("from_digit: radix is too high (maximum 36)"); } if num < radix { let num = num as u8; if num < 10 { Some((b'0' + num) as char) } else { Some((b'a' + num - 10) as char) } } else { None } } // NB: the stabilization and documentation for this trait is in // unicode/char.rs, not here #[allow(missing_docs)] // docs in libunicode/u_char.rs #[doc(hidden)] #[unstable(feature = "core_char_ext", reason = "the stable interface is `impl char` in later crate", issue = "27701")] pub trait CharExt { fn is_digit(self, radix: u32) -> bool; fn to_digit(self, radix: u32) -> Option<u32>; fn escape_unicode(self) -> EscapeUnicode; fn escape_default(self) -> EscapeDefault; fn len_utf8(self) -> usize; fn len_utf16(self) -> usize; fn encode_utf8(self, dst: &mut [u8]) -> Option<usize>; fn encode_utf16(self, dst: &mut [u16]) -> Option<usize>; } impl CharExt for char { #[inline] fn is_digit(self, radix: u32) -> bool { self.to_digit(radix).is_some() } #[inline] fn to_digit(self, radix: u32) -> Option<u32> { if radix > 36 { panic!("to_digit: radix is too high (maximum 36)"); } let val = match self { '0'... '9' => self as u32 - '0' as u32, 'a'... 'z' => self as u32 - 'a' as u32 + 10, 'A'... 'Z' => self as u32 - 'A' as u32 + 10, _ => return None, }; if val < radix { Some(val) } else { None } } #[inline] fn escape_unicode(self) -> EscapeUnicode { EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash } } #[inline] fn escape_default(self) -> EscapeDefault { let init_state = match self { '\t' => EscapeDefaultState::Backslash('t'), '\r' => EscapeDefaultState::Backslash('r'), '\n' => EscapeDefaultState::Backslash('n'), '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self), '\x20'... '\x7e' => EscapeDefaultState::Char(self), _ => EscapeDefaultState::Unicode(self.escape_unicode()) }; EscapeDefault { state: init_state } } #[inline] fn len_utf8(self) -> usize { let code = self as u32; if code < MAX_ONE_B { 1 } else if code < MAX_TWO_B { 2 } else if code < MAX_THREE_B { 3 } else { 4 } } #[inline] fn len_utf16(self) -> usize { let ch = self as u32; if (ch & 0xFFFF) == ch { 1 } else { 2 } } #[inline] fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> { encode_utf8_raw(self as u32, dst) } #[inline] fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> { encode_utf16_raw(self as u32, dst) } } /// Encodes a raw u32 value as UTF-8 into the provided byte buffer, /// and then returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[inline] #[unstable(feature = "char_internals", reason = "this function should not be exposed publicly", issue = "0")] #[doc(hidden)] pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> Option<usize> { // Marked #[inline] to allow llvm optimizing it away if code < MAX_ONE_B &&!dst.is_empty() { dst[0] = code as u8; Some(1) } else if code < MAX_TWO_B && dst.len() >= 2 { dst[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B; dst[1] = (code & 0x3F) as u8 | TAG_CONT; Some(2) } else if code < MAX_THREE_B && dst.len() >= 3 { dst[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B; dst[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT; dst[2] = (code & 0x3F) as u8 | TAG_CONT; Some(3) } else if dst.len() >= 4 { dst[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B; dst[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; dst[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; dst[3] = (code & 0x3F) as u8 | TAG_CONT; Some(4) } else { None } } /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer, /// and then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[inline] #[unstable(feature = "char_internals", reason = "this function should not be exposed publicly", issue = "0")] #[doc(hidden)] pub fn encode_utf16_raw(mut ch: u32, dst: &mut [u16]) -> Option<usize> { // Marked #[inline] to allow llvm optimizing it away if (ch & 0xFFFF) == ch &&!dst.is_empty() { // The BMP falls through (assuming non-surrogate, as it should) dst[0] = ch as u16; Some(1) } else if dst.len() >= 2 { // Supplementary planes break into surrogates. ch -= 0x1_0000; dst[0] = 0xD800 | ((ch >> 10) as u16); dst[1] = 0xDC00 | ((ch as u16) & 0x3FF); Some(2) } else { None } } /// An iterator over the characters that represent a `char`, as escaped by /// Rust's unicode escaping rules. #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct EscapeUnicode { c: char, state: EscapeUnicodeState } #[derive(Clone)] enum EscapeUnicodeState { Backslash, Type, LeftBrace, Value(usize), RightBrace, Done, } #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for EscapeUnicode { type Item = char; fn next(&mut self) -> Option<char> { match self.state { EscapeUnicodeState::Backslash => { self.state = EscapeUnicodeState::Type; Some('\\') } EscapeUnicodeState::Type => { self.state = EscapeUnicodeState::LeftBrace; Some('u') } EscapeUnicodeState::LeftBrace => { let mut n = 0; while (self.c as u32) >> (4 * (n + 1))!= 0 { n += 1; } self.state = EscapeUnicodeState::Value(n); Some('{') } EscapeUnicodeState::Value(offset) => { let c = from_digit(((self.c as u32) >> (offset * 4)) & 0xf, 16).unwrap(); if offset == 0 { self.state = EscapeUnicodeState::RightBrace; } else { self.state = EscapeUnicodeState::Value(offset - 1); } Some(c) } EscapeUnicodeState::RightBrace => { self.state = EscapeUnicodeState::Done; Some('}') } EscapeUnicodeState::Done => None, } } fn size_hint(&self) -> (usize, Option<usize>) { let mut n = 0; while (self.c as usize) >> (4 * (n + 1))!= 0 { n += 1; } let n = match self.state { EscapeUnicodeState::Backslash => n + 5, EscapeUnicodeState::Type => n + 4, EscapeUnicodeState::LeftBrace => n + 3, EscapeUnicodeState::Value(offset) => offset + 2, EscapeUnicodeState::RightBrace => 1, EscapeUnicodeState::Done => 0, }; (n, Some(n)) } } /// An iterator over the characters that represent a `char`, escaped /// for maximum portability. #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct EscapeDefault { state: EscapeDefaultState } #[derive(Clone)] enum EscapeDefaultState { Backslash(char), Char(char), Done, Unicode(EscapeUnicode), } #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for EscapeDefault { type Item = char; fn ne
mut self) -> Option<char> { match self.state { EscapeDefaultState::Backslash(c) => { self.state = EscapeDefaultState::Char(c); Some('\\') } EscapeDefaultState::Char(c) => { self.state = EscapeDefaultState::Done; Some(c) } EscapeDefaultState::Done => None, EscapeDefaultState::Unicode(ref mut iter) => iter.next(), } } fn size_hint(&self) -> (usize, Option<usize>) { match self.state { EscapeDefaultState::Char(_) => (1, Some(1)), EscapeDefaultState::Backslash(_) => (2, Some(2)), EscapeDefaultState::Unicode(ref iter) => iter.size_hint(), EscapeDefaultState::Done => (0, Some(0)), } } }
xt(&
identifier_name
char.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. //! Character manipulation. //! //! For more details, see ::rustc_unicode::char (a.k.a. std::char) #![allow(non_snake_case)] #![stable(feature = "core_char", since = "1.2.0")] use iter::Iterator; use mem::transmute; use option::Option::{None, Some}; use option::Option; use slice::SliceExt; // UTF-8 ranges and tags for encoding characters const TAG_CONT: u8 = 0b1000_0000; const TAG_TWO_B: u8 = 0b1100_0000; const TAG_THREE_B: u8 = 0b1110_0000; const TAG_FOUR_B: u8 = 0b1111_0000; const MAX_ONE_B: u32 = 0x80; const MAX_TWO_B: u32 = 0x800; const MAX_THREE_B: u32 = 0x10000; /* Lu Uppercase_Letter an uppercase letter Ll Lowercase_Letter a lowercase letter Lt Titlecase_Letter a digraphic character, with first part uppercase Lm Modifier_Letter a modifier letter Lo Other_Letter other letters, including syllables and ideographs Mn Nonspacing_Mark a nonspacing combining mark (zero advance width) Mc Spacing_Mark a spacing combining mark (positive advance width) Me Enclosing_Mark an enclosing combining mark Nd Decimal_Number a decimal digit Nl Letter_Number a letterlike numeric character No Other_Number a numeric character of other type Pc Connector_Punctuation a connecting punctuation mark, like a tie Pd Dash_Punctuation a dash or hyphen punctuation mark Ps Open_Punctuation an opening punctuation mark (of a pair) Pe Close_Punctuation a closing punctuation mark (of a pair) Pi Initial_Punctuation an initial quotation mark Pf Final_Punctuation a final quotation mark Po Other_Punctuation a punctuation mark of other type Sm Math_Symbol a symbol of primarily mathematical use Sc Currency_Symbol a currency sign Sk Modifier_Symbol a non-letterlike modifier symbol So Other_Symbol a symbol of other type Zs Space_Separator a space character (of various non-zero widths) Zl Line_Separator U+2028 LINE SEPARATOR only Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only Cc Control a C0 or C1 control code Cf Format a format control character Cs Surrogate a surrogate code point Co Private_Use a private-use character Cn Unassigned a reserved unassigned code point or a noncharacter */ /// The highest valid code point #[stable(feature = "rust1", since = "1.0.0")] pub const MAX: char = '\u{10ffff}'; /// Converts a `u32` to an `Option<char>`. /// /// # Examples /// /// ``` /// use std::char; /// /// assert_eq!(char::from_u32(0x2764), Some('❤')); /// assert_eq!(char::from_u32(0x110000), None); // invalid character /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn from_u32(i: u32) -> Option<char> { // catch out-of-bounds and surrogates if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) { None } else { Some(unsafe { from_u32_unchecked(i) }) } } /// Converts a `u32` to an `char`, not checking whether it is a valid unicode /// codepoint. #[inline] #[stable(feature = "char_from_unchecked", since = "1.5.0")] pub unsafe fn from_u32_unchecked(i: u32) -> char { transmute(i) } /// Converts a number to the character representing it. /// /// # Return value /// /// Returns `Some(char)` if `num` represents one digit under `radix`, /// using one character of `0-9` or `a-z`, or `None` if it doesn't. /// /// # Panics /// /// Panics if given an `radix` > 36. /// /// # Examples /// /// ``` /// use std::char; /// /// let c = char::from_digit(4, 10); /// /// assert_eq!(c, Some('4')); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn from_digit(num: u32, radix: u32) -> Option<char> { if radix > 36 { panic!("from_digit: radix is too high (maximum 36)"); } if num < radix { let num = num as u8; if num < 10 { Some((b'0' + num) as char) } else { Some((b'a' + num - 10) as char) } } else { None } } // NB: the stabilization and documentation for this trait is in // unicode/char.rs, not here #[allow(missing_docs)] // docs in libunicode/u_char.rs #[doc(hidden)] #[unstable(feature = "core_char_ext", reason = "the stable interface is `impl char` in later crate", issue = "27701")] pub trait CharExt { fn is_digit(self, radix: u32) -> bool; fn to_digit(self, radix: u32) -> Option<u32>; fn escape_unicode(self) -> EscapeUnicode; fn escape_default(self) -> EscapeDefault; fn len_utf8(self) -> usize; fn len_utf16(self) -> usize; fn encode_utf8(self, dst: &mut [u8]) -> Option<usize>; fn encode_utf16(self, dst: &mut [u16]) -> Option<usize>; } impl CharExt for char { #[inline] fn is_digit(self, radix: u32) -> bool { self.to_digit(radix).is_some() } #[inline] fn to_digit(self, radix: u32) -> Option<u32> { if radix > 36 { panic!("to_digit: radix is too high (maximum 36)"); } let val = match self { '0'... '9' => self as u32 - '0' as u32, 'a'... 'z' => self as u32 - 'a' as u32 + 10, 'A'... 'Z' => self as u32 - 'A' as u32 + 10, _ => return None, }; if val < radix { Some(val) } else { None } } #[inline] fn escape_unicode(self) -> EscapeUnicode { EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash } } #[inline] fn escape_default(self) -> EscapeDefault { let init_state = match self { '\t' => EscapeDefaultState::Backslash('t'), '\r' => EscapeDefaultState::Backslash('r'), '\n' => EscapeDefaultState::Backslash('n'), '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self), '\x20'... '\x7e' => EscapeDefaultState::Char(self), _ => EscapeDefaultState::Unicode(self.escape_unicode()) }; EscapeDefault { state: init_state } } #[inline] fn len_utf8(self) -> usize { let code = self as u32; if code < MAX_ONE_B { 1 } else if code < MAX_TWO_B { 2 } else if code < MAX_THREE_B { 3 } else { 4 } } #[inline] fn len_utf16(self) -> usize { let ch = self as u32; if (ch & 0xFFFF) == ch { 1 } else { 2 } } #[inline] fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> { encode_utf8_raw(self as u32, dst) } #[inline] fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> { encode_utf16_raw(self as u32, dst) } } /// Encodes a raw u32 value as UTF-8 into the provided byte buffer, /// and then returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[inline] #[unstable(feature = "char_internals", reason = "this function should not be exposed publicly", issue = "0")] #[doc(hidden)] pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> Option<usize> { // Marked #[inline] to allow llvm optimizing it away if code < MAX_ONE_B &&!dst.is_empty() { dst[0] = code as u8; Some(1) } else if code < MAX_TWO_B && dst.len() >= 2 { dst[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B; dst[1] = (code & 0x3F) as u8 | TAG_CONT; Some(2) } else if code < MAX_THREE_B && dst.len() >= 3 { dst[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B; dst[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT; dst[2] = (code & 0x3F) as u8 | TAG_CONT; Some(3) } else if dst.len() >= 4 { dst[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B; dst[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; dst[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; dst[3] = (code & 0x3F) as u8 | TAG_CONT; Some(4) } else { None } } /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer, /// and then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[inline] #[unstable(feature = "char_internals", reason = "this function should not be exposed publicly", issue = "0")] #[doc(hidden)] pub fn encode_utf16_raw(mut ch: u32, dst: &mut [u16]) -> Option<usize> { // Marked #[inline] to allow llvm optimizing it away if (ch & 0xFFFF) == ch &&!dst.is_empty() { // The BMP falls through (assuming non-surrogate, as it should) dst[0] = ch as u16; Some(1) } else if dst.len() >= 2 { // Supplementary planes break into surrogates. ch -= 0x1_0000; dst[0] = 0xD800 | ((ch >> 10) as u16); dst[1] = 0xDC00 | ((ch as u16) & 0x3FF); Some(2) } else { None } } /// An iterator over the characters that represent a `char`, as escaped by /// Rust's unicode escaping rules. #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct EscapeUnicode { c: char, state: EscapeUnicodeState } #[derive(Clone)] enum EscapeUnicodeState { Backslash, Type, LeftBrace, Value(usize), RightBrace, Done, } #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for EscapeUnicode { type Item = char; fn next(&mut self) -> Option<char> { match self.state { EscapeUnicodeState::Backslash => { self.state = EscapeUnicodeState::Type; Some('\\') } EscapeUnicodeState::Type => {
EscapeUnicodeState::LeftBrace => { let mut n = 0; while (self.c as u32) >> (4 * (n + 1))!= 0 { n += 1; } self.state = EscapeUnicodeState::Value(n); Some('{') } EscapeUnicodeState::Value(offset) => { let c = from_digit(((self.c as u32) >> (offset * 4)) & 0xf, 16).unwrap(); if offset == 0 { self.state = EscapeUnicodeState::RightBrace; } else { self.state = EscapeUnicodeState::Value(offset - 1); } Some(c) } EscapeUnicodeState::RightBrace => { self.state = EscapeUnicodeState::Done; Some('}') } EscapeUnicodeState::Done => None, } } fn size_hint(&self) -> (usize, Option<usize>) { let mut n = 0; while (self.c as usize) >> (4 * (n + 1))!= 0 { n += 1; } let n = match self.state { EscapeUnicodeState::Backslash => n + 5, EscapeUnicodeState::Type => n + 4, EscapeUnicodeState::LeftBrace => n + 3, EscapeUnicodeState::Value(offset) => offset + 2, EscapeUnicodeState::RightBrace => 1, EscapeUnicodeState::Done => 0, }; (n, Some(n)) } } /// An iterator over the characters that represent a `char`, escaped /// for maximum portability. #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct EscapeDefault { state: EscapeDefaultState } #[derive(Clone)] enum EscapeDefaultState { Backslash(char), Char(char), Done, Unicode(EscapeUnicode), } #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for EscapeDefault { type Item = char; fn next(&mut self) -> Option<char> { match self.state { EscapeDefaultState::Backslash(c) => { self.state = EscapeDefaultState::Char(c); Some('\\') } EscapeDefaultState::Char(c) => { self.state = EscapeDefaultState::Done; Some(c) } EscapeDefaultState::Done => None, EscapeDefaultState::Unicode(ref mut iter) => iter.next(), } } fn size_hint(&self) -> (usize, Option<usize>) { match self.state { EscapeDefaultState::Char(_) => (1, Some(1)), EscapeDefaultState::Backslash(_) => (2, Some(2)), EscapeDefaultState::Unicode(ref iter) => iter.size_hint(), EscapeDefaultState::Done => (0, Some(0)), } } }
self.state = EscapeUnicodeState::LeftBrace; Some('u') }
conditional_block
char.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. //! Character manipulation. //! //! For more details, see ::rustc_unicode::char (a.k.a. std::char) #![allow(non_snake_case)] #![stable(feature = "core_char", since = "1.2.0")] use iter::Iterator; use mem::transmute; use option::Option::{None, Some}; use option::Option; use slice::SliceExt;
const TAG_CONT: u8 = 0b1000_0000; const TAG_TWO_B: u8 = 0b1100_0000; const TAG_THREE_B: u8 = 0b1110_0000; const TAG_FOUR_B: u8 = 0b1111_0000; const MAX_ONE_B: u32 = 0x80; const MAX_TWO_B: u32 = 0x800; const MAX_THREE_B: u32 = 0x10000; /* Lu Uppercase_Letter an uppercase letter Ll Lowercase_Letter a lowercase letter Lt Titlecase_Letter a digraphic character, with first part uppercase Lm Modifier_Letter a modifier letter Lo Other_Letter other letters, including syllables and ideographs Mn Nonspacing_Mark a nonspacing combining mark (zero advance width) Mc Spacing_Mark a spacing combining mark (positive advance width) Me Enclosing_Mark an enclosing combining mark Nd Decimal_Number a decimal digit Nl Letter_Number a letterlike numeric character No Other_Number a numeric character of other type Pc Connector_Punctuation a connecting punctuation mark, like a tie Pd Dash_Punctuation a dash or hyphen punctuation mark Ps Open_Punctuation an opening punctuation mark (of a pair) Pe Close_Punctuation a closing punctuation mark (of a pair) Pi Initial_Punctuation an initial quotation mark Pf Final_Punctuation a final quotation mark Po Other_Punctuation a punctuation mark of other type Sm Math_Symbol a symbol of primarily mathematical use Sc Currency_Symbol a currency sign Sk Modifier_Symbol a non-letterlike modifier symbol So Other_Symbol a symbol of other type Zs Space_Separator a space character (of various non-zero widths) Zl Line_Separator U+2028 LINE SEPARATOR only Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only Cc Control a C0 or C1 control code Cf Format a format control character Cs Surrogate a surrogate code point Co Private_Use a private-use character Cn Unassigned a reserved unassigned code point or a noncharacter */ /// The highest valid code point #[stable(feature = "rust1", since = "1.0.0")] pub const MAX: char = '\u{10ffff}'; /// Converts a `u32` to an `Option<char>`. /// /// # Examples /// /// ``` /// use std::char; /// /// assert_eq!(char::from_u32(0x2764), Some('❤')); /// assert_eq!(char::from_u32(0x110000), None); // invalid character /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn from_u32(i: u32) -> Option<char> { // catch out-of-bounds and surrogates if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) { None } else { Some(unsafe { from_u32_unchecked(i) }) } } /// Converts a `u32` to an `char`, not checking whether it is a valid unicode /// codepoint. #[inline] #[stable(feature = "char_from_unchecked", since = "1.5.0")] pub unsafe fn from_u32_unchecked(i: u32) -> char { transmute(i) } /// Converts a number to the character representing it. /// /// # Return value /// /// Returns `Some(char)` if `num` represents one digit under `radix`, /// using one character of `0-9` or `a-z`, or `None` if it doesn't. /// /// # Panics /// /// Panics if given an `radix` > 36. /// /// # Examples /// /// ``` /// use std::char; /// /// let c = char::from_digit(4, 10); /// /// assert_eq!(c, Some('4')); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn from_digit(num: u32, radix: u32) -> Option<char> { if radix > 36 { panic!("from_digit: radix is too high (maximum 36)"); } if num < radix { let num = num as u8; if num < 10 { Some((b'0' + num) as char) } else { Some((b'a' + num - 10) as char) } } else { None } } // NB: the stabilization and documentation for this trait is in // unicode/char.rs, not here #[allow(missing_docs)] // docs in libunicode/u_char.rs #[doc(hidden)] #[unstable(feature = "core_char_ext", reason = "the stable interface is `impl char` in later crate", issue = "27701")] pub trait CharExt { fn is_digit(self, radix: u32) -> bool; fn to_digit(self, radix: u32) -> Option<u32>; fn escape_unicode(self) -> EscapeUnicode; fn escape_default(self) -> EscapeDefault; fn len_utf8(self) -> usize; fn len_utf16(self) -> usize; fn encode_utf8(self, dst: &mut [u8]) -> Option<usize>; fn encode_utf16(self, dst: &mut [u16]) -> Option<usize>; } impl CharExt for char { #[inline] fn is_digit(self, radix: u32) -> bool { self.to_digit(radix).is_some() } #[inline] fn to_digit(self, radix: u32) -> Option<u32> { if radix > 36 { panic!("to_digit: radix is too high (maximum 36)"); } let val = match self { '0'... '9' => self as u32 - '0' as u32, 'a'... 'z' => self as u32 - 'a' as u32 + 10, 'A'... 'Z' => self as u32 - 'A' as u32 + 10, _ => return None, }; if val < radix { Some(val) } else { None } } #[inline] fn escape_unicode(self) -> EscapeUnicode { EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash } } #[inline] fn escape_default(self) -> EscapeDefault { let init_state = match self { '\t' => EscapeDefaultState::Backslash('t'), '\r' => EscapeDefaultState::Backslash('r'), '\n' => EscapeDefaultState::Backslash('n'), '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self), '\x20'... '\x7e' => EscapeDefaultState::Char(self), _ => EscapeDefaultState::Unicode(self.escape_unicode()) }; EscapeDefault { state: init_state } } #[inline] fn len_utf8(self) -> usize { let code = self as u32; if code < MAX_ONE_B { 1 } else if code < MAX_TWO_B { 2 } else if code < MAX_THREE_B { 3 } else { 4 } } #[inline] fn len_utf16(self) -> usize { let ch = self as u32; if (ch & 0xFFFF) == ch { 1 } else { 2 } } #[inline] fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> { encode_utf8_raw(self as u32, dst) } #[inline] fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> { encode_utf16_raw(self as u32, dst) } } /// Encodes a raw u32 value as UTF-8 into the provided byte buffer, /// and then returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[inline] #[unstable(feature = "char_internals", reason = "this function should not be exposed publicly", issue = "0")] #[doc(hidden)] pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> Option<usize> { // Marked #[inline] to allow llvm optimizing it away if code < MAX_ONE_B &&!dst.is_empty() { dst[0] = code as u8; Some(1) } else if code < MAX_TWO_B && dst.len() >= 2 { dst[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B; dst[1] = (code & 0x3F) as u8 | TAG_CONT; Some(2) } else if code < MAX_THREE_B && dst.len() >= 3 { dst[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B; dst[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT; dst[2] = (code & 0x3F) as u8 | TAG_CONT; Some(3) } else if dst.len() >= 4 { dst[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B; dst[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; dst[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; dst[3] = (code & 0x3F) as u8 | TAG_CONT; Some(4) } else { None } } /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer, /// and then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[inline] #[unstable(feature = "char_internals", reason = "this function should not be exposed publicly", issue = "0")] #[doc(hidden)] pub fn encode_utf16_raw(mut ch: u32, dst: &mut [u16]) -> Option<usize> { // Marked #[inline] to allow llvm optimizing it away if (ch & 0xFFFF) == ch &&!dst.is_empty() { // The BMP falls through (assuming non-surrogate, as it should) dst[0] = ch as u16; Some(1) } else if dst.len() >= 2 { // Supplementary planes break into surrogates. ch -= 0x1_0000; dst[0] = 0xD800 | ((ch >> 10) as u16); dst[1] = 0xDC00 | ((ch as u16) & 0x3FF); Some(2) } else { None } } /// An iterator over the characters that represent a `char`, as escaped by /// Rust's unicode escaping rules. #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct EscapeUnicode { c: char, state: EscapeUnicodeState } #[derive(Clone)] enum EscapeUnicodeState { Backslash, Type, LeftBrace, Value(usize), RightBrace, Done, } #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for EscapeUnicode { type Item = char; fn next(&mut self) -> Option<char> { match self.state { EscapeUnicodeState::Backslash => { self.state = EscapeUnicodeState::Type; Some('\\') } EscapeUnicodeState::Type => { self.state = EscapeUnicodeState::LeftBrace; Some('u') } EscapeUnicodeState::LeftBrace => { let mut n = 0; while (self.c as u32) >> (4 * (n + 1))!= 0 { n += 1; } self.state = EscapeUnicodeState::Value(n); Some('{') } EscapeUnicodeState::Value(offset) => { let c = from_digit(((self.c as u32) >> (offset * 4)) & 0xf, 16).unwrap(); if offset == 0 { self.state = EscapeUnicodeState::RightBrace; } else { self.state = EscapeUnicodeState::Value(offset - 1); } Some(c) } EscapeUnicodeState::RightBrace => { self.state = EscapeUnicodeState::Done; Some('}') } EscapeUnicodeState::Done => None, } } fn size_hint(&self) -> (usize, Option<usize>) { let mut n = 0; while (self.c as usize) >> (4 * (n + 1))!= 0 { n += 1; } let n = match self.state { EscapeUnicodeState::Backslash => n + 5, EscapeUnicodeState::Type => n + 4, EscapeUnicodeState::LeftBrace => n + 3, EscapeUnicodeState::Value(offset) => offset + 2, EscapeUnicodeState::RightBrace => 1, EscapeUnicodeState::Done => 0, }; (n, Some(n)) } } /// An iterator over the characters that represent a `char`, escaped /// for maximum portability. #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct EscapeDefault { state: EscapeDefaultState } #[derive(Clone)] enum EscapeDefaultState { Backslash(char), Char(char), Done, Unicode(EscapeUnicode), } #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for EscapeDefault { type Item = char; fn next(&mut self) -> Option<char> { match self.state { EscapeDefaultState::Backslash(c) => { self.state = EscapeDefaultState::Char(c); Some('\\') } EscapeDefaultState::Char(c) => { self.state = EscapeDefaultState::Done; Some(c) } EscapeDefaultState::Done => None, EscapeDefaultState::Unicode(ref mut iter) => iter.next(), } } fn size_hint(&self) -> (usize, Option<usize>) { match self.state { EscapeDefaultState::Char(_) => (1, Some(1)), EscapeDefaultState::Backslash(_) => (2, Some(2)), EscapeDefaultState::Unicode(ref iter) => iter.size_hint(), EscapeDefaultState::Done => (0, Some(0)), } } }
// UTF-8 ranges and tags for encoding characters
random_line_split
char.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. //! Character manipulation. //! //! For more details, see ::rustc_unicode::char (a.k.a. std::char) #![allow(non_snake_case)] #![stable(feature = "core_char", since = "1.2.0")] use iter::Iterator; use mem::transmute; use option::Option::{None, Some}; use option::Option; use slice::SliceExt; // UTF-8 ranges and tags for encoding characters const TAG_CONT: u8 = 0b1000_0000; const TAG_TWO_B: u8 = 0b1100_0000; const TAG_THREE_B: u8 = 0b1110_0000; const TAG_FOUR_B: u8 = 0b1111_0000; const MAX_ONE_B: u32 = 0x80; const MAX_TWO_B: u32 = 0x800; const MAX_THREE_B: u32 = 0x10000; /* Lu Uppercase_Letter an uppercase letter Ll Lowercase_Letter a lowercase letter Lt Titlecase_Letter a digraphic character, with first part uppercase Lm Modifier_Letter a modifier letter Lo Other_Letter other letters, including syllables and ideographs Mn Nonspacing_Mark a nonspacing combining mark (zero advance width) Mc Spacing_Mark a spacing combining mark (positive advance width) Me Enclosing_Mark an enclosing combining mark Nd Decimal_Number a decimal digit Nl Letter_Number a letterlike numeric character No Other_Number a numeric character of other type Pc Connector_Punctuation a connecting punctuation mark, like a tie Pd Dash_Punctuation a dash or hyphen punctuation mark Ps Open_Punctuation an opening punctuation mark (of a pair) Pe Close_Punctuation a closing punctuation mark (of a pair) Pi Initial_Punctuation an initial quotation mark Pf Final_Punctuation a final quotation mark Po Other_Punctuation a punctuation mark of other type Sm Math_Symbol a symbol of primarily mathematical use Sc Currency_Symbol a currency sign Sk Modifier_Symbol a non-letterlike modifier symbol So Other_Symbol a symbol of other type Zs Space_Separator a space character (of various non-zero widths) Zl Line_Separator U+2028 LINE SEPARATOR only Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only Cc Control a C0 or C1 control code Cf Format a format control character Cs Surrogate a surrogate code point Co Private_Use a private-use character Cn Unassigned a reserved unassigned code point or a noncharacter */ /// The highest valid code point #[stable(feature = "rust1", since = "1.0.0")] pub const MAX: char = '\u{10ffff}'; /// Converts a `u32` to an `Option<char>`. /// /// # Examples /// /// ``` /// use std::char; /// /// assert_eq!(char::from_u32(0x2764), Some('❤')); /// assert_eq!(char::from_u32(0x110000), None); // invalid character /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn from_u32(i: u32) -> Option<char> { // catch out-of-bounds and surrogates if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) { None } else { Some(unsafe { from_u32_unchecked(i) }) } } /// Converts a `u32` to an `char`, not checking whether it is a valid unicode /// codepoint. #[inline] #[stable(feature = "char_from_unchecked", since = "1.5.0")] pub unsafe fn from_u32_unchecked(i: u32) -> char { transmute(i) } /// Converts a number to the character representing it. /// /// # Return value /// /// Returns `Some(char)` if `num` represents one digit under `radix`, /// using one character of `0-9` or `a-z`, or `None` if it doesn't. /// /// # Panics /// /// Panics if given an `radix` > 36. /// /// # Examples /// /// ``` /// use std::char; /// /// let c = char::from_digit(4, 10); /// /// assert_eq!(c, Some('4')); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn from_digit(num: u32, radix: u32) -> Option<char> { if radix > 36 { panic!("from_digit: radix is too high (maximum 36)"); } if num < radix { let num = num as u8; if num < 10 { Some((b'0' + num) as char) } else { Some((b'a' + num - 10) as char) } } else { None } } // NB: the stabilization and documentation for this trait is in // unicode/char.rs, not here #[allow(missing_docs)] // docs in libunicode/u_char.rs #[doc(hidden)] #[unstable(feature = "core_char_ext", reason = "the stable interface is `impl char` in later crate", issue = "27701")] pub trait CharExt { fn is_digit(self, radix: u32) -> bool; fn to_digit(self, radix: u32) -> Option<u32>; fn escape_unicode(self) -> EscapeUnicode; fn escape_default(self) -> EscapeDefault; fn len_utf8(self) -> usize; fn len_utf16(self) -> usize; fn encode_utf8(self, dst: &mut [u8]) -> Option<usize>; fn encode_utf16(self, dst: &mut [u16]) -> Option<usize>; } impl CharExt for char { #[inline] fn is_digit(self, radix: u32) -> bool {
#[inline] fn to_digit(self, radix: u32) -> Option<u32> { if radix > 36 { panic!("to_digit: radix is too high (maximum 36)"); } let val = match self { '0'... '9' => self as u32 - '0' as u32, 'a'... 'z' => self as u32 - 'a' as u32 + 10, 'A'... 'Z' => self as u32 - 'A' as u32 + 10, _ => return None, }; if val < radix { Some(val) } else { None } } #[inline] fn escape_unicode(self) -> EscapeUnicode { EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash } } #[inline] fn escape_default(self) -> EscapeDefault { let init_state = match self { '\t' => EscapeDefaultState::Backslash('t'), '\r' => EscapeDefaultState::Backslash('r'), '\n' => EscapeDefaultState::Backslash('n'), '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self), '\x20'... '\x7e' => EscapeDefaultState::Char(self), _ => EscapeDefaultState::Unicode(self.escape_unicode()) }; EscapeDefault { state: init_state } } #[inline] fn len_utf8(self) -> usize { let code = self as u32; if code < MAX_ONE_B { 1 } else if code < MAX_TWO_B { 2 } else if code < MAX_THREE_B { 3 } else { 4 } } #[inline] fn len_utf16(self) -> usize { let ch = self as u32; if (ch & 0xFFFF) == ch { 1 } else { 2 } } #[inline] fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> { encode_utf8_raw(self as u32, dst) } #[inline] fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> { encode_utf16_raw(self as u32, dst) } } /// Encodes a raw u32 value as UTF-8 into the provided byte buffer, /// and then returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[inline] #[unstable(feature = "char_internals", reason = "this function should not be exposed publicly", issue = "0")] #[doc(hidden)] pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> Option<usize> { // Marked #[inline] to allow llvm optimizing it away if code < MAX_ONE_B &&!dst.is_empty() { dst[0] = code as u8; Some(1) } else if code < MAX_TWO_B && dst.len() >= 2 { dst[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B; dst[1] = (code & 0x3F) as u8 | TAG_CONT; Some(2) } else if code < MAX_THREE_B && dst.len() >= 3 { dst[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B; dst[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT; dst[2] = (code & 0x3F) as u8 | TAG_CONT; Some(3) } else if dst.len() >= 4 { dst[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B; dst[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; dst[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; dst[3] = (code & 0x3F) as u8 | TAG_CONT; Some(4) } else { None } } /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer, /// and then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[inline] #[unstable(feature = "char_internals", reason = "this function should not be exposed publicly", issue = "0")] #[doc(hidden)] pub fn encode_utf16_raw(mut ch: u32, dst: &mut [u16]) -> Option<usize> { // Marked #[inline] to allow llvm optimizing it away if (ch & 0xFFFF) == ch &&!dst.is_empty() { // The BMP falls through (assuming non-surrogate, as it should) dst[0] = ch as u16; Some(1) } else if dst.len() >= 2 { // Supplementary planes break into surrogates. ch -= 0x1_0000; dst[0] = 0xD800 | ((ch >> 10) as u16); dst[1] = 0xDC00 | ((ch as u16) & 0x3FF); Some(2) } else { None } } /// An iterator over the characters that represent a `char`, as escaped by /// Rust's unicode escaping rules. #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct EscapeUnicode { c: char, state: EscapeUnicodeState } #[derive(Clone)] enum EscapeUnicodeState { Backslash, Type, LeftBrace, Value(usize), RightBrace, Done, } #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for EscapeUnicode { type Item = char; fn next(&mut self) -> Option<char> { match self.state { EscapeUnicodeState::Backslash => { self.state = EscapeUnicodeState::Type; Some('\\') } EscapeUnicodeState::Type => { self.state = EscapeUnicodeState::LeftBrace; Some('u') } EscapeUnicodeState::LeftBrace => { let mut n = 0; while (self.c as u32) >> (4 * (n + 1))!= 0 { n += 1; } self.state = EscapeUnicodeState::Value(n); Some('{') } EscapeUnicodeState::Value(offset) => { let c = from_digit(((self.c as u32) >> (offset * 4)) & 0xf, 16).unwrap(); if offset == 0 { self.state = EscapeUnicodeState::RightBrace; } else { self.state = EscapeUnicodeState::Value(offset - 1); } Some(c) } EscapeUnicodeState::RightBrace => { self.state = EscapeUnicodeState::Done; Some('}') } EscapeUnicodeState::Done => None, } } fn size_hint(&self) -> (usize, Option<usize>) { let mut n = 0; while (self.c as usize) >> (4 * (n + 1))!= 0 { n += 1; } let n = match self.state { EscapeUnicodeState::Backslash => n + 5, EscapeUnicodeState::Type => n + 4, EscapeUnicodeState::LeftBrace => n + 3, EscapeUnicodeState::Value(offset) => offset + 2, EscapeUnicodeState::RightBrace => 1, EscapeUnicodeState::Done => 0, }; (n, Some(n)) } } /// An iterator over the characters that represent a `char`, escaped /// for maximum portability. #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct EscapeDefault { state: EscapeDefaultState } #[derive(Clone)] enum EscapeDefaultState { Backslash(char), Char(char), Done, Unicode(EscapeUnicode), } #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for EscapeDefault { type Item = char; fn next(&mut self) -> Option<char> { match self.state { EscapeDefaultState::Backslash(c) => { self.state = EscapeDefaultState::Char(c); Some('\\') } EscapeDefaultState::Char(c) => { self.state = EscapeDefaultState::Done; Some(c) } EscapeDefaultState::Done => None, EscapeDefaultState::Unicode(ref mut iter) => iter.next(), } } fn size_hint(&self) -> (usize, Option<usize>) { match self.state { EscapeDefaultState::Char(_) => (1, Some(1)), EscapeDefaultState::Backslash(_) => (2, Some(2)), EscapeDefaultState::Unicode(ref iter) => iter.size_hint(), EscapeDefaultState::Done => (0, Some(0)), } } }
self.to_digit(radix).is_some() }
identifier_body
spoticli.rs
extern crate spotify; use spotify::{Spotify, SpotifyError}; use std::{thread, time}; fn main() { let spotify = match Spotify::connect() { Ok(result) => result, Err(error) => { match error { SpotifyError::ClientNotRunning => { println!("The Spotify Client is not running!"); std::process::exit(1); } SpotifyError::WebHelperNotRunning => {
std::process::exit(3); } } } }; let reactor = spotify.poll(|client, status, change| { if change.client_version { println!("Spotify Client (Version {})", status.version()); } if change.track { println!("Now playing: {:#}", status.track()); println!("{}", status.full_track().track.uri); } true }); if reactor.join().ok().is_none() { println!("Unable to join into the live-update."); std::process::exit(4); } }
println!("The SpotifyWebHelper process is not running!"); std::process::exit(2); } SpotifyError::InternalError(err) => { println!("Internal Error: {:?}", err);
random_line_split
spoticli.rs
extern crate spotify; use spotify::{Spotify, SpotifyError}; use std::{thread, time}; fn main()
let reactor = spotify.poll(|client, status, change| { if change.client_version { println!("Spotify Client (Version {})", status.version()); } if change.track { println!("Now playing: {:#}", status.track()); println!("{}", status.full_track().track.uri); } true }); if reactor.join().ok().is_none() { println!("Unable to join into the live-update."); std::process::exit(4); } }
{ let spotify = match Spotify::connect() { Ok(result) => result, Err(error) => { match error { SpotifyError::ClientNotRunning => { println!("The Spotify Client is not running!"); std::process::exit(1); } SpotifyError::WebHelperNotRunning => { println!("The SpotifyWebHelper process is not running!"); std::process::exit(2); } SpotifyError::InternalError(err) => { println!("Internal Error: {:?}", err); std::process::exit(3); } } } };
identifier_body
spoticli.rs
extern crate spotify; use spotify::{Spotify, SpotifyError}; use std::{thread, time}; fn
() { let spotify = match Spotify::connect() { Ok(result) => result, Err(error) => { match error { SpotifyError::ClientNotRunning => { println!("The Spotify Client is not running!"); std::process::exit(1); } SpotifyError::WebHelperNotRunning => { println!("The SpotifyWebHelper process is not running!"); std::process::exit(2); } SpotifyError::InternalError(err) => { println!("Internal Error: {:?}", err); std::process::exit(3); } } } }; let reactor = spotify.poll(|client, status, change| { if change.client_version { println!("Spotify Client (Version {})", status.version()); } if change.track { println!("Now playing: {:#}", status.track()); println!("{}", status.full_track().track.uri); } true }); if reactor.join().ok().is_none() { println!("Unable to join into the live-update."); std::process::exit(4); } }
main
identifier_name
lib.rs
#![allow(bad_style)] extern crate libc; /* automatically generated by rust-bindgen */ pub enum Struct_blip_t { } pub type blip_t = Struct_blip_t; pub type Enum_Unnamed1 = ::libc::c_uint; pub const blip_max_ratio: ::libc::c_uint = 1048576; pub type Enum_Unnamed2 = ::libc::c_uint; pub const blip_max_frame: ::libc::c_uint = 4000; pub type blip_buffer_t = blip_t; extern "C" { pub fn blip_new(sample_count: ::libc::c_int) -> *mut blip_t; pub fn blip_set_rates(arg1: *mut blip_t, clock_rate: ::libc::c_double, sample_rate: ::libc::c_double) -> (); pub fn blip_clear(arg1: *mut blip_t) -> (); pub fn blip_add_delta(arg1: *mut blip_t, clock_time: ::libc::c_uint, delta: ::libc::c_int) -> (); pub fn blip_add_delta_fast(arg1: *mut blip_t, clock_time: ::libc::c_uint, delta: ::libc::c_int) -> (); pub fn blip_clocks_needed(arg1: *const blip_t, sample_count: ::libc::c_int) -> ::libc::c_int;
pub fn blip_end_frame(arg1: *mut blip_t, clock_duration: ::libc::c_uint) -> (); pub fn blip_samples_avail(arg1: *const blip_t) -> ::libc::c_int; pub fn blip_read_samples(arg1: *mut blip_t, out: *mut ::libc::c_short, count: ::libc::c_int, stereo: ::libc::c_int) -> ::libc::c_int; pub fn blip_delete(arg1: *mut blip_t) -> (); }
random_line_split
lib.rs
#![allow(bad_style)] extern crate libc; /* automatically generated by rust-bindgen */ pub enum
{ } pub type blip_t = Struct_blip_t; pub type Enum_Unnamed1 = ::libc::c_uint; pub const blip_max_ratio: ::libc::c_uint = 1048576; pub type Enum_Unnamed2 = ::libc::c_uint; pub const blip_max_frame: ::libc::c_uint = 4000; pub type blip_buffer_t = blip_t; extern "C" { pub fn blip_new(sample_count: ::libc::c_int) -> *mut blip_t; pub fn blip_set_rates(arg1: *mut blip_t, clock_rate: ::libc::c_double, sample_rate: ::libc::c_double) -> (); pub fn blip_clear(arg1: *mut blip_t) -> (); pub fn blip_add_delta(arg1: *mut blip_t, clock_time: ::libc::c_uint, delta: ::libc::c_int) -> (); pub fn blip_add_delta_fast(arg1: *mut blip_t, clock_time: ::libc::c_uint, delta: ::libc::c_int) -> (); pub fn blip_clocks_needed(arg1: *const blip_t, sample_count: ::libc::c_int) -> ::libc::c_int; pub fn blip_end_frame(arg1: *mut blip_t, clock_duration: ::libc::c_uint) -> (); pub fn blip_samples_avail(arg1: *const blip_t) -> ::libc::c_int; pub fn blip_read_samples(arg1: *mut blip_t, out: *mut ::libc::c_short, count: ::libc::c_int, stereo: ::libc::c_int) -> ::libc::c_int; pub fn blip_delete(arg1: *mut blip_t) -> (); }
Struct_blip_t
identifier_name
traits.rs
use {Vec2, Vec3, Vec4, Mat2, Mat3, Mat4, Quaternion}; use std::ops::{Add, Sub, Mul, Div}; use std::ops::{AddAssign, SubAssign, MulAssign, DivAssign}; use std::ops::{Neg}; use std::cmp::{PartialEq, PartialOrd}; /// Allows us to be generic over numeric types in vectors pub trait Number: Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Div<Output = Self> + AddAssign + SubAssign + MulAssign + DivAssign + PartialEq + PartialOrd + Sized + Copy { const ONE: Self; const ZERO: Self; } /// Allows us to be generic over signed numeric types in vectors pub trait Signed: Number + Neg<Output = Self> { #[inline(always)] fn abs(self) -> Self { if self < Self::ZERO { -self } else { self } } } macro_rules! impl_number { ($type: ident, $one: expr, $zero: expr) => { impl Number for $type { const ONE: Self = $one; const ZERO: Self = $zero; } }; } impl_number!(i8, 1, 0); impl_number!(i16, 1, 0); impl_number!(i32, 1, 0); impl_number!(i64, 1, 0); impl_number!(u8, 1, 0); impl_number!(u16, 1, 0); impl_number!(u32, 1, 0); impl_number!(u64, 1, 0); impl_number!(f32, 1.0, 0.0); impl_number!(f64, 1.0, 0.0); impl Signed for i8 {} impl Signed for i16 {} impl Signed for i32 {} impl Signed for i64 {} impl Signed for f32 {} impl Signed for f64 {} macro_rules! impl_float { ($($fn: ident),*) => { /// Allows us to be generic over floating point types pub trait Float: Number + Signed + Round {
impl Float for f32 { $(#[inline(always)] fn $fn(self) -> Self { self.$fn() })* #[inline(always)] fn sin_cos(self) -> (Self, Self) { self.sin_cos() } #[inline(always)] fn atan2(self, other: Self) -> Self { self.atan2(other) } } impl Float for f64 { $(#[inline(always)] fn $fn(self) -> Self { self.$fn() })* #[inline(always)] fn sin_cos(self) -> (Self, Self) { self.sin_cos() } #[inline(always)] fn atan2(self, other: Self) -> Self { self.atan2(other) } } }; } impl_float!(sin, cos, tan, asin, acos, atan, sqrt, floor, ceil, to_radians); /// Provides convenience functions for rounding all memebers of math types in various ways. pub trait Round { type Step: Copy; /// Rounds this value so that it has no decimal places. fn round(self) -> Self; /// Rounds the given value to the given number of decimals. fn round_to_precision(self, precision: usize) -> Self; /// Rounds the given value to the next multiple of `step`. fn round_to_step(self, step: Self::Step) -> Self; } impl Round for f32 { fn round(self) -> Self { f32::round(self) } fn round_to_precision(self, precision: usize) -> Self { let s = 10f32.powi(precision as i32); (self * s).round() / s } type Step = f32; fn round_to_step(self, step: f32) -> Self { (self / step).round() * step } } impl Round for f64 { fn round(self) -> Self { f64::round(self) } fn round_to_precision(self, precision: usize) -> Self { let s = 10f64.powi(precision as i32); (self * s).round() / s } type Step = f64; fn round_to_step(self, step: f64) -> Self { (self / step).round() * step } } macro_rules! impl_round { ($ty: ty, [$($field: ident),*]) => { impl<T: Round> Round for $ty { fn round(self) -> Self { Self { $($field: self.$field.round()),* } } fn round_to_precision(self, precision: usize) -> Self { Self { $($field: self.$field.round_to_precision(precision)),* } } type Step = T::Step; fn round_to_step(self, step: T::Step) -> Self { Self { $($field: self.$field.round_to_step(step)),* } } } }; } impl_round!(Vec2<T>, [x, y]); impl_round!(Vec3<T>, [x, y, z]); impl_round!(Vec4<T>, [x, y, z, w]); impl_round!(Quaternion<T>, [x, y, z, w]); impl_round!(Mat2<T>, [a11, a12, a21, a22]); impl_round!(Mat3<T>, [a11, a12, a13, a21, a22, a23, a31, a32, a33]); impl_round!(Mat4<T>, [a11, a12, a13, a14, a21, a22, a23, a24, a31, a32, a33, a34, a41, a42, a43, a44]);
$(fn $fn(self) -> Self;)* fn sin_cos(self) -> (Self, Self); fn atan2(self, other: Self) -> Self; }
random_line_split
traits.rs
use {Vec2, Vec3, Vec4, Mat2, Mat3, Mat4, Quaternion}; use std::ops::{Add, Sub, Mul, Div}; use std::ops::{AddAssign, SubAssign, MulAssign, DivAssign}; use std::ops::{Neg}; use std::cmp::{PartialEq, PartialOrd}; /// Allows us to be generic over numeric types in vectors pub trait Number: Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Div<Output = Self> + AddAssign + SubAssign + MulAssign + DivAssign + PartialEq + PartialOrd + Sized + Copy { const ONE: Self; const ZERO: Self; } /// Allows us to be generic over signed numeric types in vectors pub trait Signed: Number + Neg<Output = Self> { #[inline(always)] fn abs(self) -> Self { if self < Self::ZERO
else { self } } } macro_rules! impl_number { ($type: ident, $one: expr, $zero: expr) => { impl Number for $type { const ONE: Self = $one; const ZERO: Self = $zero; } }; } impl_number!(i8, 1, 0); impl_number!(i16, 1, 0); impl_number!(i32, 1, 0); impl_number!(i64, 1, 0); impl_number!(u8, 1, 0); impl_number!(u16, 1, 0); impl_number!(u32, 1, 0); impl_number!(u64, 1, 0); impl_number!(f32, 1.0, 0.0); impl_number!(f64, 1.0, 0.0); impl Signed for i8 {} impl Signed for i16 {} impl Signed for i32 {} impl Signed for i64 {} impl Signed for f32 {} impl Signed for f64 {} macro_rules! impl_float { ($($fn: ident),*) => { /// Allows us to be generic over floating point types pub trait Float: Number + Signed + Round { $(fn $fn(self) -> Self;)* fn sin_cos(self) -> (Self, Self); fn atan2(self, other: Self) -> Self; } impl Float for f32 { $(#[inline(always)] fn $fn(self) -> Self { self.$fn() })* #[inline(always)] fn sin_cos(self) -> (Self, Self) { self.sin_cos() } #[inline(always)] fn atan2(self, other: Self) -> Self { self.atan2(other) } } impl Float for f64 { $(#[inline(always)] fn $fn(self) -> Self { self.$fn() })* #[inline(always)] fn sin_cos(self) -> (Self, Self) { self.sin_cos() } #[inline(always)] fn atan2(self, other: Self) -> Self { self.atan2(other) } } }; } impl_float!(sin, cos, tan, asin, acos, atan, sqrt, floor, ceil, to_radians); /// Provides convenience functions for rounding all memebers of math types in various ways. pub trait Round { type Step: Copy; /// Rounds this value so that it has no decimal places. fn round(self) -> Self; /// Rounds the given value to the given number of decimals. fn round_to_precision(self, precision: usize) -> Self; /// Rounds the given value to the next multiple of `step`. fn round_to_step(self, step: Self::Step) -> Self; } impl Round for f32 { fn round(self) -> Self { f32::round(self) } fn round_to_precision(self, precision: usize) -> Self { let s = 10f32.powi(precision as i32); (self * s).round() / s } type Step = f32; fn round_to_step(self, step: f32) -> Self { (self / step).round() * step } } impl Round for f64 { fn round(self) -> Self { f64::round(self) } fn round_to_precision(self, precision: usize) -> Self { let s = 10f64.powi(precision as i32); (self * s).round() / s } type Step = f64; fn round_to_step(self, step: f64) -> Self { (self / step).round() * step } } macro_rules! impl_round { ($ty: ty, [$($field: ident),*]) => { impl<T: Round> Round for $ty { fn round(self) -> Self { Self { $($field: self.$field.round()),* } } fn round_to_precision(self, precision: usize) -> Self { Self { $($field: self.$field.round_to_precision(precision)),* } } type Step = T::Step; fn round_to_step(self, step: T::Step) -> Self { Self { $($field: self.$field.round_to_step(step)),* } } } }; } impl_round!(Vec2<T>, [x, y]); impl_round!(Vec3<T>, [x, y, z]); impl_round!(Vec4<T>, [x, y, z, w]); impl_round!(Quaternion<T>, [x, y, z, w]); impl_round!(Mat2<T>, [a11, a12, a21, a22]); impl_round!(Mat3<T>, [a11, a12, a13, a21, a22, a23, a31, a32, a33]); impl_round!(Mat4<T>, [a11, a12, a13, a14, a21, a22, a23, a24, a31, a32, a33, a34, a41, a42, a43, a44]);
{ -self }
conditional_block
traits.rs
use {Vec2, Vec3, Vec4, Mat2, Mat3, Mat4, Quaternion}; use std::ops::{Add, Sub, Mul, Div}; use std::ops::{AddAssign, SubAssign, MulAssign, DivAssign}; use std::ops::{Neg}; use std::cmp::{PartialEq, PartialOrd}; /// Allows us to be generic over numeric types in vectors pub trait Number: Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Div<Output = Self> + AddAssign + SubAssign + MulAssign + DivAssign + PartialEq + PartialOrd + Sized + Copy { const ONE: Self; const ZERO: Self; } /// Allows us to be generic over signed numeric types in vectors pub trait Signed: Number + Neg<Output = Self> { #[inline(always)] fn abs(self) -> Self
} macro_rules! impl_number { ($type: ident, $one: expr, $zero: expr) => { impl Number for $type { const ONE: Self = $one; const ZERO: Self = $zero; } }; } impl_number!(i8, 1, 0); impl_number!(i16, 1, 0); impl_number!(i32, 1, 0); impl_number!(i64, 1, 0); impl_number!(u8, 1, 0); impl_number!(u16, 1, 0); impl_number!(u32, 1, 0); impl_number!(u64, 1, 0); impl_number!(f32, 1.0, 0.0); impl_number!(f64, 1.0, 0.0); impl Signed for i8 {} impl Signed for i16 {} impl Signed for i32 {} impl Signed for i64 {} impl Signed for f32 {} impl Signed for f64 {} macro_rules! impl_float { ($($fn: ident),*) => { /// Allows us to be generic over floating point types pub trait Float: Number + Signed + Round { $(fn $fn(self) -> Self;)* fn sin_cos(self) -> (Self, Self); fn atan2(self, other: Self) -> Self; } impl Float for f32 { $(#[inline(always)] fn $fn(self) -> Self { self.$fn() })* #[inline(always)] fn sin_cos(self) -> (Self, Self) { self.sin_cos() } #[inline(always)] fn atan2(self, other: Self) -> Self { self.atan2(other) } } impl Float for f64 { $(#[inline(always)] fn $fn(self) -> Self { self.$fn() })* #[inline(always)] fn sin_cos(self) -> (Self, Self) { self.sin_cos() } #[inline(always)] fn atan2(self, other: Self) -> Self { self.atan2(other) } } }; } impl_float!(sin, cos, tan, asin, acos, atan, sqrt, floor, ceil, to_radians); /// Provides convenience functions for rounding all memebers of math types in various ways. pub trait Round { type Step: Copy; /// Rounds this value so that it has no decimal places. fn round(self) -> Self; /// Rounds the given value to the given number of decimals. fn round_to_precision(self, precision: usize) -> Self; /// Rounds the given value to the next multiple of `step`. fn round_to_step(self, step: Self::Step) -> Self; } impl Round for f32 { fn round(self) -> Self { f32::round(self) } fn round_to_precision(self, precision: usize) -> Self { let s = 10f32.powi(precision as i32); (self * s).round() / s } type Step = f32; fn round_to_step(self, step: f32) -> Self { (self / step).round() * step } } impl Round for f64 { fn round(self) -> Self { f64::round(self) } fn round_to_precision(self, precision: usize) -> Self { let s = 10f64.powi(precision as i32); (self * s).round() / s } type Step = f64; fn round_to_step(self, step: f64) -> Self { (self / step).round() * step } } macro_rules! impl_round { ($ty: ty, [$($field: ident),*]) => { impl<T: Round> Round for $ty { fn round(self) -> Self { Self { $($field: self.$field.round()),* } } fn round_to_precision(self, precision: usize) -> Self { Self { $($field: self.$field.round_to_precision(precision)),* } } type Step = T::Step; fn round_to_step(self, step: T::Step) -> Self { Self { $($field: self.$field.round_to_step(step)),* } } } }; } impl_round!(Vec2<T>, [x, y]); impl_round!(Vec3<T>, [x, y, z]); impl_round!(Vec4<T>, [x, y, z, w]); impl_round!(Quaternion<T>, [x, y, z, w]); impl_round!(Mat2<T>, [a11, a12, a21, a22]); impl_round!(Mat3<T>, [a11, a12, a13, a21, a22, a23, a31, a32, a33]); impl_round!(Mat4<T>, [a11, a12, a13, a14, a21, a22, a23, a24, a31, a32, a33, a34, a41, a42, a43, a44]);
{ if self < Self::ZERO { -self } else { self } }
identifier_body
traits.rs
use {Vec2, Vec3, Vec4, Mat2, Mat3, Mat4, Quaternion}; use std::ops::{Add, Sub, Mul, Div}; use std::ops::{AddAssign, SubAssign, MulAssign, DivAssign}; use std::ops::{Neg}; use std::cmp::{PartialEq, PartialOrd}; /// Allows us to be generic over numeric types in vectors pub trait Number: Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Div<Output = Self> + AddAssign + SubAssign + MulAssign + DivAssign + PartialEq + PartialOrd + Sized + Copy { const ONE: Self; const ZERO: Self; } /// Allows us to be generic over signed numeric types in vectors pub trait Signed: Number + Neg<Output = Self> { #[inline(always)] fn abs(self) -> Self { if self < Self::ZERO { -self } else { self } } } macro_rules! impl_number { ($type: ident, $one: expr, $zero: expr) => { impl Number for $type { const ONE: Self = $one; const ZERO: Self = $zero; } }; } impl_number!(i8, 1, 0); impl_number!(i16, 1, 0); impl_number!(i32, 1, 0); impl_number!(i64, 1, 0); impl_number!(u8, 1, 0); impl_number!(u16, 1, 0); impl_number!(u32, 1, 0); impl_number!(u64, 1, 0); impl_number!(f32, 1.0, 0.0); impl_number!(f64, 1.0, 0.0); impl Signed for i8 {} impl Signed for i16 {} impl Signed for i32 {} impl Signed for i64 {} impl Signed for f32 {} impl Signed for f64 {} macro_rules! impl_float { ($($fn: ident),*) => { /// Allows us to be generic over floating point types pub trait Float: Number + Signed + Round { $(fn $fn(self) -> Self;)* fn sin_cos(self) -> (Self, Self); fn atan2(self, other: Self) -> Self; } impl Float for f32 { $(#[inline(always)] fn $fn(self) -> Self { self.$fn() })* #[inline(always)] fn sin_cos(self) -> (Self, Self) { self.sin_cos() } #[inline(always)] fn atan2(self, other: Self) -> Self { self.atan2(other) } } impl Float for f64 { $(#[inline(always)] fn $fn(self) -> Self { self.$fn() })* #[inline(always)] fn sin_cos(self) -> (Self, Self) { self.sin_cos() } #[inline(always)] fn atan2(self, other: Self) -> Self { self.atan2(other) } } }; } impl_float!(sin, cos, tan, asin, acos, atan, sqrt, floor, ceil, to_radians); /// Provides convenience functions for rounding all memebers of math types in various ways. pub trait Round { type Step: Copy; /// Rounds this value so that it has no decimal places. fn round(self) -> Self; /// Rounds the given value to the given number of decimals. fn round_to_precision(self, precision: usize) -> Self; /// Rounds the given value to the next multiple of `step`. fn round_to_step(self, step: Self::Step) -> Self; } impl Round for f32 { fn round(self) -> Self { f32::round(self) } fn round_to_precision(self, precision: usize) -> Self { let s = 10f32.powi(precision as i32); (self * s).round() / s } type Step = f32; fn
(self, step: f32) -> Self { (self / step).round() * step } } impl Round for f64 { fn round(self) -> Self { f64::round(self) } fn round_to_precision(self, precision: usize) -> Self { let s = 10f64.powi(precision as i32); (self * s).round() / s } type Step = f64; fn round_to_step(self, step: f64) -> Self { (self / step).round() * step } } macro_rules! impl_round { ($ty: ty, [$($field: ident),*]) => { impl<T: Round> Round for $ty { fn round(self) -> Self { Self { $($field: self.$field.round()),* } } fn round_to_precision(self, precision: usize) -> Self { Self { $($field: self.$field.round_to_precision(precision)),* } } type Step = T::Step; fn round_to_step(self, step: T::Step) -> Self { Self { $($field: self.$field.round_to_step(step)),* } } } }; } impl_round!(Vec2<T>, [x, y]); impl_round!(Vec3<T>, [x, y, z]); impl_round!(Vec4<T>, [x, y, z, w]); impl_round!(Quaternion<T>, [x, y, z, w]); impl_round!(Mat2<T>, [a11, a12, a21, a22]); impl_round!(Mat3<T>, [a11, a12, a13, a21, a22, a23, a31, a32, a33]); impl_round!(Mat4<T>, [a11, a12, a13, a14, a21, a22, a23, a24, a31, a32, a33, a34, a41, a42, a43, a44]);
round_to_step
identifier_name
uievent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBinding; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, RootedReference}; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::window::Window; use servo_atoms::Atom; use std::cell::Cell; use std::default::Default; // https://w3c.github.io/uievents/#interface-uievent #[dom_struct] pub struct UIEvent { event: Event, view: MutNullableHeap<JS<Window>>, detail: Cell<i32> } impl UIEvent { pub fn new_inherited() -> UIEvent { UIEvent { event: Event::new_inherited(), view: Default::default(), detail: Cell::new(0), } } pub fn new_uninitialized(window: &Window) -> Root<UIEvent> { reflect_dom_object(box UIEvent::new_inherited(), window, UIEventBinding::Wrap) } pub fn new(window: &Window, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, view: Option<&Window>, detail: i32) -> Root<UIEvent> { let ev = UIEvent::new_uninitialized(window); ev.InitUIEvent(type_, bool::from(can_bubble), bool::from(cancelable), view, detail); ev } pub fn Constructor(window: &Window, type_: DOMString, init: &UIEventBinding::UIEventInit) -> Fallible<Root<UIEvent>> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); let event = UIEvent::new(window, type_, bubbles, cancelable, init.view.r(), init.detail); Ok(event) } } impl UIEventMethods for UIEvent { // https://w3c.github.io/uievents/#widl-UIEvent-view fn GetView(&self) -> Option<Root<Window>> { self.view.get() } // https://w3c.github.io/uievents/#widl-UIEvent-detail fn Detail(&self) -> i32 { self.detail.get() } // https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent fn InitUIEvent(&self, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32) { let event = self.upcast::<Event>(); if event.dispatching() { return; } event.init_event(Atom::from(type_), can_bubble, cancelable); self.view.set(view); self.detail.set(detail); } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool
}
{ self.event.IsTrusted() }
identifier_body
uievent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBinding; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, RootedReference}; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::window::Window; use servo_atoms::Atom; use std::cell::Cell; use std::default::Default; // https://w3c.github.io/uievents/#interface-uievent #[dom_struct] pub struct UIEvent { event: Event, view: MutNullableHeap<JS<Window>>, detail: Cell<i32> } impl UIEvent { pub fn
() -> UIEvent { UIEvent { event: Event::new_inherited(), view: Default::default(), detail: Cell::new(0), } } pub fn new_uninitialized(window: &Window) -> Root<UIEvent> { reflect_dom_object(box UIEvent::new_inherited(), window, UIEventBinding::Wrap) } pub fn new(window: &Window, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, view: Option<&Window>, detail: i32) -> Root<UIEvent> { let ev = UIEvent::new_uninitialized(window); ev.InitUIEvent(type_, bool::from(can_bubble), bool::from(cancelable), view, detail); ev } pub fn Constructor(window: &Window, type_: DOMString, init: &UIEventBinding::UIEventInit) -> Fallible<Root<UIEvent>> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); let event = UIEvent::new(window, type_, bubbles, cancelable, init.view.r(), init.detail); Ok(event) } } impl UIEventMethods for UIEvent { // https://w3c.github.io/uievents/#widl-UIEvent-view fn GetView(&self) -> Option<Root<Window>> { self.view.get() } // https://w3c.github.io/uievents/#widl-UIEvent-detail fn Detail(&self) -> i32 { self.detail.get() } // https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent fn InitUIEvent(&self, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32) { let event = self.upcast::<Event>(); if event.dispatching() { return; } event.init_event(Atom::from(type_), can_bubble, cancelable); self.view.set(view); self.detail.set(detail); } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
new_inherited
identifier_name
uievent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBinding; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, RootedReference}; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::window::Window; use servo_atoms::Atom; use std::cell::Cell; use std::default::Default; // https://w3c.github.io/uievents/#interface-uievent #[dom_struct] pub struct UIEvent { event: Event, view: MutNullableHeap<JS<Window>>, detail: Cell<i32> } impl UIEvent { pub fn new_inherited() -> UIEvent { UIEvent { event: Event::new_inherited(), view: Default::default(), detail: Cell::new(0), } } pub fn new_uninitialized(window: &Window) -> Root<UIEvent> { reflect_dom_object(box UIEvent::new_inherited(), window, UIEventBinding::Wrap) } pub fn new(window: &Window, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, view: Option<&Window>, detail: i32) -> Root<UIEvent> { let ev = UIEvent::new_uninitialized(window); ev.InitUIEvent(type_, bool::from(can_bubble), bool::from(cancelable), view, detail); ev } pub fn Constructor(window: &Window, type_: DOMString, init: &UIEventBinding::UIEventInit) -> Fallible<Root<UIEvent>> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); let event = UIEvent::new(window, type_, bubbles, cancelable, init.view.r(), init.detail); Ok(event) } } impl UIEventMethods for UIEvent { // https://w3c.github.io/uievents/#widl-UIEvent-view fn GetView(&self) -> Option<Root<Window>> { self.view.get() } // https://w3c.github.io/uievents/#widl-UIEvent-detail fn Detail(&self) -> i32 { self.detail.get() } // https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent fn InitUIEvent(&self, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32) { let event = self.upcast::<Event>(); if event.dispatching()
event.init_event(Atom::from(type_), can_bubble, cancelable); self.view.set(view); self.detail.set(detail); } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
{ return; }
conditional_block
uievent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBinding; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, RootedReference}; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::window::Window; use servo_atoms::Atom; use std::cell::Cell; use std::default::Default; // https://w3c.github.io/uievents/#interface-uievent #[dom_struct] pub struct UIEvent { event: Event, view: MutNullableHeap<JS<Window>>, detail: Cell<i32> } impl UIEvent { pub fn new_inherited() -> UIEvent { UIEvent { event: Event::new_inherited(), view: Default::default(), detail: Cell::new(0), } } pub fn new_uninitialized(window: &Window) -> Root<UIEvent> { reflect_dom_object(box UIEvent::new_inherited(), window, UIEventBinding::Wrap) } pub fn new(window: &Window, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, view: Option<&Window>, detail: i32) -> Root<UIEvent> { let ev = UIEvent::new_uninitialized(window); ev.InitUIEvent(type_, bool::from(can_bubble), bool::from(cancelable), view, detail); ev } pub fn Constructor(window: &Window, type_: DOMString, init: &UIEventBinding::UIEventInit) -> Fallible<Root<UIEvent>> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); let event = UIEvent::new(window, type_, bubbles, cancelable, init.view.r(), init.detail); Ok(event)
fn GetView(&self) -> Option<Root<Window>> { self.view.get() } // https://w3c.github.io/uievents/#widl-UIEvent-detail fn Detail(&self) -> i32 { self.detail.get() } // https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent fn InitUIEvent(&self, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32) { let event = self.upcast::<Event>(); if event.dispatching() { return; } event.init_event(Atom::from(type_), can_bubble, cancelable); self.view.set(view); self.detail.set(detail); } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
} } impl UIEventMethods for UIEvent { // https://w3c.github.io/uievents/#widl-UIEvent-view
random_line_split
cfixed_string.rs
use std::borrow::{Borrow, Cow}; use std::ffi::{CStr, CString}; use std::fmt; use std::mem; use std::ops; use std::os::raw::c_char; use std::ptr; const STRING_SIZE: usize = 512; /// This is a C String abstractions that presents a CStr like /// interface for interop purposes but tries to be little nicer /// by avoiding heap allocations if the string is within the /// generous bounds (512 bytes) of the statically sized buffer. /// Strings over this limit will be heap allocated, but the /// interface outside of this abstraction remains the same. pub enum CFixedString { Local { s: [c_char; STRING_SIZE], len: usize, }, Heap { s: CString, len: usize, }, } impl CFixedString { /// Creates an empty CFixedString, this is intended to be /// used with write! or the `fmt::Write` trait pub fn new() -> Self { unsafe { CFixedString::Local { s: mem::uninitialized(), len: 0, } } } pub fn from_str<S: AsRef<str>>(s: S) -> Self { Self::from(s.as_ref()) } pub fn as_ptr(&self) -> *const c_char { match *self { CFixedString::Local { ref s,.. } => s.as_ptr(), CFixedString::Heap { ref s,.. } => s.as_ptr(), } } /// Returns true if the string has been heap allocated pub fn is_allocated(&self) -> bool { match *self { CFixedString::Local {.. } => false, _ => true, } } /// Converts a `CFixedString` into a `Cow<str>`. /// /// This function will calculate the length of this string (which normally /// requires a linear amount of work to be done) and then return the /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences /// with `U+FFFD REPLACEMENT CHARACTER`. If there are no invalid UTF-8 /// sequences, this will merely return a borrowed slice. pub fn to_string(&self) -> Cow<str> { String::from_utf8_lossy(&self.to_bytes()) } pub unsafe fn as_str(&self) -> &str { use std::slice; use std::str; match *self { CFixedString::Local { ref s, len } =>
CFixedString::Heap { ref s, len } => { str::from_utf8_unchecked(slice::from_raw_parts(s.as_ptr() as *const u8, len)) } } } } impl<'a> From<&'a str> for CFixedString { fn from(s: &'a str) -> Self { use std::fmt::Write; let mut string = CFixedString::new(); string.write_str(s).unwrap(); string } } impl fmt::Write for CFixedString { fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { // use std::fmt::Write; unsafe { let cur_len = self.as_str().len(); match cur_len + s.len() { len if len <= STRING_SIZE - 1 => { match *self { CFixedString::Local { s: ref mut ls, len: ref mut lslen } => { let ptr = ls.as_mut_ptr() as *mut u8; ptr::copy(s.as_ptr(), ptr.offset(cur_len as isize), s.len()); *ptr.offset(len as isize) = 0; *lslen = len; } _ => unreachable!(), } } len => { let mut heapstring = String::with_capacity(len + 1); heapstring.write_str(self.as_str()).unwrap(); heapstring.write_str(s).unwrap(); *self = CFixedString::Heap { s: CString::new(heapstring).unwrap(), len: len, }; } } } // Yah....we should do error handling Ok(()) } } impl From<CFixedString> for String { fn from(s: CFixedString) -> Self { String::from_utf8_lossy(&s.to_bytes()).into_owned() } } impl ops::Deref for CFixedString { type Target = CStr; fn deref(&self) -> &CStr { use std::slice; match *self { CFixedString::Local { ref s, len } => unsafe { mem::transmute(slice::from_raw_parts(s.as_ptr(), len + 1)) }, CFixedString::Heap { ref s,.. } => s, } } } impl Borrow<CStr> for CFixedString { fn borrow(&self) -> &CStr { self } } impl AsRef<CStr> for CFixedString { fn as_ref(&self) -> &CStr { self } } impl Borrow<str> for CFixedString { fn borrow(&self) -> &str { unsafe { self.as_str() } } } impl AsRef<str> for CFixedString { fn as_ref(&self) -> &str { unsafe { self.as_str() } } } macro_rules! format_c { // This does not work on stable, to change the * to a + and // have this arm be used when there are no arguments :( // ($fmt:expr) => { // use std::fmt::Write; // let mut fixed = CFixedString::new(); // write!(&mut fixed, $fmt).unwrap(); // fixed // } ($fmt:expr, $($args:tt)*) => ({ use std::fmt::Write; let mut fixed = CFixedString::new(); write!(&mut fixed, $fmt, $($args)*).unwrap(); fixed }) } #[cfg(test)] mod tests { use super::*; use std::fmt::Write; fn gen_string(len: usize) -> String { let mut out = String::with_capacity(len); for _ in 0..len / 16 { out.write_str("zyxvutabcdef9876").unwrap(); } for i in 0..len % 16 { out.write_char((i as u8 + 'A' as u8) as char).unwrap(); } assert_eq!(out.len(), len); out } #[test] fn test_empty_handler() { let short_string = ""; let t = CFixedString::from_str(short_string); assert!(!t.is_allocated()); assert_eq!(&t.to_string(), short_string); } #[test] fn test_short_1() { let short_string = "test_local"; let t = CFixedString::from_str(short_string); assert!(!t.is_allocated()); assert_eq!(&t.to_string(), short_string); } #[test] fn test_short_2() { let short_string = "test_local stoheusthsotheost"; let t = CFixedString::from_str(short_string); assert!(!t.is_allocated()); assert_eq!(&t.to_string(), short_string); } #[test] fn test_511() { // this string (width 511) buffer should just fit let test_511_string = gen_string(511); let t = CFixedString::from_str(&test_511_string); assert!(!t.is_allocated()); assert_eq!(&t.to_string(), &test_511_string); } #[test] fn test_512() { // this string (width 512) buffer should not fit let test_512_string = gen_string(512); let t = CFixedString::from_str(&test_512_string); assert!(t.is_allocated()); assert_eq!(&t.to_string(), &test_512_string); } #[test] fn test_513() { // this string (width 513) buffer should not fit let test_513_string = gen_string(513); let t = CFixedString::from_str(&test_513_string); assert!(t.is_allocated()); assert_eq!(&t.to_string(), &test_513_string); } #[test] fn test_to_owned() { let short = "this is an amazing string"; let t = CFixedString::from_str(short); assert!(!t.is_allocated()); assert_eq!(&String::from(t), short); let long = gen_string(1025); let t = CFixedString::from_str(&long); assert!(t.is_allocated()); assert_eq!(&String::from(t), &long); } #[test] fn test_short_format() { let mut fixed = CFixedString::new(); write!(&mut fixed, "one_{}", 1).unwrap(); write!(&mut fixed, "_two_{}", "two").unwrap(); write!(&mut fixed, "_three_{}-{}-{:.3}", 23, "some string data", 56.789) .unwrap(); assert!(!fixed.is_allocated()); assert_eq!(&fixed.to_string(), "one_1_two_two_three_23-some string data-56.789"); } #[test] fn test_long_format() { let mut fixed = CFixedString::new(); let mut string = String::new(); for i in 1..30 { let genned = gen_string(i * i); write!(&mut fixed, "{}_{}", i, genned).unwrap(); write!(&mut string, "{}_{}", i, genned).unwrap(); } assert!(fixed.is_allocated()); assert_eq!(&fixed.to_string(), &string); } // TODO: Reenable this test once the empty match arm is allowed // by the compiler // #[test] // fn test_empty_fmt_macro() { // let empty = format_c!(""); // let no_args = format_c!("there are no format args"); // // assert!(!empty.is_allocated()); // assert_eq!(&empty.to_string(), ""); // // assert!(!no_args.is_allocated()); // assert_eq!(&no_args.to_string(), "there are no format args"); // } #[test] fn test_short_fmt_macro() { let first = 23; let second = "#@!*()&^%_-+={}[]|\\/?><,.:;~`"; let third = u32::max_value(); let fourth = gen_string(512 - 45); let fixed = format_c!("{}_{}_0x{:x}_{}", first, second, third, fourth); let heaped = format!("{}_{}_0x{:x}_{}", first, second, third, fourth); assert!(!fixed.is_allocated()); assert_eq!(&fixed.to_string(), &heaped); } #[test] fn test_long_fmt_macro() { let first = ""; let second = gen_string(510); let third = 3; let fourth = gen_string(513 * 8); let fixed = format_c!("{}_{}{}{}", first, second, third, fourth); let heaped = format!("{}_{}{}{}", first, second, third, fourth); assert!(fixed.is_allocated()); assert_eq!(&fixed.to_string(), &heaped); } }
{ str::from_utf8_unchecked(slice::from_raw_parts(s.as_ptr() as *const u8, len)) }
conditional_block