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
pair.rs
//! Hashable pair of objects implementing `HasUid`. use data::hash; use data::hash::HashFun; use data::uid_remap::FastKey; // XXX: Rename this `FastKeyPair`. /// An unordered pair of elements implementing `HasUid`. #[derive(Clone, Copy, RustcEncodable, RustcDecodable)] pub struct Pair { /// first object of the pair pub first: FastKey, /// second object of the pair pub second: FastKey, ifirst: usize, isecond: usize } impl Pair { /// Builds a new `Pair`. pub fn new(a: FastKey, b: FastKey) -> Pair { let ia = a.uid(); let ib = b.uid(); if a.uid() < b.uid()
else { Pair { first: a, second: b, ifirst: ib, isecond: ia } } } } impl PartialEq for Pair { #[inline] fn eq(&self, other: &Pair) -> bool { self.ifirst == other.ifirst && self.isecond == other.isecond } } /// Tomas Wang based hash function for a `Pair` object. #[derive(RustcEncodable, RustcDecodable)] pub struct PairTWHash { unused: usize } // FIXME: ICE with zero-sized structs impl PairTWHash { /// Creates a new PairTWHash pub fn new() -> PairTWHash { PairTWHash { unused: 0 } } } impl HashFun<Pair> for PairTWHash { #[inline] fn hash(&self, p: &Pair) -> usize { hash::tomas_wang_hash( hash::key_from_pair( p.ifirst, p.isecond ) ) } }
{ Pair { first: a, second: b, ifirst: ia, isecond: ib } }
conditional_block
pair.rs
//! Hashable pair of objects implementing `HasUid`. use data::hash; use data::hash::HashFun; use data::uid_remap::FastKey; // XXX: Rename this `FastKeyPair`. /// An unordered pair of elements implementing `HasUid`. #[derive(Clone, Copy, RustcEncodable, RustcDecodable)] pub struct Pair { /// first object of the pair pub first: FastKey, /// second object of the pair pub second: FastKey, ifirst: usize, isecond: usize } impl Pair { /// Builds a new `Pair`. pub fn new(a: FastKey, b: FastKey) -> Pair { let ia = a.uid(); let ib = b.uid(); if a.uid() < b.uid() { Pair { first: a, second: b, ifirst: ia, isecond: ib } } else { Pair { first: a, second: b, ifirst: ib, isecond: ia } } } } impl PartialEq for Pair { #[inline] fn eq(&self, other: &Pair) -> bool { self.ifirst == other.ifirst && self.isecond == other.isecond } } /// Tomas Wang based hash function for a `Pair` object. #[derive(RustcEncodable, RustcDecodable)] pub struct PairTWHash { unused: usize } // FIXME: ICE with zero-sized structs impl PairTWHash { /// Creates a new PairTWHash pub fn new() -> PairTWHash { PairTWHash { unused: 0 } } } impl HashFun<Pair> for PairTWHash { #[inline] fn hash(&self, p: &Pair) -> usize
}
{ hash::tomas_wang_hash( hash::key_from_pair( p.ifirst, p.isecond ) ) }
identifier_body
pair.rs
//! Hashable pair of objects implementing `HasUid`. use data::hash; use data::hash::HashFun; use data::uid_remap::FastKey; // XXX: Rename this `FastKeyPair`. /// An unordered pair of elements implementing `HasUid`. #[derive(Clone, Copy, RustcEncodable, RustcDecodable)] pub struct Pair { /// first object of the pair pub first: FastKey, /// second object of the pair pub second: FastKey, ifirst: usize, isecond: usize } impl Pair { /// Builds a new `Pair`. pub fn new(a: FastKey, b: FastKey) -> Pair { let ia = a.uid(); let ib = b.uid(); if a.uid() < b.uid() { Pair { first: a, second: b, ifirst: ia, isecond: ib } } else { Pair { first: a, second: b, ifirst: ib, isecond: ia } } } } impl PartialEq for Pair { #[inline] fn
(&self, other: &Pair) -> bool { self.ifirst == other.ifirst && self.isecond == other.isecond } } /// Tomas Wang based hash function for a `Pair` object. #[derive(RustcEncodable, RustcDecodable)] pub struct PairTWHash { unused: usize } // FIXME: ICE with zero-sized structs impl PairTWHash { /// Creates a new PairTWHash pub fn new() -> PairTWHash { PairTWHash { unused: 0 } } } impl HashFun<Pair> for PairTWHash { #[inline] fn hash(&self, p: &Pair) -> usize { hash::tomas_wang_hash( hash::key_from_pair( p.ifirst, p.isecond ) ) } }
eq
identifier_name
pair.rs
//! Hashable pair of objects implementing `HasUid`. use data::hash; use data::hash::HashFun; use data::uid_remap::FastKey; // XXX: Rename this `FastKeyPair`. /// An unordered pair of elements implementing `HasUid`.
pub struct Pair { /// first object of the pair pub first: FastKey, /// second object of the pair pub second: FastKey, ifirst: usize, isecond: usize } impl Pair { /// Builds a new `Pair`. pub fn new(a: FastKey, b: FastKey) -> Pair { let ia = a.uid(); let ib = b.uid(); if a.uid() < b.uid() { Pair { first: a, second: b, ifirst: ia, isecond: ib } } else { Pair { first: a, second: b, ifirst: ib, isecond: ia } } } } impl PartialEq for Pair { #[inline] fn eq(&self, other: &Pair) -> bool { self.ifirst == other.ifirst && self.isecond == other.isecond } } /// Tomas Wang based hash function for a `Pair` object. #[derive(RustcEncodable, RustcDecodable)] pub struct PairTWHash { unused: usize } // FIXME: ICE with zero-sized structs impl PairTWHash { /// Creates a new PairTWHash pub fn new() -> PairTWHash { PairTWHash { unused: 0 } } } impl HashFun<Pair> for PairTWHash { #[inline] fn hash(&self, p: &Pair) -> usize { hash::tomas_wang_hash( hash::key_from_pair( p.ifirst, p.isecond ) ) } }
#[derive(Clone, Copy, RustcEncodable, RustcDecodable)]
random_line_split
lib.rs
#[macro_use] extern crate syntaxis; use syntaxis::{M, GR, NonTerminalSet, TerminalSet, NonTerminal, RegularProductions, gr_to_afndl, minify, afndl_to_afd}; #[test] fn
() { let vn: NonTerminalSet = charset!('S'); let vt: TerminalSet = charset!('a'); let q0: NonTerminal = 'S'; let productions: RegularProductions = r_productions!(('S', "aS"), ('S', "a")); let gr: GR = GR::new(vt, vn, productions, q0); let m: M = gr_to_afndl(&gr); println!("afndl {:?}", m); let m: M = afndl_to_afd(&m); println!("afd {:?}", m); let min_m: M = minify(&m); println!("minified {:?}", min_m); assert_eq!(m, min_m); //TODO: improve this test }
grammar_to_automata_min
identifier_name
lib.rs
#[macro_use] extern crate syntaxis; use syntaxis::{M, GR, NonTerminalSet, TerminalSet, NonTerminal, RegularProductions, gr_to_afndl, minify, afndl_to_afd}; #[test] fn grammar_to_automata_min() { let vn: NonTerminalSet = charset!('S'); let vt: TerminalSet = charset!('a'); let q0: NonTerminal = 'S'; let productions: RegularProductions = r_productions!(('S', "aS"), ('S', "a")); let gr: GR = GR::new(vt, vn, productions, q0); let m: M = gr_to_afndl(&gr); println!("afndl {:?}", m); let m: M = afndl_to_afd(&m);
println!("minified {:?}", min_m); assert_eq!(m, min_m); //TODO: improve this test }
println!("afd {:?}", m); let min_m: M = minify(&m);
random_line_split
lib.rs
#[macro_use] extern crate syntaxis; use syntaxis::{M, GR, NonTerminalSet, TerminalSet, NonTerminal, RegularProductions, gr_to_afndl, minify, afndl_to_afd}; #[test] fn grammar_to_automata_min()
{ let vn: NonTerminalSet = charset!('S'); let vt: TerminalSet = charset!('a'); let q0: NonTerminal = 'S'; let productions: RegularProductions = r_productions!(('S', "aS"), ('S', "a")); let gr: GR = GR::new(vt, vn, productions, q0); let m: M = gr_to_afndl(&gr); println!("afndl {:?}", m); let m: M = afndl_to_afd(&m); println!("afd {:?}", m); let min_m: M = minify(&m); println!("minified {:?}", min_m); assert_eq!(m, min_m); //TODO: improve this test }
identifier_body
otp_mmap.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 use crate::otp::otp_img::OtpImg; use crate::otp::vmem_serialize::*; use crate::util::num_de::{self, DeferredValue}; use anyhow::{anyhow, bail, Result}; use serde::Deserialize; use std::collections::HashMap; use std::convert::TryInto; use std::fs; use std::path::Path; #[derive(Deserialize, Debug)] struct OtpMapConfig { #[serde(with = "num_de")] width: usize, #[serde(with = "num_de")] depth: usize, } #[derive(Deserialize, Debug)] struct OtpMapKey { name: String, value: DeferredValue, } #[derive(Deserialize, Debug)] struct OtpMapDigest { name: String, iv_value: DeferredValue, cnst_value: DeferredValue, } #[derive(Deserialize, Debug)] struct OtpMapScrambling { #[serde(with = "num_de")] key_size: usize, #[serde(with = "num_de")] iv_size: usize, #[serde(with = "num_de")] cnst_size: usize,
#[derive(Deserialize, Debug)] struct OtpMapItem { name: String, #[serde(with = "num_de")] size: usize, #[serde(default)] isdigest: bool, inv_default: Option<DeferredValue>, } #[derive(Deserialize, Debug)] pub struct OtpMapPartition { name: String, secret: bool, #[serde(default, with = "num_de")] size: usize, sw_digest: bool, hw_digest: bool, key_sel: String, items: Vec<OtpMapItem>, } #[derive(Deserialize, Debug)] pub struct OtpMap { seed: String, otp: OtpMapConfig, scrambling: OtpMapScrambling, partitions: Vec<OtpMapPartition>, } impl OtpMap { pub fn new(in_file: &Path) -> Result<OtpMap> { let json_text = fs::read_to_string(in_file)?; let res: OtpMap = deser_hjson::from_str(&json_text)?; Ok(res) } pub fn generate_keys(&self, img: &OtpImg) -> HashMap<String, Vec<u8>> { let mut rng = img.get_rng(); let mut map = HashMap::new(); for key in &self.scrambling.keys { let value = key.value.resolve(self.scrambling.key_size, &mut rng); map.insert(key.name.clone(), value); } map } pub fn make_vmem(&mut self, img: &mut OtpImg) -> Result<VmemImage> { // Seeded RNG needed for "<random>" values. let mut rng = img.get_rng(); let mut vmem_partitions = Vec::<VmemPartition>::new(); for partition in &self.partitions { let key_name = match partition.key_sel.as_str() { "NoKey" => None, key => Some(key.to_owned()), }; let digest_type = if!partition.sw_digest &&!partition.hw_digest { DigestType::Unlocked } else if partition.sw_digest &&!partition.hw_digest { DigestType::Software } else if!partition.sw_digest && partition.hw_digest { // Extra information needed to compute HW digests. let iv_size = self.scrambling.iv_size; let cnst_size = self.scrambling.cnst_size; let digest_info = self .scrambling .digests .iter_mut() .find(|v| v.name == "CnstyDigest") .ok_or(anyhow!("Couldn't find digest info"))?; const IV_SIZE: usize = std::mem::size_of::<DigestIV>(); const CNST_SIZE: usize = std::mem::size_of::<DigestCnst>(); let iv_value: [u8; IV_SIZE] = digest_info .iv_value .resolve(iv_size, &mut rng) .try_into() .map_err(|_| anyhow!("Bad IV size {}", iv_size))?; let cnst_value: [u8; CNST_SIZE] = digest_info .cnst_value .resolve(cnst_size, &mut rng) .try_into() .map_err(|_| anyhow!("Bad scrambling constant size {}", cnst_size))?; DigestType::Hardware( DigestIV::from_ne_bytes(iv_value), DigestCnst::from_ne_bytes(cnst_value), ) } else { bail!("Invalid digest configuration"); }; let mut vmem_partition = VmemPartition::new( partition.name.clone(), partition.size, digest_type, key_name, ); // Fetch the img definition for partition, this contains the associated values for // paritition items. let mut img_partition = img.get_partition(&partition.name); let mut offset = 0usize; // Resolve all values and convert to Vmem representation. for item in &partition.items { let img_item_value = match &mut img_partition { Some(v) => { let item_value = v.get_item(&item.name); match item_value { Some(v) => v.value.resolve(item.size, &mut rng), None => vec![0u8; item.size], } } None => vec![0u8; item.size], }; let vmem_item = VmemItem::new(img_item_value, offset, item.name.clone()); offset += item.size; vmem_partition.push_item(vmem_item); } if partition.size == 0 { const SCRAMBLE_BLOCK_WIDTH: usize = 8; const DIGEST_SIZE: usize = 8; let mut size = SCRAMBLE_BLOCK_WIDTH * ((offset + SCRAMBLE_BLOCK_WIDTH - 1) / SCRAMBLE_BLOCK_WIDTH); if partition.hw_digest || partition.sw_digest { size += DIGEST_SIZE; } vmem_partition.set_size(size); } vmem_partitions.push(vmem_partition); } Ok(VmemImage::new( vmem_partitions, self.otp.width, self.otp.depth, )) } } #[cfg(test)] mod tests { use super::*; use crate::testdata; use std::fs::read_to_string; #[test] fn test_mmap_deserialize() { let _: OtpMap = deser_hjson::from_str(&read_to_string(testdata!("otp_ctrl_mmap.hjson")).unwrap()) .unwrap(); } #[test] fn test_img_deserialize() { let _: OtpImg = deser_hjson::from_str(&read_to_string(testdata!("otp_ctrl_img_dev.hjson")).unwrap()) .unwrap(); } }
keys: Vec<OtpMapKey>, digests: Vec<OtpMapDigest>, }
random_line_split
otp_mmap.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 use crate::otp::otp_img::OtpImg; use crate::otp::vmem_serialize::*; use crate::util::num_de::{self, DeferredValue}; use anyhow::{anyhow, bail, Result}; use serde::Deserialize; use std::collections::HashMap; use std::convert::TryInto; use std::fs; use std::path::Path; #[derive(Deserialize, Debug)] struct OtpMapConfig { #[serde(with = "num_de")] width: usize, #[serde(with = "num_de")] depth: usize, } #[derive(Deserialize, Debug)] struct
{ name: String, value: DeferredValue, } #[derive(Deserialize, Debug)] struct OtpMapDigest { name: String, iv_value: DeferredValue, cnst_value: DeferredValue, } #[derive(Deserialize, Debug)] struct OtpMapScrambling { #[serde(with = "num_de")] key_size: usize, #[serde(with = "num_de")] iv_size: usize, #[serde(with = "num_de")] cnst_size: usize, keys: Vec<OtpMapKey>, digests: Vec<OtpMapDigest>, } #[derive(Deserialize, Debug)] struct OtpMapItem { name: String, #[serde(with = "num_de")] size: usize, #[serde(default)] isdigest: bool, inv_default: Option<DeferredValue>, } #[derive(Deserialize, Debug)] pub struct OtpMapPartition { name: String, secret: bool, #[serde(default, with = "num_de")] size: usize, sw_digest: bool, hw_digest: bool, key_sel: String, items: Vec<OtpMapItem>, } #[derive(Deserialize, Debug)] pub struct OtpMap { seed: String, otp: OtpMapConfig, scrambling: OtpMapScrambling, partitions: Vec<OtpMapPartition>, } impl OtpMap { pub fn new(in_file: &Path) -> Result<OtpMap> { let json_text = fs::read_to_string(in_file)?; let res: OtpMap = deser_hjson::from_str(&json_text)?; Ok(res) } pub fn generate_keys(&self, img: &OtpImg) -> HashMap<String, Vec<u8>> { let mut rng = img.get_rng(); let mut map = HashMap::new(); for key in &self.scrambling.keys { let value = key.value.resolve(self.scrambling.key_size, &mut rng); map.insert(key.name.clone(), value); } map } pub fn make_vmem(&mut self, img: &mut OtpImg) -> Result<VmemImage> { // Seeded RNG needed for "<random>" values. let mut rng = img.get_rng(); let mut vmem_partitions = Vec::<VmemPartition>::new(); for partition in &self.partitions { let key_name = match partition.key_sel.as_str() { "NoKey" => None, key => Some(key.to_owned()), }; let digest_type = if!partition.sw_digest &&!partition.hw_digest { DigestType::Unlocked } else if partition.sw_digest &&!partition.hw_digest { DigestType::Software } else if!partition.sw_digest && partition.hw_digest { // Extra information needed to compute HW digests. let iv_size = self.scrambling.iv_size; let cnst_size = self.scrambling.cnst_size; let digest_info = self .scrambling .digests .iter_mut() .find(|v| v.name == "CnstyDigest") .ok_or(anyhow!("Couldn't find digest info"))?; const IV_SIZE: usize = std::mem::size_of::<DigestIV>(); const CNST_SIZE: usize = std::mem::size_of::<DigestCnst>(); let iv_value: [u8; IV_SIZE] = digest_info .iv_value .resolve(iv_size, &mut rng) .try_into() .map_err(|_| anyhow!("Bad IV size {}", iv_size))?; let cnst_value: [u8; CNST_SIZE] = digest_info .cnst_value .resolve(cnst_size, &mut rng) .try_into() .map_err(|_| anyhow!("Bad scrambling constant size {}", cnst_size))?; DigestType::Hardware( DigestIV::from_ne_bytes(iv_value), DigestCnst::from_ne_bytes(cnst_value), ) } else { bail!("Invalid digest configuration"); }; let mut vmem_partition = VmemPartition::new( partition.name.clone(), partition.size, digest_type, key_name, ); // Fetch the img definition for partition, this contains the associated values for // paritition items. let mut img_partition = img.get_partition(&partition.name); let mut offset = 0usize; // Resolve all values and convert to Vmem representation. for item in &partition.items { let img_item_value = match &mut img_partition { Some(v) => { let item_value = v.get_item(&item.name); match item_value { Some(v) => v.value.resolve(item.size, &mut rng), None => vec![0u8; item.size], } } None => vec![0u8; item.size], }; let vmem_item = VmemItem::new(img_item_value, offset, item.name.clone()); offset += item.size; vmem_partition.push_item(vmem_item); } if partition.size == 0 { const SCRAMBLE_BLOCK_WIDTH: usize = 8; const DIGEST_SIZE: usize = 8; let mut size = SCRAMBLE_BLOCK_WIDTH * ((offset + SCRAMBLE_BLOCK_WIDTH - 1) / SCRAMBLE_BLOCK_WIDTH); if partition.hw_digest || partition.sw_digest { size += DIGEST_SIZE; } vmem_partition.set_size(size); } vmem_partitions.push(vmem_partition); } Ok(VmemImage::new( vmem_partitions, self.otp.width, self.otp.depth, )) } } #[cfg(test)] mod tests { use super::*; use crate::testdata; use std::fs::read_to_string; #[test] fn test_mmap_deserialize() { let _: OtpMap = deser_hjson::from_str(&read_to_string(testdata!("otp_ctrl_mmap.hjson")).unwrap()) .unwrap(); } #[test] fn test_img_deserialize() { let _: OtpImg = deser_hjson::from_str(&read_to_string(testdata!("otp_ctrl_img_dev.hjson")).unwrap()) .unwrap(); } }
OtpMapKey
identifier_name
otp_mmap.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 use crate::otp::otp_img::OtpImg; use crate::otp::vmem_serialize::*; use crate::util::num_de::{self, DeferredValue}; use anyhow::{anyhow, bail, Result}; use serde::Deserialize; use std::collections::HashMap; use std::convert::TryInto; use std::fs; use std::path::Path; #[derive(Deserialize, Debug)] struct OtpMapConfig { #[serde(with = "num_de")] width: usize, #[serde(with = "num_de")] depth: usize, } #[derive(Deserialize, Debug)] struct OtpMapKey { name: String, value: DeferredValue, } #[derive(Deserialize, Debug)] struct OtpMapDigest { name: String, iv_value: DeferredValue, cnst_value: DeferredValue, } #[derive(Deserialize, Debug)] struct OtpMapScrambling { #[serde(with = "num_de")] key_size: usize, #[serde(with = "num_de")] iv_size: usize, #[serde(with = "num_de")] cnst_size: usize, keys: Vec<OtpMapKey>, digests: Vec<OtpMapDigest>, } #[derive(Deserialize, Debug)] struct OtpMapItem { name: String, #[serde(with = "num_de")] size: usize, #[serde(default)] isdigest: bool, inv_default: Option<DeferredValue>, } #[derive(Deserialize, Debug)] pub struct OtpMapPartition { name: String, secret: bool, #[serde(default, with = "num_de")] size: usize, sw_digest: bool, hw_digest: bool, key_sel: String, items: Vec<OtpMapItem>, } #[derive(Deserialize, Debug)] pub struct OtpMap { seed: String, otp: OtpMapConfig, scrambling: OtpMapScrambling, partitions: Vec<OtpMapPartition>, } impl OtpMap { pub fn new(in_file: &Path) -> Result<OtpMap> { let json_text = fs::read_to_string(in_file)?; let res: OtpMap = deser_hjson::from_str(&json_text)?; Ok(res) } pub fn generate_keys(&self, img: &OtpImg) -> HashMap<String, Vec<u8>> { let mut rng = img.get_rng(); let mut map = HashMap::new(); for key in &self.scrambling.keys { let value = key.value.resolve(self.scrambling.key_size, &mut rng); map.insert(key.name.clone(), value); } map } pub fn make_vmem(&mut self, img: &mut OtpImg) -> Result<VmemImage> { // Seeded RNG needed for "<random>" values. let mut rng = img.get_rng(); let mut vmem_partitions = Vec::<VmemPartition>::new(); for partition in &self.partitions { let key_name = match partition.key_sel.as_str() { "NoKey" => None, key => Some(key.to_owned()), }; let digest_type = if!partition.sw_digest &&!partition.hw_digest { DigestType::Unlocked } else if partition.sw_digest &&!partition.hw_digest { DigestType::Software } else if!partition.sw_digest && partition.hw_digest { // Extra information needed to compute HW digests. let iv_size = self.scrambling.iv_size; let cnst_size = self.scrambling.cnst_size; let digest_info = self .scrambling .digests .iter_mut() .find(|v| v.name == "CnstyDigest") .ok_or(anyhow!("Couldn't find digest info"))?; const IV_SIZE: usize = std::mem::size_of::<DigestIV>(); const CNST_SIZE: usize = std::mem::size_of::<DigestCnst>(); let iv_value: [u8; IV_SIZE] = digest_info .iv_value .resolve(iv_size, &mut rng) .try_into() .map_err(|_| anyhow!("Bad IV size {}", iv_size))?; let cnst_value: [u8; CNST_SIZE] = digest_info .cnst_value .resolve(cnst_size, &mut rng) .try_into() .map_err(|_| anyhow!("Bad scrambling constant size {}", cnst_size))?; DigestType::Hardware( DigestIV::from_ne_bytes(iv_value), DigestCnst::from_ne_bytes(cnst_value), ) } else { bail!("Invalid digest configuration"); }; let mut vmem_partition = VmemPartition::new( partition.name.clone(), partition.size, digest_type, key_name, ); // Fetch the img definition for partition, this contains the associated values for // paritition items. let mut img_partition = img.get_partition(&partition.name); let mut offset = 0usize; // Resolve all values and convert to Vmem representation. for item in &partition.items { let img_item_value = match &mut img_partition { Some(v) => { let item_value = v.get_item(&item.name); match item_value { Some(v) => v.value.resolve(item.size, &mut rng), None => vec![0u8; item.size], } } None => vec![0u8; item.size], }; let vmem_item = VmemItem::new(img_item_value, offset, item.name.clone()); offset += item.size; vmem_partition.push_item(vmem_item); } if partition.size == 0 { const SCRAMBLE_BLOCK_WIDTH: usize = 8; const DIGEST_SIZE: usize = 8; let mut size = SCRAMBLE_BLOCK_WIDTH * ((offset + SCRAMBLE_BLOCK_WIDTH - 1) / SCRAMBLE_BLOCK_WIDTH); if partition.hw_digest || partition.sw_digest { size += DIGEST_SIZE; } vmem_partition.set_size(size); } vmem_partitions.push(vmem_partition); } Ok(VmemImage::new( vmem_partitions, self.otp.width, self.otp.depth, )) } } #[cfg(test)] mod tests { use super::*; use crate::testdata; use std::fs::read_to_string; #[test] fn test_mmap_deserialize() { let _: OtpMap = deser_hjson::from_str(&read_to_string(testdata!("otp_ctrl_mmap.hjson")).unwrap()) .unwrap(); } #[test] fn test_img_deserialize()
}
{ let _: OtpImg = deser_hjson::from_str(&read_to_string(testdata!("otp_ctrl_img_dev.hjson")).unwrap()) .unwrap(); }
identifier_body
shrink_to_fit.rs
extern crate rand; extern crate ropey; use rand::Rng; use ropey::Rope;
let mut rng = rand::thread_rng(); let mut rope = Rope::new(); // Do a bunch of random incoherent inserts for _ in 0..(1 << 12) { let len = rope.len_chars().max(1); rope.insert(rng.gen::<usize>() % len, "Hello "); rope.insert(rng.gen::<usize>() % len, "world! "); rope.insert(rng.gen::<usize>() % len, "How are "); rope.insert(rng.gen::<usize>() % len, "you "); rope.insert(rng.gen::<usize>() % len, "doing?\r\n"); rope.insert(rng.gen::<usize>() % len, "Let's "); rope.insert(rng.gen::<usize>() % len, "keep "); rope.insert(rng.gen::<usize>() % len, "inserting "); rope.insert(rng.gen::<usize>() % len, "more "); rope.insert(rng.gen::<usize>() % len, "items.\r\n"); rope.insert(rng.gen::<usize>() % len, "こんいけは、"); rope.insert(rng.gen::<usize>() % len, "みんγͺさん!"); } let rope2 = rope.clone(); rope.shrink_to_fit(); assert_eq!(rope, rope2); assert!(rope.capacity() < rope2.capacity()); // Make sure the rope is sound rope.assert_integrity(); rope.assert_invariants(); rope2.assert_integrity(); rope2.assert_invariants(); }
#[test] fn shrink_to_fit() {
random_line_split
shrink_to_fit.rs
extern crate rand; extern crate ropey; use rand::Rng; use ropey::Rope; #[test] fn
() { let mut rng = rand::thread_rng(); let mut rope = Rope::new(); // Do a bunch of random incoherent inserts for _ in 0..(1 << 12) { let len = rope.len_chars().max(1); rope.insert(rng.gen::<usize>() % len, "Hello "); rope.insert(rng.gen::<usize>() % len, "world! "); rope.insert(rng.gen::<usize>() % len, "How are "); rope.insert(rng.gen::<usize>() % len, "you "); rope.insert(rng.gen::<usize>() % len, "doing?\r\n"); rope.insert(rng.gen::<usize>() % len, "Let's "); rope.insert(rng.gen::<usize>() % len, "keep "); rope.insert(rng.gen::<usize>() % len, "inserting "); rope.insert(rng.gen::<usize>() % len, "more "); rope.insert(rng.gen::<usize>() % len, "items.\r\n"); rope.insert(rng.gen::<usize>() % len, "こんいけは、"); rope.insert(rng.gen::<usize>() % len, "みんγͺさん!"); } let rope2 = rope.clone(); rope.shrink_to_fit(); assert_eq!(rope, rope2); assert!(rope.capacity() < rope2.capacity()); // Make sure the rope is sound rope.assert_integrity(); rope.assert_invariants(); rope2.assert_integrity(); rope2.assert_invariants(); }
shrink_to_fit
identifier_name
shrink_to_fit.rs
extern crate rand; extern crate ropey; use rand::Rng; use ropey::Rope; #[test] fn shrink_to_fit()
let rope2 = rope.clone(); rope.shrink_to_fit(); assert_eq!(rope, rope2); assert!(rope.capacity() < rope2.capacity()); // Make sure the rope is sound rope.assert_integrity(); rope.assert_invariants(); rope2.assert_integrity(); rope2.assert_invariants(); }
{ let mut rng = rand::thread_rng(); let mut rope = Rope::new(); // Do a bunch of random incoherent inserts for _ in 0..(1 << 12) { let len = rope.len_chars().max(1); rope.insert(rng.gen::<usize>() % len, "Hello "); rope.insert(rng.gen::<usize>() % len, "world! "); rope.insert(rng.gen::<usize>() % len, "How are "); rope.insert(rng.gen::<usize>() % len, "you "); rope.insert(rng.gen::<usize>() % len, "doing?\r\n"); rope.insert(rng.gen::<usize>() % len, "Let's "); rope.insert(rng.gen::<usize>() % len, "keep "); rope.insert(rng.gen::<usize>() % len, "inserting "); rope.insert(rng.gen::<usize>() % len, "more "); rope.insert(rng.gen::<usize>() % len, "items.\r\n"); rope.insert(rng.gen::<usize>() % len, "こんいけは、"); rope.insert(rng.gen::<usize>() % len, "みんγͺさん!"); }
identifier_body
backend.rs
//! Abstraction around the object writing crate use std::convert::{TryFrom, TryInto}; use rustc_data_structures::fx::FxHashMap; use rustc_session::Session; use cranelift_codegen::isa::TargetIsa; use cranelift_module::FuncId; use cranelift_object::{ObjectBuilder, ObjectModule, ObjectProduct}; use object::write::*; use object::{RelocationEncoding, SectionKind, SymbolFlags}; use gimli::SectionId; use crate::debuginfo::{DebugReloc, DebugRelocName}; pub(crate) trait WriteMetadata { fn add_rustc_section(&mut self, symbol_name: String, data: Vec<u8>); } impl WriteMetadata for object::write::Object { fn add_rustc_section(&mut self, symbol_name: String, data: Vec<u8>) { let segment = self.segment_name(object::write::StandardSegment::Data).to_vec(); let section_id = self.add_section(segment, b".rustc".to_vec(), object::SectionKind::Data); let offset = self.append_section_data(section_id, &data, 1); // For MachO and probably PE this is necessary to prevent the linker from throwing away the //.rustc section. For ELF this isn't necessary, but it also doesn't harm. self.add_symbol(object::write::Symbol { name: symbol_name.into_bytes(), value: offset, size: data.len() as u64, kind: object::SymbolKind::Data, scope: object::SymbolScope::Dynamic, weak: false, section: SymbolSection::Section(section_id), flags: SymbolFlags::None, }); } } pub(crate) trait WriteDebugInfo { type SectionId: Copy; fn add_debug_section(&mut self, name: SectionId, data: Vec<u8>) -> Self::SectionId; fn add_debug_reloc( &mut self, section_map: &FxHashMap<SectionId, Self::SectionId>, from: &Self::SectionId, reloc: &DebugReloc, ); } impl WriteDebugInfo for ObjectProduct { type SectionId = (object::write::SectionId, object::write::SymbolId); fn add_debug_section( &mut self, id: SectionId, data: Vec<u8>, ) -> (object::write::SectionId, object::write::SymbolId) { let name = if self.object.format() == object::BinaryFormat::MachO { id.name().replace('.', "__") // machO expects __debug_info instead of.debug_info } else { id.name().to_string() } .into_bytes(); let segment = self.object.segment_name(StandardSegment::Debug).to_vec(); // FIXME use SHT_X86_64_UNWIND for.eh_frame let section_id = self.object.add_section( segment, name, if id == SectionId::EhFrame { SectionKind::ReadOnlyData } else { SectionKind::Debug }, ); self.object .section_mut(section_id) .set_data(data, if id == SectionId::EhFrame { 8 } else { 1 }); let symbol_id = self.object.section_symbol(section_id); (section_id, symbol_id) } fn add_debug_reloc( &mut self, section_map: &FxHashMap<SectionId, Self::SectionId>, from: &Self::SectionId, reloc: &DebugReloc, ) { let (symbol, symbol_offset) = match reloc.name { DebugRelocName::Section(id) => (section_map.get(&id).unwrap().1, 0), DebugRelocName::Symbol(id) => { let symbol_id = self.function_symbol(FuncId::from_u32(id.try_into().unwrap())); self.object .symbol_section_and_offset(symbol_id) .expect("Debug reloc for undef sym???") } }; self.object .add_relocation( from.0, Relocation { offset: u64::from(reloc.offset), symbol, kind: reloc.kind, encoding: RelocationEncoding::Generic, size: reloc.size * 8, addend: i64::try_from(symbol_offset).unwrap() + reloc.addend, }, ) .unwrap(); } } pub(crate) fn with_object(sess: &Session, name: &str, f: impl FnOnce(&mut Object)) -> Vec<u8> { let triple = crate::target_triple(sess); let binary_format = match triple.binary_format { target_lexicon::BinaryFormat::Elf => object::BinaryFormat::Elf, target_lexicon::BinaryFormat::Coff => object::BinaryFormat::Coff, target_lexicon::BinaryFormat::Macho => object::BinaryFormat::MachO, binary_format => sess.fatal(&format!("binary format {} is unsupported", binary_format)), }; let architecture = match triple.architecture { target_lexicon::Architecture::X86_32(_) => object::Architecture::I386, target_lexicon::Architecture::X86_64 => object::Architecture::X86_64, target_lexicon::Architecture::Arm(_) => object::Architecture::Arm, target_lexicon::Architecture::Aarch64(_) => object::Architecture::Aarch64, architecture => { sess.fatal(&format!("target architecture {:?} is unsupported", architecture,)) }
target_lexicon::Endianness::Little => object::Endianness::Little, target_lexicon::Endianness::Big => object::Endianness::Big, }; let mut metadata_object = object::write::Object::new(binary_format, architecture, endian); metadata_object.add_file_symbol(name.as_bytes().to_vec()); f(&mut metadata_object); metadata_object.write().unwrap() } pub(crate) fn make_module(sess: &Session, isa: Box<dyn TargetIsa>, name: String) -> ObjectModule { let mut builder = ObjectBuilder::new(isa, name + ".o", cranelift_module::default_libcall_names()).unwrap(); // Unlike cg_llvm, cg_clif defaults to disabling -Zfunction-sections. For cg_llvm binary size // is important, while cg_clif cares more about compilation times. Enabling -Zfunction-sections // can easily double the amount of time necessary to perform linking. builder.per_function_section(sess.opts.debugging_opts.function_sections.unwrap_or(false)); ObjectModule::new(builder) }
}; let endian = match triple.endianness().unwrap() {
random_line_split
backend.rs
//! Abstraction around the object writing crate use std::convert::{TryFrom, TryInto}; use rustc_data_structures::fx::FxHashMap; use rustc_session::Session; use cranelift_codegen::isa::TargetIsa; use cranelift_module::FuncId; use cranelift_object::{ObjectBuilder, ObjectModule, ObjectProduct}; use object::write::*; use object::{RelocationEncoding, SectionKind, SymbolFlags}; use gimli::SectionId; use crate::debuginfo::{DebugReloc, DebugRelocName}; pub(crate) trait WriteMetadata { fn add_rustc_section(&mut self, symbol_name: String, data: Vec<u8>); } impl WriteMetadata for object::write::Object { fn add_rustc_section(&mut self, symbol_name: String, data: Vec<u8>) { let segment = self.segment_name(object::write::StandardSegment::Data).to_vec(); let section_id = self.add_section(segment, b".rustc".to_vec(), object::SectionKind::Data); let offset = self.append_section_data(section_id, &data, 1); // For MachO and probably PE this is necessary to prevent the linker from throwing away the //.rustc section. For ELF this isn't necessary, but it also doesn't harm. self.add_symbol(object::write::Symbol { name: symbol_name.into_bytes(), value: offset, size: data.len() as u64, kind: object::SymbolKind::Data, scope: object::SymbolScope::Dynamic, weak: false, section: SymbolSection::Section(section_id), flags: SymbolFlags::None, }); } } pub(crate) trait WriteDebugInfo { type SectionId: Copy; fn add_debug_section(&mut self, name: SectionId, data: Vec<u8>) -> Self::SectionId; fn add_debug_reloc( &mut self, section_map: &FxHashMap<SectionId, Self::SectionId>, from: &Self::SectionId, reloc: &DebugReloc, ); } impl WriteDebugInfo for ObjectProduct { type SectionId = (object::write::SectionId, object::write::SymbolId); fn add_debug_section( &mut self, id: SectionId, data: Vec<u8>, ) -> (object::write::SectionId, object::write::SymbolId) { let name = if self.object.format() == object::BinaryFormat::MachO { id.name().replace('.', "__") // machO expects __debug_info instead of.debug_info } else { id.name().to_string() } .into_bytes(); let segment = self.object.segment_name(StandardSegment::Debug).to_vec(); // FIXME use SHT_X86_64_UNWIND for.eh_frame let section_id = self.object.add_section( segment, name, if id == SectionId::EhFrame { SectionKind::ReadOnlyData } else { SectionKind::Debug }, ); self.object .section_mut(section_id) .set_data(data, if id == SectionId::EhFrame { 8 } else { 1 }); let symbol_id = self.object.section_symbol(section_id); (section_id, symbol_id) } fn add_debug_reloc( &mut self, section_map: &FxHashMap<SectionId, Self::SectionId>, from: &Self::SectionId, reloc: &DebugReloc, ) { let (symbol, symbol_offset) = match reloc.name { DebugRelocName::Section(id) => (section_map.get(&id).unwrap().1, 0), DebugRelocName::Symbol(id) => { let symbol_id = self.function_symbol(FuncId::from_u32(id.try_into().unwrap())); self.object .symbol_section_and_offset(symbol_id) .expect("Debug reloc for undef sym???") } }; self.object .add_relocation( from.0, Relocation { offset: u64::from(reloc.offset), symbol, kind: reloc.kind, encoding: RelocationEncoding::Generic, size: reloc.size * 8, addend: i64::try_from(symbol_offset).unwrap() + reloc.addend, }, ) .unwrap(); } } pub(crate) fn with_object(sess: &Session, name: &str, f: impl FnOnce(&mut Object)) -> Vec<u8> { let triple = crate::target_triple(sess); let binary_format = match triple.binary_format { target_lexicon::BinaryFormat::Elf => object::BinaryFormat::Elf, target_lexicon::BinaryFormat::Coff => object::BinaryFormat::Coff, target_lexicon::BinaryFormat::Macho => object::BinaryFormat::MachO, binary_format => sess.fatal(&format!("binary format {} is unsupported", binary_format)), }; let architecture = match triple.architecture { target_lexicon::Architecture::X86_32(_) => object::Architecture::I386, target_lexicon::Architecture::X86_64 => object::Architecture::X86_64, target_lexicon::Architecture::Arm(_) => object::Architecture::Arm, target_lexicon::Architecture::Aarch64(_) => object::Architecture::Aarch64, architecture => { sess.fatal(&format!("target architecture {:?} is unsupported", architecture,)) } }; let endian = match triple.endianness().unwrap() { target_lexicon::Endianness::Little => object::Endianness::Little, target_lexicon::Endianness::Big => object::Endianness::Big, }; let mut metadata_object = object::write::Object::new(binary_format, architecture, endian); metadata_object.add_file_symbol(name.as_bytes().to_vec()); f(&mut metadata_object); metadata_object.write().unwrap() } pub(crate) fn make_module(sess: &Session, isa: Box<dyn TargetIsa>, name: String) -> ObjectModule
{ let mut builder = ObjectBuilder::new(isa, name + ".o", cranelift_module::default_libcall_names()).unwrap(); // Unlike cg_llvm, cg_clif defaults to disabling -Zfunction-sections. For cg_llvm binary size // is important, while cg_clif cares more about compilation times. Enabling -Zfunction-sections // can easily double the amount of time necessary to perform linking. builder.per_function_section(sess.opts.debugging_opts.function_sections.unwrap_or(false)); ObjectModule::new(builder) }
identifier_body
backend.rs
//! Abstraction around the object writing crate use std::convert::{TryFrom, TryInto}; use rustc_data_structures::fx::FxHashMap; use rustc_session::Session; use cranelift_codegen::isa::TargetIsa; use cranelift_module::FuncId; use cranelift_object::{ObjectBuilder, ObjectModule, ObjectProduct}; use object::write::*; use object::{RelocationEncoding, SectionKind, SymbolFlags}; use gimli::SectionId; use crate::debuginfo::{DebugReloc, DebugRelocName}; pub(crate) trait WriteMetadata { fn add_rustc_section(&mut self, symbol_name: String, data: Vec<u8>); } impl WriteMetadata for object::write::Object { fn
(&mut self, symbol_name: String, data: Vec<u8>) { let segment = self.segment_name(object::write::StandardSegment::Data).to_vec(); let section_id = self.add_section(segment, b".rustc".to_vec(), object::SectionKind::Data); let offset = self.append_section_data(section_id, &data, 1); // For MachO and probably PE this is necessary to prevent the linker from throwing away the //.rustc section. For ELF this isn't necessary, but it also doesn't harm. self.add_symbol(object::write::Symbol { name: symbol_name.into_bytes(), value: offset, size: data.len() as u64, kind: object::SymbolKind::Data, scope: object::SymbolScope::Dynamic, weak: false, section: SymbolSection::Section(section_id), flags: SymbolFlags::None, }); } } pub(crate) trait WriteDebugInfo { type SectionId: Copy; fn add_debug_section(&mut self, name: SectionId, data: Vec<u8>) -> Self::SectionId; fn add_debug_reloc( &mut self, section_map: &FxHashMap<SectionId, Self::SectionId>, from: &Self::SectionId, reloc: &DebugReloc, ); } impl WriteDebugInfo for ObjectProduct { type SectionId = (object::write::SectionId, object::write::SymbolId); fn add_debug_section( &mut self, id: SectionId, data: Vec<u8>, ) -> (object::write::SectionId, object::write::SymbolId) { let name = if self.object.format() == object::BinaryFormat::MachO { id.name().replace('.', "__") // machO expects __debug_info instead of.debug_info } else { id.name().to_string() } .into_bytes(); let segment = self.object.segment_name(StandardSegment::Debug).to_vec(); // FIXME use SHT_X86_64_UNWIND for.eh_frame let section_id = self.object.add_section( segment, name, if id == SectionId::EhFrame { SectionKind::ReadOnlyData } else { SectionKind::Debug }, ); self.object .section_mut(section_id) .set_data(data, if id == SectionId::EhFrame { 8 } else { 1 }); let symbol_id = self.object.section_symbol(section_id); (section_id, symbol_id) } fn add_debug_reloc( &mut self, section_map: &FxHashMap<SectionId, Self::SectionId>, from: &Self::SectionId, reloc: &DebugReloc, ) { let (symbol, symbol_offset) = match reloc.name { DebugRelocName::Section(id) => (section_map.get(&id).unwrap().1, 0), DebugRelocName::Symbol(id) => { let symbol_id = self.function_symbol(FuncId::from_u32(id.try_into().unwrap())); self.object .symbol_section_and_offset(symbol_id) .expect("Debug reloc for undef sym???") } }; self.object .add_relocation( from.0, Relocation { offset: u64::from(reloc.offset), symbol, kind: reloc.kind, encoding: RelocationEncoding::Generic, size: reloc.size * 8, addend: i64::try_from(symbol_offset).unwrap() + reloc.addend, }, ) .unwrap(); } } pub(crate) fn with_object(sess: &Session, name: &str, f: impl FnOnce(&mut Object)) -> Vec<u8> { let triple = crate::target_triple(sess); let binary_format = match triple.binary_format { target_lexicon::BinaryFormat::Elf => object::BinaryFormat::Elf, target_lexicon::BinaryFormat::Coff => object::BinaryFormat::Coff, target_lexicon::BinaryFormat::Macho => object::BinaryFormat::MachO, binary_format => sess.fatal(&format!("binary format {} is unsupported", binary_format)), }; let architecture = match triple.architecture { target_lexicon::Architecture::X86_32(_) => object::Architecture::I386, target_lexicon::Architecture::X86_64 => object::Architecture::X86_64, target_lexicon::Architecture::Arm(_) => object::Architecture::Arm, target_lexicon::Architecture::Aarch64(_) => object::Architecture::Aarch64, architecture => { sess.fatal(&format!("target architecture {:?} is unsupported", architecture,)) } }; let endian = match triple.endianness().unwrap() { target_lexicon::Endianness::Little => object::Endianness::Little, target_lexicon::Endianness::Big => object::Endianness::Big, }; let mut metadata_object = object::write::Object::new(binary_format, architecture, endian); metadata_object.add_file_symbol(name.as_bytes().to_vec()); f(&mut metadata_object); metadata_object.write().unwrap() } pub(crate) fn make_module(sess: &Session, isa: Box<dyn TargetIsa>, name: String) -> ObjectModule { let mut builder = ObjectBuilder::new(isa, name + ".o", cranelift_module::default_libcall_names()).unwrap(); // Unlike cg_llvm, cg_clif defaults to disabling -Zfunction-sections. For cg_llvm binary size // is important, while cg_clif cares more about compilation times. Enabling -Zfunction-sections // can easily double the amount of time necessary to perform linking. builder.per_function_section(sess.opts.debugging_opts.function_sections.unwrap_or(false)); ObjectModule::new(builder) }
add_rustc_section
identifier_name
main.rs
// Copyright 2014 Nick Fitzgerald // // 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. //! A Scheme implementation, in Rust. #![feature(collections)] #![feature(core)] #![feature(env)] #![feature(old_io)] #![feature(old_path)] #![feature(test)] #![feature(unicode)] #![feature(unsafe_destructor)] use std::old_io; use std::env; pub mod environment; pub mod eval; pub mod heap; pub mod primitives; pub mod read; pub mod value; /// Start a Read -> Evaluate -> Print loop. pub fn
(heap: &mut heap::Heap) { println!("Welcome to oxischeme!"); println!("C-c to exit."); println!(""); loop { let stdin = old_io::stdio::stdin(); let reader = read::Read::new(stdin, heap, "stdin".to_string()); print!("oxischeme> "); for (location, read_result) in reader { match read_result { Err(msg) => { println!("{}", msg); break; }, Ok(form) => { match eval::evaluate(heap, &form, location) { Ok(val) => println!("{}", *val), Err(e) => println!("{}", e), }; } } heap.collect_garbage(); print!("oxischeme> "); } } } /// Given no arguments, start the REPL. Otherwise, treat each argument as a file /// path and read and evaluate each of them in turn. pub fn main() { let heap = &mut heap::Heap::new(); let mut args_were_passed = false; for file_path in env::args().skip(1) { args_were_passed = true; match eval::evaluate_file(heap, file_path.as_slice()) { Ok(_) => { }, Err(msg) => { let mut stderr = old_io::stdio::stderr(); (write!(&mut stderr, "{}", msg)).ok().expect("IO ERROR!"); return; } } } if!args_were_passed { repl(heap); } }
repl
identifier_name
main.rs
// Copyright 2014 Nick Fitzgerald // // 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. //! A Scheme implementation, in Rust. #![feature(collections)] #![feature(core)] #![feature(env)] #![feature(old_io)] #![feature(old_path)] #![feature(test)] #![feature(unicode)] #![feature(unsafe_destructor)] use std::old_io; use std::env; pub mod environment; pub mod eval; pub mod heap; pub mod primitives; pub mod read; pub mod value; /// Start a Read -> Evaluate -> Print loop. pub fn repl(heap: &mut heap::Heap) { println!("Welcome to oxischeme!"); println!("C-c to exit."); println!(""); loop { let stdin = old_io::stdio::stdin(); let reader = read::Read::new(stdin, heap, "stdin".to_string()); print!("oxischeme> "); for (location, read_result) in reader { match read_result { Err(msg) => { println!("{}", msg); break; }, Ok(form) => { match eval::evaluate(heap, &form, location) { Ok(val) => println!("{}", *val), Err(e) => println!("{}", e), }; } } heap.collect_garbage(); print!("oxischeme> "); } } } /// Given no arguments, start the REPL. Otherwise, treat each argument as a file /// path and read and evaluate each of them in turn. pub fn main()
} }
{ let heap = &mut heap::Heap::new(); let mut args_were_passed = false; for file_path in env::args().skip(1) { args_were_passed = true; match eval::evaluate_file(heap, file_path.as_slice()) { Ok(_) => { }, Err(msg) => { let mut stderr = old_io::stdio::stderr(); (write!(&mut stderr, "{}", msg)).ok().expect("IO ERROR!"); return; } } } if !args_were_passed { repl(heap);
identifier_body
main.rs
// Copyright 2014 Nick Fitzgerald // // 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. //! A Scheme implementation, in Rust.
#![feature(old_path)] #![feature(test)] #![feature(unicode)] #![feature(unsafe_destructor)] use std::old_io; use std::env; pub mod environment; pub mod eval; pub mod heap; pub mod primitives; pub mod read; pub mod value; /// Start a Read -> Evaluate -> Print loop. pub fn repl(heap: &mut heap::Heap) { println!("Welcome to oxischeme!"); println!("C-c to exit."); println!(""); loop { let stdin = old_io::stdio::stdin(); let reader = read::Read::new(stdin, heap, "stdin".to_string()); print!("oxischeme> "); for (location, read_result) in reader { match read_result { Err(msg) => { println!("{}", msg); break; }, Ok(form) => { match eval::evaluate(heap, &form, location) { Ok(val) => println!("{}", *val), Err(e) => println!("{}", e), }; } } heap.collect_garbage(); print!("oxischeme> "); } } } /// Given no arguments, start the REPL. Otherwise, treat each argument as a file /// path and read and evaluate each of them in turn. pub fn main() { let heap = &mut heap::Heap::new(); let mut args_were_passed = false; for file_path in env::args().skip(1) { args_were_passed = true; match eval::evaluate_file(heap, file_path.as_slice()) { Ok(_) => { }, Err(msg) => { let mut stderr = old_io::stdio::stderr(); (write!(&mut stderr, "{}", msg)).ok().expect("IO ERROR!"); return; } } } if!args_were_passed { repl(heap); } }
#![feature(collections)] #![feature(core)] #![feature(env)] #![feature(old_io)]
random_line_split
compression.rs
use libc::{c_int,size_t,intptr_t}; #[link(name="libfwnt",kind="dylib")] extern { fn libfwnt_lzxpress_huffman_decompress( compressed_data: *const u8, compressed_data_size: size_t, uncompressed_data: *mut u8, uncompressed_data_size: *mut size_t, error: *mut intptr_t ) -> c_int; } pub fn decompress(compressed_data: &[u8],uncompressed_size: usize) -> Option<Vec<u8>> { unsafe { // Get size of compressed data let compressed_data_size = compressed_data.len() as size_t; // Create compressed data pointer let compressed_data_ptr = compressed_data.as_ptr(); let mut uncompressed_data_size: size_t = uncompressed_size; // To hold uncompressed data let mut uncompressed_data: Vec<u8> = Vec::with_capacity( uncompressed_data_size as usize ); let uncompressed_data_ptr = uncompressed_data.as_mut_ptr(); // Error ptr... not sure if this is how it should be handled... let mut error: intptr_t = 0; let result: c_int = libfwnt_lzxpress_huffman_decompress( compressed_data_ptr, compressed_data_size, uncompressed_data_ptr, &mut uncompressed_data_size, &mut error ); if result == 1 { uncompressed_data.set_len( uncompressed_data_size as usize ); Some(uncompressed_data) } else
} }
{ // TODO Handle Errors. -1 == ERROR None }
conditional_block
compression.rs
use libc::{c_int,size_t,intptr_t}; #[link(name="libfwnt",kind="dylib")] extern { fn libfwnt_lzxpress_huffman_decompress( compressed_data: *const u8, compressed_data_size: size_t, uncompressed_data: *mut u8, uncompressed_data_size: *mut size_t, error: *mut intptr_t ) -> c_int; } pub fn decompress(compressed_data: &[u8],uncompressed_size: usize) -> Option<Vec<u8>> { unsafe { // Get size of compressed data let compressed_data_size = compressed_data.len() as size_t; // Create compressed data pointer let compressed_data_ptr = compressed_data.as_ptr(); let mut uncompressed_data_size: size_t = uncompressed_size; // To hold uncompressed data let mut uncompressed_data: Vec<u8> = Vec::with_capacity( uncompressed_data_size as usize ); let uncompressed_data_ptr = uncompressed_data.as_mut_ptr(); // Error ptr... not sure if this is how it should be handled... let mut error: intptr_t = 0; let result: c_int = libfwnt_lzxpress_huffman_decompress( compressed_data_ptr, compressed_data_size, uncompressed_data_ptr, &mut uncompressed_data_size, &mut error ); if result == 1 { uncompressed_data.set_len( uncompressed_data_size as usize ); Some(uncompressed_data) } else {
// TODO Handle Errors. -1 == ERROR None } } }
random_line_split
compression.rs
use libc::{c_int,size_t,intptr_t}; #[link(name="libfwnt",kind="dylib")] extern { fn libfwnt_lzxpress_huffman_decompress( compressed_data: *const u8, compressed_data_size: size_t, uncompressed_data: *mut u8, uncompressed_data_size: *mut size_t, error: *mut intptr_t ) -> c_int; } pub fn decompress(compressed_data: &[u8],uncompressed_size: usize) -> Option<Vec<u8>>
compressed_data_ptr, compressed_data_size, uncompressed_data_ptr, &mut uncompressed_data_size, &mut error ); if result == 1 { uncompressed_data.set_len( uncompressed_data_size as usize ); Some(uncompressed_data) } else { // TODO Handle Errors. -1 == ERROR None } } }
{ unsafe { // Get size of compressed data let compressed_data_size = compressed_data.len() as size_t; // Create compressed data pointer let compressed_data_ptr = compressed_data.as_ptr(); let mut uncompressed_data_size: size_t = uncompressed_size; // To hold uncompressed data let mut uncompressed_data: Vec<u8> = Vec::with_capacity( uncompressed_data_size as usize ); let uncompressed_data_ptr = uncompressed_data.as_mut_ptr(); // Error ptr... not sure if this is how it should be handled... let mut error: intptr_t = 0; let result: c_int = libfwnt_lzxpress_huffman_decompress(
identifier_body
compression.rs
use libc::{c_int,size_t,intptr_t}; #[link(name="libfwnt",kind="dylib")] extern { fn libfwnt_lzxpress_huffman_decompress( compressed_data: *const u8, compressed_data_size: size_t, uncompressed_data: *mut u8, uncompressed_data_size: *mut size_t, error: *mut intptr_t ) -> c_int; } pub fn
(compressed_data: &[u8],uncompressed_size: usize) -> Option<Vec<u8>> { unsafe { // Get size of compressed data let compressed_data_size = compressed_data.len() as size_t; // Create compressed data pointer let compressed_data_ptr = compressed_data.as_ptr(); let mut uncompressed_data_size: size_t = uncompressed_size; // To hold uncompressed data let mut uncompressed_data: Vec<u8> = Vec::with_capacity( uncompressed_data_size as usize ); let uncompressed_data_ptr = uncompressed_data.as_mut_ptr(); // Error ptr... not sure if this is how it should be handled... let mut error: intptr_t = 0; let result: c_int = libfwnt_lzxpress_huffman_decompress( compressed_data_ptr, compressed_data_size, uncompressed_data_ptr, &mut uncompressed_data_size, &mut error ); if result == 1 { uncompressed_data.set_len( uncompressed_data_size as usize ); Some(uncompressed_data) } else { // TODO Handle Errors. -1 == ERROR None } } }
decompress
identifier_name
js.rs
const JS_DOM_EVENT_ATTRS: &'static [&str] = &[ // From WHATWG HTML spec 8.1.5.2 "Event handlers on elements, Document objects, and Window objects":
"onauxclick", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragexit", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onformdata", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onwheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onresize", "onscroll", "onsecuritypolicyviolation", "onseeked", "onseeking", "onselect", "onslotchange", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "onvolumechange", "onwaiting", "onwebkitanimationend", "onwebkitanimationiteration", "onwebkitanimationstart", "onwebkittransitionend", // Event handlers for <body/> and <frameset/> elements "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onmessageerror", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onrejectionhandled", "onstorage", "onunhandledrejection", "onunload", // Event handlers for <html/> element "oncut", "oncopy", "onpaste", ]; // Returns true if DOM attribute name matches a native JavaScript event handler pub fn attr_is_event_handler(attr_name: &str) -> bool { JS_DOM_EVENT_ATTRS .iter() .find(|a| attr_name.eq_ignore_ascii_case(a)) .is_some() }
// https://html.spec.whatwg.org/#event-handlers-on-elements,-document-objects,-and-window-objects // https://html.spec.whatwg.org/#attributes-3 (table "List of event handler content attributes") // Global event handlers "onabort",
random_line_split
js.rs
const JS_DOM_EVENT_ATTRS: &'static [&str] = &[ // From WHATWG HTML spec 8.1.5.2 "Event handlers on elements, Document objects, and Window objects": // https://html.spec.whatwg.org/#event-handlers-on-elements,-document-objects,-and-window-objects // https://html.spec.whatwg.org/#attributes-3 (table "List of event handler content attributes") // Global event handlers "onabort", "onauxclick", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragexit", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onformdata", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onwheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onresize", "onscroll", "onsecuritypolicyviolation", "onseeked", "onseeking", "onselect", "onslotchange", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "onvolumechange", "onwaiting", "onwebkitanimationend", "onwebkitanimationiteration", "onwebkitanimationstart", "onwebkittransitionend", // Event handlers for <body/> and <frameset/> elements "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onmessageerror", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onrejectionhandled", "onstorage", "onunhandledrejection", "onunload", // Event handlers for <html/> element "oncut", "oncopy", "onpaste", ]; // Returns true if DOM attribute name matches a native JavaScript event handler pub fn
(attr_name: &str) -> bool { JS_DOM_EVENT_ATTRS .iter() .find(|a| attr_name.eq_ignore_ascii_case(a)) .is_some() }
attr_is_event_handler
identifier_name
js.rs
const JS_DOM_EVENT_ATTRS: &'static [&str] = &[ // From WHATWG HTML spec 8.1.5.2 "Event handlers on elements, Document objects, and Window objects": // https://html.spec.whatwg.org/#event-handlers-on-elements,-document-objects,-and-window-objects // https://html.spec.whatwg.org/#attributes-3 (table "List of event handler content attributes") // Global event handlers "onabort", "onauxclick", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragexit", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onformdata", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onwheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onresize", "onscroll", "onsecuritypolicyviolation", "onseeked", "onseeking", "onselect", "onslotchange", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "onvolumechange", "onwaiting", "onwebkitanimationend", "onwebkitanimationiteration", "onwebkitanimationstart", "onwebkittransitionend", // Event handlers for <body/> and <frameset/> elements "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onmessageerror", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onrejectionhandled", "onstorage", "onunhandledrejection", "onunload", // Event handlers for <html/> element "oncut", "oncopy", "onpaste", ]; // Returns true if DOM attribute name matches a native JavaScript event handler pub fn attr_is_event_handler(attr_name: &str) -> bool
{ JS_DOM_EVENT_ATTRS .iter() .find(|a| attr_name.eq_ignore_ascii_case(a)) .is_some() }
identifier_body
main.rs
extern crate serde_json; extern crate gossyp_base; extern crate gossyp_toolkit; extern crate gossyp_lang; use serde_json::*; use gossyp_base::*; use gossyp_base::basic::*; use gossyp_toolkit::io::*; use gossyp_toolkit::io::tool::*; use gossyp_lang::script::*; use gossyp_lang::script::tool::*; fn main()
let parse_script = main_env.get_json_tool(PARSE_SCRIPT).unwrap(); let eval_script = main_env.get_json_tool(EVAL_SCRIPT).unwrap(); let display_prompt = main_env.get_typed_tool::<(), ()>("display-prompt"); // Display a prompt display_prompt .map(|tool| tool.invoke((), &main_env).unwrap()) .map_err(|_| print_string.invoke(String::from("\n=Β» "), &main_env).unwrap()) .unwrap_or(()); // Read the next line let next_line = read_line.invoke((), &main_env); match next_line { Ok(result) => { // Evaluate the result let eval_result = lex_line.invoke(result.line, &main_env) .and_then(|lexed| parse_script.invoke_json(lexed, &main_env)) .and_then(|parsed| eval_script.invoke_json(parsed, &main_env)); // Print it out match eval_result { Ok(Value::Null) => { }, Ok(not_null) => { print_value.invoke(not_null, &main_env).unwrap(); }, Err(erm) => { print_string.invoke(String::from("*** Error: "), &main_env).unwrap(); print_value.invoke(erm, &main_env).unwrap(); } } print_string.invoke(String::from("\n"), &main_env).unwrap(); // Stop on EOF if result.eof { break; } }, Err(erm) => { // Stop if we hit an error print_string.invoke(String::from("Error while reading from prompt: "), &main_env).unwrap(); print_value.invoke(erm, &main_env).unwrap(); break; }, } } }
{ // Start up let main_env = DynamicEnvironment::new(); main_env.import(IoTools::new_stdio()); main_env.import(ScriptTools::new()); // Display a header let print_string = main_env.get_typed_tool::<String, ()>("print").unwrap(); print_string.invoke(format!("{} {} by {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_AUTHORS")), &main_env).unwrap(); // Create some state, replacing the default eval tool with one that tracks state let create_evaluator = main_env.get_typed_tool::<&str, ()>(CREATE_EVALUATOR_WITH_STATE).unwrap(); create_evaluator.invoke(EVAL_SCRIPT, &main_env).unwrap(); // Start a REPL loop { let print_string = main_env.get_typed_tool::<String, ()>(PRINT).unwrap(); let print_value = main_env.get_typed_tool::<Value, ()>(PRINT).unwrap(); let read_line = main_env.get_typed_tool::<(), ReadLineResult>(READ_LINE).unwrap(); let lex_line = main_env.get_typed_tool::<String, Value>(LEX_SCRIPT).unwrap();
identifier_body
main.rs
extern crate serde_json; extern crate gossyp_base; extern crate gossyp_toolkit; extern crate gossyp_lang; use serde_json::*; use gossyp_base::*; use gossyp_base::basic::*; use gossyp_toolkit::io::*; use gossyp_toolkit::io::tool::*; use gossyp_lang::script::*; use gossyp_lang::script::tool::*; fn main() { // Start up let main_env = DynamicEnvironment::new(); main_env.import(IoTools::new_stdio()); main_env.import(ScriptTools::new()); // Display a header let print_string = main_env.get_typed_tool::<String, ()>("print").unwrap(); print_string.invoke(format!("{} {} by {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_AUTHORS")), &main_env).unwrap(); // Create some state, replacing the default eval tool with one that tracks state let create_evaluator = main_env.get_typed_tool::<&str, ()>(CREATE_EVALUATOR_WITH_STATE).unwrap(); create_evaluator.invoke(EVAL_SCRIPT, &main_env).unwrap(); // Start a REPL loop { let print_string = main_env.get_typed_tool::<String, ()>(PRINT).unwrap(); let print_value = main_env.get_typed_tool::<Value, ()>(PRINT).unwrap(); let read_line = main_env.get_typed_tool::<(), ReadLineResult>(READ_LINE).unwrap(); let lex_line = main_env.get_typed_tool::<String, Value>(LEX_SCRIPT).unwrap(); let parse_script = main_env.get_json_tool(PARSE_SCRIPT).unwrap(); let eval_script = main_env.get_json_tool(EVAL_SCRIPT).unwrap(); let display_prompt = main_env.get_typed_tool::<(), ()>("display-prompt"); // Display a prompt display_prompt .map(|tool| tool.invoke((), &main_env).unwrap()) .map_err(|_| print_string.invoke(String::from("\n=Β» "), &main_env).unwrap()) .unwrap_or(()); // Read the next line let next_line = read_line.invoke((), &main_env); match next_line { Ok(result) => { // Evaluate the result let eval_result = lex_line.invoke(result.line, &main_env) .and_then(|lexed| parse_script.invoke_json(lexed, &main_env)) .and_then(|parsed| eval_script.invoke_json(parsed, &main_env)); // Print it out match eval_result { Ok(Value::Null) => { }, Ok(not_null) => { print_value.invoke(not_null, &main_env).unwrap(); }, Err(erm) => { print_string.invoke(String::from("*** Error: "), &main_env).unwrap(); print_value.invoke(erm, &main_env).unwrap(); } }
break; } }, Err(erm) => { // Stop if we hit an error print_string.invoke(String::from("Error while reading from prompt: "), &main_env).unwrap(); print_value.invoke(erm, &main_env).unwrap(); break; }, } } }
print_string.invoke(String::from("\n"), &main_env).unwrap(); // Stop on EOF if result.eof {
random_line_split
main.rs
extern crate serde_json; extern crate gossyp_base; extern crate gossyp_toolkit; extern crate gossyp_lang; use serde_json::*; use gossyp_base::*; use gossyp_base::basic::*; use gossyp_toolkit::io::*; use gossyp_toolkit::io::tool::*; use gossyp_lang::script::*; use gossyp_lang::script::tool::*; fn
() { // Start up let main_env = DynamicEnvironment::new(); main_env.import(IoTools::new_stdio()); main_env.import(ScriptTools::new()); // Display a header let print_string = main_env.get_typed_tool::<String, ()>("print").unwrap(); print_string.invoke(format!("{} {} by {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_AUTHORS")), &main_env).unwrap(); // Create some state, replacing the default eval tool with one that tracks state let create_evaluator = main_env.get_typed_tool::<&str, ()>(CREATE_EVALUATOR_WITH_STATE).unwrap(); create_evaluator.invoke(EVAL_SCRIPT, &main_env).unwrap(); // Start a REPL loop { let print_string = main_env.get_typed_tool::<String, ()>(PRINT).unwrap(); let print_value = main_env.get_typed_tool::<Value, ()>(PRINT).unwrap(); let read_line = main_env.get_typed_tool::<(), ReadLineResult>(READ_LINE).unwrap(); let lex_line = main_env.get_typed_tool::<String, Value>(LEX_SCRIPT).unwrap(); let parse_script = main_env.get_json_tool(PARSE_SCRIPT).unwrap(); let eval_script = main_env.get_json_tool(EVAL_SCRIPT).unwrap(); let display_prompt = main_env.get_typed_tool::<(), ()>("display-prompt"); // Display a prompt display_prompt .map(|tool| tool.invoke((), &main_env).unwrap()) .map_err(|_| print_string.invoke(String::from("\n=Β» "), &main_env).unwrap()) .unwrap_or(()); // Read the next line let next_line = read_line.invoke((), &main_env); match next_line { Ok(result) => { // Evaluate the result let eval_result = lex_line.invoke(result.line, &main_env) .and_then(|lexed| parse_script.invoke_json(lexed, &main_env)) .and_then(|parsed| eval_script.invoke_json(parsed, &main_env)); // Print it out match eval_result { Ok(Value::Null) => { }, Ok(not_null) => { print_value.invoke(not_null, &main_env).unwrap(); }, Err(erm) => { print_string.invoke(String::from("*** Error: "), &main_env).unwrap(); print_value.invoke(erm, &main_env).unwrap(); } } print_string.invoke(String::from("\n"), &main_env).unwrap(); // Stop on EOF if result.eof { break; } }, Err(erm) => { // Stop if we hit an error print_string.invoke(String::from("Error while reading from prompt: "), &main_env).unwrap(); print_value.invoke(erm, &main_env).unwrap(); break; }, } } }
main
identifier_name
inline-syntax.rs
// revisions: x86_64 arm //[x86_64] compile-flags: --target x86_64-unknown-linux-gnu //[x86_64] check-pass //[x86_64] needs-llvm-components: x86 //[x86_64_allowed] compile-flags: --target x86_64-unknown-linux-gnu //[x86_64_allowed] check-pass //[x86_64_allowed] needs-llvm-components: x86 //[arm] compile-flags: --target armv7-unknown-linux-gnueabihf //[arm] build-fail //[arm] needs-llvm-components: arm #![feature(no_core, lang_items, rustc_attrs)] #![crate_type = "rlib"] #![no_core] #![cfg_attr(x86_64_allowed, allow(bad_asm_style))] #[rustc_builtin_macro] macro_rules! asm { () => {}; } #[rustc_builtin_macro] macro_rules! global_asm { () => {}; } #[lang = "sized"] trait Sized {} pub fn main()
.intel_syntax noprefix nop" ); //[x86_64]~^^^ WARN avoid using `.intel_syntax` //[arm]~^^^^ ERROR unknown directive } } global_asm!(".intel_syntax noprefix", "nop"); //[x86_64]~^ WARN avoid using `.intel_syntax` // Assembler errors don't have line numbers, so no error on ARM
{ unsafe { asm!(".intel_syntax noprefix", "nop"); //[x86_64]~^ WARN avoid using `.intel_syntax` //[arm]~^^ ERROR unknown directive asm!(".intel_syntax aaa noprefix", "nop"); //[x86_64]~^ WARN avoid using `.intel_syntax` //[arm]~^^ ERROR unknown directive asm!(".att_syntax noprefix", "nop"); //[x86_64]~^ WARN avoid using `.att_syntax` //[arm]~^^ ERROR unknown directive asm!(".att_syntax bbb noprefix", "nop"); //[x86_64]~^ WARN avoid using `.att_syntax` //[arm]~^^ ERROR unknown directive asm!(".intel_syntax noprefix; nop"); //[x86_64]~^ WARN avoid using `.intel_syntax` //[arm]~^^ ERROR unknown directive asm!( r"
identifier_body
inline-syntax.rs
// revisions: x86_64 arm //[x86_64] compile-flags: --target x86_64-unknown-linux-gnu //[x86_64] check-pass //[x86_64] needs-llvm-components: x86 //[x86_64_allowed] compile-flags: --target x86_64-unknown-linux-gnu //[x86_64_allowed] check-pass //[x86_64_allowed] needs-llvm-components: x86 //[arm] compile-flags: --target armv7-unknown-linux-gnueabihf //[arm] build-fail //[arm] needs-llvm-components: arm #![feature(no_core, lang_items, rustc_attrs)] #![crate_type = "rlib"] #![no_core] #![cfg_attr(x86_64_allowed, allow(bad_asm_style))] #[rustc_builtin_macro] macro_rules! asm { () => {}; } #[rustc_builtin_macro] macro_rules! global_asm { () => {}; } #[lang = "sized"] trait Sized {} pub fn
() { unsafe { asm!(".intel_syntax noprefix", "nop"); //[x86_64]~^ WARN avoid using `.intel_syntax` //[arm]~^^ ERROR unknown directive asm!(".intel_syntax aaa noprefix", "nop"); //[x86_64]~^ WARN avoid using `.intel_syntax` //[arm]~^^ ERROR unknown directive asm!(".att_syntax noprefix", "nop"); //[x86_64]~^ WARN avoid using `.att_syntax` //[arm]~^^ ERROR unknown directive asm!(".att_syntax bbb noprefix", "nop"); //[x86_64]~^ WARN avoid using `.att_syntax` //[arm]~^^ ERROR unknown directive asm!(".intel_syntax noprefix; nop"); //[x86_64]~^ WARN avoid using `.intel_syntax` //[arm]~^^ ERROR unknown directive asm!( r" .intel_syntax noprefix nop" ); //[x86_64]~^^^ WARN avoid using `.intel_syntax` //[arm]~^^^^ ERROR unknown directive } } global_asm!(".intel_syntax noprefix", "nop"); //[x86_64]~^ WARN avoid using `.intel_syntax` // Assembler errors don't have line numbers, so no error on ARM
main
identifier_name
inline-syntax.rs
// revisions: x86_64 arm
//[x86_64] needs-llvm-components: x86 //[x86_64_allowed] compile-flags: --target x86_64-unknown-linux-gnu //[x86_64_allowed] check-pass //[x86_64_allowed] needs-llvm-components: x86 //[arm] compile-flags: --target armv7-unknown-linux-gnueabihf //[arm] build-fail //[arm] needs-llvm-components: arm #![feature(no_core, lang_items, rustc_attrs)] #![crate_type = "rlib"] #![no_core] #![cfg_attr(x86_64_allowed, allow(bad_asm_style))] #[rustc_builtin_macro] macro_rules! asm { () => {}; } #[rustc_builtin_macro] macro_rules! global_asm { () => {}; } #[lang = "sized"] trait Sized {} pub fn main() { unsafe { asm!(".intel_syntax noprefix", "nop"); //[x86_64]~^ WARN avoid using `.intel_syntax` //[arm]~^^ ERROR unknown directive asm!(".intel_syntax aaa noprefix", "nop"); //[x86_64]~^ WARN avoid using `.intel_syntax` //[arm]~^^ ERROR unknown directive asm!(".att_syntax noprefix", "nop"); //[x86_64]~^ WARN avoid using `.att_syntax` //[arm]~^^ ERROR unknown directive asm!(".att_syntax bbb noprefix", "nop"); //[x86_64]~^ WARN avoid using `.att_syntax` //[arm]~^^ ERROR unknown directive asm!(".intel_syntax noprefix; nop"); //[x86_64]~^ WARN avoid using `.intel_syntax` //[arm]~^^ ERROR unknown directive asm!( r" .intel_syntax noprefix nop" ); //[x86_64]~^^^ WARN avoid using `.intel_syntax` //[arm]~^^^^ ERROR unknown directive } } global_asm!(".intel_syntax noprefix", "nop"); //[x86_64]~^ WARN avoid using `.intel_syntax` // Assembler errors don't have line numbers, so no error on ARM
//[x86_64] compile-flags: --target x86_64-unknown-linux-gnu //[x86_64] check-pass
random_line_split
ssh.rs
use libc::{c_char, execvp}; use std::io::prelude::*; use std::ffi::CString; use std::ptr; macro_rules! c_ptr { ($x:expr) => {{ CString::new($x).unwrap().as_ptr() }};
if verbose { println!("Running {}", ssh_command) } let argv: &[*const c_char] = &[c_ptr!("ssh"), c_ptr!("-t"), c_ptr!("-o"), c_ptr!("StrictHostKeyChecking=no"), c_ptr!("-o"), c_ptr!("UserKnownHostsFile=/dev/null"), c_ptr!(user_host), c_ptr!(command), ptr::null()]; unsafe { execvp(argv[0], &argv[0]); } die!("ssh command failed: {}", ssh_command); } fn ssh_command_arg(user: Option<String>, command: Option<String>) -> String { let user_prefix = user.and_then(|u| Some(format!("sudo -u \"{}\"", u))); let escaped_command = command.and_then(|c| Some(c.replace("\"", "\\\""))); match user_prefix { Some(u) => match escaped_command { Some(c) => format!("{} -- sh -cl \"{}\"", u, c), None => format!("{} -s", u) }, None => escaped_command.unwrap_or("".to_string()) } } pub fn ssh_connect(ip: String, user: Option<String>, command: Option<String>, verbose: bool) { exec_ssh(&ip, &ssh_command_arg(user, command), verbose); } #[cfg(test)] mod tests { mod ssh_command_arg { use super::super::ssh_command_arg; #[test] fn no_user() { assert_eq!("pwd".to_string(), ssh_command_arg(None, Some("pwd".to_string()))); } #[test] fn no_command() { assert_eq!("sudo -u \"sean\" -s".to_string(), ssh_command_arg(Some("sean".to_string()), None)); } #[test] fn user_and_command() { assert_eq!("sudo -u \"sean\" -- sh -cl \"cd / && /bin/bash\"".to_string(), ssh_command_arg(Some("sean".to_string()), Some("cd / && /bin/bash".to_string()))); } } }
} fn exec_ssh(ip: &str, command: &str, verbose: bool) { let user_host: &str = &format!("rightscale@{}", ip); let ssh_command = format!("ssh -t -o StrictHostKeychecking=no -o UserKnownHostsFile=/dev/null {} \"{}\"", user_host, command);
random_line_split
ssh.rs
use libc::{c_char, execvp}; use std::io::prelude::*; use std::ffi::CString; use std::ptr; macro_rules! c_ptr { ($x:expr) => {{ CString::new($x).unwrap().as_ptr() }}; } fn exec_ssh(ip: &str, command: &str, verbose: bool) { let user_host: &str = &format!("rightscale@{}", ip); let ssh_command = format!("ssh -t -o StrictHostKeychecking=no -o UserKnownHostsFile=/dev/null {} \"{}\"", user_host, command); if verbose { println!("Running {}", ssh_command) } let argv: &[*const c_char] = &[c_ptr!("ssh"), c_ptr!("-t"), c_ptr!("-o"), c_ptr!("StrictHostKeyChecking=no"), c_ptr!("-o"), c_ptr!("UserKnownHostsFile=/dev/null"), c_ptr!(user_host), c_ptr!(command), ptr::null()]; unsafe { execvp(argv[0], &argv[0]); } die!("ssh command failed: {}", ssh_command); } fn ssh_command_arg(user: Option<String>, command: Option<String>) -> String { let user_prefix = user.and_then(|u| Some(format!("sudo -u \"{}\"", u))); let escaped_command = command.and_then(|c| Some(c.replace("\"", "\\\""))); match user_prefix { Some(u) => match escaped_command { Some(c) => format!("{} -- sh -cl \"{}\"", u, c), None => format!("{} -s", u) }, None => escaped_command.unwrap_or("".to_string()) } } pub fn ssh_connect(ip: String, user: Option<String>, command: Option<String>, verbose: bool)
#[cfg(test)] mod tests { mod ssh_command_arg { use super::super::ssh_command_arg; #[test] fn no_user() { assert_eq!("pwd".to_string(), ssh_command_arg(None, Some("pwd".to_string()))); } #[test] fn no_command() { assert_eq!("sudo -u \"sean\" -s".to_string(), ssh_command_arg(Some("sean".to_string()), None)); } #[test] fn user_and_command() { assert_eq!("sudo -u \"sean\" -- sh -cl \"cd / && /bin/bash\"".to_string(), ssh_command_arg(Some("sean".to_string()), Some("cd / && /bin/bash".to_string()))); } } }
{ exec_ssh(&ip, &ssh_command_arg(user, command), verbose); }
identifier_body
ssh.rs
use libc::{c_char, execvp}; use std::io::prelude::*; use std::ffi::CString; use std::ptr; macro_rules! c_ptr { ($x:expr) => {{ CString::new($x).unwrap().as_ptr() }}; } fn exec_ssh(ip: &str, command: &str, verbose: bool) { let user_host: &str = &format!("rightscale@{}", ip); let ssh_command = format!("ssh -t -o StrictHostKeychecking=no -o UserKnownHostsFile=/dev/null {} \"{}\"", user_host, command); if verbose { println!("Running {}", ssh_command) } let argv: &[*const c_char] = &[c_ptr!("ssh"), c_ptr!("-t"), c_ptr!("-o"), c_ptr!("StrictHostKeyChecking=no"), c_ptr!("-o"), c_ptr!("UserKnownHostsFile=/dev/null"), c_ptr!(user_host), c_ptr!(command), ptr::null()]; unsafe { execvp(argv[0], &argv[0]); } die!("ssh command failed: {}", ssh_command); } fn
(user: Option<String>, command: Option<String>) -> String { let user_prefix = user.and_then(|u| Some(format!("sudo -u \"{}\"", u))); let escaped_command = command.and_then(|c| Some(c.replace("\"", "\\\""))); match user_prefix { Some(u) => match escaped_command { Some(c) => format!("{} -- sh -cl \"{}\"", u, c), None => format!("{} -s", u) }, None => escaped_command.unwrap_or("".to_string()) } } pub fn ssh_connect(ip: String, user: Option<String>, command: Option<String>, verbose: bool) { exec_ssh(&ip, &ssh_command_arg(user, command), verbose); } #[cfg(test)] mod tests { mod ssh_command_arg { use super::super::ssh_command_arg; #[test] fn no_user() { assert_eq!("pwd".to_string(), ssh_command_arg(None, Some("pwd".to_string()))); } #[test] fn no_command() { assert_eq!("sudo -u \"sean\" -s".to_string(), ssh_command_arg(Some("sean".to_string()), None)); } #[test] fn user_and_command() { assert_eq!("sudo -u \"sean\" -- sh -cl \"cd / && /bin/bash\"".to_string(), ssh_command_arg(Some("sean".to_string()), Some("cd / && /bin/bash".to_string()))); } } }
ssh_command_arg
identifier_name
errors.rs
use std::fmt; use std::ops::FnOnce; error_chain! { } pub struct
<'a> { value: &'a Error } impl<'a> fmt::Display for FormattedError<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let e = self.value; write!(f, "{}", e)?; let mut last_error = e.to_string(); for e in e.iter().skip(1) { let this_err: String = e.to_string(); if last_error!= this_err { writeln!(f, " [due to]:")?; write!(f, " βž₯ {}", e)?; } last_error = this_err } // The backtrace is generated with environment `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { writeln!(f, "")?; writeln!(f, " =>: {:?}", backtrace)?; } Ok(()) } } impl Error { pub fn format<'a>(&'a self) -> FormattedError<'a> { FormattedError{value: self} } }
FormattedError
identifier_name
errors.rs
use std::fmt; use std::ops::FnOnce; error_chain! { } pub struct FormattedError<'a> { value: &'a Error } impl<'a> fmt::Display for FormattedError<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let e = self.value; write!(f, "{}", e)?; let mut last_error = e.to_string(); for e in e.iter().skip(1) { let this_err: String = e.to_string(); if last_error!= this_err { writeln!(f, " [due to]:")?; write!(f, " βž₯ {}", e)?; } last_error = this_err } // The backtrace is generated with environment `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() {
Ok(()) } } impl Error { pub fn format<'a>(&'a self) -> FormattedError<'a> { FormattedError{value: self} } }
writeln!(f, "")?; writeln!(f, " =>: {:?}", backtrace)?; }
conditional_block
errors.rs
use std::fmt; use std::ops::FnOnce; error_chain! { } pub struct FormattedError<'a> { value: &'a Error } impl<'a> fmt::Display for FormattedError<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let e = self.value; write!(f, "{}", e)?; let mut last_error = e.to_string(); for e in e.iter().skip(1) { let this_err: String = e.to_string(); if last_error!= this_err { writeln!(f, " [due to]:")?; write!(f, " βž₯ {}", e)?; } last_error = this_err }
// The backtrace is generated with environment `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { writeln!(f, "")?; writeln!(f, " =>: {:?}", backtrace)?; } Ok(()) } } impl Error { pub fn format<'a>(&'a self) -> FormattedError<'a> { FormattedError{value: self} } }
random_line_split
cast.rs
/* kernel/cast.rs * * Copyright (c) 2014, Chris Williams (diosix.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ /* allow the kernel to recast variables */ /* grab the compiler's built-in functions */ extern "rust-intrinsic" { pub fn forget<T>(_: T) -> (); pub fn transmute<T,U>(e: T) -> U; } /* cast::kforget Take ownership of a variable but do not trigger any cleanup or memory management tasks – literally allow the system to forget about it. => var = variable to discard */ #[inline] pub fn kf
>(var: T) { unsafe { forget(var); } } /* cast::ktransmute::<L, G> Convert a variable from one type to another. => var = variable of type L to convert <= returns variable as type G */ #[inline] pub fn ktransmute<L, G>(var: L) -> G { unsafe { transmute(var) } }
orget<T
identifier_name
cast.rs
/* kernel/cast.rs * * Copyright (c) 2014, Chris Williams (diosix.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ /* allow the kernel to recast variables */ /* grab the compiler's built-in functions */ extern "rust-intrinsic" { pub fn forget<T>(_: T) -> (); pub fn transmute<T,U>(e: T) -> U; } /* cast::kforget Take ownership of a variable but do not trigger any cleanup or memory management tasks – literally allow the system to forget about it. => var = variable to discard */ #[inline] pub fn kforget<T>(var: T) {
/* cast::ktransmute::<L, G> Convert a variable from one type to another. => var = variable of type L to convert <= returns variable as type G */ #[inline] pub fn ktransmute<L, G>(var: L) -> G { unsafe { transmute(var) } }
unsafe { forget(var); } }
identifier_body
cast.rs
/* kernel/cast.rs * * Copyright (c) 2014, Chris Williams (diosix.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ /* allow the kernel to recast variables */ /* grab the compiler's built-in functions */ extern "rust-intrinsic" { pub fn forget<T>(_: T) -> (); pub fn transmute<T,U>(e: T) -> U; } /* cast::kforget Take ownership of a variable but do not trigger any cleanup or memory management tasks – literally allow the system to forget about it. => var = variable to discard */ #[inline] pub fn kforget<T>(var: T) { unsafe { forget(var); } } /* cast::ktransmute::<L, G> Convert a variable from one type to another. => var = variable of type L to convert <= returns variable as type G */ #[inline] pub fn ktransmute<L, G>(var: L) -> G { unsafe { transmute(var) } }
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
random_line_split
delete.rs
use actix_identity::Identity; use actix_web::{error, http::header, post, web, Error, HttpResponse, Result}; use crate::DbPool; use super::actions; use crate::uri_helpers::*; #[post("/likes/{id}/delete")] pub async fn delete(ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpResponse, Error> { if ident.identity().is_none()
let pool_ = pool.clone(); let like = web::block(move || { let conn = pool_.get()?; actions::get_like(id.into_inner(), &conn) }) .await? .map_err(|e| error::ErrorInternalServerError(format!("Database error: {}", e)))?; let _deleted = web::block(move || { let conn = pool.get()?; actions::delete_like(like.id, &conn) }) .await .map_err(|e| error::ErrorInternalServerError(format!("Database error: {}", e)))?; Ok(HttpResponse::Found() .append_header((header::LOCATION, likes_uri())) .finish()) }
{ return Result::Err(error::ErrorForbidden("You have to be logged in to see this page")); }
conditional_block
delete.rs
use actix_identity::Identity; use actix_web::{error, http::header, post, web, Error, HttpResponse, Result};
use super::actions; use crate::uri_helpers::*; #[post("/likes/{id}/delete")] pub async fn delete(ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpResponse, Error> { if ident.identity().is_none() { return Result::Err(error::ErrorForbidden("You have to be logged in to see this page")); } let pool_ = pool.clone(); let like = web::block(move || { let conn = pool_.get()?; actions::get_like(id.into_inner(), &conn) }) .await? .map_err(|e| error::ErrorInternalServerError(format!("Database error: {}", e)))?; let _deleted = web::block(move || { let conn = pool.get()?; actions::delete_like(like.id, &conn) }) .await .map_err(|e| error::ErrorInternalServerError(format!("Database error: {}", e)))?; Ok(HttpResponse::Found() .append_header((header::LOCATION, likes_uri())) .finish()) }
use crate::DbPool;
random_line_split
delete.rs
use actix_identity::Identity; use actix_web::{error, http::header, post, web, Error, HttpResponse, Result}; use crate::DbPool; use super::actions; use crate::uri_helpers::*; #[post("/likes/{id}/delete")] pub async fn
(ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpResponse, Error> { if ident.identity().is_none() { return Result::Err(error::ErrorForbidden("You have to be logged in to see this page")); } let pool_ = pool.clone(); let like = web::block(move || { let conn = pool_.get()?; actions::get_like(id.into_inner(), &conn) }) .await? .map_err(|e| error::ErrorInternalServerError(format!("Database error: {}", e)))?; let _deleted = web::block(move || { let conn = pool.get()?; actions::delete_like(like.id, &conn) }) .await .map_err(|e| error::ErrorInternalServerError(format!("Database error: {}", e)))?; Ok(HttpResponse::Found() .append_header((header::LOCATION, likes_uri())) .finish()) }
delete
identifier_name
delete.rs
use actix_identity::Identity; use actix_web::{error, http::header, post, web, Error, HttpResponse, Result}; use crate::DbPool; use super::actions; use crate::uri_helpers::*; #[post("/likes/{id}/delete")] pub async fn delete(ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpResponse, Error>
Ok(HttpResponse::Found() .append_header((header::LOCATION, likes_uri())) .finish()) }
{ if ident.identity().is_none() { return Result::Err(error::ErrorForbidden("You have to be logged in to see this page")); } let pool_ = pool.clone(); let like = web::block(move || { let conn = pool_.get()?; actions::get_like(id.into_inner(), &conn) }) .await? .map_err(|e| error::ErrorInternalServerError(format!("Database error: {}", e)))?; let _deleted = web::block(move || { let conn = pool.get()?; actions::delete_like(like.id, &conn) }) .await .map_err(|e| error::ErrorInternalServerError(format!("Database error: {}", e)))?;
identifier_body
ethstore.rs
// Copyright 2015, 2016 Ethcore (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/>. use std::collections::BTreeMap; use std::mem; use ethkey::KeyPair; use crypto::KEY_ITERATIONS; use random::Random; use ethkey::{Signature, Address, Message, Secret, Public}; use dir::KeyDirectory; use account::SafeAccount; use {Error, SecretStore}; use json; use json::UUID; use parking_lot::RwLock; use presale::PresaleWallet; use import; pub struct EthStore { dir: Box<KeyDirectory>, iterations: u32, cache: RwLock<BTreeMap<Address, SafeAccount>>, } impl EthStore { pub fn open(directory: Box<KeyDirectory>) -> Result<Self, Error> { Self::open_with_iterations(directory, KEY_ITERATIONS as u32) } pub fn open_with_iterations(directory: Box<KeyDirectory>, iterations: u32) -> Result<Self, Error> { let accounts = try!(directory.load()); let cache = accounts.into_iter().map(|account| (account.address.clone(), account)).collect(); let store = EthStore { dir: directory, iterations: iterations, cache: RwLock::new(cache), }; Ok(store) } fn save(&self, account: SafeAccount) -> Result<(), Error> { // save to file let account = try!(self.dir.insert(account.clone())); // update cache let mut cache = self.cache.write(); cache.insert(account.address.clone(), account); Ok(()) } fn reload_accounts(&self) -> Result<(), Error> { let mut cache = self.cache.write(); let accounts = try!(self.dir.load()); let new_accounts: BTreeMap<_, _> = accounts.into_iter().map(|account| (account.address.clone(), account)).collect(); mem::replace(&mut *cache, new_accounts); Ok(()) } fn get(&self, address: &Address) -> Result<SafeAccount, Error> { { let cache = self.cache.read(); if let Some(account) = cache.get(address)
} try!(self.reload_accounts()); let cache = self.cache.read(); cache.get(address).cloned().ok_or(Error::InvalidAccount) } } impl SecretStore for EthStore { fn insert_account(&self, secret: Secret, password: &str) -> Result<Address, Error> { let keypair = try!(KeyPair::from_secret(secret).map_err(|_| Error::CreationFailed)); let id: [u8; 16] = Random::random(); let account = SafeAccount::create(&keypair, id, password, self.iterations, "".to_owned(), "{}".to_owned()); let address = account.address.clone(); try!(self.save(account)); Ok(address) } fn import_presale(&self, json: &[u8], password: &str) -> Result<Address, Error> { let json_wallet = try!(json::PresaleWallet::load(json).map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))); let wallet = PresaleWallet::from(json_wallet); let keypair = try!(wallet.decrypt(password).map_err(|_| Error::InvalidPassword)); self.insert_account(keypair.secret().clone(), password) } fn import_wallet(&self, json: &[u8], password: &str) -> Result<Address, Error> { let json_keyfile = try!(json::KeyFile::load(json).map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))); let mut safe_account = SafeAccount::from_file(json_keyfile, None); let secret = try!(safe_account.crypto.secret(password).map_err(|_| Error::InvalidPassword)); safe_account.address = try!(KeyPair::from_secret(secret)).address(); let address = safe_account.address.clone(); try!(self.save(safe_account)); Ok(address) } fn accounts(&self) -> Result<Vec<Address>, Error> { try!(self.reload_accounts()); Ok(self.cache.read().keys().cloned().collect()) } fn change_password(&self, address: &Address, old_password: &str, new_password: &str) -> Result<(), Error> { // change password let account = try!(self.get(address)); let account = try!(account.change_password(old_password, new_password, self.iterations)); // save to file self.save(account) } fn remove_account(&self, address: &Address, password: &str) -> Result<(), Error> { let can_remove = { let account = try!(self.get(address)); account.check_password(password) }; if can_remove { try!(self.dir.remove(address)); let mut cache = self.cache.write(); cache.remove(address); Ok(()) } else { Err(Error::InvalidPassword) } } fn sign(&self, address: &Address, password: &str, message: &Message) -> Result<Signature, Error> { let account = try!(self.get(address)); account.sign(password, message) } fn decrypt(&self, account: &Address, password: &str, shared_mac: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> { let account = try!(self.get(account)); account.decrypt(password, shared_mac, message) } fn public(&self, account: &Address, password: &str) -> Result<Public, Error> { let account = try!(self.get(account)); account.public(password) } fn uuid(&self, address: &Address) -> Result<UUID, Error> { let account = try!(self.get(address)); Ok(account.id.into()) } fn name(&self, address: &Address) -> Result<String, Error> { let account = try!(self.get(address)); Ok(account.name.clone()) } fn meta(&self, address: &Address) -> Result<String, Error> { let account = try!(self.get(address)); Ok(account.meta.clone()) } fn set_name(&self, address: &Address, name: String) -> Result<(), Error> { let mut account = try!(self.get(address)); account.name = name; // save to file self.save(account) } fn set_meta(&self, address: &Address, meta: String) -> Result<(), Error> { let mut account = try!(self.get(address)); account.meta = meta; // save to file self.save(account) } fn local_path(&self) -> String { self.dir.path().map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| String::new()) } fn list_geth_accounts(&self, testnet: bool) -> Vec<Address> { import::read_geth_accounts(testnet) } fn import_geth_accounts(&self, desired: Vec<Address>, testnet: bool) -> Result<Vec<Address>, Error> { import::import_geth_accounts(&*self.dir, desired.into_iter().collect(), testnet) } }
{ return Ok(account.clone()) }
conditional_block
ethstore.rs
// Copyright 2015, 2016 Ethcore (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/>. use std::collections::BTreeMap; use std::mem; use ethkey::KeyPair; use crypto::KEY_ITERATIONS; use random::Random; use ethkey::{Signature, Address, Message, Secret, Public}; use dir::KeyDirectory; use account::SafeAccount; use {Error, SecretStore}; use json; use json::UUID; use parking_lot::RwLock; use presale::PresaleWallet; use import; pub struct EthStore { dir: Box<KeyDirectory>, iterations: u32, cache: RwLock<BTreeMap<Address, SafeAccount>>, } impl EthStore { pub fn open(directory: Box<KeyDirectory>) -> Result<Self, Error> { Self::open_with_iterations(directory, KEY_ITERATIONS as u32) } pub fn open_with_iterations(directory: Box<KeyDirectory>, iterations: u32) -> Result<Self, Error> { let accounts = try!(directory.load()); let cache = accounts.into_iter().map(|account| (account.address.clone(), account)).collect(); let store = EthStore { dir: directory, iterations: iterations, cache: RwLock::new(cache), }; Ok(store) } fn save(&self, account: SafeAccount) -> Result<(), Error> { // save to file let account = try!(self.dir.insert(account.clone())); // update cache let mut cache = self.cache.write(); cache.insert(account.address.clone(), account); Ok(()) } fn reload_accounts(&self) -> Result<(), Error> { let mut cache = self.cache.write(); let accounts = try!(self.dir.load()); let new_accounts: BTreeMap<_, _> = accounts.into_iter().map(|account| (account.address.clone(), account)).collect(); mem::replace(&mut *cache, new_accounts); Ok(()) } fn get(&self, address: &Address) -> Result<SafeAccount, Error> { { let cache = self.cache.read(); if let Some(account) = cache.get(address) { return Ok(account.clone()) } } try!(self.reload_accounts()); let cache = self.cache.read(); cache.get(address).cloned().ok_or(Error::InvalidAccount) } } impl SecretStore for EthStore { fn insert_account(&self, secret: Secret, password: &str) -> Result<Address, Error> { let keypair = try!(KeyPair::from_secret(secret).map_err(|_| Error::CreationFailed)); let id: [u8; 16] = Random::random(); let account = SafeAccount::create(&keypair, id, password, self.iterations, "".to_owned(), "{}".to_owned()); let address = account.address.clone(); try!(self.save(account)); Ok(address) } fn import_presale(&self, json: &[u8], password: &str) -> Result<Address, Error> { let json_wallet = try!(json::PresaleWallet::load(json).map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))); let wallet = PresaleWallet::from(json_wallet); let keypair = try!(wallet.decrypt(password).map_err(|_| Error::InvalidPassword)); self.insert_account(keypair.secret().clone(), password) } fn import_wallet(&self, json: &[u8], password: &str) -> Result<Address, Error> { let json_keyfile = try!(json::KeyFile::load(json).map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))); let mut safe_account = SafeAccount::from_file(json_keyfile, None); let secret = try!(safe_account.crypto.secret(password).map_err(|_| Error::InvalidPassword)); safe_account.address = try!(KeyPair::from_secret(secret)).address(); let address = safe_account.address.clone(); try!(self.save(safe_account)); Ok(address) } fn accounts(&self) -> Result<Vec<Address>, Error> { try!(self.reload_accounts()); Ok(self.cache.read().keys().cloned().collect()) } fn change_password(&self, address: &Address, old_password: &str, new_password: &str) -> Result<(), Error> { // change password let account = try!(self.get(address)); let account = try!(account.change_password(old_password, new_password, self.iterations)); // save to file self.save(account) } fn remove_account(&self, address: &Address, password: &str) -> Result<(), Error> { let can_remove = { let account = try!(self.get(address)); account.check_password(password) }; if can_remove { try!(self.dir.remove(address)); let mut cache = self.cache.write(); cache.remove(address); Ok(()) } else { Err(Error::InvalidPassword) } } fn sign(&self, address: &Address, password: &str, message: &Message) -> Result<Signature, Error> { let account = try!(self.get(address)); account.sign(password, message) } fn decrypt(&self, account: &Address, password: &str, shared_mac: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> { let account = try!(self.get(account)); account.decrypt(password, shared_mac, message) } fn public(&self, account: &Address, password: &str) -> Result<Public, Error> { let account = try!(self.get(account)); account.public(password) } fn uuid(&self, address: &Address) -> Result<UUID, Error> { let account = try!(self.get(address)); Ok(account.id.into()) } fn name(&self, address: &Address) -> Result<String, Error> { let account = try!(self.get(address)); Ok(account.name.clone()) } fn meta(&self, address: &Address) -> Result<String, Error> { let account = try!(self.get(address)); Ok(account.meta.clone()) } fn set_name(&self, address: &Address, name: String) -> Result<(), Error> { let mut account = try!(self.get(address)); account.name = name; // save to file self.save(account) } fn set_meta(&self, address: &Address, meta: String) -> Result<(), Error> { let mut account = try!(self.get(address)); account.meta = meta; // save to file self.save(account) } fn local_path(&self) -> String { self.dir.path().map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| String::new()) } fn list_geth_accounts(&self, testnet: bool) -> Vec<Address> { import::read_geth_accounts(testnet) } fn import_geth_accounts(&self, desired: Vec<Address>, testnet: bool) -> Result<Vec<Address>, Error> {
import::import_geth_accounts(&*self.dir, desired.into_iter().collect(), testnet) } }
random_line_split
ethstore.rs
// Copyright 2015, 2016 Ethcore (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/>. use std::collections::BTreeMap; use std::mem; use ethkey::KeyPair; use crypto::KEY_ITERATIONS; use random::Random; use ethkey::{Signature, Address, Message, Secret, Public}; use dir::KeyDirectory; use account::SafeAccount; use {Error, SecretStore}; use json; use json::UUID; use parking_lot::RwLock; use presale::PresaleWallet; use import; pub struct EthStore { dir: Box<KeyDirectory>, iterations: u32, cache: RwLock<BTreeMap<Address, SafeAccount>>, } impl EthStore { pub fn open(directory: Box<KeyDirectory>) -> Result<Self, Error> { Self::open_with_iterations(directory, KEY_ITERATIONS as u32) } pub fn open_with_iterations(directory: Box<KeyDirectory>, iterations: u32) -> Result<Self, Error> { let accounts = try!(directory.load()); let cache = accounts.into_iter().map(|account| (account.address.clone(), account)).collect(); let store = EthStore { dir: directory, iterations: iterations, cache: RwLock::new(cache), }; Ok(store) } fn save(&self, account: SafeAccount) -> Result<(), Error> { // save to file let account = try!(self.dir.insert(account.clone())); // update cache let mut cache = self.cache.write(); cache.insert(account.address.clone(), account); Ok(()) } fn reload_accounts(&self) -> Result<(), Error>
fn get(&self, address: &Address) -> Result<SafeAccount, Error> { { let cache = self.cache.read(); if let Some(account) = cache.get(address) { return Ok(account.clone()) } } try!(self.reload_accounts()); let cache = self.cache.read(); cache.get(address).cloned().ok_or(Error::InvalidAccount) } } impl SecretStore for EthStore { fn insert_account(&self, secret: Secret, password: &str) -> Result<Address, Error> { let keypair = try!(KeyPair::from_secret(secret).map_err(|_| Error::CreationFailed)); let id: [u8; 16] = Random::random(); let account = SafeAccount::create(&keypair, id, password, self.iterations, "".to_owned(), "{}".to_owned()); let address = account.address.clone(); try!(self.save(account)); Ok(address) } fn import_presale(&self, json: &[u8], password: &str) -> Result<Address, Error> { let json_wallet = try!(json::PresaleWallet::load(json).map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))); let wallet = PresaleWallet::from(json_wallet); let keypair = try!(wallet.decrypt(password).map_err(|_| Error::InvalidPassword)); self.insert_account(keypair.secret().clone(), password) } fn import_wallet(&self, json: &[u8], password: &str) -> Result<Address, Error> { let json_keyfile = try!(json::KeyFile::load(json).map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))); let mut safe_account = SafeAccount::from_file(json_keyfile, None); let secret = try!(safe_account.crypto.secret(password).map_err(|_| Error::InvalidPassword)); safe_account.address = try!(KeyPair::from_secret(secret)).address(); let address = safe_account.address.clone(); try!(self.save(safe_account)); Ok(address) } fn accounts(&self) -> Result<Vec<Address>, Error> { try!(self.reload_accounts()); Ok(self.cache.read().keys().cloned().collect()) } fn change_password(&self, address: &Address, old_password: &str, new_password: &str) -> Result<(), Error> { // change password let account = try!(self.get(address)); let account = try!(account.change_password(old_password, new_password, self.iterations)); // save to file self.save(account) } fn remove_account(&self, address: &Address, password: &str) -> Result<(), Error> { let can_remove = { let account = try!(self.get(address)); account.check_password(password) }; if can_remove { try!(self.dir.remove(address)); let mut cache = self.cache.write(); cache.remove(address); Ok(()) } else { Err(Error::InvalidPassword) } } fn sign(&self, address: &Address, password: &str, message: &Message) -> Result<Signature, Error> { let account = try!(self.get(address)); account.sign(password, message) } fn decrypt(&self, account: &Address, password: &str, shared_mac: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> { let account = try!(self.get(account)); account.decrypt(password, shared_mac, message) } fn public(&self, account: &Address, password: &str) -> Result<Public, Error> { let account = try!(self.get(account)); account.public(password) } fn uuid(&self, address: &Address) -> Result<UUID, Error> { let account = try!(self.get(address)); Ok(account.id.into()) } fn name(&self, address: &Address) -> Result<String, Error> { let account = try!(self.get(address)); Ok(account.name.clone()) } fn meta(&self, address: &Address) -> Result<String, Error> { let account = try!(self.get(address)); Ok(account.meta.clone()) } fn set_name(&self, address: &Address, name: String) -> Result<(), Error> { let mut account = try!(self.get(address)); account.name = name; // save to file self.save(account) } fn set_meta(&self, address: &Address, meta: String) -> Result<(), Error> { let mut account = try!(self.get(address)); account.meta = meta; // save to file self.save(account) } fn local_path(&self) -> String { self.dir.path().map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| String::new()) } fn list_geth_accounts(&self, testnet: bool) -> Vec<Address> { import::read_geth_accounts(testnet) } fn import_geth_accounts(&self, desired: Vec<Address>, testnet: bool) -> Result<Vec<Address>, Error> { import::import_geth_accounts(&*self.dir, desired.into_iter().collect(), testnet) } }
{ let mut cache = self.cache.write(); let accounts = try!(self.dir.load()); let new_accounts: BTreeMap<_, _> = accounts.into_iter().map(|account| (account.address.clone(), account)).collect(); mem::replace(&mut *cache, new_accounts); Ok(()) }
identifier_body
ethstore.rs
// Copyright 2015, 2016 Ethcore (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/>. use std::collections::BTreeMap; use std::mem; use ethkey::KeyPair; use crypto::KEY_ITERATIONS; use random::Random; use ethkey::{Signature, Address, Message, Secret, Public}; use dir::KeyDirectory; use account::SafeAccount; use {Error, SecretStore}; use json; use json::UUID; use parking_lot::RwLock; use presale::PresaleWallet; use import; pub struct EthStore { dir: Box<KeyDirectory>, iterations: u32, cache: RwLock<BTreeMap<Address, SafeAccount>>, } impl EthStore { pub fn open(directory: Box<KeyDirectory>) -> Result<Self, Error> { Self::open_with_iterations(directory, KEY_ITERATIONS as u32) } pub fn open_with_iterations(directory: Box<KeyDirectory>, iterations: u32) -> Result<Self, Error> { let accounts = try!(directory.load()); let cache = accounts.into_iter().map(|account| (account.address.clone(), account)).collect(); let store = EthStore { dir: directory, iterations: iterations, cache: RwLock::new(cache), }; Ok(store) } fn save(&self, account: SafeAccount) -> Result<(), Error> { // save to file let account = try!(self.dir.insert(account.clone())); // update cache let mut cache = self.cache.write(); cache.insert(account.address.clone(), account); Ok(()) } fn reload_accounts(&self) -> Result<(), Error> { let mut cache = self.cache.write(); let accounts = try!(self.dir.load()); let new_accounts: BTreeMap<_, _> = accounts.into_iter().map(|account| (account.address.clone(), account)).collect(); mem::replace(&mut *cache, new_accounts); Ok(()) } fn
(&self, address: &Address) -> Result<SafeAccount, Error> { { let cache = self.cache.read(); if let Some(account) = cache.get(address) { return Ok(account.clone()) } } try!(self.reload_accounts()); let cache = self.cache.read(); cache.get(address).cloned().ok_or(Error::InvalidAccount) } } impl SecretStore for EthStore { fn insert_account(&self, secret: Secret, password: &str) -> Result<Address, Error> { let keypair = try!(KeyPair::from_secret(secret).map_err(|_| Error::CreationFailed)); let id: [u8; 16] = Random::random(); let account = SafeAccount::create(&keypair, id, password, self.iterations, "".to_owned(), "{}".to_owned()); let address = account.address.clone(); try!(self.save(account)); Ok(address) } fn import_presale(&self, json: &[u8], password: &str) -> Result<Address, Error> { let json_wallet = try!(json::PresaleWallet::load(json).map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))); let wallet = PresaleWallet::from(json_wallet); let keypair = try!(wallet.decrypt(password).map_err(|_| Error::InvalidPassword)); self.insert_account(keypair.secret().clone(), password) } fn import_wallet(&self, json: &[u8], password: &str) -> Result<Address, Error> { let json_keyfile = try!(json::KeyFile::load(json).map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))); let mut safe_account = SafeAccount::from_file(json_keyfile, None); let secret = try!(safe_account.crypto.secret(password).map_err(|_| Error::InvalidPassword)); safe_account.address = try!(KeyPair::from_secret(secret)).address(); let address = safe_account.address.clone(); try!(self.save(safe_account)); Ok(address) } fn accounts(&self) -> Result<Vec<Address>, Error> { try!(self.reload_accounts()); Ok(self.cache.read().keys().cloned().collect()) } fn change_password(&self, address: &Address, old_password: &str, new_password: &str) -> Result<(), Error> { // change password let account = try!(self.get(address)); let account = try!(account.change_password(old_password, new_password, self.iterations)); // save to file self.save(account) } fn remove_account(&self, address: &Address, password: &str) -> Result<(), Error> { let can_remove = { let account = try!(self.get(address)); account.check_password(password) }; if can_remove { try!(self.dir.remove(address)); let mut cache = self.cache.write(); cache.remove(address); Ok(()) } else { Err(Error::InvalidPassword) } } fn sign(&self, address: &Address, password: &str, message: &Message) -> Result<Signature, Error> { let account = try!(self.get(address)); account.sign(password, message) } fn decrypt(&self, account: &Address, password: &str, shared_mac: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> { let account = try!(self.get(account)); account.decrypt(password, shared_mac, message) } fn public(&self, account: &Address, password: &str) -> Result<Public, Error> { let account = try!(self.get(account)); account.public(password) } fn uuid(&self, address: &Address) -> Result<UUID, Error> { let account = try!(self.get(address)); Ok(account.id.into()) } fn name(&self, address: &Address) -> Result<String, Error> { let account = try!(self.get(address)); Ok(account.name.clone()) } fn meta(&self, address: &Address) -> Result<String, Error> { let account = try!(self.get(address)); Ok(account.meta.clone()) } fn set_name(&self, address: &Address, name: String) -> Result<(), Error> { let mut account = try!(self.get(address)); account.name = name; // save to file self.save(account) } fn set_meta(&self, address: &Address, meta: String) -> Result<(), Error> { let mut account = try!(self.get(address)); account.meta = meta; // save to file self.save(account) } fn local_path(&self) -> String { self.dir.path().map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| String::new()) } fn list_geth_accounts(&self, testnet: bool) -> Vec<Address> { import::read_geth_accounts(testnet) } fn import_geth_accounts(&self, desired: Vec<Address>, testnet: bool) -> Result<Vec<Address>, Error> { import::import_geth_accounts(&*self.dir, desired.into_iter().collect(), testnet) } }
get
identifier_name
service.rs
// NOTE: All this code is basically copied verbatim from its previous home in // the Launcher module. Once all the service-related functionality that we're // going to move over to the Supervisor has been moved, we can take a look at // perhaps refactoring some of this a bit. use crate::{manager::ShutdownConfig, sys::ShutdownMethod}; use habitat_core::os::process::{is_alive, signal, Pid, Signal}; use libc::{self, pid_t}; use std::{ops::Neg, thread, time::{Duration, Instant}}; /// Kill a service process. pub fn kill(pid: Pid, shutdown_config: &ShutdownConfig) -> ShutdownMethod { let process = Process::new(pid); process.kill(shutdown_config) } /////////////////////////////////////////////////////////////////////// // Private Code // TODO (CM): We may not want this struct in the end... keeping it for // now to keep some parity with the Windows implementation. Once we // pull over all the "service" functionality from the Launcher, we can // re-evaluate. struct Process { pid: pid_t, } impl Process { fn new(pid: Pid) -> Self { Process { pid } } /// Attempt to gracefully terminate a proccess and then forcefully /// kill it after 8 seconds if it has not terminated. fn kill(&self, shutdown_config: &ShutdownConfig) -> ShutdownMethod { let ShutdownConfig { signal: shutdown_signal, timeout, } = *shutdown_config; let shutdown_signal = shutdown_signal.into(); let mut pid_to_kill = self.pid; // check the group of the process being killed
// to prevent orphaned processes. let pgid = unsafe { libc::getpgid(self.pid) }; if self.pid == pgid { debug!("pid to kill {} is the process group root. Sending signal to process group.", self.pid); // sending a signal to the negative pid sends it to the // entire process group instead just the single pid pid_to_kill = self.pid.neg(); } // JW TODO: Determine if the error represents a case where the // process was already exited before we return out and assume // so. trace!("Sending {:?} signal to process {}", shutdown_signal, pid_to_kill); #[allow(clippy::question_mark)] if signal(pid_to_kill, shutdown_signal).is_err() { return ShutdownMethod::AlreadyExited; } let timeout: Duration = timeout.into(); trace!("Waiting up to {} seconds before sending KILL to process {}", timeout.as_secs(), pid_to_kill); let start_time = Instant::now(); loop { if!is_alive(pid_to_kill) { return ShutdownMethod::GracefulTermination; } if start_time.elapsed() >= timeout { break; } thread::sleep(Duration::from_millis(5)); } trace!("Timeout exceeded; killing process {}", pid_to_kill); match signal(pid_to_kill, Signal::KILL) { Ok(_) => ShutdownMethod::Killed, Err(_) => { // JW TODO: Determine if the error represents a case // where the process was already exited before we // return out and assume so. ShutdownMethod::GracefulTermination } } } }
// if it is the root process of the process group // we send our signals to the entire process group
random_line_split
service.rs
// NOTE: All this code is basically copied verbatim from its previous home in // the Launcher module. Once all the service-related functionality that we're // going to move over to the Supervisor has been moved, we can take a look at // perhaps refactoring some of this a bit. use crate::{manager::ShutdownConfig, sys::ShutdownMethod}; use habitat_core::os::process::{is_alive, signal, Pid, Signal}; use libc::{self, pid_t}; use std::{ops::Neg, thread, time::{Duration, Instant}}; /// Kill a service process. pub fn kill(pid: Pid, shutdown_config: &ShutdownConfig) -> ShutdownMethod { let process = Process::new(pid); process.kill(shutdown_config) } /////////////////////////////////////////////////////////////////////// // Private Code // TODO (CM): We may not want this struct in the end... keeping it for // now to keep some parity with the Windows implementation. Once we // pull over all the "service" functionality from the Launcher, we can // re-evaluate. struct Process { pid: pid_t, } impl Process { fn new(pid: Pid) -> Self { Process { pid } } /// Attempt to gracefully terminate a proccess and then forcefully /// kill it after 8 seconds if it has not terminated. fn kill(&self, shutdown_config: &ShutdownConfig) -> ShutdownMethod { let ShutdownConfig { signal: shutdown_signal, timeout, } = *shutdown_config; let shutdown_signal = shutdown_signal.into(); let mut pid_to_kill = self.pid; // check the group of the process being killed // if it is the root process of the process group // we send our signals to the entire process group // to prevent orphaned processes. let pgid = unsafe { libc::getpgid(self.pid) }; if self.pid == pgid
// JW TODO: Determine if the error represents a case where the // process was already exited before we return out and assume // so. trace!("Sending {:?} signal to process {}", shutdown_signal, pid_to_kill); #[allow(clippy::question_mark)] if signal(pid_to_kill, shutdown_signal).is_err() { return ShutdownMethod::AlreadyExited; } let timeout: Duration = timeout.into(); trace!("Waiting up to {} seconds before sending KILL to process {}", timeout.as_secs(), pid_to_kill); let start_time = Instant::now(); loop { if!is_alive(pid_to_kill) { return ShutdownMethod::GracefulTermination; } if start_time.elapsed() >= timeout { break; } thread::sleep(Duration::from_millis(5)); } trace!("Timeout exceeded; killing process {}", pid_to_kill); match signal(pid_to_kill, Signal::KILL) { Ok(_) => ShutdownMethod::Killed, Err(_) => { // JW TODO: Determine if the error represents a case // where the process was already exited before we // return out and assume so. ShutdownMethod::GracefulTermination } } } }
{ debug!("pid to kill {} is the process group root. Sending signal to process group.", self.pid); // sending a signal to the negative pid sends it to the // entire process group instead just the single pid pid_to_kill = self.pid.neg(); }
conditional_block
service.rs
// NOTE: All this code is basically copied verbatim from its previous home in // the Launcher module. Once all the service-related functionality that we're // going to move over to the Supervisor has been moved, we can take a look at // perhaps refactoring some of this a bit. use crate::{manager::ShutdownConfig, sys::ShutdownMethod}; use habitat_core::os::process::{is_alive, signal, Pid, Signal}; use libc::{self, pid_t}; use std::{ops::Neg, thread, time::{Duration, Instant}}; /// Kill a service process. pub fn kill(pid: Pid, shutdown_config: &ShutdownConfig) -> ShutdownMethod { let process = Process::new(pid); process.kill(shutdown_config) } /////////////////////////////////////////////////////////////////////// // Private Code // TODO (CM): We may not want this struct in the end... keeping it for // now to keep some parity with the Windows implementation. Once we // pull over all the "service" functionality from the Launcher, we can // re-evaluate. struct
{ pid: pid_t, } impl Process { fn new(pid: Pid) -> Self { Process { pid } } /// Attempt to gracefully terminate a proccess and then forcefully /// kill it after 8 seconds if it has not terminated. fn kill(&self, shutdown_config: &ShutdownConfig) -> ShutdownMethod { let ShutdownConfig { signal: shutdown_signal, timeout, } = *shutdown_config; let shutdown_signal = shutdown_signal.into(); let mut pid_to_kill = self.pid; // check the group of the process being killed // if it is the root process of the process group // we send our signals to the entire process group // to prevent orphaned processes. let pgid = unsafe { libc::getpgid(self.pid) }; if self.pid == pgid { debug!("pid to kill {} is the process group root. Sending signal to process group.", self.pid); // sending a signal to the negative pid sends it to the // entire process group instead just the single pid pid_to_kill = self.pid.neg(); } // JW TODO: Determine if the error represents a case where the // process was already exited before we return out and assume // so. trace!("Sending {:?} signal to process {}", shutdown_signal, pid_to_kill); #[allow(clippy::question_mark)] if signal(pid_to_kill, shutdown_signal).is_err() { return ShutdownMethod::AlreadyExited; } let timeout: Duration = timeout.into(); trace!("Waiting up to {} seconds before sending KILL to process {}", timeout.as_secs(), pid_to_kill); let start_time = Instant::now(); loop { if!is_alive(pid_to_kill) { return ShutdownMethod::GracefulTermination; } if start_time.elapsed() >= timeout { break; } thread::sleep(Duration::from_millis(5)); } trace!("Timeout exceeded; killing process {}", pid_to_kill); match signal(pid_to_kill, Signal::KILL) { Ok(_) => ShutdownMethod::Killed, Err(_) => { // JW TODO: Determine if the error represents a case // where the process was already exited before we // return out and assume so. ShutdownMethod::GracefulTermination } } } }
Process
identifier_name
service.rs
// NOTE: All this code is basically copied verbatim from its previous home in // the Launcher module. Once all the service-related functionality that we're // going to move over to the Supervisor has been moved, we can take a look at // perhaps refactoring some of this a bit. use crate::{manager::ShutdownConfig, sys::ShutdownMethod}; use habitat_core::os::process::{is_alive, signal, Pid, Signal}; use libc::{self, pid_t}; use std::{ops::Neg, thread, time::{Duration, Instant}}; /// Kill a service process. pub fn kill(pid: Pid, shutdown_config: &ShutdownConfig) -> ShutdownMethod { let process = Process::new(pid); process.kill(shutdown_config) } /////////////////////////////////////////////////////////////////////// // Private Code // TODO (CM): We may not want this struct in the end... keeping it for // now to keep some parity with the Windows implementation. Once we // pull over all the "service" functionality from the Launcher, we can // re-evaluate. struct Process { pid: pid_t, } impl Process { fn new(pid: Pid) -> Self
/// Attempt to gracefully terminate a proccess and then forcefully /// kill it after 8 seconds if it has not terminated. fn kill(&self, shutdown_config: &ShutdownConfig) -> ShutdownMethod { let ShutdownConfig { signal: shutdown_signal, timeout, } = *shutdown_config; let shutdown_signal = shutdown_signal.into(); let mut pid_to_kill = self.pid; // check the group of the process being killed // if it is the root process of the process group // we send our signals to the entire process group // to prevent orphaned processes. let pgid = unsafe { libc::getpgid(self.pid) }; if self.pid == pgid { debug!("pid to kill {} is the process group root. Sending signal to process group.", self.pid); // sending a signal to the negative pid sends it to the // entire process group instead just the single pid pid_to_kill = self.pid.neg(); } // JW TODO: Determine if the error represents a case where the // process was already exited before we return out and assume // so. trace!("Sending {:?} signal to process {}", shutdown_signal, pid_to_kill); #[allow(clippy::question_mark)] if signal(pid_to_kill, shutdown_signal).is_err() { return ShutdownMethod::AlreadyExited; } let timeout: Duration = timeout.into(); trace!("Waiting up to {} seconds before sending KILL to process {}", timeout.as_secs(), pid_to_kill); let start_time = Instant::now(); loop { if!is_alive(pid_to_kill) { return ShutdownMethod::GracefulTermination; } if start_time.elapsed() >= timeout { break; } thread::sleep(Duration::from_millis(5)); } trace!("Timeout exceeded; killing process {}", pid_to_kill); match signal(pid_to_kill, Signal::KILL) { Ok(_) => ShutdownMethod::Killed, Err(_) => { // JW TODO: Determine if the error represents a case // where the process was already exited before we // return out and assume so. ShutdownMethod::GracefulTermination } } } }
{ Process { pid } }
identifier_body
utils.rs
use crate::errors::{ParsingError, Result}; /// Try to parse the given array of bytes into an f64, by first converting /// it to the corresponding ASCII (or even here, UTF-8) values. pub fn parse_f64(value : &[u8]) -> Result<f64> { let res = std::str::from_utf8(value)?; let res_f64 = res.parse::<f64>()?; Ok(res_f64 as f64) } /// Try to parse the given array of bytes into an i64, by first converting /// it to the corresponding ASCII (or even here, UTF-8) values. pub fn parse_i64(value : &[u8]) -> Result<i64> { let res = std::str::from_utf8(value)?; let res_u64 = res.parse::<i64>()?; Ok(res_u64) } /// Try to parse the given array of bytes into an u64, by first converting /// it to the corresponding ASCII (or even here, UTF-8) values. pub fn parse_u64(value : &[u8]) -> Result<u64> { let res = std::str::from_utf8(value)?; let res_u64 = res.parse::<u64>()?; Ok(res_u64) } /// Try to parse the given array of bytes into an f64: /// - INFINITY if it represents `"true"` in ASCII /// - -INFINITY if it represents `"false"` in ASCII /// - If it represents an integer in ASCII, returns that integer under an /// f64 form. /// /// Return an error in any other case. pub fn parse_u64_or_bool(value : &[u8]) -> Result<f64> { match value { b"true" => Ok(f64::INFINITY), b"false" => Ok(f64::NEG_INFINITY), val => { let res_u64 = parse_u64(val)?; Ok(res_u64 as f64) } } } /// Try to parse the given array of bytes into a bool: /// - `true` if it represents `"true"` in ASCII /// - `false` if it represents `"false"` in ASCII /// /// Return an error in any other case. pub fn parse_bool(value : &[u8]) -> Result<bool> { match value { b"true" => Ok(true), b"false" => Ok(false), val => { let mut base_str = "Invalid boolean: ".to_owned(); let val = std::str::from_utf8(val)?; base_str.push_str(val); Err(ParsingError(base_str)) } } } // TODO Is something like 5- also valid here? // It seems to be but it's not yet handled here // (We could use e.g. the `INFINITY` float value) pub fn parse_byte_range(value : &[u8]) -> Result<(f64, f64)> { let mut cursor = 0usize; let start; loop { if cursor >= value.len() { let e = ParsingError("Invalid byte-range: end encountered too soon".to_owned()); return Err(e); } if value[cursor] == b'-' { start = parse_u64(&value[0..cursor])?; break; } cursor += 1; } let end = parse_u64(&value[cursor + 1..value.len()])?; Ok((start as f64, end as f64)) } /// Parse ISO 8601 duration format (e.g. P5Y10M43HT22H8M3S) into the /// corresponding seconds in a float format. /// This code could be much simpler if it was RegExp-based but I preferred not /// to, mainly because I didn't want to incur the size cost of importing regex /// code in here pub fn parse_iso_8601_duration(value : &[u8]) -> Result<f64> { if value.is_empty() || value[0]!= b'P' { let err = ParsingError("Unexpected duration. Should start with \"P\"".to_owned()); return Err(err); } let mut base = 1; let mut result = 0.; if value[1]!= b'T' { loop { let (number, i) = read_next_float(value, base)?; if i == value.len() { let e = ParsingError("Invalid ISO 8601 duration: end encountered too soon".to_owned()); return Err(e); } let factor = match value[i] { b'Y' => 365 * 24 * 60 * 60, b'M' => 30 * 24 * 60 * 60, b'D' => 24 * 60 * 60, _ => { let e = ParsingError("Invalid duration: unexpected unit.".to_owned()); return Err(e); } }; result += number * (factor as f64); base = i + 1; if base == value.len() { return Ok(result as f64); } if value[base] == b'T' { break; } } } base += 1; loop { let (number, i) = read_next_float(value, base)?; if i == value.len() { let e = ParsingError("Invalid ISO 8601 duration: end encountered too soon".to_owned()); return Err(e); } let factor = match value[i] { b'H' => 60 * 60, b'M' => 60, b'S' => 1, _ => { let e = ParsingError("Invalid duration: unexpected unit.".to_owned()); return Err(e); } }; result += number * (factor as f64); base = i + 1; if base == value.len() { return Ok(result as f64); } } } /// Parse a floating point number, represented by `value` in ASCII, starting at /// the position `base_offset`. /// The decimal separator can either a be a point ('.') or a colon (','). /// /// If it succeeds, returns both the floating point number as an f64 and the /// offset coming just after that float in `value` (or the length of `value` if /// it ended with a float). fn read_next_float( value : &[u8], base_offset : usize ) -> Result<(f64, usize)> { let mut i = base_offset; while i < value.len() && value[i] >= b'0' && value[i] <= b'9' { i += 1; } if i == value.len() || (value[i]!= b'.' && value[i]!= b',') { // UNSAFE: We already checked that this string represents a valid integer let val_str = unsafe { std::str::from_utf8_unchecked(&value[base_offset..i]) }; let val_u64 = val_str.parse::<u64>()?; return Ok((val_u64 as f64, i)); } i += 1; while i < value.len() && value[i] >= b'0' && value[i] <= b'9' { i += 1; } // UNSAFE: We already checked that this string represents a valid float let val_str = unsafe { std::str::from_utf8_unchecked(&value[base_offset..i]) }; let val_f64 = val_str.parse::<f64>()?; Ok((val_f64, i)) } pub fn u32_to_u8_slice_be(x:u32) -> [u8;4] { let b1 : u8 = ((x >> 24) & 0xff) as u8; let b2 : u8 = ((x >> 16) & 0xff) as u8; let b3 : u8 = ((x >> 8) & 0xff) as u8; let b4 : u8 = (x & 0xff) as u8; return [b1, b2, b3, b4] } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_8601_duration() { assert_eq!(parse_iso_8601_duration(b"P1Y10M43DT22H8M3S").unwrap(), 61250883.); assert_eq!(parse_iso_8601_duration(b"P1Y10M43DT22H8M3S").unwrap(), 61250883.); assert_eq!(parse_iso_8601_duration(b"PT3S").unwrap(), 3.); assert_eq!(parse_iso_8601_duration(b"PT1M3.4S").unwrap(), 63.4); assert!(parse_iso_8601_duration(b"").err().is_some()); assert!(parse_iso_8601_duration(b"3S").err().is_some());
#[test] fn test_parse_byte_range() { assert_eq!(parse_byte_range(b"1-2").unwrap(), (1., 2.)); assert_eq!(parse_byte_range(b"100-200").unwrap(), (100., 200.)); assert!(parse_byte_range(b"").err().is_some()); assert!(parse_byte_range(b"A").err().is_some()); assert!(parse_byte_range(b"15-A").err().is_some()); } }
assert!(parse_iso_8601_duration(b"T3S").err().is_some()); assert!(parse_iso_8601_duration(b"P3S").err().is_some()); }
random_line_split
utils.rs
use crate::errors::{ParsingError, Result}; /// Try to parse the given array of bytes into an f64, by first converting /// it to the corresponding ASCII (or even here, UTF-8) values. pub fn
(value : &[u8]) -> Result<f64> { let res = std::str::from_utf8(value)?; let res_f64 = res.parse::<f64>()?; Ok(res_f64 as f64) } /// Try to parse the given array of bytes into an i64, by first converting /// it to the corresponding ASCII (or even here, UTF-8) values. pub fn parse_i64(value : &[u8]) -> Result<i64> { let res = std::str::from_utf8(value)?; let res_u64 = res.parse::<i64>()?; Ok(res_u64) } /// Try to parse the given array of bytes into an u64, by first converting /// it to the corresponding ASCII (or even here, UTF-8) values. pub fn parse_u64(value : &[u8]) -> Result<u64> { let res = std::str::from_utf8(value)?; let res_u64 = res.parse::<u64>()?; Ok(res_u64) } /// Try to parse the given array of bytes into an f64: /// - INFINITY if it represents `"true"` in ASCII /// - -INFINITY if it represents `"false"` in ASCII /// - If it represents an integer in ASCII, returns that integer under an /// f64 form. /// /// Return an error in any other case. pub fn parse_u64_or_bool(value : &[u8]) -> Result<f64> { match value { b"true" => Ok(f64::INFINITY), b"false" => Ok(f64::NEG_INFINITY), val => { let res_u64 = parse_u64(val)?; Ok(res_u64 as f64) } } } /// Try to parse the given array of bytes into a bool: /// - `true` if it represents `"true"` in ASCII /// - `false` if it represents `"false"` in ASCII /// /// Return an error in any other case. pub fn parse_bool(value : &[u8]) -> Result<bool> { match value { b"true" => Ok(true), b"false" => Ok(false), val => { let mut base_str = "Invalid boolean: ".to_owned(); let val = std::str::from_utf8(val)?; base_str.push_str(val); Err(ParsingError(base_str)) } } } // TODO Is something like 5- also valid here? // It seems to be but it's not yet handled here // (We could use e.g. the `INFINITY` float value) pub fn parse_byte_range(value : &[u8]) -> Result<(f64, f64)> { let mut cursor = 0usize; let start; loop { if cursor >= value.len() { let e = ParsingError("Invalid byte-range: end encountered too soon".to_owned()); return Err(e); } if value[cursor] == b'-' { start = parse_u64(&value[0..cursor])?; break; } cursor += 1; } let end = parse_u64(&value[cursor + 1..value.len()])?; Ok((start as f64, end as f64)) } /// Parse ISO 8601 duration format (e.g. P5Y10M43HT22H8M3S) into the /// corresponding seconds in a float format. /// This code could be much simpler if it was RegExp-based but I preferred not /// to, mainly because I didn't want to incur the size cost of importing regex /// code in here pub fn parse_iso_8601_duration(value : &[u8]) -> Result<f64> { if value.is_empty() || value[0]!= b'P' { let err = ParsingError("Unexpected duration. Should start with \"P\"".to_owned()); return Err(err); } let mut base = 1; let mut result = 0.; if value[1]!= b'T' { loop { let (number, i) = read_next_float(value, base)?; if i == value.len() { let e = ParsingError("Invalid ISO 8601 duration: end encountered too soon".to_owned()); return Err(e); } let factor = match value[i] { b'Y' => 365 * 24 * 60 * 60, b'M' => 30 * 24 * 60 * 60, b'D' => 24 * 60 * 60, _ => { let e = ParsingError("Invalid duration: unexpected unit.".to_owned()); return Err(e); } }; result += number * (factor as f64); base = i + 1; if base == value.len() { return Ok(result as f64); } if value[base] == b'T' { break; } } } base += 1; loop { let (number, i) = read_next_float(value, base)?; if i == value.len() { let e = ParsingError("Invalid ISO 8601 duration: end encountered too soon".to_owned()); return Err(e); } let factor = match value[i] { b'H' => 60 * 60, b'M' => 60, b'S' => 1, _ => { let e = ParsingError("Invalid duration: unexpected unit.".to_owned()); return Err(e); } }; result += number * (factor as f64); base = i + 1; if base == value.len() { return Ok(result as f64); } } } /// Parse a floating point number, represented by `value` in ASCII, starting at /// the position `base_offset`. /// The decimal separator can either a be a point ('.') or a colon (','). /// /// If it succeeds, returns both the floating point number as an f64 and the /// offset coming just after that float in `value` (or the length of `value` if /// it ended with a float). fn read_next_float( value : &[u8], base_offset : usize ) -> Result<(f64, usize)> { let mut i = base_offset; while i < value.len() && value[i] >= b'0' && value[i] <= b'9' { i += 1; } if i == value.len() || (value[i]!= b'.' && value[i]!= b',') { // UNSAFE: We already checked that this string represents a valid integer let val_str = unsafe { std::str::from_utf8_unchecked(&value[base_offset..i]) }; let val_u64 = val_str.parse::<u64>()?; return Ok((val_u64 as f64, i)); } i += 1; while i < value.len() && value[i] >= b'0' && value[i] <= b'9' { i += 1; } // UNSAFE: We already checked that this string represents a valid float let val_str = unsafe { std::str::from_utf8_unchecked(&value[base_offset..i]) }; let val_f64 = val_str.parse::<f64>()?; Ok((val_f64, i)) } pub fn u32_to_u8_slice_be(x:u32) -> [u8;4] { let b1 : u8 = ((x >> 24) & 0xff) as u8; let b2 : u8 = ((x >> 16) & 0xff) as u8; let b3 : u8 = ((x >> 8) & 0xff) as u8; let b4 : u8 = (x & 0xff) as u8; return [b1, b2, b3, b4] } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_8601_duration() { assert_eq!(parse_iso_8601_duration(b"P1Y10M43DT22H8M3S").unwrap(), 61250883.); assert_eq!(parse_iso_8601_duration(b"P1Y10M43DT22H8M3S").unwrap(), 61250883.); assert_eq!(parse_iso_8601_duration(b"PT3S").unwrap(), 3.); assert_eq!(parse_iso_8601_duration(b"PT1M3.4S").unwrap(), 63.4); assert!(parse_iso_8601_duration(b"").err().is_some()); assert!(parse_iso_8601_duration(b"3S").err().is_some()); assert!(parse_iso_8601_duration(b"T3S").err().is_some()); assert!(parse_iso_8601_duration(b"P3S").err().is_some()); } #[test] fn test_parse_byte_range() { assert_eq!(parse_byte_range(b"1-2").unwrap(), (1., 2.)); assert_eq!(parse_byte_range(b"100-200").unwrap(), (100., 200.)); assert!(parse_byte_range(b"").err().is_some()); assert!(parse_byte_range(b"A").err().is_some()); assert!(parse_byte_range(b"15-A").err().is_some()); } }
parse_f64
identifier_name
utils.rs
use crate::errors::{ParsingError, Result}; /// Try to parse the given array of bytes into an f64, by first converting /// it to the corresponding ASCII (or even here, UTF-8) values. pub fn parse_f64(value : &[u8]) -> Result<f64> { let res = std::str::from_utf8(value)?; let res_f64 = res.parse::<f64>()?; Ok(res_f64 as f64) } /// Try to parse the given array of bytes into an i64, by first converting /// it to the corresponding ASCII (or even here, UTF-8) values. pub fn parse_i64(value : &[u8]) -> Result<i64>
/// Try to parse the given array of bytes into an u64, by first converting /// it to the corresponding ASCII (or even here, UTF-8) values. pub fn parse_u64(value : &[u8]) -> Result<u64> { let res = std::str::from_utf8(value)?; let res_u64 = res.parse::<u64>()?; Ok(res_u64) } /// Try to parse the given array of bytes into an f64: /// - INFINITY if it represents `"true"` in ASCII /// - -INFINITY if it represents `"false"` in ASCII /// - If it represents an integer in ASCII, returns that integer under an /// f64 form. /// /// Return an error in any other case. pub fn parse_u64_or_bool(value : &[u8]) -> Result<f64> { match value { b"true" => Ok(f64::INFINITY), b"false" => Ok(f64::NEG_INFINITY), val => { let res_u64 = parse_u64(val)?; Ok(res_u64 as f64) } } } /// Try to parse the given array of bytes into a bool: /// - `true` if it represents `"true"` in ASCII /// - `false` if it represents `"false"` in ASCII /// /// Return an error in any other case. pub fn parse_bool(value : &[u8]) -> Result<bool> { match value { b"true" => Ok(true), b"false" => Ok(false), val => { let mut base_str = "Invalid boolean: ".to_owned(); let val = std::str::from_utf8(val)?; base_str.push_str(val); Err(ParsingError(base_str)) } } } // TODO Is something like 5- also valid here? // It seems to be but it's not yet handled here // (We could use e.g. the `INFINITY` float value) pub fn parse_byte_range(value : &[u8]) -> Result<(f64, f64)> { let mut cursor = 0usize; let start; loop { if cursor >= value.len() { let e = ParsingError("Invalid byte-range: end encountered too soon".to_owned()); return Err(e); } if value[cursor] == b'-' { start = parse_u64(&value[0..cursor])?; break; } cursor += 1; } let end = parse_u64(&value[cursor + 1..value.len()])?; Ok((start as f64, end as f64)) } /// Parse ISO 8601 duration format (e.g. P5Y10M43HT22H8M3S) into the /// corresponding seconds in a float format. /// This code could be much simpler if it was RegExp-based but I preferred not /// to, mainly because I didn't want to incur the size cost of importing regex /// code in here pub fn parse_iso_8601_duration(value : &[u8]) -> Result<f64> { if value.is_empty() || value[0]!= b'P' { let err = ParsingError("Unexpected duration. Should start with \"P\"".to_owned()); return Err(err); } let mut base = 1; let mut result = 0.; if value[1]!= b'T' { loop { let (number, i) = read_next_float(value, base)?; if i == value.len() { let e = ParsingError("Invalid ISO 8601 duration: end encountered too soon".to_owned()); return Err(e); } let factor = match value[i] { b'Y' => 365 * 24 * 60 * 60, b'M' => 30 * 24 * 60 * 60, b'D' => 24 * 60 * 60, _ => { let e = ParsingError("Invalid duration: unexpected unit.".to_owned()); return Err(e); } }; result += number * (factor as f64); base = i + 1; if base == value.len() { return Ok(result as f64); } if value[base] == b'T' { break; } } } base += 1; loop { let (number, i) = read_next_float(value, base)?; if i == value.len() { let e = ParsingError("Invalid ISO 8601 duration: end encountered too soon".to_owned()); return Err(e); } let factor = match value[i] { b'H' => 60 * 60, b'M' => 60, b'S' => 1, _ => { let e = ParsingError("Invalid duration: unexpected unit.".to_owned()); return Err(e); } }; result += number * (factor as f64); base = i + 1; if base == value.len() { return Ok(result as f64); } } } /// Parse a floating point number, represented by `value` in ASCII, starting at /// the position `base_offset`. /// The decimal separator can either a be a point ('.') or a colon (','). /// /// If it succeeds, returns both the floating point number as an f64 and the /// offset coming just after that float in `value` (or the length of `value` if /// it ended with a float). fn read_next_float( value : &[u8], base_offset : usize ) -> Result<(f64, usize)> { let mut i = base_offset; while i < value.len() && value[i] >= b'0' && value[i] <= b'9' { i += 1; } if i == value.len() || (value[i]!= b'.' && value[i]!= b',') { // UNSAFE: We already checked that this string represents a valid integer let val_str = unsafe { std::str::from_utf8_unchecked(&value[base_offset..i]) }; let val_u64 = val_str.parse::<u64>()?; return Ok((val_u64 as f64, i)); } i += 1; while i < value.len() && value[i] >= b'0' && value[i] <= b'9' { i += 1; } // UNSAFE: We already checked that this string represents a valid float let val_str = unsafe { std::str::from_utf8_unchecked(&value[base_offset..i]) }; let val_f64 = val_str.parse::<f64>()?; Ok((val_f64, i)) } pub fn u32_to_u8_slice_be(x:u32) -> [u8;4] { let b1 : u8 = ((x >> 24) & 0xff) as u8; let b2 : u8 = ((x >> 16) & 0xff) as u8; let b3 : u8 = ((x >> 8) & 0xff) as u8; let b4 : u8 = (x & 0xff) as u8; return [b1, b2, b3, b4] } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_8601_duration() { assert_eq!(parse_iso_8601_duration(b"P1Y10M43DT22H8M3S").unwrap(), 61250883.); assert_eq!(parse_iso_8601_duration(b"P1Y10M43DT22H8M3S").unwrap(), 61250883.); assert_eq!(parse_iso_8601_duration(b"PT3S").unwrap(), 3.); assert_eq!(parse_iso_8601_duration(b"PT1M3.4S").unwrap(), 63.4); assert!(parse_iso_8601_duration(b"").err().is_some()); assert!(parse_iso_8601_duration(b"3S").err().is_some()); assert!(parse_iso_8601_duration(b"T3S").err().is_some()); assert!(parse_iso_8601_duration(b"P3S").err().is_some()); } #[test] fn test_parse_byte_range() { assert_eq!(parse_byte_range(b"1-2").unwrap(), (1., 2.)); assert_eq!(parse_byte_range(b"100-200").unwrap(), (100., 200.)); assert!(parse_byte_range(b"").err().is_some()); assert!(parse_byte_range(b"A").err().is_some()); assert!(parse_byte_range(b"15-A").err().is_some()); } }
{ let res = std::str::from_utf8(value)?; let res_u64 = res.parse::<i64>()?; Ok(res_u64) }
identifier_body
regions-glb-free-free.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. mod argparse { extern mod std; pub struct Flag<'self> { name: &'self str, desc: &'self str, max_count: uint, value: uint } pub fn
<'r>(name: &'r str, desc: &'r str) -> Flag<'r> { Flag { name: name, desc: desc, max_count: 1, value: 0 } } pub impl<'self> Flag<'self> { fn set_desc(self, s: &str) -> Flag<'self> { Flag { //~ ERROR cannot infer an appropriate lifetime name: self.name, desc: s, max_count: self.max_count, value: self.value } } } } fn main () { let f : argparse::Flag = argparse::flag(~"flag", ~"My flag"); let updated_flag = f.set_desc(~"My new flag"); assert!(updated_flag.desc == "My new flag"); }
flag
identifier_name
regions-glb-free-free.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. mod argparse { extern mod std; pub struct Flag<'self> { name: &'self str, desc: &'self str, max_count: uint, value: uint } pub fn flag<'r>(name: &'r str, desc: &'r str) -> Flag<'r> { Flag { name: name, desc: desc, max_count: 1, value: 0 } } pub impl<'self> Flag<'self> { fn set_desc(self, s: &str) -> Flag<'self> { Flag { //~ ERROR cannot infer an appropriate lifetime name: self.name, desc: s, max_count: self.max_count, value: self.value } } } } fn main ()
{ let f : argparse::Flag = argparse::flag(~"flag", ~"My flag"); let updated_flag = f.set_desc(~"My new flag"); assert!(updated_flag.desc == "My new flag"); }
identifier_body
regions-glb-free-free.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. mod argparse { extern mod std; pub struct Flag<'self> { name: &'self str, desc: &'self str, max_count: uint, value: uint
Flag { name: name, desc: desc, max_count: 1, value: 0 } } pub impl<'self> Flag<'self> { fn set_desc(self, s: &str) -> Flag<'self> { Flag { //~ ERROR cannot infer an appropriate lifetime name: self.name, desc: s, max_count: self.max_count, value: self.value } } } } fn main () { let f : argparse::Flag = argparse::flag(~"flag", ~"My flag"); let updated_flag = f.set_desc(~"My new flag"); assert!(updated_flag.desc == "My new flag"); }
} pub fn flag<'r>(name: &'r str, desc: &'r str) -> Flag<'r> {
random_line_split
lib.rs
// Copyright 2016 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Storage of core types using RocksDB. #![deny(non_upper_case_globals)] #![deny(non_camel_case_types)] #![deny(non_snake_case)] #![deny(unused_mut)] #![warn(missing_docs)] extern crate byteorder; extern crate grin_core as core; extern crate rocksdb; const SEP: u8 = ':' as u8; use std::fmt; use std::iter::Iterator; use std::marker::PhantomData; use std::sync::RwLock; use byteorder::{WriteBytesExt, BigEndian}; use rocksdb::{DB, WriteBatch, DBCompactionStyle, DBIterator, IteratorMode, Direction}; use core::ser; /// Main error type for this crate. #[derive(Debug)] pub enum Error { /// Couldn't find what we were looking for NotFoundErr, /// Wraps an error originating from RocksDB (which unfortunately returns /// string errors). RocksDbErr(String), /// Wraps a serialization error for Writeable or Readable SerErr(ser::Error), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Error::NotFoundErr => write!(f, "Not Found"), &Error::RocksDbErr(ref s) => write!(f, "RocksDb Error: {}", s), &Error::SerErr(ref e) => write!(f, "Serialization Error: {}", e.to_string()), } } } impl From<rocksdb::Error> for Error { fn from(e: rocksdb::Error) -> Error { Error::RocksDbErr(e.to_string()) } } /// Thread-safe rocksdb wrapper pub struct Store { rdb: RwLock<DB>, } unsafe impl Sync for Store {} unsafe impl Send for Store {} impl Store { /// Opens a new RocksDB at the specified location. pub fn open(path: &str) -> Result<Store, Error> { let mut opts = rocksdb::Options::default(); opts.create_if_missing(true); opts.set_compaction_style(DBCompactionStyle::Universal); opts.set_max_open_files(256); opts.set_use_fsync(false); let db = try!(DB::open(&opts, &path)); Ok(Store { rdb: RwLock::new(db) }) } /// Writes a single key/value pair to the db pub fn put(&self, key: &[u8], value: Vec<u8>) -> Result<(), Error> { let db = self.rdb.write().unwrap(); db.put(key, &value[..]).map_err(&From::from) } /// Writes a single key and its `Writeable` value to the db. Encapsulates /// serialization. pub fn put_ser<W: ser::Writeable>(&self, key: &[u8], value: &W) -> Result<(), Error> { let ser_value = ser::ser_vec(value); match ser_value { Ok(data) => self.put(key, data), Err(err) => Err(Error::SerErr(err)), } } /// Gets a value from the db, provided its key pub fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Error> { let db = self.rdb.read().unwrap(); db.get(key).map(|r| r.map(|o| o.to_vec())).map_err(From::from) } /// Gets a `Readable` value from the db, provided its key. Encapsulates /// serialization. pub fn get_ser<T: ser::Readable>(&self, key: &[u8]) -> Result<Option<T>, Error> { self.get_ser_limited(key, 0) } /// Gets a `Readable` value from the db, provided its key, allowing to /// extract only partial data. The underlying Readable size must align /// accordingly. Encapsulates serialization. pub fn get_ser_limited<T: ser::Readable>(&self, key: &[u8], len: usize) -> Result<Option<T>, Error> { let data = try!(self.get(key)); match data { Some(val) => { let mut lval = if len > 0 { &val[..len] } else { &val[..] }; let r = try!(ser::deserialize(&mut lval).map_err(Error::SerErr)); Ok(Some(r)) } None => Ok(None), } } /// Whether the provided key exists pub fn exists(&self, key: &[u8]) -> Result<bool, Error> { let db = self.rdb.read().unwrap(); db.get(key).map(|r| r.is_some()).map_err(From::from) } /// Deletes a key/value pair from the db pub fn delete(&self, key: &[u8]) -> Result<(), Error> { let db = self.rdb.write().unwrap(); db.delete(key).map_err(From::from) } /// Produces an iterator of `Readable` types moving forward from the /// provided /// key. pub fn iter<T: ser::Readable>(&self, from: &[u8]) -> SerIterator<T> { let db = self.rdb.read().unwrap(); SerIterator { iter: db.iterator(IteratorMode::From(from, Direction::Forward)), _marker: PhantomData, } } /// Builds a new batch to be used with this store. pub fn batch(&self) -> Batch { Batch { store: self, batch: WriteBatch::default(), } } fn write(&self, batch: WriteBatch) -> Result<(), Error> { let db = self.rdb.write().unwrap(); db.write(batch).map_err(From::from) } } /// Batch to write multiple Writeables to RocksDb in an atomic manner. pub struct Batch<'a> { store: &'a Store, batch: WriteBatch, } impl<'a> Batch<'a> { /// Writes a single key and its `Writeable` value to the batch. The write /// function must be called to "commit" the batch to storage. pub fn put_ser<W: ser::Writeable>(mut self, key: &[u8], value: &W) -> Result<Batch<'a>, Error> { let ser_value = ser::ser_vec(value); match ser_value { Ok(data) => { self.batch.put(key, &data[..])?; Ok(self) } Err(err) => Err(Error::SerErr(err)), } } /// Delete a single key from the batch. The write function /// must be called to "commit" the batch to storage. pub fn delete(mut self, key: &[u8]) -> Result<Batch<'a>, Error> { self.batch.delete(key)?; Ok(self) } /// Writes the batch to RocksDb. pub fn write(self) -> Result<(), Error> { self.store.write(self.batch) } } /// An iterator thad produces Readable instances back. Wraps the lower level /// DBIterator and deserializes the returned values. pub struct SerIterator<T> where T: ser::Readable { iter: DBIterator, _marker: PhantomData<T>, } impl<T> Iterator for SerIterator<T> where T: ser::Readable { type Item = T; fn next(&mut self) -> Option<T> { let next = self.iter.next(); next.and_then(|r| { let (_, v) = r; ser::deserialize(&mut &v[..]).ok() }) } } /// Build a db key from a prefix and a byte vector identifier. pub fn to_key(prefix: u8, k: &mut Vec<u8>) -> Vec<u8> { let mut res = Vec::with_capacity(k.len() + 2); res.push(prefix); res.push(SEP); res.append(k); res } /// Build a db key from a prefix and a numeric identifier. pub fn u64_to_key<'a>(prefix: u8, val: u64) -> Vec<u8> { let mut u64_vec = vec![]; u64_vec.write_u64::<BigEndian>(val).unwrap(); u64_vec.insert(0, SEP); u64_vec.insert(0, prefix); u64_vec } /// unwraps the inner option by converting the none case to a not found error pub fn option_to_not_found<T>(res: Result<Option<T>, Error>) -> Result<T, Error>
{ match res { Ok(None) => Err(Error::NotFoundErr), Ok(Some(o)) => Ok(o), Err(e) => Err(e), } }
identifier_body
lib.rs
// Copyright 2016 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Storage of core types using RocksDB. #![deny(non_upper_case_globals)] #![deny(non_camel_case_types)] #![deny(non_snake_case)] #![deny(unused_mut)] #![warn(missing_docs)] extern crate byteorder; extern crate grin_core as core; extern crate rocksdb; const SEP: u8 = ':' as u8; use std::fmt; use std::iter::Iterator; use std::marker::PhantomData; use std::sync::RwLock; use byteorder::{WriteBytesExt, BigEndian}; use rocksdb::{DB, WriteBatch, DBCompactionStyle, DBIterator, IteratorMode, Direction}; use core::ser; /// Main error type for this crate. #[derive(Debug)] pub enum Error { /// Couldn't find what we were looking for NotFoundErr, /// Wraps an error originating from RocksDB (which unfortunately returns /// string errors). RocksDbErr(String), /// Wraps a serialization error for Writeable or Readable SerErr(ser::Error), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Error::NotFoundErr => write!(f, "Not Found"), &Error::RocksDbErr(ref s) => write!(f, "RocksDb Error: {}", s), &Error::SerErr(ref e) => write!(f, "Serialization Error: {}", e.to_string()), } } } impl From<rocksdb::Error> for Error { fn from(e: rocksdb::Error) -> Error { Error::RocksDbErr(e.to_string()) } } /// Thread-safe rocksdb wrapper pub struct Store { rdb: RwLock<DB>, } unsafe impl Sync for Store {} unsafe impl Send for Store {} impl Store { /// Opens a new RocksDB at the specified location. pub fn open(path: &str) -> Result<Store, Error> { let mut opts = rocksdb::Options::default(); opts.create_if_missing(true); opts.set_compaction_style(DBCompactionStyle::Universal); opts.set_max_open_files(256); opts.set_use_fsync(false); let db = try!(DB::open(&opts, &path)); Ok(Store { rdb: RwLock::new(db) }) } /// Writes a single key/value pair to the db pub fn put(&self, key: &[u8], value: Vec<u8>) -> Result<(), Error> { let db = self.rdb.write().unwrap(); db.put(key, &value[..]).map_err(&From::from) } /// Writes a single key and its `Writeable` value to the db. Encapsulates /// serialization. pub fn put_ser<W: ser::Writeable>(&self, key: &[u8], value: &W) -> Result<(), Error> { let ser_value = ser::ser_vec(value); match ser_value { Ok(data) => self.put(key, data), Err(err) => Err(Error::SerErr(err)), } } /// Gets a value from the db, provided its key pub fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Error> { let db = self.rdb.read().unwrap(); db.get(key).map(|r| r.map(|o| o.to_vec())).map_err(From::from) } /// Gets a `Readable` value from the db, provided its key. Encapsulates /// serialization. pub fn get_ser<T: ser::Readable>(&self, key: &[u8]) -> Result<Option<T>, Error> { self.get_ser_limited(key, 0) } /// Gets a `Readable` value from the db, provided its key, allowing to /// extract only partial data. The underlying Readable size must align /// accordingly. Encapsulates serialization. pub fn get_ser_limited<T: ser::Readable>(&self, key: &[u8], len: usize) -> Result<Option<T>, Error> { let data = try!(self.get(key)); match data { Some(val) => { let mut lval = if len > 0 { &val[..len] } else { &val[..] }; let r = try!(ser::deserialize(&mut lval).map_err(Error::SerErr)); Ok(Some(r)) } None => Ok(None), } } /// Whether the provided key exists pub fn exists(&self, key: &[u8]) -> Result<bool, Error> { let db = self.rdb.read().unwrap(); db.get(key).map(|r| r.is_some()).map_err(From::from) } /// Deletes a key/value pair from the db pub fn delete(&self, key: &[u8]) -> Result<(), Error> { let db = self.rdb.write().unwrap(); db.delete(key).map_err(From::from) } /// Produces an iterator of `Readable` types moving forward from the /// provided /// key. pub fn iter<T: ser::Readable>(&self, from: &[u8]) -> SerIterator<T> { let db = self.rdb.read().unwrap(); SerIterator { iter: db.iterator(IteratorMode::From(from, Direction::Forward)), _marker: PhantomData, } } /// Builds a new batch to be used with this store. pub fn batch(&self) -> Batch { Batch { store: self, batch: WriteBatch::default(), } } fn write(&self, batch: WriteBatch) -> Result<(), Error> { let db = self.rdb.write().unwrap(); db.write(batch).map_err(From::from) } } /// Batch to write multiple Writeables to RocksDb in an atomic manner. pub struct
<'a> { store: &'a Store, batch: WriteBatch, } impl<'a> Batch<'a> { /// Writes a single key and its `Writeable` value to the batch. The write /// function must be called to "commit" the batch to storage. pub fn put_ser<W: ser::Writeable>(mut self, key: &[u8], value: &W) -> Result<Batch<'a>, Error> { let ser_value = ser::ser_vec(value); match ser_value { Ok(data) => { self.batch.put(key, &data[..])?; Ok(self) } Err(err) => Err(Error::SerErr(err)), } } /// Delete a single key from the batch. The write function /// must be called to "commit" the batch to storage. pub fn delete(mut self, key: &[u8]) -> Result<Batch<'a>, Error> { self.batch.delete(key)?; Ok(self) } /// Writes the batch to RocksDb. pub fn write(self) -> Result<(), Error> { self.store.write(self.batch) } } /// An iterator thad produces Readable instances back. Wraps the lower level /// DBIterator and deserializes the returned values. pub struct SerIterator<T> where T: ser::Readable { iter: DBIterator, _marker: PhantomData<T>, } impl<T> Iterator for SerIterator<T> where T: ser::Readable { type Item = T; fn next(&mut self) -> Option<T> { let next = self.iter.next(); next.and_then(|r| { let (_, v) = r; ser::deserialize(&mut &v[..]).ok() }) } } /// Build a db key from a prefix and a byte vector identifier. pub fn to_key(prefix: u8, k: &mut Vec<u8>) -> Vec<u8> { let mut res = Vec::with_capacity(k.len() + 2); res.push(prefix); res.push(SEP); res.append(k); res } /// Build a db key from a prefix and a numeric identifier. pub fn u64_to_key<'a>(prefix: u8, val: u64) -> Vec<u8> { let mut u64_vec = vec![]; u64_vec.write_u64::<BigEndian>(val).unwrap(); u64_vec.insert(0, SEP); u64_vec.insert(0, prefix); u64_vec } /// unwraps the inner option by converting the none case to a not found error pub fn option_to_not_found<T>(res: Result<Option<T>, Error>) -> Result<T, Error> { match res { Ok(None) => Err(Error::NotFoundErr), Ok(Some(o)) => Ok(o), Err(e) => Err(e), } }
Batch
identifier_name
lib.rs
// Copyright 2016 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS,
// limitations under the License. //! Storage of core types using RocksDB. #![deny(non_upper_case_globals)] #![deny(non_camel_case_types)] #![deny(non_snake_case)] #![deny(unused_mut)] #![warn(missing_docs)] extern crate byteorder; extern crate grin_core as core; extern crate rocksdb; const SEP: u8 = ':' as u8; use std::fmt; use std::iter::Iterator; use std::marker::PhantomData; use std::sync::RwLock; use byteorder::{WriteBytesExt, BigEndian}; use rocksdb::{DB, WriteBatch, DBCompactionStyle, DBIterator, IteratorMode, Direction}; use core::ser; /// Main error type for this crate. #[derive(Debug)] pub enum Error { /// Couldn't find what we were looking for NotFoundErr, /// Wraps an error originating from RocksDB (which unfortunately returns /// string errors). RocksDbErr(String), /// Wraps a serialization error for Writeable or Readable SerErr(ser::Error), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Error::NotFoundErr => write!(f, "Not Found"), &Error::RocksDbErr(ref s) => write!(f, "RocksDb Error: {}", s), &Error::SerErr(ref e) => write!(f, "Serialization Error: {}", e.to_string()), } } } impl From<rocksdb::Error> for Error { fn from(e: rocksdb::Error) -> Error { Error::RocksDbErr(e.to_string()) } } /// Thread-safe rocksdb wrapper pub struct Store { rdb: RwLock<DB>, } unsafe impl Sync for Store {} unsafe impl Send for Store {} impl Store { /// Opens a new RocksDB at the specified location. pub fn open(path: &str) -> Result<Store, Error> { let mut opts = rocksdb::Options::default(); opts.create_if_missing(true); opts.set_compaction_style(DBCompactionStyle::Universal); opts.set_max_open_files(256); opts.set_use_fsync(false); let db = try!(DB::open(&opts, &path)); Ok(Store { rdb: RwLock::new(db) }) } /// Writes a single key/value pair to the db pub fn put(&self, key: &[u8], value: Vec<u8>) -> Result<(), Error> { let db = self.rdb.write().unwrap(); db.put(key, &value[..]).map_err(&From::from) } /// Writes a single key and its `Writeable` value to the db. Encapsulates /// serialization. pub fn put_ser<W: ser::Writeable>(&self, key: &[u8], value: &W) -> Result<(), Error> { let ser_value = ser::ser_vec(value); match ser_value { Ok(data) => self.put(key, data), Err(err) => Err(Error::SerErr(err)), } } /// Gets a value from the db, provided its key pub fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Error> { let db = self.rdb.read().unwrap(); db.get(key).map(|r| r.map(|o| o.to_vec())).map_err(From::from) } /// Gets a `Readable` value from the db, provided its key. Encapsulates /// serialization. pub fn get_ser<T: ser::Readable>(&self, key: &[u8]) -> Result<Option<T>, Error> { self.get_ser_limited(key, 0) } /// Gets a `Readable` value from the db, provided its key, allowing to /// extract only partial data. The underlying Readable size must align /// accordingly. Encapsulates serialization. pub fn get_ser_limited<T: ser::Readable>(&self, key: &[u8], len: usize) -> Result<Option<T>, Error> { let data = try!(self.get(key)); match data { Some(val) => { let mut lval = if len > 0 { &val[..len] } else { &val[..] }; let r = try!(ser::deserialize(&mut lval).map_err(Error::SerErr)); Ok(Some(r)) } None => Ok(None), } } /// Whether the provided key exists pub fn exists(&self, key: &[u8]) -> Result<bool, Error> { let db = self.rdb.read().unwrap(); db.get(key).map(|r| r.is_some()).map_err(From::from) } /// Deletes a key/value pair from the db pub fn delete(&self, key: &[u8]) -> Result<(), Error> { let db = self.rdb.write().unwrap(); db.delete(key).map_err(From::from) } /// Produces an iterator of `Readable` types moving forward from the /// provided /// key. pub fn iter<T: ser::Readable>(&self, from: &[u8]) -> SerIterator<T> { let db = self.rdb.read().unwrap(); SerIterator { iter: db.iterator(IteratorMode::From(from, Direction::Forward)), _marker: PhantomData, } } /// Builds a new batch to be used with this store. pub fn batch(&self) -> Batch { Batch { store: self, batch: WriteBatch::default(), } } fn write(&self, batch: WriteBatch) -> Result<(), Error> { let db = self.rdb.write().unwrap(); db.write(batch).map_err(From::from) } } /// Batch to write multiple Writeables to RocksDb in an atomic manner. pub struct Batch<'a> { store: &'a Store, batch: WriteBatch, } impl<'a> Batch<'a> { /// Writes a single key and its `Writeable` value to the batch. The write /// function must be called to "commit" the batch to storage. pub fn put_ser<W: ser::Writeable>(mut self, key: &[u8], value: &W) -> Result<Batch<'a>, Error> { let ser_value = ser::ser_vec(value); match ser_value { Ok(data) => { self.batch.put(key, &data[..])?; Ok(self) } Err(err) => Err(Error::SerErr(err)), } } /// Delete a single key from the batch. The write function /// must be called to "commit" the batch to storage. pub fn delete(mut self, key: &[u8]) -> Result<Batch<'a>, Error> { self.batch.delete(key)?; Ok(self) } /// Writes the batch to RocksDb. pub fn write(self) -> Result<(), Error> { self.store.write(self.batch) } } /// An iterator thad produces Readable instances back. Wraps the lower level /// DBIterator and deserializes the returned values. pub struct SerIterator<T> where T: ser::Readable { iter: DBIterator, _marker: PhantomData<T>, } impl<T> Iterator for SerIterator<T> where T: ser::Readable { type Item = T; fn next(&mut self) -> Option<T> { let next = self.iter.next(); next.and_then(|r| { let (_, v) = r; ser::deserialize(&mut &v[..]).ok() }) } } /// Build a db key from a prefix and a byte vector identifier. pub fn to_key(prefix: u8, k: &mut Vec<u8>) -> Vec<u8> { let mut res = Vec::with_capacity(k.len() + 2); res.push(prefix); res.push(SEP); res.append(k); res } /// Build a db key from a prefix and a numeric identifier. pub fn u64_to_key<'a>(prefix: u8, val: u64) -> Vec<u8> { let mut u64_vec = vec![]; u64_vec.write_u64::<BigEndian>(val).unwrap(); u64_vec.insert(0, SEP); u64_vec.insert(0, prefix); u64_vec } /// unwraps the inner option by converting the none case to a not found error pub fn option_to_not_found<T>(res: Result<Option<T>, Error>) -> Result<T, Error> { match res { Ok(None) => Err(Error::NotFoundErr), Ok(Some(o)) => Ok(o), Err(e) => Err(e), } }
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and
random_line_split
flags.rs
// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2015 Mikhail Zabaluev <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA use gtype::GType; use types::guint; use std::error::Error as ErrorTrait; use std::fmt; pub trait IntrospectedFlags : Sized { fn from_uint(v: guint) -> Result<Self, UnknownFlags>; fn to_uint(&self) -> guint; } pub trait FlagsType : IntrospectedFlags { fn get_type() -> GType; } #[derive(Copy, Clone)] pub struct UnknownFlags { actual: guint, known_mask: guint } impl UnknownFlags { pub fn new(flags: guint, known_mask: guint) -> UnknownFlags { UnknownFlags { actual: flags, known_mask: known_mask } } pub fn actual(&self) -> guint { self.actual } pub fn unknown(&self) -> guint { self.actual &!self.known_mask } pub fn known(&self) -> guint { self.actual & self.known_mask } } pub mod prelude { pub use super::{IntrospectedFlags, FlagsType, UnknownFlags}; pub use gtype::GType; pub use types::guint; } impl ErrorTrait for UnknownFlags { fn description(&self) -> &str { "unknown bit flags encountered" } } impl fmt::Display for UnknownFlags { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "unsupported bit flag value 0b{:b} (unknown flags: 0b{:b})", self.actual(), self.unknown()) } } impl fmt::Debug for UnknownFlags { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "UnknownFlags {{ actual: 0b{:b}, known_mask: 0b{:b} }}", self.actual, self.known_mask) } } pub fn from_uint<F>(v: guint) -> Result<F, UnknownFlags> where F: IntrospectedFlags { IntrospectedFlags::from_uint(v) } pub fn type_of<F>() -> GType where F: FlagsType { <F as FlagsType>::get_type() }
fmt
identifier_name
flags.rs
// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2015 Mikhail Zabaluev <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA use gtype::GType; use types::guint; use std::error::Error as ErrorTrait; use std::fmt; pub trait IntrospectedFlags : Sized { fn from_uint(v: guint) -> Result<Self, UnknownFlags>; fn to_uint(&self) -> guint; } pub trait FlagsType : IntrospectedFlags { fn get_type() -> GType; } #[derive(Copy, Clone)] pub struct UnknownFlags { actual: guint, known_mask: guint } impl UnknownFlags { pub fn new(flags: guint, known_mask: guint) -> UnknownFlags { UnknownFlags { actual: flags, known_mask: known_mask } } pub fn actual(&self) -> guint { self.actual } pub fn unknown(&self) -> guint
pub fn known(&self) -> guint { self.actual & self.known_mask } } pub mod prelude { pub use super::{IntrospectedFlags, FlagsType, UnknownFlags}; pub use gtype::GType; pub use types::guint; } impl ErrorTrait for UnknownFlags { fn description(&self) -> &str { "unknown bit flags encountered" } } impl fmt::Display for UnknownFlags { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "unsupported bit flag value 0b{:b} (unknown flags: 0b{:b})", self.actual(), self.unknown()) } } impl fmt::Debug for UnknownFlags { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "UnknownFlags {{ actual: 0b{:b}, known_mask: 0b{:b} }}", self.actual, self.known_mask) } } pub fn from_uint<F>(v: guint) -> Result<F, UnknownFlags> where F: IntrospectedFlags { IntrospectedFlags::from_uint(v) } pub fn type_of<F>() -> GType where F: FlagsType { <F as FlagsType>::get_type() }
{ self.actual & !self.known_mask }
identifier_body
flags.rs
// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2015 Mikhail Zabaluev <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA use gtype::GType; use types::guint; use std::error::Error as ErrorTrait; use std::fmt; pub trait IntrospectedFlags : Sized { fn from_uint(v: guint) -> Result<Self, UnknownFlags>; fn to_uint(&self) -> guint; } pub trait FlagsType : IntrospectedFlags { fn get_type() -> GType; }
#[derive(Copy, Clone)] pub struct UnknownFlags { actual: guint, known_mask: guint } impl UnknownFlags { pub fn new(flags: guint, known_mask: guint) -> UnknownFlags { UnknownFlags { actual: flags, known_mask: known_mask } } pub fn actual(&self) -> guint { self.actual } pub fn unknown(&self) -> guint { self.actual &!self.known_mask } pub fn known(&self) -> guint { self.actual & self.known_mask } } pub mod prelude { pub use super::{IntrospectedFlags, FlagsType, UnknownFlags}; pub use gtype::GType; pub use types::guint; } impl ErrorTrait for UnknownFlags { fn description(&self) -> &str { "unknown bit flags encountered" } } impl fmt::Display for UnknownFlags { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "unsupported bit flag value 0b{:b} (unknown flags: 0b{:b})", self.actual(), self.unknown()) } } impl fmt::Debug for UnknownFlags { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "UnknownFlags {{ actual: 0b{:b}, known_mask: 0b{:b} }}", self.actual, self.known_mask) } } pub fn from_uint<F>(v: guint) -> Result<F, UnknownFlags> where F: IntrospectedFlags { IntrospectedFlags::from_uint(v) } pub fn type_of<F>() -> GType where F: FlagsType { <F as FlagsType>::get_type() }
random_line_split
issue-85155.rs
// This is a test with a setup similar to issue 85155, which triggers a const eval error: a const // argument value is outside the range expected by the `stdarch` intrinsic. // // It's not the exact code mentioned in that issue because it depends both on `stdarch` intrinsics // only available on x64, and internal implementation details of `stdarch`. But mostly because these // are not important to trigger the diagnostics issue: it's specifically about the lack of context // in the diagnostics of post-monomorphization errors (PMEs) for consts, happening in a dependency. // Therefore, its setup is reproduced with an aux crate, which will similarly trigger a PME // depending on the const argument value, like the `stdarch` intrinsics would. // // aux-build: post_monomorphization_error.rs // build-fail: this is a post-monomorphization error, it passes check runs and requires building // to actually fail. extern crate post_monomorphization_error; fn
() { // This function triggers a PME whenever the const argument does not fit in 1-bit. post_monomorphization_error::stdarch_intrinsic::<2>(); //~^ NOTE the above error was encountered while instantiating }
main
identifier_name
issue-85155.rs
// This is a test with a setup similar to issue 85155, which triggers a const eval error: a const // argument value is outside the range expected by the `stdarch` intrinsic. // // It's not the exact code mentioned in that issue because it depends both on `stdarch` intrinsics // only available on x64, and internal implementation details of `stdarch`. But mostly because these // are not important to trigger the diagnostics issue: it's specifically about the lack of context // in the diagnostics of post-monomorphization errors (PMEs) for consts, happening in a dependency. // Therefore, its setup is reproduced with an aux crate, which will similarly trigger a PME // depending on the const argument value, like the `stdarch` intrinsics would. // // aux-build: post_monomorphization_error.rs // build-fail: this is a post-monomorphization error, it passes check runs and requires building // to actually fail. extern crate post_monomorphization_error; fn main()
{ // This function triggers a PME whenever the const argument does not fit in 1-bit. post_monomorphization_error::stdarch_intrinsic::<2>(); //~^ NOTE the above error was encountered while instantiating }
identifier_body
issue-85155.rs
// This is a test with a setup similar to issue 85155, which triggers a const eval error: a const // argument value is outside the range expected by the `stdarch` intrinsic. // // It's not the exact code mentioned in that issue because it depends both on `stdarch` intrinsics // only available on x64, and internal implementation details of `stdarch`. But mostly because these // are not important to trigger the diagnostics issue: it's specifically about the lack of context // in the diagnostics of post-monomorphization errors (PMEs) for consts, happening in a dependency. // Therefore, its setup is reproduced with an aux crate, which will similarly trigger a PME
extern crate post_monomorphization_error; fn main() { // This function triggers a PME whenever the const argument does not fit in 1-bit. post_monomorphization_error::stdarch_intrinsic::<2>(); //~^ NOTE the above error was encountered while instantiating }
// depending on the const argument value, like the `stdarch` intrinsics would. // // aux-build: post_monomorphization_error.rs // build-fail: this is a post-monomorphization error, it passes check runs and requires building // to actually fail.
random_line_split
atomic_umin_acqrel.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_umin_acqrel; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread; // pub fn atomic_umin_acqrel<T>(dst: *mut T, src: T) -> T; struct A<T> { v: UnsafeCell<T> } unsafe impl Sync for A<T> {} impl<T> A<T> { fn new(v: T) -> A<T>
} type T = isize; macro_rules! atomic_umin_acqrel_test { ($init:expr, $value:expr, $result:expr) => ({ let value: T = $init; let a: A<T> = A::<T>::new(value); let data: Arc<A<T>> = Arc::<A<T>>::new(a); let clone: Arc<A<T>> = data.clone(); thread::spawn(move || { let dst: *mut T = clone.v.get(); let src: T = $value; let old: T = unsafe { atomic_umin_acqrel::<T>(dst, src) }; assert_eq!(old, $init); }); thread::sleep_ms(10); let ptr: *mut T = data.v.get(); assert_eq!(unsafe { *ptr }, $result); }) } #[test] fn atomic_umin_acqrel_test1() { atomic_umin_acqrel_test!(!0, 0, 0 ); } }
{ A { v: UnsafeCell::<T>::new(v) } }
identifier_body
atomic_umin_acqrel.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_umin_acqrel; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread;
// pub fn atomic_umin_acqrel<T>(dst: *mut T, src: T) -> T; struct A<T> { v: UnsafeCell<T> } unsafe impl Sync for A<T> {} impl<T> A<T> { fn new(v: T) -> A<T> { A { v: UnsafeCell::<T>::new(v) } } } type T = isize; macro_rules! atomic_umin_acqrel_test { ($init:expr, $value:expr, $result:expr) => ({ let value: T = $init; let a: A<T> = A::<T>::new(value); let data: Arc<A<T>> = Arc::<A<T>>::new(a); let clone: Arc<A<T>> = data.clone(); thread::spawn(move || { let dst: *mut T = clone.v.get(); let src: T = $value; let old: T = unsafe { atomic_umin_acqrel::<T>(dst, src) }; assert_eq!(old, $init); }); thread::sleep_ms(10); let ptr: *mut T = data.v.get(); assert_eq!(unsafe { *ptr }, $result); }) } #[test] fn atomic_umin_acqrel_test1() { atomic_umin_acqrel_test!(!0, 0, 0 ); } }
random_line_split
atomic_umin_acqrel.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_umin_acqrel; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread; // pub fn atomic_umin_acqrel<T>(dst: *mut T, src: T) -> T; struct
<T> { v: UnsafeCell<T> } unsafe impl Sync for A<T> {} impl<T> A<T> { fn new(v: T) -> A<T> { A { v: UnsafeCell::<T>::new(v) } } } type T = isize; macro_rules! atomic_umin_acqrel_test { ($init:expr, $value:expr, $result:expr) => ({ let value: T = $init; let a: A<T> = A::<T>::new(value); let data: Arc<A<T>> = Arc::<A<T>>::new(a); let clone: Arc<A<T>> = data.clone(); thread::spawn(move || { let dst: *mut T = clone.v.get(); let src: T = $value; let old: T = unsafe { atomic_umin_acqrel::<T>(dst, src) }; assert_eq!(old, $init); }); thread::sleep_ms(10); let ptr: *mut T = data.v.get(); assert_eq!(unsafe { *ptr }, $result); }) } #[test] fn atomic_umin_acqrel_test1() { atomic_umin_acqrel_test!(!0, 0, 0 ); } }
A
identifier_name
characterdata.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/. */ //! DOM bindings for `CharacterData`. use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId}; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, LayoutDom}; use dom::bindings::str::DOMString; use dom::comment::Comment; use dom::document::Document; use dom::element::Element; use dom::node::{ChildrenMutation, Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: DomRefCell<DOMString>, } impl CharacterData { pub fn new_inherited(data: DOMString, document: &Document) -> CharacterData { CharacterData { node: Node::new_inherited(document), data: DomRefCell::new(data), } } pub fn clone_with_data(&self, data: DOMString, document: &Document) -> DomRoot<Node> { match self.upcast::<Node>().type_id() { NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { DomRoot::upcast(Comment::new(data, &document)) } NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { let pi = self.downcast::<ProcessingInstruction>().unwrap(); DomRoot::upcast(ProcessingInstruction::new(pi.Target(), data, &document)) }, NodeTypeId::CharacterData(CharacterDataTypeId::Text) => { DomRoot::upcast(Text::new(data, &document)) }, _ => unreachable!(), } } #[inline] pub fn data(&self) -> Ref<DOMString> { self.data.borrow() } #[inline] pub fn append_data(&self, data: &str) { self.data.borrow_mut().push_str(data); self.content_changed(); } fn content_changed(&self) { let node = self.upcast::<Node>(); node.dirty(NodeDamage::OtherNodeDamage); } } impl CharacterDataMethods for CharacterData { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(&self) -> DOMString { self.data.borrow().clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(&self, data: DOMString) { let old_length = self.Length(); let new_length = data.encode_utf16().count() as u32; *self.data.borrow_mut() = data; self.content_changed(); let node = self.upcast::<Node>(); node.ranges().replace_code_units(node, 0, old_length, new_length); // If this is a Text node, we might need to re-parse (say, if our parent // is a <style> element.) We don't need to if this is a Comment or // ProcessingInstruction. if self.is::<Text>() { if let Some(parent_node) = node.GetParentNode() { let mutation = ChildrenMutation::ChangeText; vtable_for(&parent_node).children_changed(&mutation); } } } // https://dom.spec.whatwg.org/#dom-characterdata-length fn Length(&self) -> u32 { self.data.borrow().encode_utf16().count() as u32 } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let mut substring = String::new(); let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } remaining = s; } // Step 2. Err(()) => return Err(Error::IndexSize), } match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => substring = substring + remaining, // Steps 4. Ok((s, astral, _)) => { substring = substring + s; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } } }; Ok(DOMString::from(substring)) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddatadata fn AppendData(&self, data: DOMString) { // FIXME(ajeffrey): Efficient append on DOMStrings? self.append_data(&*data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdataoffset-data fn InsertData(&self, offset: u32, arg: DOMString) -> ErrorResult {
} // https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, DOMString::new()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(&self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { let mut new_data; { let data = self.data.borrow(); let prefix; let replacement_before; let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((p, astral, r)) => { prefix = p; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" }; remaining = r; } // Step 2. Err(()) => return Err(Error::IndexSize), }; let replacement_after; let suffix; match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => { replacement_after = ""; suffix = ""; } Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" }; suffix = s; } }; // Step 4: Mutation observers. // Step 5 to 7. new_data = String::with_capacity( prefix.len() + replacement_before.len() + arg.len() + replacement_after.len() + suffix.len()); new_data.push_str(prefix); new_data.push_str(replacement_before); new_data.push_str(&arg); new_data.push_str(replacement_after); new_data.push_str(suffix); } *self.data.borrow_mut() = DOMString::from(new_data); self.content_changed(); // Steps 8-11. let node = self.upcast::<Node>(); node.ranges().replace_code_units( node, offset, count, arg.encode_utf16().count() as u32); Ok(()) } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(&self) { let node = self.upcast::<Node>(); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>().preceding_siblings().filter_map(DomRoot::downcast).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>().following_siblings().filter_map(DomRoot::downcast).next() } } #[allow(unsafe_code)] pub trait LayoutCharacterDataHelpers { unsafe fn data_for_layout(&self) -> &str; } #[allow(unsafe_code)] impl LayoutCharacterDataHelpers for LayoutDom<CharacterData> { #[inline] unsafe fn data_for_layout(&self) -> &str { &(*self.unsafe_get()).data.borrow_for_layout() } } /// Split the given string at the given position measured in UTF-16 code units from the start. /// /// * `Err(())` indicates that `offset` if after the end of the string /// * `Ok((before, None, after))` indicates that `offset` is between Unicode code points. /// The two string slices are such that: /// `before == s.to_utf16()[..offset].to_utf8()` and /// `after == s.to_utf16()[offset..].to_utf8()` /// * `Ok((before, Some(ch), after))` indicates that `offset` is "in the middle" /// of a single Unicode code point that would be represented in UTF-16 by a surrogate pair /// of two 16-bit code units. /// `ch` is that code point. /// The two string slices are such that: /// `before == s.to_utf16()[..offset - 1].to_utf8()` and /// `after == s.to_utf16()[offset + 1..].to_utf8()` /// /// # Panics /// /// Note that the third variant is only ever returned when the `-Z replace-surrogates` /// command-line option is specified. /// When it *would* be returned but the option is *not* specified, this function panics. fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option<char>, &str), ()> { let mut code_units = 0; for (i, c) in s.char_indices() { if code_units == offset { let (a, b) = s.split_at(i); return Ok((a, None, b)); } code_units += 1; if c > '\u{FFFF}' { if code_units == offset { if opts::get().replace_surrogates { debug_assert!(c.len_utf8() == 4); return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..])) } panic!("\n\n\ Would split a surrogate pair in CharacterData API.\n\ If you see this in real content, please comment with the URL\n\ on https://github.com/servo/servo/issues/6873\n\ \n"); } code_units += 1; } } if code_units == offset { Ok((s, None, "")) } else { Err(()) } }
self.ReplaceData(offset, 0, arg)
random_line_split
characterdata.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/. */ //! DOM bindings for `CharacterData`. use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId}; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, LayoutDom}; use dom::bindings::str::DOMString; use dom::comment::Comment; use dom::document::Document; use dom::element::Element; use dom::node::{ChildrenMutation, Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: DomRefCell<DOMString>, } impl CharacterData { pub fn new_inherited(data: DOMString, document: &Document) -> CharacterData { CharacterData { node: Node::new_inherited(document), data: DomRefCell::new(data), } } pub fn clone_with_data(&self, data: DOMString, document: &Document) -> DomRoot<Node> { match self.upcast::<Node>().type_id() { NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { DomRoot::upcast(Comment::new(data, &document)) } NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { let pi = self.downcast::<ProcessingInstruction>().unwrap(); DomRoot::upcast(ProcessingInstruction::new(pi.Target(), data, &document)) }, NodeTypeId::CharacterData(CharacterDataTypeId::Text) => { DomRoot::upcast(Text::new(data, &document)) }, _ => unreachable!(), } } #[inline] pub fn data(&self) -> Ref<DOMString> { self.data.borrow() } #[inline] pub fn append_data(&self, data: &str) { self.data.borrow_mut().push_str(data); self.content_changed(); } fn content_changed(&self) { let node = self.upcast::<Node>(); node.dirty(NodeDamage::OtherNodeDamage); } } impl CharacterDataMethods for CharacterData { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(&self) -> DOMString { self.data.borrow().clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(&self, data: DOMString) { let old_length = self.Length(); let new_length = data.encode_utf16().count() as u32; *self.data.borrow_mut() = data; self.content_changed(); let node = self.upcast::<Node>(); node.ranges().replace_code_units(node, 0, old_length, new_length); // If this is a Text node, we might need to re-parse (say, if our parent // is a <style> element.) We don't need to if this is a Comment or // ProcessingInstruction. if self.is::<Text>() { if let Some(parent_node) = node.GetParentNode() { let mutation = ChildrenMutation::ChangeText; vtable_for(&parent_node).children_changed(&mutation); } } } // https://dom.spec.whatwg.org/#dom-characterdata-length fn
(&self) -> u32 { self.data.borrow().encode_utf16().count() as u32 } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let mut substring = String::new(); let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } remaining = s; } // Step 2. Err(()) => return Err(Error::IndexSize), } match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => substring = substring + remaining, // Steps 4. Ok((s, astral, _)) => { substring = substring + s; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } } }; Ok(DOMString::from(substring)) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddatadata fn AppendData(&self, data: DOMString) { // FIXME(ajeffrey): Efficient append on DOMStrings? self.append_data(&*data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdataoffset-data fn InsertData(&self, offset: u32, arg: DOMString) -> ErrorResult { self.ReplaceData(offset, 0, arg) } // https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, DOMString::new()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(&self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { let mut new_data; { let data = self.data.borrow(); let prefix; let replacement_before; let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((p, astral, r)) => { prefix = p; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" }; remaining = r; } // Step 2. Err(()) => return Err(Error::IndexSize), }; let replacement_after; let suffix; match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => { replacement_after = ""; suffix = ""; } Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" }; suffix = s; } }; // Step 4: Mutation observers. // Step 5 to 7. new_data = String::with_capacity( prefix.len() + replacement_before.len() + arg.len() + replacement_after.len() + suffix.len()); new_data.push_str(prefix); new_data.push_str(replacement_before); new_data.push_str(&arg); new_data.push_str(replacement_after); new_data.push_str(suffix); } *self.data.borrow_mut() = DOMString::from(new_data); self.content_changed(); // Steps 8-11. let node = self.upcast::<Node>(); node.ranges().replace_code_units( node, offset, count, arg.encode_utf16().count() as u32); Ok(()) } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(&self) { let node = self.upcast::<Node>(); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>().preceding_siblings().filter_map(DomRoot::downcast).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>().following_siblings().filter_map(DomRoot::downcast).next() } } #[allow(unsafe_code)] pub trait LayoutCharacterDataHelpers { unsafe fn data_for_layout(&self) -> &str; } #[allow(unsafe_code)] impl LayoutCharacterDataHelpers for LayoutDom<CharacterData> { #[inline] unsafe fn data_for_layout(&self) -> &str { &(*self.unsafe_get()).data.borrow_for_layout() } } /// Split the given string at the given position measured in UTF-16 code units from the start. /// /// * `Err(())` indicates that `offset` if after the end of the string /// * `Ok((before, None, after))` indicates that `offset` is between Unicode code points. /// The two string slices are such that: /// `before == s.to_utf16()[..offset].to_utf8()` and /// `after == s.to_utf16()[offset..].to_utf8()` /// * `Ok((before, Some(ch), after))` indicates that `offset` is "in the middle" /// of a single Unicode code point that would be represented in UTF-16 by a surrogate pair /// of two 16-bit code units. /// `ch` is that code point. /// The two string slices are such that: /// `before == s.to_utf16()[..offset - 1].to_utf8()` and /// `after == s.to_utf16()[offset + 1..].to_utf8()` /// /// # Panics /// /// Note that the third variant is only ever returned when the `-Z replace-surrogates` /// command-line option is specified. /// When it *would* be returned but the option is *not* specified, this function panics. fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option<char>, &str), ()> { let mut code_units = 0; for (i, c) in s.char_indices() { if code_units == offset { let (a, b) = s.split_at(i); return Ok((a, None, b)); } code_units += 1; if c > '\u{FFFF}' { if code_units == offset { if opts::get().replace_surrogates { debug_assert!(c.len_utf8() == 4); return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..])) } panic!("\n\n\ Would split a surrogate pair in CharacterData API.\n\ If you see this in real content, please comment with the URL\n\ on https://github.com/servo/servo/issues/6873\n\ \n"); } code_units += 1; } } if code_units == offset { Ok((s, None, "")) } else { Err(()) } }
Length
identifier_name
characterdata.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/. */ //! DOM bindings for `CharacterData`. use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId}; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, LayoutDom}; use dom::bindings::str::DOMString; use dom::comment::Comment; use dom::document::Document; use dom::element::Element; use dom::node::{ChildrenMutation, Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: DomRefCell<DOMString>, } impl CharacterData { pub fn new_inherited(data: DOMString, document: &Document) -> CharacterData { CharacterData { node: Node::new_inherited(document), data: DomRefCell::new(data), } } pub fn clone_with_data(&self, data: DOMString, document: &Document) -> DomRoot<Node> { match self.upcast::<Node>().type_id() { NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { DomRoot::upcast(Comment::new(data, &document)) } NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { let pi = self.downcast::<ProcessingInstruction>().unwrap(); DomRoot::upcast(ProcessingInstruction::new(pi.Target(), data, &document)) }, NodeTypeId::CharacterData(CharacterDataTypeId::Text) => { DomRoot::upcast(Text::new(data, &document)) }, _ => unreachable!(), } } #[inline] pub fn data(&self) -> Ref<DOMString> { self.data.borrow() } #[inline] pub fn append_data(&self, data: &str)
fn content_changed(&self) { let node = self.upcast::<Node>(); node.dirty(NodeDamage::OtherNodeDamage); } } impl CharacterDataMethods for CharacterData { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(&self) -> DOMString { self.data.borrow().clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(&self, data: DOMString) { let old_length = self.Length(); let new_length = data.encode_utf16().count() as u32; *self.data.borrow_mut() = data; self.content_changed(); let node = self.upcast::<Node>(); node.ranges().replace_code_units(node, 0, old_length, new_length); // If this is a Text node, we might need to re-parse (say, if our parent // is a <style> element.) We don't need to if this is a Comment or // ProcessingInstruction. if self.is::<Text>() { if let Some(parent_node) = node.GetParentNode() { let mutation = ChildrenMutation::ChangeText; vtable_for(&parent_node).children_changed(&mutation); } } } // https://dom.spec.whatwg.org/#dom-characterdata-length fn Length(&self) -> u32 { self.data.borrow().encode_utf16().count() as u32 } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let mut substring = String::new(); let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } remaining = s; } // Step 2. Err(()) => return Err(Error::IndexSize), } match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => substring = substring + remaining, // Steps 4. Ok((s, astral, _)) => { substring = substring + s; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } } }; Ok(DOMString::from(substring)) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddatadata fn AppendData(&self, data: DOMString) { // FIXME(ajeffrey): Efficient append on DOMStrings? self.append_data(&*data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdataoffset-data fn InsertData(&self, offset: u32, arg: DOMString) -> ErrorResult { self.ReplaceData(offset, 0, arg) } // https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, DOMString::new()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(&self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { let mut new_data; { let data = self.data.borrow(); let prefix; let replacement_before; let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((p, astral, r)) => { prefix = p; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" }; remaining = r; } // Step 2. Err(()) => return Err(Error::IndexSize), }; let replacement_after; let suffix; match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => { replacement_after = ""; suffix = ""; } Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" }; suffix = s; } }; // Step 4: Mutation observers. // Step 5 to 7. new_data = String::with_capacity( prefix.len() + replacement_before.len() + arg.len() + replacement_after.len() + suffix.len()); new_data.push_str(prefix); new_data.push_str(replacement_before); new_data.push_str(&arg); new_data.push_str(replacement_after); new_data.push_str(suffix); } *self.data.borrow_mut() = DOMString::from(new_data); self.content_changed(); // Steps 8-11. let node = self.upcast::<Node>(); node.ranges().replace_code_units( node, offset, count, arg.encode_utf16().count() as u32); Ok(()) } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(&self) { let node = self.upcast::<Node>(); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>().preceding_siblings().filter_map(DomRoot::downcast).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>().following_siblings().filter_map(DomRoot::downcast).next() } } #[allow(unsafe_code)] pub trait LayoutCharacterDataHelpers { unsafe fn data_for_layout(&self) -> &str; } #[allow(unsafe_code)] impl LayoutCharacterDataHelpers for LayoutDom<CharacterData> { #[inline] unsafe fn data_for_layout(&self) -> &str { &(*self.unsafe_get()).data.borrow_for_layout() } } /// Split the given string at the given position measured in UTF-16 code units from the start. /// /// * `Err(())` indicates that `offset` if after the end of the string /// * `Ok((before, None, after))` indicates that `offset` is between Unicode code points. /// The two string slices are such that: /// `before == s.to_utf16()[..offset].to_utf8()` and /// `after == s.to_utf16()[offset..].to_utf8()` /// * `Ok((before, Some(ch), after))` indicates that `offset` is "in the middle" /// of a single Unicode code point that would be represented in UTF-16 by a surrogate pair /// of two 16-bit code units. /// `ch` is that code point. /// The two string slices are such that: /// `before == s.to_utf16()[..offset - 1].to_utf8()` and /// `after == s.to_utf16()[offset + 1..].to_utf8()` /// /// # Panics /// /// Note that the third variant is only ever returned when the `-Z replace-surrogates` /// command-line option is specified. /// When it *would* be returned but the option is *not* specified, this function panics. fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option<char>, &str), ()> { let mut code_units = 0; for (i, c) in s.char_indices() { if code_units == offset { let (a, b) = s.split_at(i); return Ok((a, None, b)); } code_units += 1; if c > '\u{FFFF}' { if code_units == offset { if opts::get().replace_surrogates { debug_assert!(c.len_utf8() == 4); return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..])) } panic!("\n\n\ Would split a surrogate pair in CharacterData API.\n\ If you see this in real content, please comment with the URL\n\ on https://github.com/servo/servo/issues/6873\n\ \n"); } code_units += 1; } } if code_units == offset { Ok((s, None, "")) } else { Err(()) } }
{ self.data.borrow_mut().push_str(data); self.content_changed(); }
identifier_body
characterdata.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/. */ //! DOM bindings for `CharacterData`. use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId}; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, LayoutDom}; use dom::bindings::str::DOMString; use dom::comment::Comment; use dom::document::Document; use dom::element::Element; use dom::node::{ChildrenMutation, Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: DomRefCell<DOMString>, } impl CharacterData { pub fn new_inherited(data: DOMString, document: &Document) -> CharacterData { CharacterData { node: Node::new_inherited(document), data: DomRefCell::new(data), } } pub fn clone_with_data(&self, data: DOMString, document: &Document) -> DomRoot<Node> { match self.upcast::<Node>().type_id() { NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { DomRoot::upcast(Comment::new(data, &document)) } NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) =>
, NodeTypeId::CharacterData(CharacterDataTypeId::Text) => { DomRoot::upcast(Text::new(data, &document)) }, _ => unreachable!(), } } #[inline] pub fn data(&self) -> Ref<DOMString> { self.data.borrow() } #[inline] pub fn append_data(&self, data: &str) { self.data.borrow_mut().push_str(data); self.content_changed(); } fn content_changed(&self) { let node = self.upcast::<Node>(); node.dirty(NodeDamage::OtherNodeDamage); } } impl CharacterDataMethods for CharacterData { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(&self) -> DOMString { self.data.borrow().clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(&self, data: DOMString) { let old_length = self.Length(); let new_length = data.encode_utf16().count() as u32; *self.data.borrow_mut() = data; self.content_changed(); let node = self.upcast::<Node>(); node.ranges().replace_code_units(node, 0, old_length, new_length); // If this is a Text node, we might need to re-parse (say, if our parent // is a <style> element.) We don't need to if this is a Comment or // ProcessingInstruction. if self.is::<Text>() { if let Some(parent_node) = node.GetParentNode() { let mutation = ChildrenMutation::ChangeText; vtable_for(&parent_node).children_changed(&mutation); } } } // https://dom.spec.whatwg.org/#dom-characterdata-length fn Length(&self) -> u32 { self.data.borrow().encode_utf16().count() as u32 } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let mut substring = String::new(); let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } remaining = s; } // Step 2. Err(()) => return Err(Error::IndexSize), } match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => substring = substring + remaining, // Steps 4. Ok((s, astral, _)) => { substring = substring + s; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } } }; Ok(DOMString::from(substring)) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddatadata fn AppendData(&self, data: DOMString) { // FIXME(ajeffrey): Efficient append on DOMStrings? self.append_data(&*data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdataoffset-data fn InsertData(&self, offset: u32, arg: DOMString) -> ErrorResult { self.ReplaceData(offset, 0, arg) } // https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, DOMString::new()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(&self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { let mut new_data; { let data = self.data.borrow(); let prefix; let replacement_before; let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((p, astral, r)) => { prefix = p; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" }; remaining = r; } // Step 2. Err(()) => return Err(Error::IndexSize), }; let replacement_after; let suffix; match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => { replacement_after = ""; suffix = ""; } Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" }; suffix = s; } }; // Step 4: Mutation observers. // Step 5 to 7. new_data = String::with_capacity( prefix.len() + replacement_before.len() + arg.len() + replacement_after.len() + suffix.len()); new_data.push_str(prefix); new_data.push_str(replacement_before); new_data.push_str(&arg); new_data.push_str(replacement_after); new_data.push_str(suffix); } *self.data.borrow_mut() = DOMString::from(new_data); self.content_changed(); // Steps 8-11. let node = self.upcast::<Node>(); node.ranges().replace_code_units( node, offset, count, arg.encode_utf16().count() as u32); Ok(()) } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(&self) { let node = self.upcast::<Node>(); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>().preceding_siblings().filter_map(DomRoot::downcast).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>().following_siblings().filter_map(DomRoot::downcast).next() } } #[allow(unsafe_code)] pub trait LayoutCharacterDataHelpers { unsafe fn data_for_layout(&self) -> &str; } #[allow(unsafe_code)] impl LayoutCharacterDataHelpers for LayoutDom<CharacterData> { #[inline] unsafe fn data_for_layout(&self) -> &str { &(*self.unsafe_get()).data.borrow_for_layout() } } /// Split the given string at the given position measured in UTF-16 code units from the start. /// /// * `Err(())` indicates that `offset` if after the end of the string /// * `Ok((before, None, after))` indicates that `offset` is between Unicode code points. /// The two string slices are such that: /// `before == s.to_utf16()[..offset].to_utf8()` and /// `after == s.to_utf16()[offset..].to_utf8()` /// * `Ok((before, Some(ch), after))` indicates that `offset` is "in the middle" /// of a single Unicode code point that would be represented in UTF-16 by a surrogate pair /// of two 16-bit code units. /// `ch` is that code point. /// The two string slices are such that: /// `before == s.to_utf16()[..offset - 1].to_utf8()` and /// `after == s.to_utf16()[offset + 1..].to_utf8()` /// /// # Panics /// /// Note that the third variant is only ever returned when the `-Z replace-surrogates` /// command-line option is specified. /// When it *would* be returned but the option is *not* specified, this function panics. fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option<char>, &str), ()> { let mut code_units = 0; for (i, c) in s.char_indices() { if code_units == offset { let (a, b) = s.split_at(i); return Ok((a, None, b)); } code_units += 1; if c > '\u{FFFF}' { if code_units == offset { if opts::get().replace_surrogates { debug_assert!(c.len_utf8() == 4); return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..])) } panic!("\n\n\ Would split a surrogate pair in CharacterData API.\n\ If you see this in real content, please comment with the URL\n\ on https://github.com/servo/servo/issues/6873\n\ \n"); } code_units += 1; } } if code_units == offset { Ok((s, None, "")) } else { Err(()) } }
{ let pi = self.downcast::<ProcessingInstruction>().unwrap(); DomRoot::upcast(ProcessingInstruction::new(pi.Target(), data, &document)) }
conditional_block
las.rs
//! Source las points. use std::io::{Read, Seek}; use std::path::Path; use las; use Result; use point::{Intensity, Point, ScanDirection}; use source::{FileSource, Source}; impl<R: Read + Seek> Source for las::Reader<R> { fn source(&mut self, want: usize) -> Result<Option<Vec<Point>>> { let mut points = Vec::with_capacity(want); for _ in 0..want { match try!(self.read_point()) { Some(point) => points.push(Point::from(point)), None => { if points.is_empty() { return Ok(None); } else { return Ok(Some(points)); } } } } Ok(Some(points)) } fn source_len(&mut self) -> Option<usize> { Some(self.npoints() as usize) } } impl<R: Read + Seek> FileSource for las::Reader<R> { type Config = LasConfig; fn open_file_source<P>(path: P, _: LasConfig) -> Result<Box<Source>> where P: AsRef<Path> { Ok(Box::new(try!(las::Reader::from_path(path)))) } } /// Decodable configuration object. #[derive(Clone, Copy, Debug, Default, RustcDecodable)] pub struct
; impl From<las::Point> for Point { fn from(point: las::Point) -> Point { Point { x: point.x, y: point.y, z: point.z, intensity: Intensity::from_u16(point.intensity), return_number: Some(point.return_number.as_u8() as usize), number_of_returns: Some(point.number_of_returns.as_u8() as usize), gps_time: point.gps_time, scan_direction: match point.scan_direction { las::point::ScanDirection::Forward => ScanDirection::Forward, las::point::ScanDirection::Backward => ScanDirection::Backward, }, edge_of_flight_line: point.edge_of_flight_line, classification: point.classification.as_u8(), synthetic: point.synthetic, key_point: point.key_point, withheld: point.withheld, scan_angle: Some(point.scan_angle_rank as f64), point_source_id: Some(point.point_source_id), user_data: Some(point.user_data), ..Default::default() } } }
LasConfig
identifier_name
las.rs
//! Source las points. use std::io::{Read, Seek}; use std::path::Path; use las; use Result; use point::{Intensity, Point, ScanDirection}; use source::{FileSource, Source}; impl<R: Read + Seek> Source for las::Reader<R> { fn source(&mut self, want: usize) -> Result<Option<Vec<Point>>> { let mut points = Vec::with_capacity(want); for _ in 0..want { match try!(self.read_point()) { Some(point) => points.push(Point::from(point)), None => { if points.is_empty() { return Ok(None); } else { return Ok(Some(points)); } } } } Ok(Some(points)) } fn source_len(&mut self) -> Option<usize> { Some(self.npoints() as usize) } } impl<R: Read + Seek> FileSource for las::Reader<R> { type Config = LasConfig; fn open_file_source<P>(path: P, _: LasConfig) -> Result<Box<Source>> where P: AsRef<Path> { Ok(Box::new(try!(las::Reader::from_path(path)))) } } /// Decodable configuration object. #[derive(Clone, Copy, Debug, Default, RustcDecodable)] pub struct LasConfig; impl From<las::Point> for Point { fn from(point: las::Point) -> Point { Point { x: point.x,
number_of_returns: Some(point.number_of_returns.as_u8() as usize), gps_time: point.gps_time, scan_direction: match point.scan_direction { las::point::ScanDirection::Forward => ScanDirection::Forward, las::point::ScanDirection::Backward => ScanDirection::Backward, }, edge_of_flight_line: point.edge_of_flight_line, classification: point.classification.as_u8(), synthetic: point.synthetic, key_point: point.key_point, withheld: point.withheld, scan_angle: Some(point.scan_angle_rank as f64), point_source_id: Some(point.point_source_id), user_data: Some(point.user_data), ..Default::default() } } }
y: point.y, z: point.z, intensity: Intensity::from_u16(point.intensity), return_number: Some(point.return_number.as_u8() as usize),
random_line_split
f64.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. //! Operations and constants for 64-bits floats (`f64` type) #![doc(primitive = "f64")] // FIXME: MIN_VALUE and MAX_VALUE literals are parsed as -inf and inf #14353 #![allow(overflowing_literals)] #![stable] use intrinsics; use mem; use num::Float; use num::FpCategory as Fp; use option::Option; // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective // members of `Bounded` and `Float`. #[unstable = "pending integer conventions"] pub const RADIX: uint = 2; pub const MANTISSA_DIGITS: uint = 53; #[unstable = "pending integer conventions"] pub const DIGITS: uint = 15; #[stable] pub const EPSILON: f64 = 2.2204460492503131e-16_f64; /// Smallest finite f64 value #[stable] pub const MIN_VALUE: f64 = -1.7976931348623157e+308_f64; /// Smallest positive, normalized f64 value #[stable] pub const MIN_POS_VALUE: f64 = 2.2250738585072014e-308_f64; /// Largest finite f64 value #[stable] pub const MAX_VALUE: f64 = 1.7976931348623157e+308_f64; #[unstable = "pending integer conventions"] pub const MIN_EXP: int = -1021; #[unstable = "pending integer conventions"] pub const MAX_EXP: int = 1024; #[unstable = "pending integer conventions"] pub const MIN_10_EXP: int = -307; #[unstable = "pending integer conventions"] pub const MAX_10_EXP: int = 308; #[stable] pub const NAN: f64 = 0.0_f64/0.0_f64; #[stable] pub const INFINITY: f64 = 1.0_f64/0.0_f64; #[stable] pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64; /// Various useful constants. #[unstable = "naming scheme needs to be revisited"] pub mod consts { // FIXME: replace with mathematical constants from cmath. // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective members // of `Float`. /// Archimedes' constant pub const PI: f64 = 3.14159265358979323846264338327950288_f64; /// pi * 2.0 pub const PI_2: f64 = 6.28318530717958647692528676655900576_f64; /// pi/2.0 pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64; /// pi/3.0 pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64; /// pi/4.0 pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64; /// pi/6.0 pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64; /// pi/8.0 pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64; /// 1.0/pi pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64; /// 2.0/pi pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64; /// 2.0/sqrt(pi) pub const FRAC_2_SQRTPI: f64 = 1.12837916709551257389615890312154517_f64; /// sqrt(2.0) pub const SQRT2: f64 = 1.41421356237309504880168872420969808_f64; /// 1.0/sqrt(2.0) pub const FRAC_1_SQRT2: f64 = 0.707106781186547524400844362104849039_f64; /// Euler's number pub const E: f64 = 2.71828182845904523536028747135266250_f64; /// log2(e) pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64; /// log10(e) pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64; /// ln(2.0) pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64; /// ln(10.0) pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64; } #[unstable = "trait is unstable"] impl Float for f64 { #[inline] fn nan() -> f64 { NAN } #[inline] fn infinity() -> f64 { INFINITY } #[inline] fn neg_infinity() -> f64 { NEG_INFINITY } #[inline] fn zero() -> f64 { 0.0 } #[inline] fn neg_zero() -> f64 { -0.0 } #[inline] fn one() -> f64 { 1.0 } /// Returns `true` if the number is NaN. #[inline] fn is_nan(self) -> bool { self!= self } /// Returns `true` if the number is infinite. #[inline] fn is_infinite(self) -> bool { self == Float::infinity() || self == Float::neg_infinity() } /// Returns `true` if the number is neither infinite or NaN. #[inline] fn is_finite(self) -> bool { !(self.is_nan() || self.is_infinite()) } /// Returns `true` if the number is neither zero, infinite, subnormal or NaN. #[inline] fn is_normal(self) -> bool { self.classify() == Fp::Normal } /// Returns the floating point category of the number. If only one property /// is going to be tested, it is generally faster to use the specific /// predicate instead. fn classify(self) -> Fp { const EXP_MASK: u64 = 0x7ff0000000000000; const MAN_MASK: u64 = 0x000fffffffffffff; let bits: u64 = unsafe { mem::transmute(self) }; match (bits & MAN_MASK, bits & EXP_MASK) { (0, 0) => Fp::Zero, (_, 0) => Fp::Subnormal, (0, EXP_MASK) => Fp::Infinite, (_, EXP_MASK) => Fp::Nan, _ => Fp::Normal, } } #[inline] #[deprecated] fn mantissa_digits(_: Option<f64>) -> uint { MANTISSA_DIGITS } #[inline] #[deprecated] fn digits(_: Option<f64>) -> uint { DIGITS } #[inline] #[deprecated] fn epsilon() -> f64 { EPSILON } #[inline] #[deprecated] fn min_exp(_: Option<f64>) -> int { MIN_EXP } #[inline] #[deprecated] fn max_exp(_: Option<f64>) -> int { MAX_EXP } #[inline] #[deprecated] fn min_10_exp(_: Option<f64>) -> int { MIN_10_EXP } #[inline] #[deprecated] fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP } #[inline] #[deprecated] fn min_value() -> f64 { MIN_VALUE } #[inline] #[deprecated] fn min_pos_value(_: Option<f64>) -> f64 { MIN_POS_VALUE } #[inline] #[deprecated] fn max_value() -> f64 { MAX_VALUE } /// Returns the mantissa, exponent and sign as integers. fn integer_decode(self) -> (u64, i16, i8) { let bits: u64 = unsafe { mem::transmute(self) }; let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 }; let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; let mantissa = if exponent == 0 { (bits & 0xfffffffffffff) << 1 } else { (bits & 0xfffffffffffff) | 0x10000000000000 }; // Exponent bias + mantissa shift exponent -= 1023 + 52; (mantissa, exponent, sign) } /// Rounds towards minus infinity. #[inline] fn floor(self) -> f64 { unsafe { intrinsics::floorf64(self) } } /// Rounds towards plus infinity. #[inline] fn ceil(self) -> f64 { unsafe { intrinsics::ceilf64(self) } } /// Rounds to nearest integer. Rounds half-way cases away from zero. #[inline] fn round(self) -> f64 { unsafe { intrinsics::roundf64(self) } } /// Returns the integer part of the number (rounds towards zero). #[inline] fn trunc(self) -> f64 { unsafe { intrinsics::truncf64(self) } } /// The fractional part of the number, satisfying: /// /// ```rust /// use core::num::Float; /// /// let x = 1.65f64; /// assert!(x == x.trunc() + x.fract()) /// ``` #[inline] fn fract(self) -> f64 { self - self.trunc() } /// Computes the absolute value of `self`. Returns `Float::nan()` if the /// number is `Float::nan()`. #[inline] fn abs(self) -> f64 { unsafe { intrinsics::fabsf64(self) } } /// Returns a number that represents the sign of `self`. /// /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` /// - `Float::nan()` if the number is `Float::nan()` #[inline] fn signum(self) -> f64 { if self.is_nan() { Float::nan() } else { unsafe { intrinsics::copysignf64(1.0, self) } } } /// Returns `true` if `self` is positive, including `+0.0` and /// `Float::infinity()`. #[inline] fn is_positive(self) -> bool { self > 0.0 || (1.0 / self) == Float::infinity() } /// Returns `true` if `self` is negative, including `-0.0` and /// `Float::neg_infinity()`. #[inline] fn is_negative(self) -> bool { self < 0.0 || (1.0 / self) == Float::neg_infinity() } /// Fused multiply-add. Computes `(self * a) + b` with only one rounding /// error. This produces a more accurate result with better performance than /// a separate multiplication operation followed by an add. #[inline] fn mul_add(self, a: f64, b: f64) -> f64 { unsafe { intrinsics::fmaf64(self, a, b) } } /// Returns the reciprocal (multiplicative inverse) of the number. #[inline] fn recip(self) -> f64 { 1.0 / self } #[inline] fn powf(self, n: f64) -> f64 { unsafe { intrinsics::powf64(self, n) } } #[inline] fn powi(self, n: i32) -> f64 { unsafe { intrinsics::powif64(self, n) } } #[inline] fn sqrt(self) -> f64 { if self < 0.0 { NAN } else { unsafe { intrinsics::sqrtf64(self) } } } #[inline] fn rsqrt(self) -> f64 { self.sqrt().recip() } /// Returns the exponential of the number. #[inline] fn exp(self) -> f64 { unsafe { intrinsics::expf64(self) } } /// Returns 2 raised to the power of the number. #[inline] fn exp2(self) -> f64 { unsafe { intrinsics::exp2f64(self) } } /// Returns the natural logarithm of the number. #[inline] fn ln(self) -> f64 { unsafe { intrinsics::logf64(self) } } /// Returns the logarithm of the number with respect to an arbitrary base. #[inline] fn log(self, base: f64) -> f64 { self.ln() / base.ln() } /// Returns the base 2 logarithm of the number. #[inline] fn log2(self) -> f64 { unsafe { intrinsics::log2f64(self) } } /// Returns the base 10 logarithm of the number. #[inline] fn log10(self) -> f64 { unsafe { intrinsics::log10f64(self) } } /// Converts to degrees, assuming the number is in radians. #[inline] fn to_degrees(self) -> f64 { self * (180.0f64 / consts::PI) } /// Converts to radians, assuming the number is in degrees. #[inline] fn to_radians(self) -> f64 {
let value: f64 = consts::PI; self * (value / 180.0) } }
random_line_split
f64.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. //! Operations and constants for 64-bits floats (`f64` type) #![doc(primitive = "f64")] // FIXME: MIN_VALUE and MAX_VALUE literals are parsed as -inf and inf #14353 #![allow(overflowing_literals)] #![stable] use intrinsics; use mem; use num::Float; use num::FpCategory as Fp; use option::Option; // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective // members of `Bounded` and `Float`. #[unstable = "pending integer conventions"] pub const RADIX: uint = 2; pub const MANTISSA_DIGITS: uint = 53; #[unstable = "pending integer conventions"] pub const DIGITS: uint = 15; #[stable] pub const EPSILON: f64 = 2.2204460492503131e-16_f64; /// Smallest finite f64 value #[stable] pub const MIN_VALUE: f64 = -1.7976931348623157e+308_f64; /// Smallest positive, normalized f64 value #[stable] pub const MIN_POS_VALUE: f64 = 2.2250738585072014e-308_f64; /// Largest finite f64 value #[stable] pub const MAX_VALUE: f64 = 1.7976931348623157e+308_f64; #[unstable = "pending integer conventions"] pub const MIN_EXP: int = -1021; #[unstable = "pending integer conventions"] pub const MAX_EXP: int = 1024; #[unstable = "pending integer conventions"] pub const MIN_10_EXP: int = -307; #[unstable = "pending integer conventions"] pub const MAX_10_EXP: int = 308; #[stable] pub const NAN: f64 = 0.0_f64/0.0_f64; #[stable] pub const INFINITY: f64 = 1.0_f64/0.0_f64; #[stable] pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64; /// Various useful constants. #[unstable = "naming scheme needs to be revisited"] pub mod consts { // FIXME: replace with mathematical constants from cmath. // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective members // of `Float`. /// Archimedes' constant pub const PI: f64 = 3.14159265358979323846264338327950288_f64; /// pi * 2.0 pub const PI_2: f64 = 6.28318530717958647692528676655900576_f64; /// pi/2.0 pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64; /// pi/3.0 pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64; /// pi/4.0 pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64; /// pi/6.0 pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64; /// pi/8.0 pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64; /// 1.0/pi pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64; /// 2.0/pi pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64; /// 2.0/sqrt(pi) pub const FRAC_2_SQRTPI: f64 = 1.12837916709551257389615890312154517_f64; /// sqrt(2.0) pub const SQRT2: f64 = 1.41421356237309504880168872420969808_f64; /// 1.0/sqrt(2.0) pub const FRAC_1_SQRT2: f64 = 0.707106781186547524400844362104849039_f64; /// Euler's number pub const E: f64 = 2.71828182845904523536028747135266250_f64; /// log2(e) pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64; /// log10(e) pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64; /// ln(2.0) pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64; /// ln(10.0) pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64; } #[unstable = "trait is unstable"] impl Float for f64 { #[inline] fn nan() -> f64 { NAN } #[inline] fn infinity() -> f64 { INFINITY } #[inline] fn neg_infinity() -> f64 { NEG_INFINITY } #[inline] fn zero() -> f64 { 0.0 } #[inline] fn neg_zero() -> f64 { -0.0 } #[inline] fn one() -> f64 { 1.0 } /// Returns `true` if the number is NaN. #[inline] fn is_nan(self) -> bool { self!= self } /// Returns `true` if the number is infinite. #[inline] fn is_infinite(self) -> bool { self == Float::infinity() || self == Float::neg_infinity() } /// Returns `true` if the number is neither infinite or NaN. #[inline] fn is_finite(self) -> bool { !(self.is_nan() || self.is_infinite()) } /// Returns `true` if the number is neither zero, infinite, subnormal or NaN. #[inline] fn is_normal(self) -> bool { self.classify() == Fp::Normal } /// Returns the floating point category of the number. If only one property /// is going to be tested, it is generally faster to use the specific /// predicate instead. fn classify(self) -> Fp { const EXP_MASK: u64 = 0x7ff0000000000000; const MAN_MASK: u64 = 0x000fffffffffffff; let bits: u64 = unsafe { mem::transmute(self) }; match (bits & MAN_MASK, bits & EXP_MASK) { (0, 0) => Fp::Zero, (_, 0) => Fp::Subnormal, (0, EXP_MASK) => Fp::Infinite, (_, EXP_MASK) => Fp::Nan, _ => Fp::Normal, } } #[inline] #[deprecated] fn mantissa_digits(_: Option<f64>) -> uint { MANTISSA_DIGITS } #[inline] #[deprecated] fn digits(_: Option<f64>) -> uint { DIGITS } #[inline] #[deprecated] fn epsilon() -> f64 { EPSILON } #[inline] #[deprecated] fn min_exp(_: Option<f64>) -> int { MIN_EXP } #[inline] #[deprecated] fn max_exp(_: Option<f64>) -> int { MAX_EXP } #[inline] #[deprecated] fn min_10_exp(_: Option<f64>) -> int { MIN_10_EXP } #[inline] #[deprecated] fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP } #[inline] #[deprecated] fn min_value() -> f64 { MIN_VALUE } #[inline] #[deprecated] fn min_pos_value(_: Option<f64>) -> f64
#[inline] #[deprecated] fn max_value() -> f64 { MAX_VALUE } /// Returns the mantissa, exponent and sign as integers. fn integer_decode(self) -> (u64, i16, i8) { let bits: u64 = unsafe { mem::transmute(self) }; let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 }; let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; let mantissa = if exponent == 0 { (bits & 0xfffffffffffff) << 1 } else { (bits & 0xfffffffffffff) | 0x10000000000000 }; // Exponent bias + mantissa shift exponent -= 1023 + 52; (mantissa, exponent, sign) } /// Rounds towards minus infinity. #[inline] fn floor(self) -> f64 { unsafe { intrinsics::floorf64(self) } } /// Rounds towards plus infinity. #[inline] fn ceil(self) -> f64 { unsafe { intrinsics::ceilf64(self) } } /// Rounds to nearest integer. Rounds half-way cases away from zero. #[inline] fn round(self) -> f64 { unsafe { intrinsics::roundf64(self) } } /// Returns the integer part of the number (rounds towards zero). #[inline] fn trunc(self) -> f64 { unsafe { intrinsics::truncf64(self) } } /// The fractional part of the number, satisfying: /// /// ```rust /// use core::num::Float; /// /// let x = 1.65f64; /// assert!(x == x.trunc() + x.fract()) /// ``` #[inline] fn fract(self) -> f64 { self - self.trunc() } /// Computes the absolute value of `self`. Returns `Float::nan()` if the /// number is `Float::nan()`. #[inline] fn abs(self) -> f64 { unsafe { intrinsics::fabsf64(self) } } /// Returns a number that represents the sign of `self`. /// /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` /// - `Float::nan()` if the number is `Float::nan()` #[inline] fn signum(self) -> f64 { if self.is_nan() { Float::nan() } else { unsafe { intrinsics::copysignf64(1.0, self) } } } /// Returns `true` if `self` is positive, including `+0.0` and /// `Float::infinity()`. #[inline] fn is_positive(self) -> bool { self > 0.0 || (1.0 / self) == Float::infinity() } /// Returns `true` if `self` is negative, including `-0.0` and /// `Float::neg_infinity()`. #[inline] fn is_negative(self) -> bool { self < 0.0 || (1.0 / self) == Float::neg_infinity() } /// Fused multiply-add. Computes `(self * a) + b` with only one rounding /// error. This produces a more accurate result with better performance than /// a separate multiplication operation followed by an add. #[inline] fn mul_add(self, a: f64, b: f64) -> f64 { unsafe { intrinsics::fmaf64(self, a, b) } } /// Returns the reciprocal (multiplicative inverse) of the number. #[inline] fn recip(self) -> f64 { 1.0 / self } #[inline] fn powf(self, n: f64) -> f64 { unsafe { intrinsics::powf64(self, n) } } #[inline] fn powi(self, n: i32) -> f64 { unsafe { intrinsics::powif64(self, n) } } #[inline] fn sqrt(self) -> f64 { if self < 0.0 { NAN } else { unsafe { intrinsics::sqrtf64(self) } } } #[inline] fn rsqrt(self) -> f64 { self.sqrt().recip() } /// Returns the exponential of the number. #[inline] fn exp(self) -> f64 { unsafe { intrinsics::expf64(self) } } /// Returns 2 raised to the power of the number. #[inline] fn exp2(self) -> f64 { unsafe { intrinsics::exp2f64(self) } } /// Returns the natural logarithm of the number. #[inline] fn ln(self) -> f64 { unsafe { intrinsics::logf64(self) } } /// Returns the logarithm of the number with respect to an arbitrary base. #[inline] fn log(self, base: f64) -> f64 { self.ln() / base.ln() } /// Returns the base 2 logarithm of the number. #[inline] fn log2(self) -> f64 { unsafe { intrinsics::log2f64(self) } } /// Returns the base 10 logarithm of the number. #[inline] fn log10(self) -> f64 { unsafe { intrinsics::log10f64(self) } } /// Converts to degrees, assuming the number is in radians. #[inline] fn to_degrees(self) -> f64 { self * (180.0f64 / consts::PI) } /// Converts to radians, assuming the number is in degrees. #[inline] fn to_radians(self) -> f64 { let value: f64 = consts::PI; self * (value / 180.0) } }
{ MIN_POS_VALUE }
identifier_body
f64.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. //! Operations and constants for 64-bits floats (`f64` type) #![doc(primitive = "f64")] // FIXME: MIN_VALUE and MAX_VALUE literals are parsed as -inf and inf #14353 #![allow(overflowing_literals)] #![stable] use intrinsics; use mem; use num::Float; use num::FpCategory as Fp; use option::Option; // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective // members of `Bounded` and `Float`. #[unstable = "pending integer conventions"] pub const RADIX: uint = 2; pub const MANTISSA_DIGITS: uint = 53; #[unstable = "pending integer conventions"] pub const DIGITS: uint = 15; #[stable] pub const EPSILON: f64 = 2.2204460492503131e-16_f64; /// Smallest finite f64 value #[stable] pub const MIN_VALUE: f64 = -1.7976931348623157e+308_f64; /// Smallest positive, normalized f64 value #[stable] pub const MIN_POS_VALUE: f64 = 2.2250738585072014e-308_f64; /// Largest finite f64 value #[stable] pub const MAX_VALUE: f64 = 1.7976931348623157e+308_f64; #[unstable = "pending integer conventions"] pub const MIN_EXP: int = -1021; #[unstable = "pending integer conventions"] pub const MAX_EXP: int = 1024; #[unstable = "pending integer conventions"] pub const MIN_10_EXP: int = -307; #[unstable = "pending integer conventions"] pub const MAX_10_EXP: int = 308; #[stable] pub const NAN: f64 = 0.0_f64/0.0_f64; #[stable] pub const INFINITY: f64 = 1.0_f64/0.0_f64; #[stable] pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64; /// Various useful constants. #[unstable = "naming scheme needs to be revisited"] pub mod consts { // FIXME: replace with mathematical constants from cmath. // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective members // of `Float`. /// Archimedes' constant pub const PI: f64 = 3.14159265358979323846264338327950288_f64; /// pi * 2.0 pub const PI_2: f64 = 6.28318530717958647692528676655900576_f64; /// pi/2.0 pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64; /// pi/3.0 pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64; /// pi/4.0 pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64; /// pi/6.0 pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64; /// pi/8.0 pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64; /// 1.0/pi pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64; /// 2.0/pi pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64; /// 2.0/sqrt(pi) pub const FRAC_2_SQRTPI: f64 = 1.12837916709551257389615890312154517_f64; /// sqrt(2.0) pub const SQRT2: f64 = 1.41421356237309504880168872420969808_f64; /// 1.0/sqrt(2.0) pub const FRAC_1_SQRT2: f64 = 0.707106781186547524400844362104849039_f64; /// Euler's number pub const E: f64 = 2.71828182845904523536028747135266250_f64; /// log2(e) pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64; /// log10(e) pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64; /// ln(2.0) pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64; /// ln(10.0) pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64; } #[unstable = "trait is unstable"] impl Float for f64 { #[inline] fn nan() -> f64 { NAN } #[inline] fn infinity() -> f64 { INFINITY } #[inline] fn neg_infinity() -> f64 { NEG_INFINITY } #[inline] fn zero() -> f64 { 0.0 } #[inline] fn neg_zero() -> f64 { -0.0 } #[inline] fn one() -> f64 { 1.0 } /// Returns `true` if the number is NaN. #[inline] fn is_nan(self) -> bool { self!= self } /// Returns `true` if the number is infinite. #[inline] fn is_infinite(self) -> bool { self == Float::infinity() || self == Float::neg_infinity() } /// Returns `true` if the number is neither infinite or NaN. #[inline] fn is_finite(self) -> bool { !(self.is_nan() || self.is_infinite()) } /// Returns `true` if the number is neither zero, infinite, subnormal or NaN. #[inline] fn is_normal(self) -> bool { self.classify() == Fp::Normal } /// Returns the floating point category of the number. If only one property /// is going to be tested, it is generally faster to use the specific /// predicate instead. fn classify(self) -> Fp { const EXP_MASK: u64 = 0x7ff0000000000000; const MAN_MASK: u64 = 0x000fffffffffffff; let bits: u64 = unsafe { mem::transmute(self) }; match (bits & MAN_MASK, bits & EXP_MASK) { (0, 0) => Fp::Zero, (_, 0) => Fp::Subnormal, (0, EXP_MASK) => Fp::Infinite, (_, EXP_MASK) => Fp::Nan, _ => Fp::Normal, } } #[inline] #[deprecated] fn mantissa_digits(_: Option<f64>) -> uint { MANTISSA_DIGITS } #[inline] #[deprecated] fn digits(_: Option<f64>) -> uint { DIGITS } #[inline] #[deprecated] fn epsilon() -> f64 { EPSILON } #[inline] #[deprecated] fn min_exp(_: Option<f64>) -> int { MIN_EXP } #[inline] #[deprecated] fn max_exp(_: Option<f64>) -> int { MAX_EXP } #[inline] #[deprecated] fn min_10_exp(_: Option<f64>) -> int { MIN_10_EXP } #[inline] #[deprecated] fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP } #[inline] #[deprecated] fn min_value() -> f64 { MIN_VALUE } #[inline] #[deprecated] fn min_pos_value(_: Option<f64>) -> f64 { MIN_POS_VALUE } #[inline] #[deprecated] fn
() -> f64 { MAX_VALUE } /// Returns the mantissa, exponent and sign as integers. fn integer_decode(self) -> (u64, i16, i8) { let bits: u64 = unsafe { mem::transmute(self) }; let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 }; let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; let mantissa = if exponent == 0 { (bits & 0xfffffffffffff) << 1 } else { (bits & 0xfffffffffffff) | 0x10000000000000 }; // Exponent bias + mantissa shift exponent -= 1023 + 52; (mantissa, exponent, sign) } /// Rounds towards minus infinity. #[inline] fn floor(self) -> f64 { unsafe { intrinsics::floorf64(self) } } /// Rounds towards plus infinity. #[inline] fn ceil(self) -> f64 { unsafe { intrinsics::ceilf64(self) } } /// Rounds to nearest integer. Rounds half-way cases away from zero. #[inline] fn round(self) -> f64 { unsafe { intrinsics::roundf64(self) } } /// Returns the integer part of the number (rounds towards zero). #[inline] fn trunc(self) -> f64 { unsafe { intrinsics::truncf64(self) } } /// The fractional part of the number, satisfying: /// /// ```rust /// use core::num::Float; /// /// let x = 1.65f64; /// assert!(x == x.trunc() + x.fract()) /// ``` #[inline] fn fract(self) -> f64 { self - self.trunc() } /// Computes the absolute value of `self`. Returns `Float::nan()` if the /// number is `Float::nan()`. #[inline] fn abs(self) -> f64 { unsafe { intrinsics::fabsf64(self) } } /// Returns a number that represents the sign of `self`. /// /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` /// - `Float::nan()` if the number is `Float::nan()` #[inline] fn signum(self) -> f64 { if self.is_nan() { Float::nan() } else { unsafe { intrinsics::copysignf64(1.0, self) } } } /// Returns `true` if `self` is positive, including `+0.0` and /// `Float::infinity()`. #[inline] fn is_positive(self) -> bool { self > 0.0 || (1.0 / self) == Float::infinity() } /// Returns `true` if `self` is negative, including `-0.0` and /// `Float::neg_infinity()`. #[inline] fn is_negative(self) -> bool { self < 0.0 || (1.0 / self) == Float::neg_infinity() } /// Fused multiply-add. Computes `(self * a) + b` with only one rounding /// error. This produces a more accurate result with better performance than /// a separate multiplication operation followed by an add. #[inline] fn mul_add(self, a: f64, b: f64) -> f64 { unsafe { intrinsics::fmaf64(self, a, b) } } /// Returns the reciprocal (multiplicative inverse) of the number. #[inline] fn recip(self) -> f64 { 1.0 / self } #[inline] fn powf(self, n: f64) -> f64 { unsafe { intrinsics::powf64(self, n) } } #[inline] fn powi(self, n: i32) -> f64 { unsafe { intrinsics::powif64(self, n) } } #[inline] fn sqrt(self) -> f64 { if self < 0.0 { NAN } else { unsafe { intrinsics::sqrtf64(self) } } } #[inline] fn rsqrt(self) -> f64 { self.sqrt().recip() } /// Returns the exponential of the number. #[inline] fn exp(self) -> f64 { unsafe { intrinsics::expf64(self) } } /// Returns 2 raised to the power of the number. #[inline] fn exp2(self) -> f64 { unsafe { intrinsics::exp2f64(self) } } /// Returns the natural logarithm of the number. #[inline] fn ln(self) -> f64 { unsafe { intrinsics::logf64(self) } } /// Returns the logarithm of the number with respect to an arbitrary base. #[inline] fn log(self, base: f64) -> f64 { self.ln() / base.ln() } /// Returns the base 2 logarithm of the number. #[inline] fn log2(self) -> f64 { unsafe { intrinsics::log2f64(self) } } /// Returns the base 10 logarithm of the number. #[inline] fn log10(self) -> f64 { unsafe { intrinsics::log10f64(self) } } /// Converts to degrees, assuming the number is in radians. #[inline] fn to_degrees(self) -> f64 { self * (180.0f64 / consts::PI) } /// Converts to radians, assuming the number is in degrees. #[inline] fn to_radians(self) -> f64 { let value: f64 = consts::PI; self * (value / 180.0) } }
max_value
identifier_name
f64.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. //! Operations and constants for 64-bits floats (`f64` type) #![doc(primitive = "f64")] // FIXME: MIN_VALUE and MAX_VALUE literals are parsed as -inf and inf #14353 #![allow(overflowing_literals)] #![stable] use intrinsics; use mem; use num::Float; use num::FpCategory as Fp; use option::Option; // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective // members of `Bounded` and `Float`. #[unstable = "pending integer conventions"] pub const RADIX: uint = 2; pub const MANTISSA_DIGITS: uint = 53; #[unstable = "pending integer conventions"] pub const DIGITS: uint = 15; #[stable] pub const EPSILON: f64 = 2.2204460492503131e-16_f64; /// Smallest finite f64 value #[stable] pub const MIN_VALUE: f64 = -1.7976931348623157e+308_f64; /// Smallest positive, normalized f64 value #[stable] pub const MIN_POS_VALUE: f64 = 2.2250738585072014e-308_f64; /// Largest finite f64 value #[stable] pub const MAX_VALUE: f64 = 1.7976931348623157e+308_f64; #[unstable = "pending integer conventions"] pub const MIN_EXP: int = -1021; #[unstable = "pending integer conventions"] pub const MAX_EXP: int = 1024; #[unstable = "pending integer conventions"] pub const MIN_10_EXP: int = -307; #[unstable = "pending integer conventions"] pub const MAX_10_EXP: int = 308; #[stable] pub const NAN: f64 = 0.0_f64/0.0_f64; #[stable] pub const INFINITY: f64 = 1.0_f64/0.0_f64; #[stable] pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64; /// Various useful constants. #[unstable = "naming scheme needs to be revisited"] pub mod consts { // FIXME: replace with mathematical constants from cmath. // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective members // of `Float`. /// Archimedes' constant pub const PI: f64 = 3.14159265358979323846264338327950288_f64; /// pi * 2.0 pub const PI_2: f64 = 6.28318530717958647692528676655900576_f64; /// pi/2.0 pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64; /// pi/3.0 pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64; /// pi/4.0 pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64; /// pi/6.0 pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64; /// pi/8.0 pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64; /// 1.0/pi pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64; /// 2.0/pi pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64; /// 2.0/sqrt(pi) pub const FRAC_2_SQRTPI: f64 = 1.12837916709551257389615890312154517_f64; /// sqrt(2.0) pub const SQRT2: f64 = 1.41421356237309504880168872420969808_f64; /// 1.0/sqrt(2.0) pub const FRAC_1_SQRT2: f64 = 0.707106781186547524400844362104849039_f64; /// Euler's number pub const E: f64 = 2.71828182845904523536028747135266250_f64; /// log2(e) pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64; /// log10(e) pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64; /// ln(2.0) pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64; /// ln(10.0) pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64; } #[unstable = "trait is unstable"] impl Float for f64 { #[inline] fn nan() -> f64 { NAN } #[inline] fn infinity() -> f64 { INFINITY } #[inline] fn neg_infinity() -> f64 { NEG_INFINITY } #[inline] fn zero() -> f64 { 0.0 } #[inline] fn neg_zero() -> f64 { -0.0 } #[inline] fn one() -> f64 { 1.0 } /// Returns `true` if the number is NaN. #[inline] fn is_nan(self) -> bool { self!= self } /// Returns `true` if the number is infinite. #[inline] fn is_infinite(self) -> bool { self == Float::infinity() || self == Float::neg_infinity() } /// Returns `true` if the number is neither infinite or NaN. #[inline] fn is_finite(self) -> bool { !(self.is_nan() || self.is_infinite()) } /// Returns `true` if the number is neither zero, infinite, subnormal or NaN. #[inline] fn is_normal(self) -> bool { self.classify() == Fp::Normal } /// Returns the floating point category of the number. If only one property /// is going to be tested, it is generally faster to use the specific /// predicate instead. fn classify(self) -> Fp { const EXP_MASK: u64 = 0x7ff0000000000000; const MAN_MASK: u64 = 0x000fffffffffffff; let bits: u64 = unsafe { mem::transmute(self) }; match (bits & MAN_MASK, bits & EXP_MASK) { (0, 0) => Fp::Zero, (_, 0) => Fp::Subnormal, (0, EXP_MASK) => Fp::Infinite, (_, EXP_MASK) => Fp::Nan, _ => Fp::Normal, } } #[inline] #[deprecated] fn mantissa_digits(_: Option<f64>) -> uint { MANTISSA_DIGITS } #[inline] #[deprecated] fn digits(_: Option<f64>) -> uint { DIGITS } #[inline] #[deprecated] fn epsilon() -> f64 { EPSILON } #[inline] #[deprecated] fn min_exp(_: Option<f64>) -> int { MIN_EXP } #[inline] #[deprecated] fn max_exp(_: Option<f64>) -> int { MAX_EXP } #[inline] #[deprecated] fn min_10_exp(_: Option<f64>) -> int { MIN_10_EXP } #[inline] #[deprecated] fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP } #[inline] #[deprecated] fn min_value() -> f64 { MIN_VALUE } #[inline] #[deprecated] fn min_pos_value(_: Option<f64>) -> f64 { MIN_POS_VALUE } #[inline] #[deprecated] fn max_value() -> f64 { MAX_VALUE } /// Returns the mantissa, exponent and sign as integers. fn integer_decode(self) -> (u64, i16, i8) { let bits: u64 = unsafe { mem::transmute(self) }; let sign: i8 = if bits >> 63 == 0
else { -1 }; let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; let mantissa = if exponent == 0 { (bits & 0xfffffffffffff) << 1 } else { (bits & 0xfffffffffffff) | 0x10000000000000 }; // Exponent bias + mantissa shift exponent -= 1023 + 52; (mantissa, exponent, sign) } /// Rounds towards minus infinity. #[inline] fn floor(self) -> f64 { unsafe { intrinsics::floorf64(self) } } /// Rounds towards plus infinity. #[inline] fn ceil(self) -> f64 { unsafe { intrinsics::ceilf64(self) } } /// Rounds to nearest integer. Rounds half-way cases away from zero. #[inline] fn round(self) -> f64 { unsafe { intrinsics::roundf64(self) } } /// Returns the integer part of the number (rounds towards zero). #[inline] fn trunc(self) -> f64 { unsafe { intrinsics::truncf64(self) } } /// The fractional part of the number, satisfying: /// /// ```rust /// use core::num::Float; /// /// let x = 1.65f64; /// assert!(x == x.trunc() + x.fract()) /// ``` #[inline] fn fract(self) -> f64 { self - self.trunc() } /// Computes the absolute value of `self`. Returns `Float::nan()` if the /// number is `Float::nan()`. #[inline] fn abs(self) -> f64 { unsafe { intrinsics::fabsf64(self) } } /// Returns a number that represents the sign of `self`. /// /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` /// - `Float::nan()` if the number is `Float::nan()` #[inline] fn signum(self) -> f64 { if self.is_nan() { Float::nan() } else { unsafe { intrinsics::copysignf64(1.0, self) } } } /// Returns `true` if `self` is positive, including `+0.0` and /// `Float::infinity()`. #[inline] fn is_positive(self) -> bool { self > 0.0 || (1.0 / self) == Float::infinity() } /// Returns `true` if `self` is negative, including `-0.0` and /// `Float::neg_infinity()`. #[inline] fn is_negative(self) -> bool { self < 0.0 || (1.0 / self) == Float::neg_infinity() } /// Fused multiply-add. Computes `(self * a) + b` with only one rounding /// error. This produces a more accurate result with better performance than /// a separate multiplication operation followed by an add. #[inline] fn mul_add(self, a: f64, b: f64) -> f64 { unsafe { intrinsics::fmaf64(self, a, b) } } /// Returns the reciprocal (multiplicative inverse) of the number. #[inline] fn recip(self) -> f64 { 1.0 / self } #[inline] fn powf(self, n: f64) -> f64 { unsafe { intrinsics::powf64(self, n) } } #[inline] fn powi(self, n: i32) -> f64 { unsafe { intrinsics::powif64(self, n) } } #[inline] fn sqrt(self) -> f64 { if self < 0.0 { NAN } else { unsafe { intrinsics::sqrtf64(self) } } } #[inline] fn rsqrt(self) -> f64 { self.sqrt().recip() } /// Returns the exponential of the number. #[inline] fn exp(self) -> f64 { unsafe { intrinsics::expf64(self) } } /// Returns 2 raised to the power of the number. #[inline] fn exp2(self) -> f64 { unsafe { intrinsics::exp2f64(self) } } /// Returns the natural logarithm of the number. #[inline] fn ln(self) -> f64 { unsafe { intrinsics::logf64(self) } } /// Returns the logarithm of the number with respect to an arbitrary base. #[inline] fn log(self, base: f64) -> f64 { self.ln() / base.ln() } /// Returns the base 2 logarithm of the number. #[inline] fn log2(self) -> f64 { unsafe { intrinsics::log2f64(self) } } /// Returns the base 10 logarithm of the number. #[inline] fn log10(self) -> f64 { unsafe { intrinsics::log10f64(self) } } /// Converts to degrees, assuming the number is in radians. #[inline] fn to_degrees(self) -> f64 { self * (180.0f64 / consts::PI) } /// Converts to radians, assuming the number is in degrees. #[inline] fn to_radians(self) -> f64 { let value: f64 = consts::PI; self * (value / 180.0) } }
{ 1 }
conditional_block
time.rs
use std::marker::PhantomData; use chrono; use super::Module; use crate::{Color, Powerline, Style}; pub struct Time<S: TimeScheme> { time_format: &'static str, scheme: PhantomData<S>, } pub trait TimeScheme { const TIME_BG: Color; const TIME_FG: Color; } impl<S: TimeScheme> Time<S> { pub fn new() -> Time<S> { Time { time_format: "%H:%M:%S", scheme: PhantomData } } pub fn with_time_format(time_format: &'static str) -> Time<S> { Time { time_format, scheme: PhantomData } }
} impl<S: TimeScheme> Module for Time<S> { fn append_segments(&mut self, powerline: &mut Powerline) { let now = chrono::offset::Local::now().format(self.time_format); powerline.add_segment(now, Style::simple(S::TIME_FG, S::TIME_BG)); } }
random_line_split
time.rs
use std::marker::PhantomData; use chrono; use super::Module; use crate::{Color, Powerline, Style}; pub struct Time<S: TimeScheme> { time_format: &'static str, scheme: PhantomData<S>, } pub trait TimeScheme { const TIME_BG: Color; const TIME_FG: Color; } impl<S: TimeScheme> Time<S> { pub fn new() -> Time<S> { Time { time_format: "%H:%M:%S", scheme: PhantomData } } pub fn
(time_format: &'static str) -> Time<S> { Time { time_format, scheme: PhantomData } } } impl<S: TimeScheme> Module for Time<S> { fn append_segments(&mut self, powerline: &mut Powerline) { let now = chrono::offset::Local::now().format(self.time_format); powerline.add_segment(now, Style::simple(S::TIME_FG, S::TIME_BG)); } }
with_time_format
identifier_name
time.rs
use std::marker::PhantomData; use chrono; use super::Module; use crate::{Color, Powerline, Style}; pub struct Time<S: TimeScheme> { time_format: &'static str, scheme: PhantomData<S>, } pub trait TimeScheme { const TIME_BG: Color; const TIME_FG: Color; } impl<S: TimeScheme> Time<S> { pub fn new() -> Time<S>
pub fn with_time_format(time_format: &'static str) -> Time<S> { Time { time_format, scheme: PhantomData } } } impl<S: TimeScheme> Module for Time<S> { fn append_segments(&mut self, powerline: &mut Powerline) { let now = chrono::offset::Local::now().format(self.time_format); powerline.add_segment(now, Style::simple(S::TIME_FG, S::TIME_BG)); } }
{ Time { time_format: "%H:%M:%S", scheme: PhantomData } }
identifier_body
cache_tests.rs
use std::convert::TryInto; use std::io::Write; use std::path::PathBuf; use sharded_lmdb::{ShardedLmdb, DEFAULT_LEASE_TIME}; use store::Store; use tempfile::TempDir; use testutil::data::TestData; use testutil::relative_paths; use workunit_store::{RunningWorkunit, WorkunitStore}; use crate::{ CommandRunner as CommandRunnerTrait, Context, FallibleProcessResultWithPlatform, NamedCaches, Process, ProcessMetadata, }; struct RoundtripResults { uncached: Result<FallibleProcessResultWithPlatform, String>, maybe_cached: Result<FallibleProcessResultWithPlatform, String>, } fn create_local_runner() -> (Box<dyn CommandRunnerTrait>, Store, TempDir) { let runtime = task_executor::Executor::new(); let base_dir = TempDir::new().unwrap(); let named_cache_dir = base_dir.path().join("named_cache_dir"); let store_dir = base_dir.path().join("store_dir"); let store = Store::local_only(runtime.clone(), store_dir).unwrap(); let runner = Box::new(crate::local::CommandRunner::new( store.clone(), runtime.clone(), base_dir.path().to_owned(), NamedCaches::new(named_cache_dir), true, )); (runner, store, base_dir) } fn create_cached_runner( local: Box<dyn CommandRunnerTrait>, store: Store, ) -> (Box<dyn CommandRunnerTrait>, TempDir) { let runtime = task_executor::Executor::new(); let cache_dir = TempDir::new().unwrap(); let max_lmdb_size = 50 * 1024 * 1024; //50 MB - I didn't pick that number but it seems reasonable. let process_execution_store = ShardedLmdb::new( cache_dir.path().to_owned(), max_lmdb_size, runtime.clone(), DEFAULT_LEASE_TIME, 1, ) .unwrap(); let runner = Box::new(crate::cache::CommandRunner::new( local.into(), process_execution_store, store, ProcessMetadata::default(), )); (runner, cache_dir) } fn create_script(script_exit_code: i8) -> (Process, PathBuf, TempDir) { let script_dir = TempDir::new().unwrap(); let script_path = script_dir.path().join("script"); std::fs::File::create(&script_path) .and_then(|mut file| { writeln!( file, "echo -n {} > roland && echo Hello && echo >&2 World; exit {}", TestData::roland().string(), script_exit_code ) }) .unwrap(); let process = Process::new(vec![ testutil::path::find_bash(), format!("{}", script_path.display()), ]) .output_files(relative_paths(&["roland"]).collect()); (process, script_path, script_dir) } async fn run_roundtrip(script_exit_code: i8, workunit: &mut RunningWorkunit) -> RoundtripResults { let (local, store, _local_runner_dir) = create_local_runner(); let (process, script_path, _script_dir) = create_script(script_exit_code); let local_result = local .run(Context::default(), workunit, process.clone().into()) .await; let (caching, _cache_dir) = create_cached_runner(local, store.clone()); let uncached_result = caching .run(Context::default(), workunit, process.clone().into()) .await; assert_eq!(local_result, uncached_result); // Removing the file means that were the command to be run again without any caching, it would // fail due to a FileNotFound error. So, If the second run succeeds, that implies that the // cache was successfully used. std::fs::remove_file(&script_path).unwrap(); let maybe_cached_result = caching .run(Context::default(), workunit, process.into()) .await; RoundtripResults { uncached: uncached_result, maybe_cached: maybe_cached_result, } } #[tokio::test] async fn cache_success() { let (_, mut workunit) = WorkunitStore::setup_for_tests(); let results = run_roundtrip(0, &mut workunit).await; assert_eq!(results.uncached, results.maybe_cached); } #[tokio::test] async fn failures_not_cached()
#[tokio::test] async fn recover_from_missing_store_contents() { let (_, mut workunit) = WorkunitStore::setup_for_tests(); let (local, store, _local_runner_dir) = create_local_runner(); let (caching, _cache_dir) = create_cached_runner(local, store.clone()); let (process, _script_path, _script_dir) = create_script(0); // Run once to cache the process. let first_result = caching .run(Context::default(), &mut workunit, process.clone().into()) .await .unwrap(); // Delete the first child of the output directory parent to confirm that we ensure that more // than just the root of the output is present when hitting the cache. { let output_dir_digest = first_result.output_directory; let output_dir = store .load_directory(output_dir_digest) .await .unwrap() .unwrap(); let output_child_digest = output_dir .files .first() .unwrap() .digest .as_ref() .unwrap() .try_into() .unwrap(); let removed = store.remove_file(output_child_digest).await.unwrap(); assert!(removed); assert!(store .contents_for_directory(output_dir_digest) .await .err() .is_some()) } // Ensure that we don't fail if we re-run. let second_result = caching .run(Context::default(), &mut workunit, process.clone().into()) .await .unwrap(); // And that the entire output directory can be loaded. assert!(store .contents_for_directory(second_result.output_directory) .await .ok() .is_some()) }
{ let (_, mut workunit) = WorkunitStore::setup_for_tests(); let results = run_roundtrip(1, &mut workunit).await; assert_ne!(results.uncached, results.maybe_cached); assert_eq!(results.uncached.unwrap().exit_code, 1); assert_eq!(results.maybe_cached.unwrap().exit_code, 127); // aka the return code for file not found }
identifier_body
cache_tests.rs
use std::convert::TryInto; use std::io::Write; use std::path::PathBuf; use sharded_lmdb::{ShardedLmdb, DEFAULT_LEASE_TIME}; use store::Store; use tempfile::TempDir; use testutil::data::TestData; use testutil::relative_paths; use workunit_store::{RunningWorkunit, WorkunitStore}; use crate::{ CommandRunner as CommandRunnerTrait, Context, FallibleProcessResultWithPlatform, NamedCaches, Process, ProcessMetadata, }; struct RoundtripResults { uncached: Result<FallibleProcessResultWithPlatform, String>, maybe_cached: Result<FallibleProcessResultWithPlatform, String>, } fn create_local_runner() -> (Box<dyn CommandRunnerTrait>, Store, TempDir) { let runtime = task_executor::Executor::new(); let base_dir = TempDir::new().unwrap(); let named_cache_dir = base_dir.path().join("named_cache_dir"); let store_dir = base_dir.path().join("store_dir"); let store = Store::local_only(runtime.clone(), store_dir).unwrap(); let runner = Box::new(crate::local::CommandRunner::new( store.clone(), runtime.clone(), base_dir.path().to_owned(), NamedCaches::new(named_cache_dir), true, )); (runner, store, base_dir) } fn create_cached_runner( local: Box<dyn CommandRunnerTrait>, store: Store, ) -> (Box<dyn CommandRunnerTrait>, TempDir) { let runtime = task_executor::Executor::new(); let cache_dir = TempDir::new().unwrap(); let max_lmdb_size = 50 * 1024 * 1024; //50 MB - I didn't pick that number but it seems reasonable. let process_execution_store = ShardedLmdb::new( cache_dir.path().to_owned(), max_lmdb_size, runtime.clone(), DEFAULT_LEASE_TIME, 1, ) .unwrap(); let runner = Box::new(crate::cache::CommandRunner::new( local.into(), process_execution_store, store, ProcessMetadata::default(), )); (runner, cache_dir) } fn create_script(script_exit_code: i8) -> (Process, PathBuf, TempDir) { let script_dir = TempDir::new().unwrap(); let script_path = script_dir.path().join("script"); std::fs::File::create(&script_path) .and_then(|mut file| { writeln!( file, "echo -n {} > roland && echo Hello && echo >&2 World; exit {}", TestData::roland().string(), script_exit_code ) }) .unwrap(); let process = Process::new(vec![ testutil::path::find_bash(), format!("{}", script_path.display()), ]) .output_files(relative_paths(&["roland"]).collect()); (process, script_path, script_dir) } async fn run_roundtrip(script_exit_code: i8, workunit: &mut RunningWorkunit) -> RoundtripResults { let (local, store, _local_runner_dir) = create_local_runner(); let (process, script_path, _script_dir) = create_script(script_exit_code); let local_result = local .run(Context::default(), workunit, process.clone().into()) .await; let (caching, _cache_dir) = create_cached_runner(local, store.clone()); let uncached_result = caching .run(Context::default(), workunit, process.clone().into()) .await; assert_eq!(local_result, uncached_result); // Removing the file means that were the command to be run again without any caching, it would // fail due to a FileNotFound error. So, If the second run succeeds, that implies that the // cache was successfully used. std::fs::remove_file(&script_path).unwrap(); let maybe_cached_result = caching .run(Context::default(), workunit, process.into()) .await; RoundtripResults { uncached: uncached_result, maybe_cached: maybe_cached_result, } } #[tokio::test] async fn cache_success() { let (_, mut workunit) = WorkunitStore::setup_for_tests(); let results = run_roundtrip(0, &mut workunit).await; assert_eq!(results.uncached, results.maybe_cached); } #[tokio::test] async fn failures_not_cached() { let (_, mut workunit) = WorkunitStore::setup_for_tests(); let results = run_roundtrip(1, &mut workunit).await; assert_ne!(results.uncached, results.maybe_cached); assert_eq!(results.uncached.unwrap().exit_code, 1); assert_eq!(results.maybe_cached.unwrap().exit_code, 127); // aka the return code for file not found } #[tokio::test] async fn
() { let (_, mut workunit) = WorkunitStore::setup_for_tests(); let (local, store, _local_runner_dir) = create_local_runner(); let (caching, _cache_dir) = create_cached_runner(local, store.clone()); let (process, _script_path, _script_dir) = create_script(0); // Run once to cache the process. let first_result = caching .run(Context::default(), &mut workunit, process.clone().into()) .await .unwrap(); // Delete the first child of the output directory parent to confirm that we ensure that more // than just the root of the output is present when hitting the cache. { let output_dir_digest = first_result.output_directory; let output_dir = store .load_directory(output_dir_digest) .await .unwrap() .unwrap(); let output_child_digest = output_dir .files .first() .unwrap() .digest .as_ref() .unwrap() .try_into() .unwrap(); let removed = store.remove_file(output_child_digest).await.unwrap(); assert!(removed); assert!(store .contents_for_directory(output_dir_digest) .await .err() .is_some()) } // Ensure that we don't fail if we re-run. let second_result = caching .run(Context::default(), &mut workunit, process.clone().into()) .await .unwrap(); // And that the entire output directory can be loaded. assert!(store .contents_for_directory(second_result.output_directory) .await .ok() .is_some()) }
recover_from_missing_store_contents
identifier_name
cache_tests.rs
use std::convert::TryInto; use std::io::Write; use std::path::PathBuf; use sharded_lmdb::{ShardedLmdb, DEFAULT_LEASE_TIME}; use store::Store; use tempfile::TempDir; use testutil::data::TestData; use testutil::relative_paths; use workunit_store::{RunningWorkunit, WorkunitStore}; use crate::{ CommandRunner as CommandRunnerTrait, Context, FallibleProcessResultWithPlatform, NamedCaches, Process, ProcessMetadata, }; struct RoundtripResults { uncached: Result<FallibleProcessResultWithPlatform, String>, maybe_cached: Result<FallibleProcessResultWithPlatform, String>, } fn create_local_runner() -> (Box<dyn CommandRunnerTrait>, Store, TempDir) { let runtime = task_executor::Executor::new(); let base_dir = TempDir::new().unwrap(); let named_cache_dir = base_dir.path().join("named_cache_dir"); let store_dir = base_dir.path().join("store_dir"); let store = Store::local_only(runtime.clone(), store_dir).unwrap(); let runner = Box::new(crate::local::CommandRunner::new( store.clone(), runtime.clone(), base_dir.path().to_owned(), NamedCaches::new(named_cache_dir), true, )); (runner, store, base_dir) } fn create_cached_runner( local: Box<dyn CommandRunnerTrait>, store: Store, ) -> (Box<dyn CommandRunnerTrait>, TempDir) { let runtime = task_executor::Executor::new(); let cache_dir = TempDir::new().unwrap(); let max_lmdb_size = 50 * 1024 * 1024; //50 MB - I didn't pick that number but it seems reasonable. let process_execution_store = ShardedLmdb::new( cache_dir.path().to_owned(), max_lmdb_size, runtime.clone(), DEFAULT_LEASE_TIME, 1, ) .unwrap(); let runner = Box::new(crate::cache::CommandRunner::new( local.into(), process_execution_store, store, ProcessMetadata::default(), )); (runner, cache_dir) } fn create_script(script_exit_code: i8) -> (Process, PathBuf, TempDir) { let script_dir = TempDir::new().unwrap(); let script_path = script_dir.path().join("script"); std::fs::File::create(&script_path) .and_then(|mut file| { writeln!( file, "echo -n {} > roland && echo Hello && echo >&2 World; exit {}", TestData::roland().string(), script_exit_code ) }) .unwrap(); let process = Process::new(vec![ testutil::path::find_bash(), format!("{}", script_path.display()), ]) .output_files(relative_paths(&["roland"]).collect()); (process, script_path, script_dir) } async fn run_roundtrip(script_exit_code: i8, workunit: &mut RunningWorkunit) -> RoundtripResults { let (local, store, _local_runner_dir) = create_local_runner(); let (process, script_path, _script_dir) = create_script(script_exit_code); let local_result = local .run(Context::default(), workunit, process.clone().into())
let (caching, _cache_dir) = create_cached_runner(local, store.clone()); let uncached_result = caching .run(Context::default(), workunit, process.clone().into()) .await; assert_eq!(local_result, uncached_result); // Removing the file means that were the command to be run again without any caching, it would // fail due to a FileNotFound error. So, If the second run succeeds, that implies that the // cache was successfully used. std::fs::remove_file(&script_path).unwrap(); let maybe_cached_result = caching .run(Context::default(), workunit, process.into()) .await; RoundtripResults { uncached: uncached_result, maybe_cached: maybe_cached_result, } } #[tokio::test] async fn cache_success() { let (_, mut workunit) = WorkunitStore::setup_for_tests(); let results = run_roundtrip(0, &mut workunit).await; assert_eq!(results.uncached, results.maybe_cached); } #[tokio::test] async fn failures_not_cached() { let (_, mut workunit) = WorkunitStore::setup_for_tests(); let results = run_roundtrip(1, &mut workunit).await; assert_ne!(results.uncached, results.maybe_cached); assert_eq!(results.uncached.unwrap().exit_code, 1); assert_eq!(results.maybe_cached.unwrap().exit_code, 127); // aka the return code for file not found } #[tokio::test] async fn recover_from_missing_store_contents() { let (_, mut workunit) = WorkunitStore::setup_for_tests(); let (local, store, _local_runner_dir) = create_local_runner(); let (caching, _cache_dir) = create_cached_runner(local, store.clone()); let (process, _script_path, _script_dir) = create_script(0); // Run once to cache the process. let first_result = caching .run(Context::default(), &mut workunit, process.clone().into()) .await .unwrap(); // Delete the first child of the output directory parent to confirm that we ensure that more // than just the root of the output is present when hitting the cache. { let output_dir_digest = first_result.output_directory; let output_dir = store .load_directory(output_dir_digest) .await .unwrap() .unwrap(); let output_child_digest = output_dir .files .first() .unwrap() .digest .as_ref() .unwrap() .try_into() .unwrap(); let removed = store.remove_file(output_child_digest).await.unwrap(); assert!(removed); assert!(store .contents_for_directory(output_dir_digest) .await .err() .is_some()) } // Ensure that we don't fail if we re-run. let second_result = caching .run(Context::default(), &mut workunit, process.clone().into()) .await .unwrap(); // And that the entire output directory can be loaded. assert!(store .contents_for_directory(second_result.output_directory) .await .ok() .is_some()) }
.await;
random_line_split
du.rs
#![crate_name = "du"] /* * This file is part of the uutils coreutils package. * * (c) Derek Chiang <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #![allow(non_snake_case)] extern crate getopts; extern crate libc; extern crate time; use std::fs; use std::io::{stderr, Write}; use std::os::unix::fs::MetadataExt; use std::path::PathBuf; use std::sync::Arc; use time::Timespec; use std::sync::mpsc::channel; use std::thread; #[path = "../common/util.rs"] #[macro_use] mod util; static NAME: &'static str = "du"; static VERSION: &'static str = "1.0.0"; struct Options { all: bool, program_name: String, max_depth: Option<usize>, total: bool, separate_dirs: bool, } struct
{ path: PathBuf, is_dir: bool, size: u64, blocks: u64, nlink: u64, created: u64, accessed: u64, modified: u64, } impl Stat { fn new(path: &PathBuf) -> Stat { let metadata = safe_unwrap!(fs::metadata(path)); Stat { path: path.clone(), is_dir: metadata.is_dir(), size: metadata.len(), blocks: metadata.blocks() as u64, nlink: metadata.nlink() as u64, created: metadata.mtime() as u64, accessed: metadata.atime() as u64, modified: metadata.mtime() as u64 } } } // this takes `my_stat` to avoid having to stat files multiple times. fn du(path: &PathBuf, mut my_stat: Stat, options: Arc<Options>, depth: usize) -> Vec<Arc<Stat>> { let mut stats = vec!(); let mut futures = vec!(); if my_stat.is_dir { let read = match fs::read_dir(path) { Ok(read) => read, Err(e) => { safe_writeln!(stderr(), "{}: cannot read directory β€˜{}β€˜: {}", options.program_name, path.display(), e); return vec!(Arc::new(my_stat)) } }; for f in read.into_iter() { let entry = f.unwrap(); let this_stat = Stat::new(&entry.path()); if this_stat.is_dir { let oa_clone = options.clone(); let (tx, rx) = channel(); thread::spawn(move || { let result = du(&entry.path(), this_stat, oa_clone, depth + 1); tx.send(result) }); futures.push(rx); } else { my_stat.size += this_stat.size; my_stat.blocks += this_stat.blocks; if options.all { stats.push(Arc::new(this_stat)) } } } } for rx in futures.iter_mut() { for stat in rx.recv().unwrap().into_iter().rev() { if!options.separate_dirs && stat.path.parent().unwrap().to_path_buf() == my_stat.path { my_stat.size += stat.size; my_stat.blocks += stat.blocks; } if options.max_depth == None || depth < options.max_depth.unwrap() { stats.push(stat.clone()); } } } stats.push(Arc::new(my_stat)); stats } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); // In task opts.optflag("a", "all", " write counts for all files, not just directories"); // In main opts.optflag("", "apparent-size", "print apparent sizes, rather than disk usage; although the apparent size is usually smaller, it may be larger due to holes in ('sparse') files, internal fragmentation, indirect blocks, and the like"); // In main opts.optopt("B", "block-size", "scale sizes by SIZE before printing them. E.g., '-BM' prints sizes in units of 1,048,576 bytes. See SIZE format below.", "SIZE"); // In main opts.optflag("b", "bytes", "equivalent to '--apparent-size --block-size=1'"); // In main opts.optflag("c", "total", "produce a grand total"); // In task // opts.optflag("D", "dereference-args", "dereference only symlinks that are listed // on the command line"), // In main // opts.optopt("", "files0-from", "summarize disk usage of the NUL-terminated file // names specified in file F; // If F is - then read names from standard input", "F"), // // In task // opts.optflag("H", "", "equivalent to --dereference-args (-D)"), // In main opts.optflag("h", "human-readable", "print sizes in human readable format (e.g., 1K 234M 2G)"); // In main opts.optflag("", "si", "like -h, but use powers of 1000 not 1024"); // In main opts.optflag("k", "", "like --block-size=1K"); // In task opts.optflag("l", "count-links", "count sizes many times if hard linked"); // // In main opts.optflag("m", "", "like --block-size=1M"); // // In task // opts.optflag("L", "dereference", "dereference all symbolic links"), // // In task // opts.optflag("P", "no-dereference", "don't follow any symbolic links (this is the default)"), // // In main opts.optflag("0", "null", "end each output line with 0 byte rather than newline"); // In main opts.optflag("S", "separate-dirs", "do not include size of subdirectories"); // In main opts.optflag("s", "summarize", "display only a total for each argument"); // // In task // opts.optflag("x", "one-file-system", "skip directories on different file systems"), // // In task // opts.optopt("X", "exclude-from", "exclude files that match any pattern in FILE", "FILE"), // // In task // opts.optopt("", "exclude", "exclude files that match PATTERN", "PATTERN"), // In main opts.optopt("d", "max-depth", "print the total for a directory (or file, with --all) only if it is N or fewer levels below the command line argument; --max-depth=0 is the same as --summarize", "N"); // In main opts.optflagopt("", "time", "show time of the last modification of any file in the directory, or any of its subdirectories. If WORD is given, show time as WORD instead of modification time: atime, access, use, ctime or status", "WORD"); // In main opts.optopt("", "time-style", "show times using style STYLE: full-iso, long-iso, iso, +FORMAT FORMAT is interpreted like 'date'", "STYLE"); opts.optflag("", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("Invalid options\n{}", f); return 1; } }; if matches.opt_present("help") { println!("{program} {version} - estimate file space usage Usage {program} [OPTION]... [FILE]... {program} [OPTION]... --files0-from=F {usage} Display values are in units of the first available SIZE from --block-size, and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environ‐ ment variables. Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set). SIZE is an integer and optional unit (example: 10M is 10*1024*1024). Units are K, M, G, T, P, E, Z, Y (powers of 1024) or KB, MB,... (pow‐ ers of 1000).", program = NAME, version = VERSION, usage = opts.usage("Summarize disk usage of each FILE, recursively for directories.")); return 0; } else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } let summarize = matches.opt_present("summarize"); let max_depth_str = matches.opt_str("max-depth"); let max_depth = max_depth_str.as_ref().and_then(|s| s.parse::<usize>().ok()); match (max_depth_str, max_depth) { (Some(ref s), _) if summarize => { show_error!("summarizing conflicts with --max-depth={}", *s); return 1; } (Some(ref s), None) => { show_error!("invalid maximum depth '{}'", *s); return 1; } (Some(_), Some(_)) | (None, _) => { /* valid */ } } let options = Options { all: matches.opt_present("all"), program_name: NAME.to_string(), max_depth: max_depth, total: matches.opt_present("total"), separate_dirs: matches.opt_present("S"), }; let strs = if matches.free.is_empty() {vec!("./".to_string())} else {matches.free.clone()}; let options_arc = Arc::new(options); let MB = match matches.opt_present("si") { true => 1000 * 1000, false => 1024 * 1024, }; let KB = match matches.opt_present("si") { true => 1000, false => 1024, }; let block_size = match matches.opt_str("block-size") { Some(s) => { let mut found_number = false; let mut found_letter = false; let mut numbers = String::new(); let mut letters = String::new(); for c in s.chars() { if found_letter && c.is_digit(10) ||!found_number &&!c.is_digit(10) { show_error!("invalid --block-size argument '{}'", s); return 1; } else if c.is_digit(10) { found_number = true; numbers.push(c); } else if c.is_alphabetic() { found_letter = true; letters.push(c); } } let number = numbers.parse::<u64>().unwrap(); let multiple = match &letters[..] { "K" => 1024u64.pow(1), "M" => 1024u64.pow(2), "G" => 1024u64.pow(3), "T" => 1024u64.pow(4), "P" => 1024u64.pow(5), "E" => 1024u64.pow(6), "Z" => 1024u64.pow(7), "Y" => 1024u64.pow(8), "KB" => 1000u64.pow(1), "MB" => 1000u64.pow(2), "GB" => 1000u64.pow(3), "TB" => 1000u64.pow(4), "PB" => 1000u64.pow(5), "EB" => 1000u64.pow(6), "ZB" => 1000u64.pow(7), "YB" => 1000u64.pow(8), _ => { show_error!("invalid --block-size argument '{}'", s); return 1; } }; number * multiple }, None => 1024 }; let convert_size = |size: u64| -> String { if matches.opt_present("human-readable") || matches.opt_present("si") { if size >= MB { format!("{:.1}M", (size as f64) / (MB as f64)) } else if size >= KB { format!("{:.1}K", (size as f64) / (KB as f64)) } else { format!("{}B", size) } } else if matches.opt_present("k") { format!("{}", ((size as f64) / (KB as f64)).ceil()) } else if matches.opt_present("m") { format!("{}", ((size as f64) / (MB as f64)).ceil()) } else { format!("{}", ((size as f64) / (block_size as f64)).ceil()) } }; let time_format_str = match matches.opt_str("time-style") { Some(s) => { match &s[..] { "full-iso" => "%Y-%m-%d %H:%M:%S.%f %z", "long-iso" => "%Y-%m-%d %H:%M", "iso" => "%Y-%m-%d", _ => { show_error!("invalid argument '{}' for 'time style' Valid arguments are: - 'full-iso' - 'long-iso' - 'iso' Try '{} --help' for more information.", s, NAME); return 1; } } }, None => "%Y-%m-%d %H:%M" }; let line_separator = match matches.opt_present("0") { true => "\0", false => "\n", }; let mut grand_total = 0; for path_str in strs.into_iter() { let path = PathBuf::from(path_str); let iter = du(&path, Stat::new(&path), options_arc.clone(), 0).into_iter(); let (_, len) = iter.size_hint(); let len = len.unwrap(); for (index, stat) in iter.enumerate() { let size = match matches.opt_present("apparent-size") { true => stat.nlink * stat.size, // C's stat is such that each block is assume to be 512 bytes // See: http://linux.die.net/man/2/stat false => stat.blocks * 512, }; if matches.opt_present("time") { let tm = { let (secs, nsecs) = { let time = match matches.opt_str("time") { Some(s) => match &s[..] { "accessed" => stat.accessed, "created" => stat.created, "modified" => stat.modified, _ => { show_error!("invalid argument'modified' for '--time' Valid arguments are: - 'accessed', 'created','modified' Try '{} --help' for more information.", NAME); return 1; } }, None => stat.modified }; ((time / 1000) as i64, (time % 1000 * 1000000) as i32) }; time::at(Timespec::new(secs, nsecs)) }; if!summarize || (summarize && index == len-1) { let time_str = tm.strftime(time_format_str).unwrap(); print!("{}\t{}\t{}{}", convert_size(size), time_str, stat.path.display(), line_separator); } } else { if!summarize || (summarize && index == len-1) { print!("{}\t{}{}", convert_size(size), stat.path.display(), line_separator); } } if options_arc.total && index == (len - 1) { // The last element will be the total size of the the path under // path_str. We add it to the grand total. grand_total += size; } } } if options_arc.total { print!("{}\ttotal", convert_size(grand_total)); print!("{}", line_separator); } 0 }
Stat
identifier_name
du.rs
#![crate_name = "du"] /* * This file is part of the uutils coreutils package. * * (c) Derek Chiang <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #![allow(non_snake_case)] extern crate getopts; extern crate libc; extern crate time; use std::fs; use std::io::{stderr, Write}; use std::os::unix::fs::MetadataExt; use std::path::PathBuf; use std::sync::Arc; use time::Timespec; use std::sync::mpsc::channel; use std::thread; #[path = "../common/util.rs"] #[macro_use] mod util; static NAME: &'static str = "du"; static VERSION: &'static str = "1.0.0"; struct Options { all: bool, program_name: String, max_depth: Option<usize>, total: bool, separate_dirs: bool, } struct Stat { path: PathBuf, is_dir: bool, size: u64, blocks: u64, nlink: u64, created: u64, accessed: u64, modified: u64, } impl Stat { fn new(path: &PathBuf) -> Stat { let metadata = safe_unwrap!(fs::metadata(path)); Stat { path: path.clone(), is_dir: metadata.is_dir(), size: metadata.len(), blocks: metadata.blocks() as u64, nlink: metadata.nlink() as u64, created: metadata.mtime() as u64, accessed: metadata.atime() as u64, modified: metadata.mtime() as u64 } } } // this takes `my_stat` to avoid having to stat files multiple times. fn du(path: &PathBuf, mut my_stat: Stat, options: Arc<Options>, depth: usize) -> Vec<Arc<Stat>> { let mut stats = vec!(); let mut futures = vec!(); if my_stat.is_dir { let read = match fs::read_dir(path) { Ok(read) => read, Err(e) => { safe_writeln!(stderr(), "{}: cannot read directory β€˜{}β€˜: {}", options.program_name, path.display(), e); return vec!(Arc::new(my_stat)) } }; for f in read.into_iter() { let entry = f.unwrap(); let this_stat = Stat::new(&entry.path()); if this_stat.is_dir { let oa_clone = options.clone(); let (tx, rx) = channel(); thread::spawn(move || { let result = du(&entry.path(), this_stat, oa_clone, depth + 1); tx.send(result) }); futures.push(rx); } else { my_stat.size += this_stat.size; my_stat.blocks += this_stat.blocks; if options.all { stats.push(Arc::new(this_stat)) } } } } for rx in futures.iter_mut() { for stat in rx.recv().unwrap().into_iter().rev() { if!options.separate_dirs && stat.path.parent().unwrap().to_path_buf() == my_stat.path { my_stat.size += stat.size; my_stat.blocks += stat.blocks; } if options.max_depth == None || depth < options.max_depth.unwrap() { stats.push(stat.clone()); } } } stats.push(Arc::new(my_stat)); stats } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); // In task opts.optflag("a", "all", " write counts for all files, not just directories"); // In main opts.optflag("", "apparent-size", "print apparent sizes, rather than disk usage; although the apparent size is usually smaller, it may be larger due to holes in ('sparse') files, internal fragmentation, indirect blocks, and the like"); // In main opts.optopt("B", "block-size", "scale sizes by SIZE before printing them. E.g., '-BM' prints sizes in units of 1,048,576 bytes. See SIZE format below.", "SIZE"); // In main opts.optflag("b", "bytes", "equivalent to '--apparent-size --block-size=1'"); // In main opts.optflag("c", "total", "produce a grand total"); // In task // opts.optflag("D", "dereference-args", "dereference only symlinks that are listed // on the command line"), // In main // opts.optopt("", "files0-from", "summarize disk usage of the NUL-terminated file // names specified in file F; // If F is - then read names from standard input", "F"), // // In task // opts.optflag("H", "", "equivalent to --dereference-args (-D)"), // In main opts.optflag("h", "human-readable", "print sizes in human readable format (e.g., 1K 234M 2G)"); // In main opts.optflag("", "si", "like -h, but use powers of 1000 not 1024"); // In main opts.optflag("k", "", "like --block-size=1K"); // In task opts.optflag("l", "count-links", "count sizes many times if hard linked"); // // In main opts.optflag("m", "", "like --block-size=1M"); // // In task // opts.optflag("L", "dereference", "dereference all symbolic links"), // // In task // opts.optflag("P", "no-dereference", "don't follow any symbolic links (this is the default)"), // // In main opts.optflag("0", "null", "end each output line with 0 byte rather than newline"); // In main opts.optflag("S", "separate-dirs", "do not include size of subdirectories"); // In main opts.optflag("s", "summarize", "display only a total for each argument"); // // In task // opts.optflag("x", "one-file-system", "skip directories on different file systems"), // // In task // opts.optopt("X", "exclude-from", "exclude files that match any pattern in FILE", "FILE"), // // In task // opts.optopt("", "exclude", "exclude files that match PATTERN", "PATTERN"), // In main opts.optopt("d", "max-depth", "print the total for a directory (or file, with --all) only if it is N or fewer levels below the command line argument; --max-depth=0 is the same as --summarize", "N"); // In main opts.optflagopt("", "time", "show time of the last modification of any file in the directory, or any of its subdirectories. If WORD is given, show time as WORD instead of modification time: atime, access, use, ctime or status", "WORD"); // In main opts.optopt("", "time-style", "show times using style STYLE: full-iso, long-iso, iso, +FORMAT FORMAT is interpreted like 'date'", "STYLE"); opts.optflag("", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("Invalid options\n{}", f); return 1; } }; if matches.opt_present("help") { println!("{program} {version} - estimate file space usage Usage {program} [OPTION]... [FILE]... {program} [OPTION]... --files0-from=F {usage} Display values are in units of the first available SIZE from --block-size, and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environ‐ ment variables. Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set). SIZE is an integer and optional unit (example: 10M is 10*1024*1024). Units are K, M, G, T, P, E, Z, Y (powers of 1024) or KB, MB,... (pow‐ ers of 1000).", program = NAME, version = VERSION, usage = opts.usage("Summarize disk usage of each FILE, recursively for directories.")); return 0; } else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } let summarize = matches.opt_present("summarize"); let max_depth_str = matches.opt_str("max-depth"); let max_depth = max_depth_str.as_ref().and_then(|s| s.parse::<usize>().ok()); match (max_depth_str, max_depth) { (Some(ref s), _) if summarize => { show_error!("summarizing conflicts with --max-depth={}", *s); return 1; } (Some(ref s), None) => { show_error!("invalid maximum depth '{}'", *s); return 1; } (Some(_), Some(_)) | (None, _) => { /* valid */ } } let options = Options { all: matches.opt_present("all"), program_name: NAME.to_string(), max_depth: max_depth, total: matches.opt_present("total"), separate_dirs: matches.opt_present("S"), }; let strs = if matches.free.is_empty() {vec!("./".to_string())} else {matches.free.clone()}; let options_arc = Arc::new(options); let MB = match matches.opt_present("si") { true => 1000 * 1000, false => 1024 * 1024, }; let KB = match matches.opt_present("si") { true => 1000, false => 1024, }; let block_size = match matches.opt_str("block-size") { Some(s) => { let mut found_number = false; let mut found_letter = false; let mut numbers = String::new(); let mut letters = String::new(); for c in s.chars() { if found_letter && c.is_digit(10) ||!found_number &&!c.is_digit(10) { show_error!("invalid --block-size argument '{}'", s); return 1; } else if c.is_digit(10) { found_number = true; numbers.push(c); } else if c.is_alphabetic() { found_letter = true; letters.push(c); } } let number = numbers.parse::<u64>().unwrap(); let multiple = match &letters[..] { "K" => 1024u64.pow(1), "M" => 1024u64.pow(2), "G" => 1024u64.pow(3), "T" => 1024u64.pow(4), "P" => 1024u64.pow(5), "E" => 1024u64.pow(6), "Z" => 1024u64.pow(7), "Y" => 1024u64.pow(8), "KB" => 1000u64.pow(1), "MB" => 1000u64.pow(2), "GB" => 1000u64.pow(3), "TB" => 1000u64.pow(4), "PB" => 1000u64.pow(5), "EB" => 1000u64.pow(6), "ZB" => 1000u64.pow(7), "YB" => 1000u64.pow(8), _ => { show_error!("invalid --block-size argument '{}'", s); return 1; } }; number * multiple }, None => 1024 }; let convert_size = |size: u64| -> String { if matches.opt_present("human-readable") || matches.opt_present("si") { if size >= MB { format!("{:.1}M", (size as f64) / (MB as f64)) } else if size >= KB { format!("{:.1}K", (size as f64) / (KB as f64)) } else { format!("{}B", size) } } else if matches.opt_present("k") { format!("{}", ((size as f64) / (KB as f64)).ceil()) } else if matches.opt_present("m") { format!("{}", ((size as f64) / (MB as f64)).ceil()) } else { format!("{}", ((size as f64) / (block_size as f64)).ceil()) } }; let time_format_str = match matches.opt_str("time-style") { Some(s) => { match &s[..] { "full-iso" => "%Y-%m-%d %H:%M:%S.%f %z", "long-iso" => "%Y-%m-%d %H:%M", "iso" => "%Y-%m-%d", _ => { show_error!("invalid argument '{}' for 'time style' Valid arguments are: - 'full-iso' - 'long-iso' - 'iso' Try '{} --help' for more information.", s, NAME); return 1; } } }, None => "%Y-%m-%d %H:%M" }; let line_separator = match matches.opt_present("0") { true => "\0", false => "\n", }; let mut grand_total = 0; for path_str in strs.into_iter() { let path = PathBuf::from(path_str); let iter = du(&path, Stat::new(&path), options_arc.clone(), 0).into_iter(); let (_, len) = iter.size_hint(); let len = len.unwrap(); for (index, stat) in iter.enumerate() { let size = match matches.opt_present("apparent-size") { true => stat.nlink * stat.size, // C's stat is such that each block is assume to be 512 bytes // See: http://linux.die.net/man/2/stat false => stat.blocks * 512, }; if matches.opt_present("time") { let tm = { let (secs, nsecs) = { let time = match matches.opt_str("time") { Some(s) => match &s[..] { "accessed" => stat.accessed, "created" => stat.created, "modified" => stat.modified, _ => { show_error!("invalid argument'modified' for '--time' Valid arguments are: - 'accessed', 'created','modified' Try '{} --help' for more information.", NAME); return 1; } }, None => stat.modified }; ((time / 1000) as i64, (time % 1000 * 1000000) as i32) }; time::at(Timespec::new(secs, nsecs)) };
if!summarize || (summarize && index == len-1) { let time_str = tm.strftime(time_format_str).unwrap(); print!("{}\t{}\t{}{}", convert_size(size), time_str, stat.path.display(), line_separator); } } else { if!summarize || (summarize && index == len-1) { print!("{}\t{}{}", convert_size(size), stat.path.display(), line_separator); } } if options_arc.total && index == (len - 1) { // The last element will be the total size of the the path under // path_str. We add it to the grand total. grand_total += size; } } } if options_arc.total { print!("{}\ttotal", convert_size(grand_total)); print!("{}", line_separator); } 0 }
random_line_split
lib.rs
extern crate ratel; extern crate ratel_codegen; extern crate serde_json; extern crate wasm_bindgen; use wasm_bindgen::prelude::*; use ratel::error::{Error, ParseError}; fn format_errors(errors: Vec<Error>, source: &str) -> String { let error = errors .into_iter() .map(|err| { match err {
ParseError::UnexpectedToken { start, end, source: source.to_string() } } } }) .map(|err| format!("{}", err)) .collect::<Vec<String>>() .join("\n"); format!("Error: {}", error) } #[wasm_bindgen] pub fn transform(data: &str, minify: bool) -> String { match ratel::parse(&data) { Ok(module) => { ratel_codegen::codegen(&module, minify) }, Err(errors) => format_errors(errors, data) } } #[wasm_bindgen(js_name = generateAST)] pub fn generate_ast(data: &str, minify: bool) -> String { match ratel::parse(&data) { Ok(module) => { if minify { format!("{:?}", module.body()) } else { format!("{:#?}", module.body()) } }, Err(errors) => format_errors(errors, data) } } #[wasm_bindgen(js_name = generateASTEstree)] pub fn generate_ast_estree(data: &str, minify: bool) -> String { match ratel::parse(&data) { Ok(module) => { if minify { serde_json::to_string(&module).unwrap() } else { serde_json::to_string_pretty(&module).unwrap() } }, Err(errors) => format_errors(errors, data) } }
Error { start, end, .. } => {
random_line_split
lib.rs
extern crate ratel; extern crate ratel_codegen; extern crate serde_json; extern crate wasm_bindgen; use wasm_bindgen::prelude::*; use ratel::error::{Error, ParseError}; fn
(errors: Vec<Error>, source: &str) -> String { let error = errors .into_iter() .map(|err| { match err { Error { start, end,.. } => { ParseError::UnexpectedToken { start, end, source: source.to_string() } } } }) .map(|err| format!("{}", err)) .collect::<Vec<String>>() .join("\n"); format!("Error: {}", error) } #[wasm_bindgen] pub fn transform(data: &str, minify: bool) -> String { match ratel::parse(&data) { Ok(module) => { ratel_codegen::codegen(&module, minify) }, Err(errors) => format_errors(errors, data) } } #[wasm_bindgen(js_name = generateAST)] pub fn generate_ast(data: &str, minify: bool) -> String { match ratel::parse(&data) { Ok(module) => { if minify { format!("{:?}", module.body()) } else { format!("{:#?}", module.body()) } }, Err(errors) => format_errors(errors, data) } } #[wasm_bindgen(js_name = generateASTEstree)] pub fn generate_ast_estree(data: &str, minify: bool) -> String { match ratel::parse(&data) { Ok(module) => { if minify { serde_json::to_string(&module).unwrap() } else { serde_json::to_string_pretty(&module).unwrap() } }, Err(errors) => format_errors(errors, data) } }
format_errors
identifier_name
lib.rs
extern crate ratel; extern crate ratel_codegen; extern crate serde_json; extern crate wasm_bindgen; use wasm_bindgen::prelude::*; use ratel::error::{Error, ParseError}; fn format_errors(errors: Vec<Error>, source: &str) -> String
#[wasm_bindgen] pub fn transform(data: &str, minify: bool) -> String { match ratel::parse(&data) { Ok(module) => { ratel_codegen::codegen(&module, minify) }, Err(errors) => format_errors(errors, data) } } #[wasm_bindgen(js_name = generateAST)] pub fn generate_ast(data: &str, minify: bool) -> String { match ratel::parse(&data) { Ok(module) => { if minify { format!("{:?}", module.body()) } else { format!("{:#?}", module.body()) } }, Err(errors) => format_errors(errors, data) } } #[wasm_bindgen(js_name = generateASTEstree)] pub fn generate_ast_estree(data: &str, minify: bool) -> String { match ratel::parse(&data) { Ok(module) => { if minify { serde_json::to_string(&module).unwrap() } else { serde_json::to_string_pretty(&module).unwrap() } }, Err(errors) => format_errors(errors, data) } }
{ let error = errors .into_iter() .map(|err| { match err { Error { start, end, .. } => { ParseError::UnexpectedToken { start, end, source: source.to_string() } } } }) .map(|err| format!("{}", err)) .collect::<Vec<String>>() .join("\n"); format!("Error: {}", error) }
identifier_body
lib.rs
use ini::Ini; use ini::Properties; use postgres::config::Config; fn build_from_section(section: &Properties) -> Config { let mut username: Option<String> = None; let mut password: Option<String> = None; let mut builder = Config::new(); let mut options = String::new(); for (k,v) in section.iter() { match k { "host" => { builder.host(v); }, "hostaddr" => { builder.host(v); }, "port" => { builder.port(v.parse().unwrap()); }, "dbname" => { builder.dbname(v); }, "user" => username = Some(v.to_owned()), "password" => password = Some(v.to_owned()), _ => options += &format!("{}={} ", k, v), } } if!options.is_empty() { builder.options(&options); } if let Some(username) = username { builder.user(&username); } if let Some(password) = password { builder.password(&password); } builder } pub fn load_connect_params( service_name : &str ) -> Option<Config>
} None }
{ if let Ok(home) = std::env::var("HOME") { if let Ok(ini) = Ini::load_from_file(home + "/" + ".pg_service.conf") { if let Some(section) = ini.section(Some(service_name.clone())) { return Some(build_from_section(section)); } } } let confdir = std::env::var("PGSYSCONFDIR").unwrap_or("/etc/postgresql-common".into()); if let Ok(ini) = Ini::load_from_file(confdir + "/" + "pg_service.conf") { if let Some(section) = ini.section(Some(service_name)) { return Some(build_from_section(section)); }
identifier_body
lib.rs
use ini::Ini; use ini::Properties; use postgres::config::Config; fn build_from_section(section: &Properties) -> Config { let mut username: Option<String> = None; let mut password: Option<String> = None; let mut builder = Config::new(); let mut options = String::new(); for (k,v) in section.iter() { match k { "host" => { builder.host(v); }, "hostaddr" => { builder.host(v); }, "port" => { builder.port(v.parse().unwrap()); }, "dbname" => { builder.dbname(v); }, "user" => username = Some(v.to_owned()), "password" => password = Some(v.to_owned()), _ => options += &format!("{}={} ", k, v), } } if!options.is_empty() { builder.options(&options); } if let Some(username) = username { builder.user(&username); } if let Some(password) = password { builder.password(&password); } builder } pub fn load_connect_params( service_name : &str ) -> Option<Config> { if let Ok(home) = std::env::var("HOME") { if let Ok(ini) = Ini::load_from_file(home + "/" + ".pg_service.conf") { if let Some(section) = ini.section(Some(service_name.clone())) { return Some(build_from_section(section)); } } } let confdir = std::env::var("PGSYSCONFDIR").unwrap_or("/etc/postgresql-common".into()); if let Ok(ini) = Ini::load_from_file(confdir + "/" + "pg_service.conf") { if let Some(section) = ini.section(Some(service_name))
} None }
{ return Some(build_from_section(section)); }
conditional_block
lib.rs
use ini::Ini; use ini::Properties; use postgres::config::Config; fn
(section: &Properties) -> Config { let mut username: Option<String> = None; let mut password: Option<String> = None; let mut builder = Config::new(); let mut options = String::new(); for (k,v) in section.iter() { match k { "host" => { builder.host(v); }, "hostaddr" => { builder.host(v); }, "port" => { builder.port(v.parse().unwrap()); }, "dbname" => { builder.dbname(v); }, "user" => username = Some(v.to_owned()), "password" => password = Some(v.to_owned()), _ => options += &format!("{}={} ", k, v), } } if!options.is_empty() { builder.options(&options); } if let Some(username) = username { builder.user(&username); } if let Some(password) = password { builder.password(&password); } builder } pub fn load_connect_params( service_name : &str ) -> Option<Config> { if let Ok(home) = std::env::var("HOME") { if let Ok(ini) = Ini::load_from_file(home + "/" + ".pg_service.conf") { if let Some(section) = ini.section(Some(service_name.clone())) { return Some(build_from_section(section)); } } } let confdir = std::env::var("PGSYSCONFDIR").unwrap_or("/etc/postgresql-common".into()); if let Ok(ini) = Ini::load_from_file(confdir + "/" + "pg_service.conf") { if let Some(section) = ini.section(Some(service_name)) { return Some(build_from_section(section)); } } None }
build_from_section
identifier_name
lib.rs
use ini::Ini; use ini::Properties; use postgres::config::Config; fn build_from_section(section: &Properties) -> Config { let mut username: Option<String> = None; let mut password: Option<String> = None; let mut builder = Config::new(); let mut options = String::new(); for (k,v) in section.iter() { match k { "host" => { builder.host(v); }, "hostaddr" => { builder.host(v); }, "port" => { builder.port(v.parse().unwrap()); }, "dbname" => { builder.dbname(v); }, "user" => username = Some(v.to_owned()), "password" => password = Some(v.to_owned()), _ => options += &format!("{}={} ", k, v), } } if!options.is_empty() { builder.options(&options); } if let Some(username) = username { builder.user(&username); } if let Some(password) = password { builder.password(&password); } builder } pub fn load_connect_params( service_name : &str ) -> Option<Config> { if let Ok(home) = std::env::var("HOME") { if let Ok(ini) = Ini::load_from_file(home + "/" + ".pg_service.conf")
if let Some(section) = ini.section(Some(service_name.clone())) { return Some(build_from_section(section)); } } } let confdir = std::env::var("PGSYSCONFDIR").unwrap_or("/etc/postgresql-common".into()); if let Ok(ini) = Ini::load_from_file(confdir + "/" + "pg_service.conf") { if let Some(section) = ini.section(Some(service_name)) { return Some(build_from_section(section)); } } None }
{
random_line_split
main.rs
&[&img]).unwrap(); Ok(view) } // this abstraction is provided to get a slightly better API around // input handling /* TODO: input, blocked by `winit` pub struct InputHandler { key_map: HashMap<VirtualKeyCode, bool>, key_list: Vec<VirtualKeyCode> } impl InputHandler { pub fn new() -> InputHandler { InputHandler { key_map: HashMap::new(), key_list: Vec::new() } } pub fn update(& mut self, events: PollEventsIterator) { for event in events { match event { Event::KeyboardInput(ElementState::Pressed, _, key_opt) => { let pressed_key = key_opt.unwrap(); if self.key_map.contains_key(&pressed_key) { self.key_map.insert(pressed_key, true); } else { println!("unknown key {:?} pressed", key_opt); } }, Event::KeyboardInput(ElementState::Released, _, key_opt) => { let released_key = key_opt.unwrap(); if self.key_map.contains_key(&released_key) { self.key_map.insert(released_key, false); } }, _ => {} } } } pub fn watch(&mut self, key: VirtualKeyCode) { if self.key_map.contains_key(&key) { panic!("watching key that is already tracked"); } self.key_map.insert(key, false); self.key_list.push(key); } pub fn is_pressed(&self, key: VirtualKeyCode) -> bool { if self.key_map.contains_key(&key) == false { panic!("checking keydown for key that isn't being tracked"); } *self.key_map.get(&key).unwrap() } }*/ // Actual tilemap data that makes up the elements of the UBO. // NOTE: It may be a bug, but it appears that // [f32;2] won't work as UBO data. Possibly an issue with // binding generation gfx_defines!{ constant TileMapData { data: [f32; 4] = "data", } constant ProjectionStuff { model: [[f32; 4]; 4] = "u_Model", view: [[f32; 4]; 4] = "u_View", proj: [[f32; 4]; 4] = "u_Proj", } constant TilemapStuff { world_size: [f32; 4] = "u_WorldSize", tilesheet_size: [f32; 4] = "u_TilesheetSize", offsets: [f32; 2] = "u_TileOffsets", } vertex VertexData { pos: [f32; 3] = "a_Pos", buf_pos: [f32; 2] = "a_BufPos", } pipeline pipe { vbuf: gfx::VertexBuffer<VertexData> = (), projection_cb: gfx::ConstantBuffer<ProjectionStuff> = "b_VsLocals", // tilemap stuff tilemap: gfx::ConstantBuffer<TileMapData> = "b_TileMap", tilemap_cb: gfx::ConstantBuffer<TilemapStuff> = "b_PsLocals", tilesheet: gfx::TextureSampler<[f32; 4]> = "t_TileSheet", // output out_color: gfx::RenderTarget<ColorFormat> = "Target0", out_depth: gfx::DepthTarget<DepthFormat> = gfx::preset::depth::LESS_EQUAL_WRITE, } } impl TileMapData { pub fn new_empty() -> TileMapData { TileMapData { data: [0.0, 0.0, 0.0, 0.0] } } pub fn new(data: [f32; 4]) -> TileMapData { TileMapData { data: data } } } // Abstracts the plane mesh and uniform data // Also holds a Vec<TileMapData> as a working data // set for consumers pub struct TileMapPlane<R> where R: gfx::Resources { pub params: pipe::Data<R>, pub slice: gfx::Slice<R>, proj_stuff: ProjectionStuff, proj_dirty: bool, tm_stuff: TilemapStuff, tm_dirty: bool, pub data: Vec<TileMapData>, } impl<R> TileMapPlane<R> where R: gfx::Resources { pub fn new<F>(factory: &mut F, width: usize, height: usize, tile_size: usize, main_color: gfx::handle::RenderTargetView<R, ColorFormat>, main_depth: gfx::handle::DepthStencilView<R, DepthFormat>, aspect_ratio: f32) -> TileMapPlane<R> where F: gfx::Factory<R> { // charmap info let half_width = (tile_size * width) / 2; let half_height = (tile_size * height) / 2; let total_size = width*height; // tilesheet info let tilesheet_bytes = &include_bytes!("scifitiles-sheet_0.png")[..]; let tilesheet_width = 14; let tilesheet_height = 9; let tilesheet_tilesize = 32; let tilesheet_total_width = tilesheet_width * tilesheet_tilesize; let tilesheet_total_height = tilesheet_height * tilesheet_tilesize; // set up vertex data let plane = Plane::subdivide(width, width); // law out the vertices of the plane slice based on the configured tile size information, // setting the a_BufPos vertex data for the vertex shader (that ultimate gets passed through // to the frag shader as a varying, used to determine the "current tile" and the frag's offset, // which is used to calculate the displayed frag color) let vertex_data: Vec<VertexData> = plane.shared_vertex_iter() .map(|(raw_x, raw_y)| { let vertex_x = half_width as f32 * raw_x; let vertex_y = half_height as f32 * raw_y; let u_pos = (1.0 + raw_x) / 2.0; let v_pos = (1.0 + raw_y) / 2.0; let tilemap_x = (u_pos * width as f32).floor(); let tilemap_y = (v_pos * height as f32).floor(); VertexData { pos: [vertex_x, vertex_y, 0.0], buf_pos: [tilemap_x as f32, tilemap_y as f32] } }) .collect(); let index_data: Vec<u32> = plane.indexed_polygon_iter() .triangulate() .vertices() .map(|i| i as u32) .collect(); let (vbuf, slice) = factory.create_vertex_buffer_with_slice(&vertex_data, &index_data[..]); let tile_texture = load_texture(factory, tilesheet_bytes).unwrap(); let params = pipe::Data { vbuf: vbuf, projection_cb: factory.create_constant_buffer(1), tilemap: factory.create_constant_buffer(TILEMAP_BUF_LENGTH), tilemap_cb: factory.create_constant_buffer(1), tilesheet: (tile_texture, factory.create_sampler_linear()), out_color: main_color, out_depth: main_depth, }; let mut charmap_data = Vec::with_capacity(total_size); for _ in 0..total_size { charmap_data.push(TileMapData::new_empty()); } let view: AffineMatrix3<f32> = Transform::look_at( Point3::new(0.0, 0.0, 800.0), Point3::new(0.0, 0.0, 0.0), Vector3::unit_y(), ); TileMapPlane { slice: slice, params: params, proj_stuff: ProjectionStuff { model: Matrix4::identity().into(), view: view.mat.into(), proj: cgmath::perspective(cgmath::deg(60.0f32), aspect_ratio, 0.1, 4000.0).into(), }, proj_dirty: true, tm_stuff: TilemapStuff { world_size: [width as f32, height as f32, tile_size as f32, 0.0], tilesheet_size: [tilesheet_width as f32, tilesheet_height as f32, tilesheet_total_width as f32, tilesheet_total_height as f32], offsets: [0.0, 0.0], }, tm_dirty: true, data: charmap_data, } } fn prepare_buffers<C>(&mut self, encoder: &mut gfx::Encoder<R, C>, update_data: bool) where C: gfx::CommandBuffer<R> { if update_data { encoder.update_buffer(&self.params.tilemap, &self.data, 0).unwrap(); } if self.proj_dirty { encoder.update_constant_buffer(&self.params.projection_cb, &self.proj_stuff); self.proj_dirty = false; } if self.tm_dirty { encoder.update_constant_buffer(&self.params.tilemap_cb, &self.tm_stuff); self.tm_dirty = false; } } fn clear<C>(&self, encoder: &mut gfx::Encoder<R, C>) where C: gfx::CommandBuffer<R> { encoder.clear(&self.params.out_color, [16.0 / 256.0, 14.0 / 256.0, 22.0 / 256.0, 1.0]); encoder.clear_depth(&self.params.out_depth, 1.0); } pub fn update_view(&mut self, view: &AffineMatrix3<f32>) { self.proj_stuff.view = view.mat.into(); self.proj_dirty = true; } pub fn update_x_offset(&mut self, amt: f32) { self.tm_stuff.offsets[0] = amt; self.tm_dirty = true; } pub fn update_y_offset(&mut self, amt: f32) { self.tm_stuff.offsets[1] = amt; self.tm_dirty = true; } } // Encapsulates the TileMapPlane and holds state for the current // visible set of tiles. Is responsible for updating the UBO // within the TileMapData when the visible set of tiles changes pub struct TileMap<R> where R: gfx::Resources { pub tiles: Vec<TileMapData>, pso: gfx::PipelineState<R, pipe::Meta>, tilemap_plane: TileMapPlane<R>, tile_size: f32, tilemap_size: [usize; 2], charmap_size: [usize; 2], limit_coords: [usize; 2], focus_coords: [usize; 2], focus_dirty: bool, } impl<R: gfx::Resources> TileMap<R> { pub fn set_focus(&mut self, focus: [usize; 2]) { if focus[0] <= self.limit_coords[0] && focus[1] <= self.limit_coords[1] { self.focus_coords = focus; let mut charmap_ypos = 0; for ypos in self.focus_coords[1].. self.focus_coords[1]+self.charmap_size[1] { let mut charmap_xpos = 0; for xpos in self.focus_coords[0].. self.focus_coords[0]+self.charmap_size[0] { let tile_idx = (ypos * self.tilemap_size[0]) + xpos; let charmap_idx = (charmap_ypos * self.charmap_size[0]) + charmap_xpos; self.tilemap_plane.data[charmap_idx] = self.tiles[tile_idx]; charmap_xpos += 1; } charmap_ypos += 1; } self.focus_dirty = true; } else { panic!("tried to set focus to {:?} with tilemap_size of {:?}", focus, self.tilemap_size); } } pub fn apply_x_offset(&mut self, offset_amt: f32) { let mut new_offset = self.tilemap_plane.tm_stuff.offsets[0] + offset_amt; let curr_focus = self.focus_coords; let new_x = if new_offset < 0.0 { // move down if self.focus_coords[0] == 0 { new_offset = 0.0; 0 } else { new_offset = self.tile_size + new_offset as f32; self.focus_coords[0] - 1 } } else if self.focus_coords[0] == self.limit_coords[0] { // at top, no more offset new_offset = 0.0; self.focus_coords[0] } else if new_offset >= self.tile_size { new_offset = new_offset - self.tile_size as f32; self.focus_coords[0] + 1 } else { // no move self.focus_coords[0] }; if new_x!= self.focus_coords[0] { self.set_focus([new_x, curr_focus[1]]); } self.tilemap_plane.update_x_offset(new_offset); } pub fn apply_y_offset(&mut self, offset_amt: f32) { let mut new_offset = self.tilemap_plane.tm_stuff.offsets[1] + offset_amt; let curr_focus = self.focus_coords; let new_y = if new_offset < 0.0 { // move down if self.focus_coords[1] == 0 { new_offset = 0.0; 0 } else { new_offset = self.tile_size + new_offset as f32; self.focus_coords[1] - 1 } } else if self.focus_coords[1] == (self.tilemap_size[1] - self.charmap_size[1]) { // at top, no more offset new_offset = 0.0; self.focus_coords[1] } else if new_offset >= self.tile_size { new_offset = new_offset - self.tile_size as f32; self.focus_coords[1] + 1 } else { // no move self.focus_coords[1] }; if new_y!= self.focus_coords[1] { self.set_focus([curr_focus[0], new_y]); } self.tilemap_plane.update_y_offset(new_offset); } fn calc_idx(&self, xpos: usize, ypos: usize) -> usize
pub fn set_tile(&mut self, xpos: usize, ypos: usize, data: [f32; 4]) { let idx = self.calc_idx(xpos, ypos); self.tiles[idx] = TileMapData::new(data); } } fn populate_tilemap<R>(tilemap: &mut TileMap<R>, tilemap_size: [usize; 2]) where R: gfx::Resources { // paper in with dummy data for ypos in 0.. tilemap_size[1] { for xpos in 0.. tilemap_size[0] { tilemap.set_tile(xpos, ypos, [1.0, 7.0, 0.0, 0.0]); } } tilemap.set_tile(1,3,[5.0, 0.0, 0.0, 0.0]); tilemap.set_tile(2,3,[6.0, 0.0, 0.0, 0.0]); tilemap.set_tile(3,3,[7.0, 0.0, 0.0, 0.0]); tilemap.set_tile(1,2,[5.0, 1.0, 0.0, 0.0]); tilemap.set_tile(2,2,[4.0, 0.0, 0.0, 0.0]); tilemap.set_tile(3,2,[11.0, 2.0, 0.0, 0.0]); tilemap.set_tile(1,1,[5.0, 2.0, 0.0, 0.0]); tilemap.set_tile(2,1,[6.0, 2.0, 0.0, 0.0]); tilemap.set_tile(3,1,[7.0, 2.0, 0.0, 0.0]); tilemap.set_tile(1,0,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(2,0,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(3,0,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(4,2,[4.0, 2.0, 0.0, 0.0]); tilemap.set_tile(5,2,[4.0, 2.0, 0.0, 0.0]); tilemap.set_tile(6,2,[11.0, 1.0, 0.0, 0.0]); tilemap.set_tile(4,1,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(5,1,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(6,1,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(6,3,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,4,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,5,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,6,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,7,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(5,10,[5.0, 0.0, 0.0, 0.0]); tilemap.set_tile(7,10,[7.0, 0.0, 0.0, 0.0]); tilemap.set_tile(5,9,[5.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,9,[6.0, 1.0, 0.0, 0.0]); tilemap.set_tile(7,9,[7.0, 1.0, 0.0, 0.0]); tilemap.set_tile(5,8,[5.0, 2.0, 0.0, 0.0]); tilemap.set_tile(6,8,[8.0, 2.0, 0.0, 0.0]); tilemap.set_tile(7,8,[7.0, 2.0, 0.0, 0.0]); tilemap.set_tile(5,7,[2.0, 1.0, 0.0, 0.0]); tilemap.set_tile(7,7,[2.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,10,[2.0, 3.0, 0.0, 0.0]); tilemap.set_tile(6,11,[2.0, 2.0, 0.0, 0.0]); } impl<R: gfx::Resources> gfx_app::Application<R> for TileMap<R> { fn new<F: gfx::Factory<R>>(mut factory: F, init: gfx_app::Init<R>) -> Self { use gfx::traits::FactoryExt; let vs = gfx_app::shade::Source { glsl_150: include_bytes!("shader/tilemap_150.glslv"), hlsl_40: include_bytes!("data/vertex.fx"), .. gfx_app::shade::Source::empty() }; let ps = gfx_app::shade::Source { glsl_150: include_bytes!("shader/tilemap_150.glslf"), hlsl_40: include_bytes!("data/pixel.fx"), .. gfx_app::shade::Source::empty() }; // set up charmap plane and configure its tiles let tilemap_size = [24, 24]; let charmap_size = [16, 16]; let tile_size = 32; let mut tiles = Vec::new(); for _ in 0.. tilemap_size[0]*tilemap_size[1] { tiles.push(TileMapData::new_empty()); } // TODO: should probably check that charmap is smaller than tilemap let mut tm = TileMap { tiles: tiles, pso: factory.create_pipeline_simple( vs.select(init.backend).unwrap(), ps.select(init.backend).unwrap(), pipe::new() ).unwrap(), tilemap_plane: TileMapPlane::new(&mut factory, charmap_size[0], charmap_size[1], tile_size, init.color, init.depth, init.aspect_ratio), tile_size: tile_size as f32, tilemap_size: tilemap_size, charmap_size: charmap_size, limit_coords: [tilemap_size[0] - charmap_size[0], tilemap_size[1] - charmap_size[
{ (ypos * self.tilemap_size[0]) + xpos }
identifier_body
main.rs
, &[&img]).unwrap(); Ok(view) } // this abstraction is provided to get a slightly better API around // input handling /* TODO: input, blocked by `winit` pub struct InputHandler { key_map: HashMap<VirtualKeyCode, bool>, key_list: Vec<VirtualKeyCode> } impl InputHandler { pub fn new() -> InputHandler { InputHandler { key_map: HashMap::new(), key_list: Vec::new() } } pub fn update(& mut self, events: PollEventsIterator) { for event in events { match event { Event::KeyboardInput(ElementState::Pressed, _, key_opt) => { let pressed_key = key_opt.unwrap(); if self.key_map.contains_key(&pressed_key) { self.key_map.insert(pressed_key, true); } else { println!("unknown key {:?} pressed", key_opt); } }, Event::KeyboardInput(ElementState::Released, _, key_opt) => { let released_key = key_opt.unwrap(); if self.key_map.contains_key(&released_key) { self.key_map.insert(released_key, false); } }, _ => {} } } } pub fn watch(&mut self, key: VirtualKeyCode) { if self.key_map.contains_key(&key) { panic!("watching key that is already tracked"); } self.key_map.insert(key, false); self.key_list.push(key); } pub fn is_pressed(&self, key: VirtualKeyCode) -> bool { if self.key_map.contains_key(&key) == false { panic!("checking keydown for key that isn't being tracked"); } *self.key_map.get(&key).unwrap() } }*/ // Actual tilemap data that makes up the elements of the UBO. // NOTE: It may be a bug, but it appears that // [f32;2] won't work as UBO data. Possibly an issue with // binding generation gfx_defines!{ constant TileMapData { data: [f32; 4] = "data", } constant ProjectionStuff { model: [[f32; 4]; 4] = "u_Model", view: [[f32; 4]; 4] = "u_View", proj: [[f32; 4]; 4] = "u_Proj", } constant TilemapStuff { world_size: [f32; 4] = "u_WorldSize", tilesheet_size: [f32; 4] = "u_TilesheetSize", offsets: [f32; 2] = "u_TileOffsets", } vertex VertexData { pos: [f32; 3] = "a_Pos", buf_pos: [f32; 2] = "a_BufPos", } pipeline pipe { vbuf: gfx::VertexBuffer<VertexData> = (), projection_cb: gfx::ConstantBuffer<ProjectionStuff> = "b_VsLocals", // tilemap stuff tilemap: gfx::ConstantBuffer<TileMapData> = "b_TileMap", tilemap_cb: gfx::ConstantBuffer<TilemapStuff> = "b_PsLocals", tilesheet: gfx::TextureSampler<[f32; 4]> = "t_TileSheet", // output out_color: gfx::RenderTarget<ColorFormat> = "Target0", out_depth: gfx::DepthTarget<DepthFormat> = gfx::preset::depth::LESS_EQUAL_WRITE, } } impl TileMapData { pub fn new_empty() -> TileMapData { TileMapData { data: [0.0, 0.0, 0.0, 0.0] } } pub fn new(data: [f32; 4]) -> TileMapData { TileMapData { data: data } } } // Abstracts the plane mesh and uniform data // Also holds a Vec<TileMapData> as a working data // set for consumers pub struct TileMapPlane<R> where R: gfx::Resources { pub params: pipe::Data<R>, pub slice: gfx::Slice<R>, proj_stuff: ProjectionStuff, proj_dirty: bool, tm_stuff: TilemapStuff, tm_dirty: bool, pub data: Vec<TileMapData>, } impl<R> TileMapPlane<R> where R: gfx::Resources { pub fn new<F>(factory: &mut F, width: usize, height: usize, tile_size: usize, main_color: gfx::handle::RenderTargetView<R, ColorFormat>, main_depth: gfx::handle::DepthStencilView<R, DepthFormat>, aspect_ratio: f32) -> TileMapPlane<R> where F: gfx::Factory<R> { // charmap info let half_width = (tile_size * width) / 2; let half_height = (tile_size * height) / 2; let total_size = width*height; // tilesheet info let tilesheet_bytes = &include_bytes!("scifitiles-sheet_0.png")[..]; let tilesheet_width = 14; let tilesheet_height = 9; let tilesheet_tilesize = 32; let tilesheet_total_width = tilesheet_width * tilesheet_tilesize; let tilesheet_total_height = tilesheet_height * tilesheet_tilesize; // set up vertex data let plane = Plane::subdivide(width, width); // law out the vertices of the plane slice based on the configured tile size information, // setting the a_BufPos vertex data for the vertex shader (that ultimate gets passed through // to the frag shader as a varying, used to determine the "current tile" and the frag's offset, // which is used to calculate the displayed frag color) let vertex_data: Vec<VertexData> = plane.shared_vertex_iter() .map(|(raw_x, raw_y)| { let vertex_x = half_width as f32 * raw_x; let vertex_y = half_height as f32 * raw_y; let u_pos = (1.0 + raw_x) / 2.0; let v_pos = (1.0 + raw_y) / 2.0; let tilemap_x = (u_pos * width as f32).floor(); let tilemap_y = (v_pos * height as f32).floor();
pos: [vertex_x, vertex_y, 0.0], buf_pos: [tilemap_x as f32, tilemap_y as f32] } }) .collect(); let index_data: Vec<u32> = plane.indexed_polygon_iter() .triangulate() .vertices() .map(|i| i as u32) .collect(); let (vbuf, slice) = factory.create_vertex_buffer_with_slice(&vertex_data, &index_data[..]); let tile_texture = load_texture(factory, tilesheet_bytes).unwrap(); let params = pipe::Data { vbuf: vbuf, projection_cb: factory.create_constant_buffer(1), tilemap: factory.create_constant_buffer(TILEMAP_BUF_LENGTH), tilemap_cb: factory.create_constant_buffer(1), tilesheet: (tile_texture, factory.create_sampler_linear()), out_color: main_color, out_depth: main_depth, }; let mut charmap_data = Vec::with_capacity(total_size); for _ in 0..total_size { charmap_data.push(TileMapData::new_empty()); } let view: AffineMatrix3<f32> = Transform::look_at( Point3::new(0.0, 0.0, 800.0), Point3::new(0.0, 0.0, 0.0), Vector3::unit_y(), ); TileMapPlane { slice: slice, params: params, proj_stuff: ProjectionStuff { model: Matrix4::identity().into(), view: view.mat.into(), proj: cgmath::perspective(cgmath::deg(60.0f32), aspect_ratio, 0.1, 4000.0).into(), }, proj_dirty: true, tm_stuff: TilemapStuff { world_size: [width as f32, height as f32, tile_size as f32, 0.0], tilesheet_size: [tilesheet_width as f32, tilesheet_height as f32, tilesheet_total_width as f32, tilesheet_total_height as f32], offsets: [0.0, 0.0], }, tm_dirty: true, data: charmap_data, } } fn prepare_buffers<C>(&mut self, encoder: &mut gfx::Encoder<R, C>, update_data: bool) where C: gfx::CommandBuffer<R> { if update_data { encoder.update_buffer(&self.params.tilemap, &self.data, 0).unwrap(); } if self.proj_dirty { encoder.update_constant_buffer(&self.params.projection_cb, &self.proj_stuff); self.proj_dirty = false; } if self.tm_dirty { encoder.update_constant_buffer(&self.params.tilemap_cb, &self.tm_stuff); self.tm_dirty = false; } } fn clear<C>(&self, encoder: &mut gfx::Encoder<R, C>) where C: gfx::CommandBuffer<R> { encoder.clear(&self.params.out_color, [16.0 / 256.0, 14.0 / 256.0, 22.0 / 256.0, 1.0]); encoder.clear_depth(&self.params.out_depth, 1.0); } pub fn update_view(&mut self, view: &AffineMatrix3<f32>) { self.proj_stuff.view = view.mat.into(); self.proj_dirty = true; } pub fn update_x_offset(&mut self, amt: f32) { self.tm_stuff.offsets[0] = amt; self.tm_dirty = true; } pub fn update_y_offset(&mut self, amt: f32) { self.tm_stuff.offsets[1] = amt; self.tm_dirty = true; } } // Encapsulates the TileMapPlane and holds state for the current // visible set of tiles. Is responsible for updating the UBO // within the TileMapData when the visible set of tiles changes pub struct TileMap<R> where R: gfx::Resources { pub tiles: Vec<TileMapData>, pso: gfx::PipelineState<R, pipe::Meta>, tilemap_plane: TileMapPlane<R>, tile_size: f32, tilemap_size: [usize; 2], charmap_size: [usize; 2], limit_coords: [usize; 2], focus_coords: [usize; 2], focus_dirty: bool, } impl<R: gfx::Resources> TileMap<R> { pub fn set_focus(&mut self, focus: [usize; 2]) { if focus[0] <= self.limit_coords[0] && focus[1] <= self.limit_coords[1] { self.focus_coords = focus; let mut charmap_ypos = 0; for ypos in self.focus_coords[1].. self.focus_coords[1]+self.charmap_size[1] { let mut charmap_xpos = 0; for xpos in self.focus_coords[0].. self.focus_coords[0]+self.charmap_size[0] { let tile_idx = (ypos * self.tilemap_size[0]) + xpos; let charmap_idx = (charmap_ypos * self.charmap_size[0]) + charmap_xpos; self.tilemap_plane.data[charmap_idx] = self.tiles[tile_idx]; charmap_xpos += 1; } charmap_ypos += 1; } self.focus_dirty = true; } else { panic!("tried to set focus to {:?} with tilemap_size of {:?}", focus, self.tilemap_size); } } pub fn apply_x_offset(&mut self, offset_amt: f32) { let mut new_offset = self.tilemap_plane.tm_stuff.offsets[0] + offset_amt; let curr_focus = self.focus_coords; let new_x = if new_offset < 0.0 { // move down if self.focus_coords[0] == 0 { new_offset = 0.0; 0 } else { new_offset = self.tile_size + new_offset as f32; self.focus_coords[0] - 1 } } else if self.focus_coords[0] == self.limit_coords[0] { // at top, no more offset new_offset = 0.0; self.focus_coords[0] } else if new_offset >= self.tile_size { new_offset = new_offset - self.tile_size as f32; self.focus_coords[0] + 1 } else { // no move self.focus_coords[0] }; if new_x!= self.focus_coords[0] { self.set_focus([new_x, curr_focus[1]]); } self.tilemap_plane.update_x_offset(new_offset); } pub fn apply_y_offset(&mut self, offset_amt: f32) { let mut new_offset = self.tilemap_plane.tm_stuff.offsets[1] + offset_amt; let curr_focus = self.focus_coords; let new_y = if new_offset < 0.0 { // move down if self.focus_coords[1] == 0 { new_offset = 0.0; 0 } else { new_offset = self.tile_size + new_offset as f32; self.focus_coords[1] - 1 } } else if self.focus_coords[1] == (self.tilemap_size[1] - self.charmap_size[1]) { // at top, no more offset new_offset = 0.0; self.focus_coords[1] } else if new_offset >= self.tile_size { new_offset = new_offset - self.tile_size as f32; self.focus_coords[1] + 1 } else { // no move self.focus_coords[1] }; if new_y!= self.focus_coords[1] { self.set_focus([curr_focus[0], new_y]); } self.tilemap_plane.update_y_offset(new_offset); } fn calc_idx(&self, xpos: usize, ypos: usize) -> usize { (ypos * self.tilemap_size[0]) + xpos } pub fn set_tile(&mut self, xpos: usize, ypos: usize, data: [f32; 4]) { let idx = self.calc_idx(xpos, ypos); self.tiles[idx] = TileMapData::new(data); } } fn populate_tilemap<R>(tilemap: &mut TileMap<R>, tilemap_size: [usize; 2]) where R: gfx::Resources { // paper in with dummy data for ypos in 0.. tilemap_size[1] { for xpos in 0.. tilemap_size[0] { tilemap.set_tile(xpos, ypos, [1.0, 7.0, 0.0, 0.0]); } } tilemap.set_tile(1,3,[5.0, 0.0, 0.0, 0.0]); tilemap.set_tile(2,3,[6.0, 0.0, 0.0, 0.0]); tilemap.set_tile(3,3,[7.0, 0.0, 0.0, 0.0]); tilemap.set_tile(1,2,[5.0, 1.0, 0.0, 0.0]); tilemap.set_tile(2,2,[4.0, 0.0, 0.0, 0.0]); tilemap.set_tile(3,2,[11.0, 2.0, 0.0, 0.0]); tilemap.set_tile(1,1,[5.0, 2.0, 0.0, 0.0]); tilemap.set_tile(2,1,[6.0, 2.0, 0.0, 0.0]); tilemap.set_tile(3,1,[7.0, 2.0, 0.0, 0.0]); tilemap.set_tile(1,0,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(2,0,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(3,0,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(4,2,[4.0, 2.0, 0.0, 0.0]); tilemap.set_tile(5,2,[4.0, 2.0, 0.0, 0.0]); tilemap.set_tile(6,2,[11.0, 1.0, 0.0, 0.0]); tilemap.set_tile(4,1,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(5,1,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(6,1,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(6,3,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,4,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,5,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,6,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,7,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(5,10,[5.0, 0.0, 0.0, 0.0]); tilemap.set_tile(7,10,[7.0, 0.0, 0.0, 0.0]); tilemap.set_tile(5,9,[5.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,9,[6.0, 1.0, 0.0, 0.0]); tilemap.set_tile(7,9,[7.0, 1.0, 0.0, 0.0]); tilemap.set_tile(5,8,[5.0, 2.0, 0.0, 0.0]); tilemap.set_tile(6,8,[8.0, 2.0, 0.0, 0.0]); tilemap.set_tile(7,8,[7.0, 2.0, 0.0, 0.0]); tilemap.set_tile(5,7,[2.0, 1.0, 0.0, 0.0]); tilemap.set_tile(7,7,[2.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,10,[2.0, 3.0, 0.0, 0.0]); tilemap.set_tile(6,11,[2.0, 2.0, 0.0, 0.0]); } impl<R: gfx::Resources> gfx_app::Application<R> for TileMap<R> { fn new<F: gfx::Factory<R>>(mut factory: F, init: gfx_app::Init<R>) -> Self { use gfx::traits::FactoryExt; let vs = gfx_app::shade::Source { glsl_150: include_bytes!("shader/tilemap_150.glslv"), hlsl_40: include_bytes!("data/vertex.fx"), .. gfx_app::shade::Source::empty() }; let ps = gfx_app::shade::Source { glsl_150: include_bytes!("shader/tilemap_150.glslf"), hlsl_40: include_bytes!("data/pixel.fx"), .. gfx_app::shade::Source::empty() }; // set up charmap plane and configure its tiles let tilemap_size = [24, 24]; let charmap_size = [16, 16]; let tile_size = 32; let mut tiles = Vec::new(); for _ in 0.. tilemap_size[0]*tilemap_size[1] { tiles.push(TileMapData::new_empty()); } // TODO: should probably check that charmap is smaller than tilemap let mut tm = TileMap { tiles: tiles, pso: factory.create_pipeline_simple( vs.select(init.backend).unwrap(), ps.select(init.backend).unwrap(), pipe::new() ).unwrap(), tilemap_plane: TileMapPlane::new(&mut factory, charmap_size[0], charmap_size[1], tile_size, init.color, init.depth, init.aspect_ratio), tile_size: tile_size as f32, tilemap_size: tilemap_size, charmap_size: charmap_size, limit_coords: [tilemap_size[0] - charmap_size[0], tilemap_size[1] - charmap_size[1]],
VertexData {
random_line_split
main.rs
&[&img]).unwrap(); Ok(view) } // this abstraction is provided to get a slightly better API around // input handling /* TODO: input, blocked by `winit` pub struct InputHandler { key_map: HashMap<VirtualKeyCode, bool>, key_list: Vec<VirtualKeyCode> } impl InputHandler { pub fn new() -> InputHandler { InputHandler { key_map: HashMap::new(), key_list: Vec::new() } } pub fn update(& mut self, events: PollEventsIterator) { for event in events { match event { Event::KeyboardInput(ElementState::Pressed, _, key_opt) => { let pressed_key = key_opt.unwrap(); if self.key_map.contains_key(&pressed_key) { self.key_map.insert(pressed_key, true); } else { println!("unknown key {:?} pressed", key_opt); } }, Event::KeyboardInput(ElementState::Released, _, key_opt) => { let released_key = key_opt.unwrap(); if self.key_map.contains_key(&released_key) { self.key_map.insert(released_key, false); } }, _ => {} } } } pub fn watch(&mut self, key: VirtualKeyCode) { if self.key_map.contains_key(&key) { panic!("watching key that is already tracked"); } self.key_map.insert(key, false); self.key_list.push(key); } pub fn is_pressed(&self, key: VirtualKeyCode) -> bool { if self.key_map.contains_key(&key) == false { panic!("checking keydown for key that isn't being tracked"); } *self.key_map.get(&key).unwrap() } }*/ // Actual tilemap data that makes up the elements of the UBO. // NOTE: It may be a bug, but it appears that // [f32;2] won't work as UBO data. Possibly an issue with // binding generation gfx_defines!{ constant TileMapData { data: [f32; 4] = "data", } constant ProjectionStuff { model: [[f32; 4]; 4] = "u_Model", view: [[f32; 4]; 4] = "u_View", proj: [[f32; 4]; 4] = "u_Proj", } constant TilemapStuff { world_size: [f32; 4] = "u_WorldSize", tilesheet_size: [f32; 4] = "u_TilesheetSize", offsets: [f32; 2] = "u_TileOffsets", } vertex VertexData { pos: [f32; 3] = "a_Pos", buf_pos: [f32; 2] = "a_BufPos", } pipeline pipe { vbuf: gfx::VertexBuffer<VertexData> = (), projection_cb: gfx::ConstantBuffer<ProjectionStuff> = "b_VsLocals", // tilemap stuff tilemap: gfx::ConstantBuffer<TileMapData> = "b_TileMap", tilemap_cb: gfx::ConstantBuffer<TilemapStuff> = "b_PsLocals", tilesheet: gfx::TextureSampler<[f32; 4]> = "t_TileSheet", // output out_color: gfx::RenderTarget<ColorFormat> = "Target0", out_depth: gfx::DepthTarget<DepthFormat> = gfx::preset::depth::LESS_EQUAL_WRITE, } } impl TileMapData { pub fn new_empty() -> TileMapData { TileMapData { data: [0.0, 0.0, 0.0, 0.0] } } pub fn new(data: [f32; 4]) -> TileMapData { TileMapData { data: data } } } // Abstracts the plane mesh and uniform data // Also holds a Vec<TileMapData> as a working data // set for consumers pub struct TileMapPlane<R> where R: gfx::Resources { pub params: pipe::Data<R>, pub slice: gfx::Slice<R>, proj_stuff: ProjectionStuff, proj_dirty: bool, tm_stuff: TilemapStuff, tm_dirty: bool, pub data: Vec<TileMapData>, } impl<R> TileMapPlane<R> where R: gfx::Resources { pub fn new<F>(factory: &mut F, width: usize, height: usize, tile_size: usize, main_color: gfx::handle::RenderTargetView<R, ColorFormat>, main_depth: gfx::handle::DepthStencilView<R, DepthFormat>, aspect_ratio: f32) -> TileMapPlane<R> where F: gfx::Factory<R> { // charmap info let half_width = (tile_size * width) / 2; let half_height = (tile_size * height) / 2; let total_size = width*height; // tilesheet info let tilesheet_bytes = &include_bytes!("scifitiles-sheet_0.png")[..]; let tilesheet_width = 14; let tilesheet_height = 9; let tilesheet_tilesize = 32; let tilesheet_total_width = tilesheet_width * tilesheet_tilesize; let tilesheet_total_height = tilesheet_height * tilesheet_tilesize; // set up vertex data let plane = Plane::subdivide(width, width); // law out the vertices of the plane slice based on the configured tile size information, // setting the a_BufPos vertex data for the vertex shader (that ultimate gets passed through // to the frag shader as a varying, used to determine the "current tile" and the frag's offset, // which is used to calculate the displayed frag color) let vertex_data: Vec<VertexData> = plane.shared_vertex_iter() .map(|(raw_x, raw_y)| { let vertex_x = half_width as f32 * raw_x; let vertex_y = half_height as f32 * raw_y; let u_pos = (1.0 + raw_x) / 2.0; let v_pos = (1.0 + raw_y) / 2.0; let tilemap_x = (u_pos * width as f32).floor(); let tilemap_y = (v_pos * height as f32).floor(); VertexData { pos: [vertex_x, vertex_y, 0.0], buf_pos: [tilemap_x as f32, tilemap_y as f32] } }) .collect(); let index_data: Vec<u32> = plane.indexed_polygon_iter() .triangulate() .vertices() .map(|i| i as u32) .collect(); let (vbuf, slice) = factory.create_vertex_buffer_with_slice(&vertex_data, &index_data[..]); let tile_texture = load_texture(factory, tilesheet_bytes).unwrap(); let params = pipe::Data { vbuf: vbuf, projection_cb: factory.create_constant_buffer(1), tilemap: factory.create_constant_buffer(TILEMAP_BUF_LENGTH), tilemap_cb: factory.create_constant_buffer(1), tilesheet: (tile_texture, factory.create_sampler_linear()), out_color: main_color, out_depth: main_depth, }; let mut charmap_data = Vec::with_capacity(total_size); for _ in 0..total_size { charmap_data.push(TileMapData::new_empty()); } let view: AffineMatrix3<f32> = Transform::look_at( Point3::new(0.0, 0.0, 800.0), Point3::new(0.0, 0.0, 0.0), Vector3::unit_y(), ); TileMapPlane { slice: slice, params: params, proj_stuff: ProjectionStuff { model: Matrix4::identity().into(), view: view.mat.into(), proj: cgmath::perspective(cgmath::deg(60.0f32), aspect_ratio, 0.1, 4000.0).into(), }, proj_dirty: true, tm_stuff: TilemapStuff { world_size: [width as f32, height as f32, tile_size as f32, 0.0], tilesheet_size: [tilesheet_width as f32, tilesheet_height as f32, tilesheet_total_width as f32, tilesheet_total_height as f32], offsets: [0.0, 0.0], }, tm_dirty: true, data: charmap_data, } } fn prepare_buffers<C>(&mut self, encoder: &mut gfx::Encoder<R, C>, update_data: bool) where C: gfx::CommandBuffer<R> { if update_data { encoder.update_buffer(&self.params.tilemap, &self.data, 0).unwrap(); } if self.proj_dirty { encoder.update_constant_buffer(&self.params.projection_cb, &self.proj_stuff); self.proj_dirty = false; } if self.tm_dirty { encoder.update_constant_buffer(&self.params.tilemap_cb, &self.tm_stuff); self.tm_dirty = false; } } fn clear<C>(&self, encoder: &mut gfx::Encoder<R, C>) where C: gfx::CommandBuffer<R> { encoder.clear(&self.params.out_color, [16.0 / 256.0, 14.0 / 256.0, 22.0 / 256.0, 1.0]); encoder.clear_depth(&self.params.out_depth, 1.0); } pub fn update_view(&mut self, view: &AffineMatrix3<f32>) { self.proj_stuff.view = view.mat.into(); self.proj_dirty = true; } pub fn update_x_offset(&mut self, amt: f32) { self.tm_stuff.offsets[0] = amt; self.tm_dirty = true; } pub fn update_y_offset(&mut self, amt: f32) { self.tm_stuff.offsets[1] = amt; self.tm_dirty = true; } } // Encapsulates the TileMapPlane and holds state for the current // visible set of tiles. Is responsible for updating the UBO // within the TileMapData when the visible set of tiles changes pub struct TileMap<R> where R: gfx::Resources { pub tiles: Vec<TileMapData>, pso: gfx::PipelineState<R, pipe::Meta>, tilemap_plane: TileMapPlane<R>, tile_size: f32, tilemap_size: [usize; 2], charmap_size: [usize; 2], limit_coords: [usize; 2], focus_coords: [usize; 2], focus_dirty: bool, } impl<R: gfx::Resources> TileMap<R> { pub fn set_focus(&mut self, focus: [usize; 2]) { if focus[0] <= self.limit_coords[0] && focus[1] <= self.limit_coords[1] { self.focus_coords = focus; let mut charmap_ypos = 0; for ypos in self.focus_coords[1].. self.focus_coords[1]+self.charmap_size[1] { let mut charmap_xpos = 0; for xpos in self.focus_coords[0].. self.focus_coords[0]+self.charmap_size[0] { let tile_idx = (ypos * self.tilemap_size[0]) + xpos; let charmap_idx = (charmap_ypos * self.charmap_size[0]) + charmap_xpos; self.tilemap_plane.data[charmap_idx] = self.tiles[tile_idx]; charmap_xpos += 1; } charmap_ypos += 1; } self.focus_dirty = true; } else { panic!("tried to set focus to {:?} with tilemap_size of {:?}", focus, self.tilemap_size); } } pub fn apply_x_offset(&mut self, offset_amt: f32) { let mut new_offset = self.tilemap_plane.tm_stuff.offsets[0] + offset_amt; let curr_focus = self.focus_coords; let new_x = if new_offset < 0.0 { // move down if self.focus_coords[0] == 0 { new_offset = 0.0; 0 } else { new_offset = self.tile_size + new_offset as f32; self.focus_coords[0] - 1 } } else if self.focus_coords[0] == self.limit_coords[0] { // at top, no more offset new_offset = 0.0; self.focus_coords[0] } else if new_offset >= self.tile_size { new_offset = new_offset - self.tile_size as f32; self.focus_coords[0] + 1 } else { // no move self.focus_coords[0] }; if new_x!= self.focus_coords[0] { self.set_focus([new_x, curr_focus[1]]); } self.tilemap_plane.update_x_offset(new_offset); } pub fn apply_y_offset(&mut self, offset_amt: f32) { let mut new_offset = self.tilemap_plane.tm_stuff.offsets[1] + offset_amt; let curr_focus = self.focus_coords; let new_y = if new_offset < 0.0 { // move down if self.focus_coords[1] == 0 { new_offset = 0.0; 0 } else { new_offset = self.tile_size + new_offset as f32; self.focus_coords[1] - 1 } } else if self.focus_coords[1] == (self.tilemap_size[1] - self.charmap_size[1]) { // at top, no more offset new_offset = 0.0; self.focus_coords[1] } else if new_offset >= self.tile_size { new_offset = new_offset - self.tile_size as f32; self.focus_coords[1] + 1 } else { // no move self.focus_coords[1] }; if new_y!= self.focus_coords[1] { self.set_focus([curr_focus[0], new_y]); } self.tilemap_plane.update_y_offset(new_offset); } fn calc_idx(&self, xpos: usize, ypos: usize) -> usize { (ypos * self.tilemap_size[0]) + xpos } pub fn
(&mut self, xpos: usize, ypos: usize, data: [f32; 4]) { let idx = self.calc_idx(xpos, ypos); self.tiles[idx] = TileMapData::new(data); } } fn populate_tilemap<R>(tilemap: &mut TileMap<R>, tilemap_size: [usize; 2]) where R: gfx::Resources { // paper in with dummy data for ypos in 0.. tilemap_size[1] { for xpos in 0.. tilemap_size[0] { tilemap.set_tile(xpos, ypos, [1.0, 7.0, 0.0, 0.0]); } } tilemap.set_tile(1,3,[5.0, 0.0, 0.0, 0.0]); tilemap.set_tile(2,3,[6.0, 0.0, 0.0, 0.0]); tilemap.set_tile(3,3,[7.0, 0.0, 0.0, 0.0]); tilemap.set_tile(1,2,[5.0, 1.0, 0.0, 0.0]); tilemap.set_tile(2,2,[4.0, 0.0, 0.0, 0.0]); tilemap.set_tile(3,2,[11.0, 2.0, 0.0, 0.0]); tilemap.set_tile(1,1,[5.0, 2.0, 0.0, 0.0]); tilemap.set_tile(2,1,[6.0, 2.0, 0.0, 0.0]); tilemap.set_tile(3,1,[7.0, 2.0, 0.0, 0.0]); tilemap.set_tile(1,0,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(2,0,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(3,0,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(4,2,[4.0, 2.0, 0.0, 0.0]); tilemap.set_tile(5,2,[4.0, 2.0, 0.0, 0.0]); tilemap.set_tile(6,2,[11.0, 1.0, 0.0, 0.0]); tilemap.set_tile(4,1,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(5,1,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(6,1,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(6,3,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,4,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,5,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,6,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,7,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(5,10,[5.0, 0.0, 0.0, 0.0]); tilemap.set_tile(7,10,[7.0, 0.0, 0.0, 0.0]); tilemap.set_tile(5,9,[5.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,9,[6.0, 1.0, 0.0, 0.0]); tilemap.set_tile(7,9,[7.0, 1.0, 0.0, 0.0]); tilemap.set_tile(5,8,[5.0, 2.0, 0.0, 0.0]); tilemap.set_tile(6,8,[8.0, 2.0, 0.0, 0.0]); tilemap.set_tile(7,8,[7.0, 2.0, 0.0, 0.0]); tilemap.set_tile(5,7,[2.0, 1.0, 0.0, 0.0]); tilemap.set_tile(7,7,[2.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,10,[2.0, 3.0, 0.0, 0.0]); tilemap.set_tile(6,11,[2.0, 2.0, 0.0, 0.0]); } impl<R: gfx::Resources> gfx_app::Application<R> for TileMap<R> { fn new<F: gfx::Factory<R>>(mut factory: F, init: gfx_app::Init<R>) -> Self { use gfx::traits::FactoryExt; let vs = gfx_app::shade::Source { glsl_150: include_bytes!("shader/tilemap_150.glslv"), hlsl_40: include_bytes!("data/vertex.fx"), .. gfx_app::shade::Source::empty() }; let ps = gfx_app::shade::Source { glsl_150: include_bytes!("shader/tilemap_150.glslf"), hlsl_40: include_bytes!("data/pixel.fx"), .. gfx_app::shade::Source::empty() }; // set up charmap plane and configure its tiles let tilemap_size = [24, 24]; let charmap_size = [16, 16]; let tile_size = 32; let mut tiles = Vec::new(); for _ in 0.. tilemap_size[0]*tilemap_size[1] { tiles.push(TileMapData::new_empty()); } // TODO: should probably check that charmap is smaller than tilemap let mut tm = TileMap { tiles: tiles, pso: factory.create_pipeline_simple( vs.select(init.backend).unwrap(), ps.select(init.backend).unwrap(), pipe::new() ).unwrap(), tilemap_plane: TileMapPlane::new(&mut factory, charmap_size[0], charmap_size[1], tile_size, init.color, init.depth, init.aspect_ratio), tile_size: tile_size as f32, tilemap_size: tilemap_size, charmap_size: charmap_size, limit_coords: [tilemap_size[0] - charmap_size[0], tilemap_size[1] - charmap_size[
set_tile
identifier_name
main.rs
&[&img]).unwrap(); Ok(view) } // this abstraction is provided to get a slightly better API around // input handling /* TODO: input, blocked by `winit` pub struct InputHandler { key_map: HashMap<VirtualKeyCode, bool>, key_list: Vec<VirtualKeyCode> } impl InputHandler { pub fn new() -> InputHandler { InputHandler { key_map: HashMap::new(), key_list: Vec::new() } } pub fn update(& mut self, events: PollEventsIterator) { for event in events { match event { Event::KeyboardInput(ElementState::Pressed, _, key_opt) => { let pressed_key = key_opt.unwrap(); if self.key_map.contains_key(&pressed_key) { self.key_map.insert(pressed_key, true); } else { println!("unknown key {:?} pressed", key_opt); } }, Event::KeyboardInput(ElementState::Released, _, key_opt) => { let released_key = key_opt.unwrap(); if self.key_map.contains_key(&released_key) { self.key_map.insert(released_key, false); } }, _ => {} } } } pub fn watch(&mut self, key: VirtualKeyCode) { if self.key_map.contains_key(&key) { panic!("watching key that is already tracked"); } self.key_map.insert(key, false); self.key_list.push(key); } pub fn is_pressed(&self, key: VirtualKeyCode) -> bool { if self.key_map.contains_key(&key) == false { panic!("checking keydown for key that isn't being tracked"); } *self.key_map.get(&key).unwrap() } }*/ // Actual tilemap data that makes up the elements of the UBO. // NOTE: It may be a bug, but it appears that // [f32;2] won't work as UBO data. Possibly an issue with // binding generation gfx_defines!{ constant TileMapData { data: [f32; 4] = "data", } constant ProjectionStuff { model: [[f32; 4]; 4] = "u_Model", view: [[f32; 4]; 4] = "u_View", proj: [[f32; 4]; 4] = "u_Proj", } constant TilemapStuff { world_size: [f32; 4] = "u_WorldSize", tilesheet_size: [f32; 4] = "u_TilesheetSize", offsets: [f32; 2] = "u_TileOffsets", } vertex VertexData { pos: [f32; 3] = "a_Pos", buf_pos: [f32; 2] = "a_BufPos", } pipeline pipe { vbuf: gfx::VertexBuffer<VertexData> = (), projection_cb: gfx::ConstantBuffer<ProjectionStuff> = "b_VsLocals", // tilemap stuff tilemap: gfx::ConstantBuffer<TileMapData> = "b_TileMap", tilemap_cb: gfx::ConstantBuffer<TilemapStuff> = "b_PsLocals", tilesheet: gfx::TextureSampler<[f32; 4]> = "t_TileSheet", // output out_color: gfx::RenderTarget<ColorFormat> = "Target0", out_depth: gfx::DepthTarget<DepthFormat> = gfx::preset::depth::LESS_EQUAL_WRITE, } } impl TileMapData { pub fn new_empty() -> TileMapData { TileMapData { data: [0.0, 0.0, 0.0, 0.0] } } pub fn new(data: [f32; 4]) -> TileMapData { TileMapData { data: data } } } // Abstracts the plane mesh and uniform data // Also holds a Vec<TileMapData> as a working data // set for consumers pub struct TileMapPlane<R> where R: gfx::Resources { pub params: pipe::Data<R>, pub slice: gfx::Slice<R>, proj_stuff: ProjectionStuff, proj_dirty: bool, tm_stuff: TilemapStuff, tm_dirty: bool, pub data: Vec<TileMapData>, } impl<R> TileMapPlane<R> where R: gfx::Resources { pub fn new<F>(factory: &mut F, width: usize, height: usize, tile_size: usize, main_color: gfx::handle::RenderTargetView<R, ColorFormat>, main_depth: gfx::handle::DepthStencilView<R, DepthFormat>, aspect_ratio: f32) -> TileMapPlane<R> where F: gfx::Factory<R> { // charmap info let half_width = (tile_size * width) / 2; let half_height = (tile_size * height) / 2; let total_size = width*height; // tilesheet info let tilesheet_bytes = &include_bytes!("scifitiles-sheet_0.png")[..]; let tilesheet_width = 14; let tilesheet_height = 9; let tilesheet_tilesize = 32; let tilesheet_total_width = tilesheet_width * tilesheet_tilesize; let tilesheet_total_height = tilesheet_height * tilesheet_tilesize; // set up vertex data let plane = Plane::subdivide(width, width); // law out the vertices of the plane slice based on the configured tile size information, // setting the a_BufPos vertex data for the vertex shader (that ultimate gets passed through // to the frag shader as a varying, used to determine the "current tile" and the frag's offset, // which is used to calculate the displayed frag color) let vertex_data: Vec<VertexData> = plane.shared_vertex_iter() .map(|(raw_x, raw_y)| { let vertex_x = half_width as f32 * raw_x; let vertex_y = half_height as f32 * raw_y; let u_pos = (1.0 + raw_x) / 2.0; let v_pos = (1.0 + raw_y) / 2.0; let tilemap_x = (u_pos * width as f32).floor(); let tilemap_y = (v_pos * height as f32).floor(); VertexData { pos: [vertex_x, vertex_y, 0.0], buf_pos: [tilemap_x as f32, tilemap_y as f32] } }) .collect(); let index_data: Vec<u32> = plane.indexed_polygon_iter() .triangulate() .vertices() .map(|i| i as u32) .collect(); let (vbuf, slice) = factory.create_vertex_buffer_with_slice(&vertex_data, &index_data[..]); let tile_texture = load_texture(factory, tilesheet_bytes).unwrap(); let params = pipe::Data { vbuf: vbuf, projection_cb: factory.create_constant_buffer(1), tilemap: factory.create_constant_buffer(TILEMAP_BUF_LENGTH), tilemap_cb: factory.create_constant_buffer(1), tilesheet: (tile_texture, factory.create_sampler_linear()), out_color: main_color, out_depth: main_depth, }; let mut charmap_data = Vec::with_capacity(total_size); for _ in 0..total_size { charmap_data.push(TileMapData::new_empty()); } let view: AffineMatrix3<f32> = Transform::look_at( Point3::new(0.0, 0.0, 800.0), Point3::new(0.0, 0.0, 0.0), Vector3::unit_y(), ); TileMapPlane { slice: slice, params: params, proj_stuff: ProjectionStuff { model: Matrix4::identity().into(), view: view.mat.into(), proj: cgmath::perspective(cgmath::deg(60.0f32), aspect_ratio, 0.1, 4000.0).into(), }, proj_dirty: true, tm_stuff: TilemapStuff { world_size: [width as f32, height as f32, tile_size as f32, 0.0], tilesheet_size: [tilesheet_width as f32, tilesheet_height as f32, tilesheet_total_width as f32, tilesheet_total_height as f32], offsets: [0.0, 0.0], }, tm_dirty: true, data: charmap_data, } } fn prepare_buffers<C>(&mut self, encoder: &mut gfx::Encoder<R, C>, update_data: bool) where C: gfx::CommandBuffer<R> { if update_data
if self.proj_dirty { encoder.update_constant_buffer(&self.params.projection_cb, &self.proj_stuff); self.proj_dirty = false; } if self.tm_dirty { encoder.update_constant_buffer(&self.params.tilemap_cb, &self.tm_stuff); self.tm_dirty = false; } } fn clear<C>(&self, encoder: &mut gfx::Encoder<R, C>) where C: gfx::CommandBuffer<R> { encoder.clear(&self.params.out_color, [16.0 / 256.0, 14.0 / 256.0, 22.0 / 256.0, 1.0]); encoder.clear_depth(&self.params.out_depth, 1.0); } pub fn update_view(&mut self, view: &AffineMatrix3<f32>) { self.proj_stuff.view = view.mat.into(); self.proj_dirty = true; } pub fn update_x_offset(&mut self, amt: f32) { self.tm_stuff.offsets[0] = amt; self.tm_dirty = true; } pub fn update_y_offset(&mut self, amt: f32) { self.tm_stuff.offsets[1] = amt; self.tm_dirty = true; } } // Encapsulates the TileMapPlane and holds state for the current // visible set of tiles. Is responsible for updating the UBO // within the TileMapData when the visible set of tiles changes pub struct TileMap<R> where R: gfx::Resources { pub tiles: Vec<TileMapData>, pso: gfx::PipelineState<R, pipe::Meta>, tilemap_plane: TileMapPlane<R>, tile_size: f32, tilemap_size: [usize; 2], charmap_size: [usize; 2], limit_coords: [usize; 2], focus_coords: [usize; 2], focus_dirty: bool, } impl<R: gfx::Resources> TileMap<R> { pub fn set_focus(&mut self, focus: [usize; 2]) { if focus[0] <= self.limit_coords[0] && focus[1] <= self.limit_coords[1] { self.focus_coords = focus; let mut charmap_ypos = 0; for ypos in self.focus_coords[1].. self.focus_coords[1]+self.charmap_size[1] { let mut charmap_xpos = 0; for xpos in self.focus_coords[0].. self.focus_coords[0]+self.charmap_size[0] { let tile_idx = (ypos * self.tilemap_size[0]) + xpos; let charmap_idx = (charmap_ypos * self.charmap_size[0]) + charmap_xpos; self.tilemap_plane.data[charmap_idx] = self.tiles[tile_idx]; charmap_xpos += 1; } charmap_ypos += 1; } self.focus_dirty = true; } else { panic!("tried to set focus to {:?} with tilemap_size of {:?}", focus, self.tilemap_size); } } pub fn apply_x_offset(&mut self, offset_amt: f32) { let mut new_offset = self.tilemap_plane.tm_stuff.offsets[0] + offset_amt; let curr_focus = self.focus_coords; let new_x = if new_offset < 0.0 { // move down if self.focus_coords[0] == 0 { new_offset = 0.0; 0 } else { new_offset = self.tile_size + new_offset as f32; self.focus_coords[0] - 1 } } else if self.focus_coords[0] == self.limit_coords[0] { // at top, no more offset new_offset = 0.0; self.focus_coords[0] } else if new_offset >= self.tile_size { new_offset = new_offset - self.tile_size as f32; self.focus_coords[0] + 1 } else { // no move self.focus_coords[0] }; if new_x!= self.focus_coords[0] { self.set_focus([new_x, curr_focus[1]]); } self.tilemap_plane.update_x_offset(new_offset); } pub fn apply_y_offset(&mut self, offset_amt: f32) { let mut new_offset = self.tilemap_plane.tm_stuff.offsets[1] + offset_amt; let curr_focus = self.focus_coords; let new_y = if new_offset < 0.0 { // move down if self.focus_coords[1] == 0 { new_offset = 0.0; 0 } else { new_offset = self.tile_size + new_offset as f32; self.focus_coords[1] - 1 } } else if self.focus_coords[1] == (self.tilemap_size[1] - self.charmap_size[1]) { // at top, no more offset new_offset = 0.0; self.focus_coords[1] } else if new_offset >= self.tile_size { new_offset = new_offset - self.tile_size as f32; self.focus_coords[1] + 1 } else { // no move self.focus_coords[1] }; if new_y!= self.focus_coords[1] { self.set_focus([curr_focus[0], new_y]); } self.tilemap_plane.update_y_offset(new_offset); } fn calc_idx(&self, xpos: usize, ypos: usize) -> usize { (ypos * self.tilemap_size[0]) + xpos } pub fn set_tile(&mut self, xpos: usize, ypos: usize, data: [f32; 4]) { let idx = self.calc_idx(xpos, ypos); self.tiles[idx] = TileMapData::new(data); } } fn populate_tilemap<R>(tilemap: &mut TileMap<R>, tilemap_size: [usize; 2]) where R: gfx::Resources { // paper in with dummy data for ypos in 0.. tilemap_size[1] { for xpos in 0.. tilemap_size[0] { tilemap.set_tile(xpos, ypos, [1.0, 7.0, 0.0, 0.0]); } } tilemap.set_tile(1,3,[5.0, 0.0, 0.0, 0.0]); tilemap.set_tile(2,3,[6.0, 0.0, 0.0, 0.0]); tilemap.set_tile(3,3,[7.0, 0.0, 0.0, 0.0]); tilemap.set_tile(1,2,[5.0, 1.0, 0.0, 0.0]); tilemap.set_tile(2,2,[4.0, 0.0, 0.0, 0.0]); tilemap.set_tile(3,2,[11.0, 2.0, 0.0, 0.0]); tilemap.set_tile(1,1,[5.0, 2.0, 0.0, 0.0]); tilemap.set_tile(2,1,[6.0, 2.0, 0.0, 0.0]); tilemap.set_tile(3,1,[7.0, 2.0, 0.0, 0.0]); tilemap.set_tile(1,0,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(2,0,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(3,0,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(4,2,[4.0, 2.0, 0.0, 0.0]); tilemap.set_tile(5,2,[4.0, 2.0, 0.0, 0.0]); tilemap.set_tile(6,2,[11.0, 1.0, 0.0, 0.0]); tilemap.set_tile(4,1,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(5,1,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(6,1,[4.0, 7.0, 0.0, 0.0]); tilemap.set_tile(6,3,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,4,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,5,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,6,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,7,[4.0, 1.0, 0.0, 0.0]); tilemap.set_tile(5,10,[5.0, 0.0, 0.0, 0.0]); tilemap.set_tile(7,10,[7.0, 0.0, 0.0, 0.0]); tilemap.set_tile(5,9,[5.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,9,[6.0, 1.0, 0.0, 0.0]); tilemap.set_tile(7,9,[7.0, 1.0, 0.0, 0.0]); tilemap.set_tile(5,8,[5.0, 2.0, 0.0, 0.0]); tilemap.set_tile(6,8,[8.0, 2.0, 0.0, 0.0]); tilemap.set_tile(7,8,[7.0, 2.0, 0.0, 0.0]); tilemap.set_tile(5,7,[2.0, 1.0, 0.0, 0.0]); tilemap.set_tile(7,7,[2.0, 1.0, 0.0, 0.0]); tilemap.set_tile(6,10,[2.0, 3.0, 0.0, 0.0]); tilemap.set_tile(6,11,[2.0, 2.0, 0.0, 0.0]); } impl<R: gfx::Resources> gfx_app::Application<R> for TileMap<R> { fn new<F: gfx::Factory<R>>(mut factory: F, init: gfx_app::Init<R>) -> Self { use gfx::traits::FactoryExt; let vs = gfx_app::shade::Source { glsl_150: include_bytes!("shader/tilemap_150.glslv"), hlsl_40: include_bytes!("data/vertex.fx"), .. gfx_app::shade::Source::empty() }; let ps = gfx_app::shade::Source { glsl_150: include_bytes!("shader/tilemap_150.glslf"), hlsl_40: include_bytes!("data/pixel.fx"), .. gfx_app::shade::Source::empty() }; // set up charmap plane and configure its tiles let tilemap_size = [24, 24]; let charmap_size = [16, 16]; let tile_size = 32; let mut tiles = Vec::new(); for _ in 0.. tilemap_size[0]*tilemap_size[1] { tiles.push(TileMapData::new_empty()); } // TODO: should probably check that charmap is smaller than tilemap let mut tm = TileMap { tiles: tiles, pso: factory.create_pipeline_simple( vs.select(init.backend).unwrap(), ps.select(init.backend).unwrap(), pipe::new() ).unwrap(), tilemap_plane: TileMapPlane::new(&mut factory, charmap_size[0], charmap_size[1], tile_size, init.color, init.depth, init.aspect_ratio), tile_size: tile_size as f32, tilemap_size: tilemap_size, charmap_size: charmap_size, limit_coords: [tilemap_size[0] - charmap_size[0], tilemap_size[1] - charmap_size[
{ encoder.update_buffer(&self.params.tilemap, &self.data, 0).unwrap(); }
conditional_block