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
simdty.rs
// Copyright 2016 chacha20-poly1305-aead Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. #![allow(dead_code)] #![allow(non_camel_case_types)] use as_bytes::Safe; #[cfg(feature = "simd")] macro_rules! decl_simd { ($($decl:item)*) => { $( #[derive(Clone, Copy, Debug, Default)] #[repr(simd)] $decl )* } } #[cfg(not(feature = "simd"))] macro_rules! decl_simd { ($($decl:item)*) => { $( #[derive(Clone, Copy, Debug, Default)] #[repr(C)] $decl )* } } decl_simd! { pub struct Simd4<T>(pub T, pub T, pub T, pub T); pub struct Simd8<T>(pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T); pub struct Simd16<T>(pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T); } pub type u32x4 = Simd4<u32>; pub type u16x8 = Simd8<u16>; pub type u8x16 = Simd16<u8>; #[cfg_attr(feature = "clippy", allow(inline_always))] impl<T> Simd4<T> { #[inline(always)] pub fn new(e0: T, e1: T, e2: T, e3: T) -> Simd4<T>
} unsafe impl<T: Safe> Safe for Simd4<T> {} unsafe impl<T: Safe> Safe for Simd8<T> {} unsafe impl<T: Safe> Safe for Simd16<T> {}
{ Simd4(e0, e1, e2, e3) }
identifier_body
filter.rs
use htslib::bam::record::Record; pub trait RecordCheck { fn valid(&self, rec: &Record) -> bool; fn vir_pos(&self, rec: &Record) -> i32; } pub struct SingleChecker { pub tail_edge: bool, pub exact_length: bool, pub read_length: usize, pub min_quality: u8, } fn vir_pos_common(read_length: usize, tail_edge: bool, exact_length: bool, rec: &Record) -> i32 { if tail_edge { // instead of right edge of read (5') report left edge (3') if rec.is_reverse() { rec.pos() - (rec.seq().len() as i32) + 1 } else { rec.pos() + (rec.seq().len() as i32) - 1 } } else { if!exact_length && rec.is_reverse() { rec.pos() + (rec.seq().len() as i32) - (read_length as i32) } else { rec.pos() } } } impl RecordCheck for SingleChecker { fn
(&self, record: &Record) -> bool { !record.is_unmapped() && (!self.exact_length || record.seq().len() == self.read_length) && record.mapq() >= self.min_quality } fn vir_pos(&self, rec: &Record) -> i32 { vir_pos_common(self.read_length, self.tail_edge, self.exact_length, rec) } } #[derive(Copy, Clone)] pub enum PairPosition { First, Last } pub struct PairedChecker { pub tail_edge: bool, pub exact_length: bool, pub read_length: usize, pub min_quality: u8, pub min_dist: i32, pub max_dist: i32, pub force_paired: bool, pub max_distance: bool, pub select_pair: Option<PairPosition> } impl RecordCheck for PairedChecker { fn valid(&self, record: &Record) -> bool { // check single read conditions if record.is_unmapped() || (self.exact_length && record.seq().len()!= self.read_length) || record.mapq() < self.min_quality { return false; } // mandatory paired condition if (!record.is_paired() || record.is_mate_unmapped() || record.tid()!= record.mtid() ) && self.force_paired { return false; } // check pair distance if record.is_paired() && self.max_distance { let dist = (record.pos() - record.mpos()).abs() + self.read_length as i32; // TODO FIX! if dist < self.min_dist || dist > self.max_dist { return false; } } // filter for specific pair in paired reads match self.select_pair { Some( side ) => { match side { PairPosition::First => { if!record.is_first_in_template() { return false; } } PairPosition::Last => { if!record.is_last_in_template() { return false; } } } } _ => {} } true } fn vir_pos(&self, rec: &Record) -> i32 { vir_pos_common(self.read_length, self.tail_edge, self.exact_length, rec) } }
valid
identifier_name
filter.rs
use htslib::bam::record::Record; pub trait RecordCheck { fn valid(&self, rec: &Record) -> bool; fn vir_pos(&self, rec: &Record) -> i32; } pub struct SingleChecker { pub tail_edge: bool, pub exact_length: bool, pub read_length: usize, pub min_quality: u8, } fn vir_pos_common(read_length: usize, tail_edge: bool, exact_length: bool, rec: &Record) -> i32 { if tail_edge { // instead of right edge of read (5') report left edge (3') if rec.is_reverse() { rec.pos() - (rec.seq().len() as i32) + 1 } else { rec.pos() + (rec.seq().len() as i32) - 1 } } else { if!exact_length && rec.is_reverse() { rec.pos() + (rec.seq().len() as i32) - (read_length as i32) } else { rec.pos() } } } impl RecordCheck for SingleChecker { fn valid(&self, record: &Record) -> bool { !record.is_unmapped() && (!self.exact_length || record.seq().len() == self.read_length) && record.mapq() >= self.min_quality } fn vir_pos(&self, rec: &Record) -> i32 { vir_pos_common(self.read_length, self.tail_edge, self.exact_length, rec) } } #[derive(Copy, Clone)] pub enum PairPosition { First, Last } pub struct PairedChecker { pub tail_edge: bool, pub exact_length: bool, pub read_length: usize, pub min_quality: u8, pub min_dist: i32, pub max_dist: i32, pub force_paired: bool, pub max_distance: bool, pub select_pair: Option<PairPosition> } impl RecordCheck for PairedChecker { fn valid(&self, record: &Record) -> bool { // check single read conditions if record.is_unmapped() || (self.exact_length && record.seq().len()!= self.read_length) || record.mapq() < self.min_quality { return false; } // mandatory paired condition if (!record.is_paired() || record.is_mate_unmapped() || record.tid()!= record.mtid() ) && self.force_paired { return false; } // check pair distance if record.is_paired() && self.max_distance {
return false; } } // filter for specific pair in paired reads match self.select_pair { Some( side ) => { match side { PairPosition::First => { if!record.is_first_in_template() { return false; } } PairPosition::Last => { if!record.is_last_in_template() { return false; } } } } _ => {} } true } fn vir_pos(&self, rec: &Record) -> i32 { vir_pos_common(self.read_length, self.tail_edge, self.exact_length, rec) } }
let dist = (record.pos() - record.mpos()).abs() + self.read_length as i32; // TODO FIX! if dist < self.min_dist || dist > self.max_dist {
random_line_split
metrics.rs
use memmap::{Protection, Mmap}; use std::fs::File; use std::io::{ErrorKind, Error}; use std::fmt::{self, Display, Formatter}; use std::str::Chars; use text::style::{Style, StyleFlags}; use text::default::{DefaultMetrics, character_to_default}; // Each glyph takes up to 9x9 pixels. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct GlyphSize(u8); impl GlyphSize { pub fn empty() -> Self { GlyphSize(0) } pub fn new(left: u8, right: u8) -> Self {
// Incoming: an ASCII width from 0 to 8. pub fn from_default_width(width: u8) -> Self { if width == 0 { GlyphSize::empty() } else { GlyphSize::new(0, (width * 2) - 1) } } /// Returns the left side of the glyph, the X position of the leftmost column of pixels. This is from 0 to 15. pub fn left(&self) -> u8 { self.0 >> 4 } /// Returns the right side of the glyph, the X position of the rightmost column of pixels. This is from 0 to 15. pub fn right(&self) -> u8 { self.0 & 15 } /// Returns the width of the glyph on a texture map of size 256x256, with 256 characters total (16x16). The height of a glyph on the texture map is always 16. pub fn width(&self) -> u8 { self.right() + 1 - self.left() } /// Returns the advance width of the specified character in this font. The advance is the distance from the leftmost point to the rightmost point on the character's baseline. /// In MC fonts, this is 0.0 to 9.0. /// Note that this function returns the exact advance after rendering, while Minecraft char sizing may overestimate when calculating centering/trim/etc. /// Use `advance_overestimated` to emulate this. pub fn advance(&self) -> f32 { if self.left() == 0 && self.right() == 0 { 0.0 } else { ((self.width() as f32) / 2.0) + 1.0 } } /// Overestimates the advance for some characters. This mimics the behavior of the vanilla size functions, but is incorrect for other purposes. /// In addition, this should not be used for Default characters, as the vanilla code does not overestimate for default characters. pub fn advance_overestimated(&self) -> f32 { if self.right() > 7 { 9.0 } else { self.advance() } } } impl Display for GlyphSize { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!(f, "{{ left: {}, right: {}}}", self.left(), self.right()) } } pub struct GlyphMetrics { map: Mmap } impl GlyphMetrics { pub fn from_file(file: &File) -> Result<Self, Error> { Mmap::open(file, Protection::Read) .and_then(|map| if map.len() < 65536 { Err(Error::new(ErrorKind::UnexpectedEof, "Glyph size map is too short, much be at least 65536 bytes")) } else { Ok(map) } ).map(GlyphMetrics::new) } pub fn new(mmap: Mmap) -> Self { GlyphMetrics { map: mmap } } pub fn size(&self, value: u16) -> GlyphSize { // This accesses 1 byte, so it should be ok. GlyphSize(unsafe { self.map.as_slice()[value as usize] }) } } pub struct Metrics { default: Option<DefaultMetrics>, unicode: Option<GlyphMetrics> } impl Metrics { pub fn dual(default: DefaultMetrics, unicode: GlyphMetrics) -> Self { Metrics { default: Some(default), unicode: Some(unicode) } } pub fn unicode(unicode: GlyphMetrics) -> Self { Metrics { default: None, unicode: Some(unicode) } } pub fn always_unicode(&self) -> bool { self.default.is_none() && self.unicode.is_some() } pub fn size(&self, value: char) -> Option<GlyphSize> { if value == '\0' { return Some(GlyphSize::empty()) } else if value =='' { return Some(GlyphSize::from_default_width(3)) }; if let Some(ref default_metrics) = self.default { if let Some(default) = character_to_default(value) { return Some(default_metrics.size(default)) } } if let Some(ref unicode_metrics) = self.unicode { if value < '\u{10000}' { return Some(unicode_metrics.size(value as u16)) } } None } pub fn advance<'a, 'b, S, I>(&'a self, iter: S) -> Advance<'a, 'b, I> where S: IntoIterator<Item=(&'b str, Style), IntoIter=I>, I: Iterator<Item=(&'b str, Style)> { let mut iter = iter.into_iter(); let current = iter.next().map(|(run, style)| self.advance_run(run.chars(), style.flags)); Advance { metrics: &self, iter, current } } pub fn advance_run<'a, S, I>(&'a self, iter: S, style: StyleFlags) -> AdvanceRun<'a, I> where S: IntoIterator<Item=char, IntoIter=I>, I: Iterator<Item=char> { AdvanceRun { iter: iter.into_iter(), bold: style.bold(), metrics: &self } } } pub struct Advance<'a, 'b, I> where I: Iterator<Item=(&'b str, Style)> { iter: I, metrics: &'a Metrics, current: Option<AdvanceRun<'a, Chars<'b>>> } enum TryNext { None, AlmostEnd, Retry, Inner(Option<u8>) } impl<'a, 'b, I> Advance<'a, 'b, I> where I: Iterator<Item=(&'b str, Style)> { fn try_next(&mut self) -> TryNext { if let Some(ref mut current) = self.current { if let Some(next) = current.next() { TryNext::Inner(next) } else { if let Some((next_run, next_style)) = self.iter.next() { *current = self.metrics.advance_run(next_run.chars(), next_style.flags); TryNext::Retry } else { TryNext::AlmostEnd } } } else { TryNext::None } } pub fn total(self) -> Option<usize> { let mut accumulator = 0; for adv in self { accumulator += match adv { Some(advance) => advance as usize, None => return None }; } Some(accumulator) } } impl<'a, 'b, I> Iterator for Advance<'a, 'b, I> where I: Iterator<Item=(&'b str, Style)> { type Item = Option<u8>; fn next(&mut self) -> Option<Self::Item> { loop { match self.try_next() { TryNext::None => return None, TryNext::AlmostEnd => {self.current = None; return None}, TryNext::Retry => (), TryNext::Inner(inner) => return Some(inner) } } } } pub struct AdvanceRun<'a, I> where I: Iterator<Item=char> { iter: I, bold: bool, metrics: &'a Metrics } impl<'a, I> AdvanceRun<'a, I> where I: Iterator<Item=char> { pub fn total(self) -> Option<usize> { let mut accumulator = 0; for adv in self { accumulator += match adv { Some(advance) => advance as usize, None => return None }; } Some(accumulator) } } impl<'a, I> Iterator for AdvanceRun<'a, I> where I: Iterator<Item=char> { type Item = Option<u8>; fn next(&mut self) -> Option<Option<u8>> { self.iter .next() .map(|value| self.metrics .size(value) .map(|x| x.advance().floor() as u8) .map(|x| x + if self.bold {1} else {0} ) ) } } // TODO: Wrap, Trim,
GlyphSize((left << 4) | (right & 15)) }
random_line_split
metrics.rs
use memmap::{Protection, Mmap}; use std::fs::File; use std::io::{ErrorKind, Error}; use std::fmt::{self, Display, Formatter}; use std::str::Chars; use text::style::{Style, StyleFlags}; use text::default::{DefaultMetrics, character_to_default}; // Each glyph takes up to 9x9 pixels. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct GlyphSize(u8); impl GlyphSize { pub fn empty() -> Self { GlyphSize(0) } pub fn new(left: u8, right: u8) -> Self { GlyphSize((left << 4) | (right & 15)) } // Incoming: an ASCII width from 0 to 8. pub fn from_default_width(width: u8) -> Self { if width == 0 { GlyphSize::empty() } else { GlyphSize::new(0, (width * 2) - 1) } } /// Returns the left side of the glyph, the X position of the leftmost column of pixels. This is from 0 to 15. pub fn left(&self) -> u8 { self.0 >> 4 } /// Returns the right side of the glyph, the X position of the rightmost column of pixels. This is from 0 to 15. pub fn right(&self) -> u8 { self.0 & 15 } /// Returns the width of the glyph on a texture map of size 256x256, with 256 characters total (16x16). The height of a glyph on the texture map is always 16. pub fn width(&self) -> u8
/// Returns the advance width of the specified character in this font. The advance is the distance from the leftmost point to the rightmost point on the character's baseline. /// In MC fonts, this is 0.0 to 9.0. /// Note that this function returns the exact advance after rendering, while Minecraft char sizing may overestimate when calculating centering/trim/etc. /// Use `advance_overestimated` to emulate this. pub fn advance(&self) -> f32 { if self.left() == 0 && self.right() == 0 { 0.0 } else { ((self.width() as f32) / 2.0) + 1.0 } } /// Overestimates the advance for some characters. This mimics the behavior of the vanilla size functions, but is incorrect for other purposes. /// In addition, this should not be used for Default characters, as the vanilla code does not overestimate for default characters. pub fn advance_overestimated(&self) -> f32 { if self.right() > 7 { 9.0 } else { self.advance() } } } impl Display for GlyphSize { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!(f, "{{ left: {}, right: {}}}", self.left(), self.right()) } } pub struct GlyphMetrics { map: Mmap } impl GlyphMetrics { pub fn from_file(file: &File) -> Result<Self, Error> { Mmap::open(file, Protection::Read) .and_then(|map| if map.len() < 65536 { Err(Error::new(ErrorKind::UnexpectedEof, "Glyph size map is too short, much be at least 65536 bytes")) } else { Ok(map) } ).map(GlyphMetrics::new) } pub fn new(mmap: Mmap) -> Self { GlyphMetrics { map: mmap } } pub fn size(&self, value: u16) -> GlyphSize { // This accesses 1 byte, so it should be ok. GlyphSize(unsafe { self.map.as_slice()[value as usize] }) } } pub struct Metrics { default: Option<DefaultMetrics>, unicode: Option<GlyphMetrics> } impl Metrics { pub fn dual(default: DefaultMetrics, unicode: GlyphMetrics) -> Self { Metrics { default: Some(default), unicode: Some(unicode) } } pub fn unicode(unicode: GlyphMetrics) -> Self { Metrics { default: None, unicode: Some(unicode) } } pub fn always_unicode(&self) -> bool { self.default.is_none() && self.unicode.is_some() } pub fn size(&self, value: char) -> Option<GlyphSize> { if value == '\0' { return Some(GlyphSize::empty()) } else if value =='' { return Some(GlyphSize::from_default_width(3)) }; if let Some(ref default_metrics) = self.default { if let Some(default) = character_to_default(value) { return Some(default_metrics.size(default)) } } if let Some(ref unicode_metrics) = self.unicode { if value < '\u{10000}' { return Some(unicode_metrics.size(value as u16)) } } None } pub fn advance<'a, 'b, S, I>(&'a self, iter: S) -> Advance<'a, 'b, I> where S: IntoIterator<Item=(&'b str, Style), IntoIter=I>, I: Iterator<Item=(&'b str, Style)> { let mut iter = iter.into_iter(); let current = iter.next().map(|(run, style)| self.advance_run(run.chars(), style.flags)); Advance { metrics: &self, iter, current } } pub fn advance_run<'a, S, I>(&'a self, iter: S, style: StyleFlags) -> AdvanceRun<'a, I> where S: IntoIterator<Item=char, IntoIter=I>, I: Iterator<Item=char> { AdvanceRun { iter: iter.into_iter(), bold: style.bold(), metrics: &self } } } pub struct Advance<'a, 'b, I> where I: Iterator<Item=(&'b str, Style)> { iter: I, metrics: &'a Metrics, current: Option<AdvanceRun<'a, Chars<'b>>> } enum TryNext { None, AlmostEnd, Retry, Inner(Option<u8>) } impl<'a, 'b, I> Advance<'a, 'b, I> where I: Iterator<Item=(&'b str, Style)> { fn try_next(&mut self) -> TryNext { if let Some(ref mut current) = self.current { if let Some(next) = current.next() { TryNext::Inner(next) } else { if let Some((next_run, next_style)) = self.iter.next() { *current = self.metrics.advance_run(next_run.chars(), next_style.flags); TryNext::Retry } else { TryNext::AlmostEnd } } } else { TryNext::None } } pub fn total(self) -> Option<usize> { let mut accumulator = 0; for adv in self { accumulator += match adv { Some(advance) => advance as usize, None => return None }; } Some(accumulator) } } impl<'a, 'b, I> Iterator for Advance<'a, 'b, I> where I: Iterator<Item=(&'b str, Style)> { type Item = Option<u8>; fn next(&mut self) -> Option<Self::Item> { loop { match self.try_next() { TryNext::None => return None, TryNext::AlmostEnd => {self.current = None; return None}, TryNext::Retry => (), TryNext::Inner(inner) => return Some(inner) } } } } pub struct AdvanceRun<'a, I> where I: Iterator<Item=char> { iter: I, bold: bool, metrics: &'a Metrics } impl<'a, I> AdvanceRun<'a, I> where I: Iterator<Item=char> { pub fn total(self) -> Option<usize> { let mut accumulator = 0; for adv in self { accumulator += match adv { Some(advance) => advance as usize, None => return None }; } Some(accumulator) } } impl<'a, I> Iterator for AdvanceRun<'a, I> where I: Iterator<Item=char> { type Item = Option<u8>; fn next(&mut self) -> Option<Option<u8>> { self.iter .next() .map(|value| self.metrics .size(value) .map(|x| x.advance().floor() as u8) .map(|x| x + if self.bold {1} else {0} ) ) } } // TODO: Wrap, Trim,
{ self.right() + 1 - self.left() }
identifier_body
metrics.rs
use memmap::{Protection, Mmap}; use std::fs::File; use std::io::{ErrorKind, Error}; use std::fmt::{self, Display, Formatter}; use std::str::Chars; use text::style::{Style, StyleFlags}; use text::default::{DefaultMetrics, character_to_default}; // Each glyph takes up to 9x9 pixels. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct GlyphSize(u8); impl GlyphSize { pub fn empty() -> Self { GlyphSize(0) } pub fn new(left: u8, right: u8) -> Self { GlyphSize((left << 4) | (right & 15)) } // Incoming: an ASCII width from 0 to 8. pub fn from_default_width(width: u8) -> Self { if width == 0 { GlyphSize::empty() } else { GlyphSize::new(0, (width * 2) - 1) } } /// Returns the left side of the glyph, the X position of the leftmost column of pixels. This is from 0 to 15. pub fn left(&self) -> u8 { self.0 >> 4 } /// Returns the right side of the glyph, the X position of the rightmost column of pixels. This is from 0 to 15. pub fn right(&self) -> u8 { self.0 & 15 } /// Returns the width of the glyph on a texture map of size 256x256, with 256 characters total (16x16). The height of a glyph on the texture map is always 16. pub fn width(&self) -> u8 { self.right() + 1 - self.left() } /// Returns the advance width of the specified character in this font. The advance is the distance from the leftmost point to the rightmost point on the character's baseline. /// In MC fonts, this is 0.0 to 9.0. /// Note that this function returns the exact advance after rendering, while Minecraft char sizing may overestimate when calculating centering/trim/etc. /// Use `advance_overestimated` to emulate this. pub fn advance(&self) -> f32 { if self.left() == 0 && self.right() == 0 { 0.0 } else { ((self.width() as f32) / 2.0) + 1.0 } } /// Overestimates the advance for some characters. This mimics the behavior of the vanilla size functions, but is incorrect for other purposes. /// In addition, this should not be used for Default characters, as the vanilla code does not overestimate for default characters. pub fn advance_overestimated(&self) -> f32 { if self.right() > 7 { 9.0 } else { self.advance() } } } impl Display for GlyphSize { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!(f, "{{ left: {}, right: {}}}", self.left(), self.right()) } } pub struct GlyphMetrics { map: Mmap } impl GlyphMetrics { pub fn from_file(file: &File) -> Result<Self, Error> { Mmap::open(file, Protection::Read) .and_then(|map| if map.len() < 65536 { Err(Error::new(ErrorKind::UnexpectedEof, "Glyph size map is too short, much be at least 65536 bytes")) } else { Ok(map) } ).map(GlyphMetrics::new) } pub fn new(mmap: Mmap) -> Self { GlyphMetrics { map: mmap } } pub fn size(&self, value: u16) -> GlyphSize { // This accesses 1 byte, so it should be ok. GlyphSize(unsafe { self.map.as_slice()[value as usize] }) } } pub struct Metrics { default: Option<DefaultMetrics>, unicode: Option<GlyphMetrics> } impl Metrics { pub fn dual(default: DefaultMetrics, unicode: GlyphMetrics) -> Self { Metrics { default: Some(default), unicode: Some(unicode) } } pub fn unicode(unicode: GlyphMetrics) -> Self { Metrics { default: None, unicode: Some(unicode) } } pub fn always_unicode(&self) -> bool { self.default.is_none() && self.unicode.is_some() } pub fn size(&self, value: char) -> Option<GlyphSize> { if value == '\0' { return Some(GlyphSize::empty()) } else if value =='' { return Some(GlyphSize::from_default_width(3)) }; if let Some(ref default_metrics) = self.default { if let Some(default) = character_to_default(value) { return Some(default_metrics.size(default)) } } if let Some(ref unicode_metrics) = self.unicode { if value < '\u{10000}' { return Some(unicode_metrics.size(value as u16)) } } None } pub fn advance<'a, 'b, S, I>(&'a self, iter: S) -> Advance<'a, 'b, I> where S: IntoIterator<Item=(&'b str, Style), IntoIter=I>, I: Iterator<Item=(&'b str, Style)> { let mut iter = iter.into_iter(); let current = iter.next().map(|(run, style)| self.advance_run(run.chars(), style.flags)); Advance { metrics: &self, iter, current } } pub fn advance_run<'a, S, I>(&'a self, iter: S, style: StyleFlags) -> AdvanceRun<'a, I> where S: IntoIterator<Item=char, IntoIter=I>, I: Iterator<Item=char> { AdvanceRun { iter: iter.into_iter(), bold: style.bold(), metrics: &self } } } pub struct Advance<'a, 'b, I> where I: Iterator<Item=(&'b str, Style)> { iter: I, metrics: &'a Metrics, current: Option<AdvanceRun<'a, Chars<'b>>> } enum TryNext { None, AlmostEnd, Retry, Inner(Option<u8>) } impl<'a, 'b, I> Advance<'a, 'b, I> where I: Iterator<Item=(&'b str, Style)> { fn try_next(&mut self) -> TryNext { if let Some(ref mut current) = self.current { if let Some(next) = current.next() { TryNext::Inner(next) } else { if let Some((next_run, next_style)) = self.iter.next() { *current = self.metrics.advance_run(next_run.chars(), next_style.flags); TryNext::Retry } else { TryNext::AlmostEnd } } } else { TryNext::None } } pub fn total(self) -> Option<usize> { let mut accumulator = 0; for adv in self { accumulator += match adv { Some(advance) => advance as usize, None => return None }; } Some(accumulator) } } impl<'a, 'b, I> Iterator for Advance<'a, 'b, I> where I: Iterator<Item=(&'b str, Style)> { type Item = Option<u8>; fn next(&mut self) -> Option<Self::Item> { loop { match self.try_next() { TryNext::None => return None, TryNext::AlmostEnd => {self.current = None; return None}, TryNext::Retry => (), TryNext::Inner(inner) => return Some(inner) } } } } pub struct AdvanceRun<'a, I> where I: Iterator<Item=char> { iter: I, bold: bool, metrics: &'a Metrics } impl<'a, I> AdvanceRun<'a, I> where I: Iterator<Item=char> { pub fn
(self) -> Option<usize> { let mut accumulator = 0; for adv in self { accumulator += match adv { Some(advance) => advance as usize, None => return None }; } Some(accumulator) } } impl<'a, I> Iterator for AdvanceRun<'a, I> where I: Iterator<Item=char> { type Item = Option<u8>; fn next(&mut self) -> Option<Option<u8>> { self.iter .next() .map(|value| self.metrics .size(value) .map(|x| x.advance().floor() as u8) .map(|x| x + if self.bold {1} else {0} ) ) } } // TODO: Wrap, Trim,
total
identifier_name
metrics.rs
use memmap::{Protection, Mmap}; use std::fs::File; use std::io::{ErrorKind, Error}; use std::fmt::{self, Display, Formatter}; use std::str::Chars; use text::style::{Style, StyleFlags}; use text::default::{DefaultMetrics, character_to_default}; // Each glyph takes up to 9x9 pixels. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct GlyphSize(u8); impl GlyphSize { pub fn empty() -> Self { GlyphSize(0) } pub fn new(left: u8, right: u8) -> Self { GlyphSize((left << 4) | (right & 15)) } // Incoming: an ASCII width from 0 to 8. pub fn from_default_width(width: u8) -> Self { if width == 0 { GlyphSize::empty() } else { GlyphSize::new(0, (width * 2) - 1) } } /// Returns the left side of the glyph, the X position of the leftmost column of pixels. This is from 0 to 15. pub fn left(&self) -> u8 { self.0 >> 4 } /// Returns the right side of the glyph, the X position of the rightmost column of pixels. This is from 0 to 15. pub fn right(&self) -> u8 { self.0 & 15 } /// Returns the width of the glyph on a texture map of size 256x256, with 256 characters total (16x16). The height of a glyph on the texture map is always 16. pub fn width(&self) -> u8 { self.right() + 1 - self.left() } /// Returns the advance width of the specified character in this font. The advance is the distance from the leftmost point to the rightmost point on the character's baseline. /// In MC fonts, this is 0.0 to 9.0. /// Note that this function returns the exact advance after rendering, while Minecraft char sizing may overestimate when calculating centering/trim/etc. /// Use `advance_overestimated` to emulate this. pub fn advance(&self) -> f32 { if self.left() == 0 && self.right() == 0 { 0.0 } else { ((self.width() as f32) / 2.0) + 1.0 } } /// Overestimates the advance for some characters. This mimics the behavior of the vanilla size functions, but is incorrect for other purposes. /// In addition, this should not be used for Default characters, as the vanilla code does not overestimate for default characters. pub fn advance_overestimated(&self) -> f32 { if self.right() > 7 { 9.0 } else { self.advance() } } } impl Display for GlyphSize { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!(f, "{{ left: {}, right: {}}}", self.left(), self.right()) } } pub struct GlyphMetrics { map: Mmap } impl GlyphMetrics { pub fn from_file(file: &File) -> Result<Self, Error> { Mmap::open(file, Protection::Read) .and_then(|map| if map.len() < 65536 { Err(Error::new(ErrorKind::UnexpectedEof, "Glyph size map is too short, much be at least 65536 bytes")) } else { Ok(map) } ).map(GlyphMetrics::new) } pub fn new(mmap: Mmap) -> Self { GlyphMetrics { map: mmap } } pub fn size(&self, value: u16) -> GlyphSize { // This accesses 1 byte, so it should be ok. GlyphSize(unsafe { self.map.as_slice()[value as usize] }) } } pub struct Metrics { default: Option<DefaultMetrics>, unicode: Option<GlyphMetrics> } impl Metrics { pub fn dual(default: DefaultMetrics, unicode: GlyphMetrics) -> Self { Metrics { default: Some(default), unicode: Some(unicode) } } pub fn unicode(unicode: GlyphMetrics) -> Self { Metrics { default: None, unicode: Some(unicode) } } pub fn always_unicode(&self) -> bool { self.default.is_none() && self.unicode.is_some() } pub fn size(&self, value: char) -> Option<GlyphSize> { if value == '\0' { return Some(GlyphSize::empty()) } else if value =='' { return Some(GlyphSize::from_default_width(3)) }; if let Some(ref default_metrics) = self.default { if let Some(default) = character_to_default(value) { return Some(default_metrics.size(default)) } } if let Some(ref unicode_metrics) = self.unicode { if value < '\u{10000}' { return Some(unicode_metrics.size(value as u16)) } } None } pub fn advance<'a, 'b, S, I>(&'a self, iter: S) -> Advance<'a, 'b, I> where S: IntoIterator<Item=(&'b str, Style), IntoIter=I>, I: Iterator<Item=(&'b str, Style)> { let mut iter = iter.into_iter(); let current = iter.next().map(|(run, style)| self.advance_run(run.chars(), style.flags)); Advance { metrics: &self, iter, current } } pub fn advance_run<'a, S, I>(&'a self, iter: S, style: StyleFlags) -> AdvanceRun<'a, I> where S: IntoIterator<Item=char, IntoIter=I>, I: Iterator<Item=char> { AdvanceRun { iter: iter.into_iter(), bold: style.bold(), metrics: &self } } } pub struct Advance<'a, 'b, I> where I: Iterator<Item=(&'b str, Style)> { iter: I, metrics: &'a Metrics, current: Option<AdvanceRun<'a, Chars<'b>>> } enum TryNext { None, AlmostEnd, Retry, Inner(Option<u8>) } impl<'a, 'b, I> Advance<'a, 'b, I> where I: Iterator<Item=(&'b str, Style)> { fn try_next(&mut self) -> TryNext { if let Some(ref mut current) = self.current { if let Some(next) = current.next() { TryNext::Inner(next) } else { if let Some((next_run, next_style)) = self.iter.next() { *current = self.metrics.advance_run(next_run.chars(), next_style.flags); TryNext::Retry } else { TryNext::AlmostEnd } } } else { TryNext::None } } pub fn total(self) -> Option<usize> { let mut accumulator = 0; for adv in self { accumulator += match adv { Some(advance) => advance as usize, None => return None }; } Some(accumulator) } } impl<'a, 'b, I> Iterator for Advance<'a, 'b, I> where I: Iterator<Item=(&'b str, Style)> { type Item = Option<u8>; fn next(&mut self) -> Option<Self::Item> { loop { match self.try_next() { TryNext::None => return None, TryNext::AlmostEnd =>
, TryNext::Retry => (), TryNext::Inner(inner) => return Some(inner) } } } } pub struct AdvanceRun<'a, I> where I: Iterator<Item=char> { iter: I, bold: bool, metrics: &'a Metrics } impl<'a, I> AdvanceRun<'a, I> where I: Iterator<Item=char> { pub fn total(self) -> Option<usize> { let mut accumulator = 0; for adv in self { accumulator += match adv { Some(advance) => advance as usize, None => return None }; } Some(accumulator) } } impl<'a, I> Iterator for AdvanceRun<'a, I> where I: Iterator<Item=char> { type Item = Option<u8>; fn next(&mut self) -> Option<Option<u8>> { self.iter .next() .map(|value| self.metrics .size(value) .map(|x| x.advance().floor() as u8) .map(|x| x + if self.bold {1} else {0} ) ) } } // TODO: Wrap, Trim,
{self.current = None; return None}
conditional_block
seal.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/>. //! Spec seal deserialization. use hash::{H64, H256}; use bytes::Bytes; /// Ethereum seal. #[derive(Debug, PartialEq, Deserialize)] pub struct Ethereum { /// Seal nonce. pub nonce: H64, /// Seal mix hash. #[serde(rename="mixHash")] pub mix_hash: H256, } /// Generic seal. #[derive(Debug, PartialEq, Deserialize)] pub struct Generic { /// Number of fields. pub fields: usize, /// Their rlp. pub rlp: Bytes, } /// Seal variants. #[derive(Debug, PartialEq, Deserialize)] pub enum
{ /// Ethereum seal. #[serde(rename="ethereum")] Ethereum(Ethereum), /// Generic seal. #[serde(rename="generic")] Generic(Generic), } #[cfg(test)] mod tests { use serde_json; use spec::Seal; #[test] fn builtin_deserialization() { let s = r#"[{ "ethereum": { "nonce": "0x0000000000000042", "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000" } },{ "generic": { "fields": 1, "rlp": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa" } }]"#; let _deserialized: Vec<Seal> = serde_json::from_str(s).unwrap(); // TODO: validate all fields } }
Seal
identifier_name
seal.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.
//! Spec seal deserialization. use hash::{H64, H256}; use bytes::Bytes; /// Ethereum seal. #[derive(Debug, PartialEq, Deserialize)] pub struct Ethereum { /// Seal nonce. pub nonce: H64, /// Seal mix hash. #[serde(rename="mixHash")] pub mix_hash: H256, } /// Generic seal. #[derive(Debug, PartialEq, Deserialize)] pub struct Generic { /// Number of fields. pub fields: usize, /// Their rlp. pub rlp: Bytes, } /// Seal variants. #[derive(Debug, PartialEq, Deserialize)] pub enum Seal { /// Ethereum seal. #[serde(rename="ethereum")] Ethereum(Ethereum), /// Generic seal. #[serde(rename="generic")] Generic(Generic), } #[cfg(test)] mod tests { use serde_json; use spec::Seal; #[test] fn builtin_deserialization() { let s = r#"[{ "ethereum": { "nonce": "0x0000000000000042", "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000" } },{ "generic": { "fields": 1, "rlp": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa" } }]"#; let _deserialized: Vec<Seal> = serde_json::from_str(s).unwrap(); // TODO: validate all fields } }
// You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>.
random_line_split
seal.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/>. //! Spec seal deserialization. use hash::{H64, H256}; use bytes::Bytes; /// Ethereum seal. #[derive(Debug, PartialEq, Deserialize)] pub struct Ethereum { /// Seal nonce. pub nonce: H64, /// Seal mix hash. #[serde(rename="mixHash")] pub mix_hash: H256, } /// Generic seal. #[derive(Debug, PartialEq, Deserialize)] pub struct Generic { /// Number of fields. pub fields: usize, /// Their rlp. pub rlp: Bytes, } /// Seal variants. #[derive(Debug, PartialEq, Deserialize)] pub enum Seal { /// Ethereum seal. #[serde(rename="ethereum")] Ethereum(Ethereum), /// Generic seal. #[serde(rename="generic")] Generic(Generic), } #[cfg(test)] mod tests { use serde_json; use spec::Seal; #[test] fn builtin_deserialization()
}
{ let s = r#"[{ "ethereum": { "nonce": "0x0000000000000042", "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000" } },{ "generic": { "fields": 1, "rlp": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa" } }]"#; let _deserialized: Vec<Seal> = serde_json::from_str(s).unwrap(); // TODO: validate all fields }
identifier_body
issue-2190-1.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. // pretty-expanded FIXME #23616 use std::thread::Builder; static generations: usize = 1024+256+128+49; fn spawn(mut f: Box<FnMut() +'static + Send>) { Builder::new().stack_size(32 * 1024).spawn(move|| f()); } fn child_no(x: usize) -> Box<FnMut() +'static + Send> { Box::new(move|| { if x < generations
}) } pub fn main() { spawn(child_no(0)); }
{ spawn(child_no(x+1)); }
conditional_block
issue-2190-1.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. // pretty-expanded FIXME #23616 use std::thread::Builder; static generations: usize = 1024+256+128+49; fn spawn(mut f: Box<FnMut() +'static + Send>) { Builder::new().stack_size(32 * 1024).spawn(move|| f()); } fn child_no(x: usize) -> Box<FnMut() +'static + Send> { Box::new(move|| {
if x < generations { spawn(child_no(x+1)); } }) } pub fn main() { spawn(child_no(0)); }
random_line_split
issue-2190-1.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. // pretty-expanded FIXME #23616 use std::thread::Builder; static generations: usize = 1024+256+128+49; fn spawn(mut f: Box<FnMut() +'static + Send>) { Builder::new().stack_size(32 * 1024).spawn(move|| f()); } fn child_no(x: usize) -> Box<FnMut() +'static + Send> { Box::new(move|| { if x < generations { spawn(child_no(x+1)); } }) } pub fn main()
{ spawn(child_no(0)); }
identifier_body
issue-2190-1.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. // pretty-expanded FIXME #23616 use std::thread::Builder; static generations: usize = 1024+256+128+49; fn
(mut f: Box<FnMut() +'static + Send>) { Builder::new().stack_size(32 * 1024).spawn(move|| f()); } fn child_no(x: usize) -> Box<FnMut() +'static + Send> { Box::new(move|| { if x < generations { spawn(child_no(x+1)); } }) } pub fn main() { spawn(child_no(0)); }
spawn
identifier_name
lazy.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1::*; use boxed; use cell::UnsafeCell; use rt; use sync::{StaticMutex, Arc}; pub struct Lazy<T> { pub lock: StaticMutex, pub ptr: UnsafeCell<*mut Arc<T>>, pub init: fn() -> Arc<T>, } unsafe impl<T> Sync for Lazy<T> {} macro_rules! lazy_init { ($init:expr) => (::io::lazy::Lazy { lock: ::sync::MUTEX_INIT, ptr: ::cell::UnsafeCell { value: 0 as *mut _ }, init: $init, }) } impl<T: Send + Sync +'static> Lazy<T> { pub fn get(&'static self) -> Option<Arc<T>> { let _g = self.lock.lock(); unsafe { let ptr = *self.ptr.get(); if ptr.is_null() { Some(self.init()) } else if ptr as usize == 1 { None
} else { Some((*ptr).clone()) } } } unsafe fn init(&'static self) -> Arc<T> { // If we successfully register an at exit handler, then we cache the // `Arc` allocation in our own internal box (it will get deallocated by // the at exit handler). Otherwise we just return the freshly allocated // `Arc`. let registered = rt::at_exit(move || { let g = self.lock.lock(); let ptr = *self.ptr.get(); *self.ptr.get() = 1 as *mut _; drop(g); drop(Box::from_raw(ptr)) }); let ret = (self.init)(); if registered.is_ok() { *self.ptr.get() = boxed::into_raw(Box::new(ret.clone())); } return ret } }
random_line_split
lazy.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1::*; use boxed; use cell::UnsafeCell; use rt; use sync::{StaticMutex, Arc}; pub struct Lazy<T> { pub lock: StaticMutex, pub ptr: UnsafeCell<*mut Arc<T>>, pub init: fn() -> Arc<T>, } unsafe impl<T> Sync for Lazy<T> {} macro_rules! lazy_init { ($init:expr) => (::io::lazy::Lazy { lock: ::sync::MUTEX_INIT, ptr: ::cell::UnsafeCell { value: 0 as *mut _ }, init: $init, }) } impl<T: Send + Sync +'static> Lazy<T> { pub fn get(&'static self) -> Option<Arc<T>> { let _g = self.lock.lock(); unsafe { let ptr = *self.ptr.get(); if ptr.is_null()
else if ptr as usize == 1 { None } else { Some((*ptr).clone()) } } } unsafe fn init(&'static self) -> Arc<T> { // If we successfully register an at exit handler, then we cache the // `Arc` allocation in our own internal box (it will get deallocated by // the at exit handler). Otherwise we just return the freshly allocated // `Arc`. let registered = rt::at_exit(move || { let g = self.lock.lock(); let ptr = *self.ptr.get(); *self.ptr.get() = 1 as *mut _; drop(g); drop(Box::from_raw(ptr)) }); let ret = (self.init)(); if registered.is_ok() { *self.ptr.get() = boxed::into_raw(Box::new(ret.clone())); } return ret } }
{ Some(self.init()) }
conditional_block
lazy.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1::*; use boxed; use cell::UnsafeCell; use rt; use sync::{StaticMutex, Arc}; pub struct Lazy<T> { pub lock: StaticMutex, pub ptr: UnsafeCell<*mut Arc<T>>, pub init: fn() -> Arc<T>, } unsafe impl<T> Sync for Lazy<T> {} macro_rules! lazy_init { ($init:expr) => (::io::lazy::Lazy { lock: ::sync::MUTEX_INIT, ptr: ::cell::UnsafeCell { value: 0 as *mut _ }, init: $init, }) } impl<T: Send + Sync +'static> Lazy<T> { pub fn get(&'static self) -> Option<Arc<T>> { let _g = self.lock.lock(); unsafe { let ptr = *self.ptr.get(); if ptr.is_null() { Some(self.init()) } else if ptr as usize == 1 { None } else { Some((*ptr).clone()) } } } unsafe fn
(&'static self) -> Arc<T> { // If we successfully register an at exit handler, then we cache the // `Arc` allocation in our own internal box (it will get deallocated by // the at exit handler). Otherwise we just return the freshly allocated // `Arc`. let registered = rt::at_exit(move || { let g = self.lock.lock(); let ptr = *self.ptr.get(); *self.ptr.get() = 1 as *mut _; drop(g); drop(Box::from_raw(ptr)) }); let ret = (self.init)(); if registered.is_ok() { *self.ptr.get() = boxed::into_raw(Box::new(ret.clone())); } return ret } }
init
identifier_name
lazy.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1::*; use boxed; use cell::UnsafeCell; use rt; use sync::{StaticMutex, Arc}; pub struct Lazy<T> { pub lock: StaticMutex, pub ptr: UnsafeCell<*mut Arc<T>>, pub init: fn() -> Arc<T>, } unsafe impl<T> Sync for Lazy<T> {} macro_rules! lazy_init { ($init:expr) => (::io::lazy::Lazy { lock: ::sync::MUTEX_INIT, ptr: ::cell::UnsafeCell { value: 0 as *mut _ }, init: $init, }) } impl<T: Send + Sync +'static> Lazy<T> { pub fn get(&'static self) -> Option<Arc<T>>
unsafe fn init(&'static self) -> Arc<T> { // If we successfully register an at exit handler, then we cache the // `Arc` allocation in our own internal box (it will get deallocated by // the at exit handler). Otherwise we just return the freshly allocated // `Arc`. let registered = rt::at_exit(move || { let g = self.lock.lock(); let ptr = *self.ptr.get(); *self.ptr.get() = 1 as *mut _; drop(g); drop(Box::from_raw(ptr)) }); let ret = (self.init)(); if registered.is_ok() { *self.ptr.get() = boxed::into_raw(Box::new(ret.clone())); } return ret } }
{ let _g = self.lock.lock(); unsafe { let ptr = *self.ptr.get(); if ptr.is_null() { Some(self.init()) } else if ptr as usize == 1 { None } else { Some((*ptr).clone()) } } }
identifier_body
x86stdcall2.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. pub type HANDLE = u32; pub type DWORD = u32; pub type SIZE_T = u32; pub type LPVOID = uint; pub type BOOL = u8; #[cfg(windows)] mod kernel32 { use super::{HANDLE, DWORD, SIZE_T, LPVOID, BOOL}; extern "system" { pub fn GetProcessHeap() -> HANDLE; pub fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID; pub fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID) -> BOOL; } } #[cfg(windows)] pub fn main() { let heap = unsafe { kernel32::GetProcessHeap() }; let mem = unsafe { kernel32::HeapAlloc(heap, 0, 100) }; assert!(mem!= 0); let res = unsafe { kernel32::HeapFree(heap, 0, mem) }; assert!(res!= 0); } #[cfg(not(windows))] pub fn
() { }
main
identifier_name
x86stdcall2.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.
// option. This file may not be copied, modified, or distributed // except according to those terms. pub type HANDLE = u32; pub type DWORD = u32; pub type SIZE_T = u32; pub type LPVOID = uint; pub type BOOL = u8; #[cfg(windows)] mod kernel32 { use super::{HANDLE, DWORD, SIZE_T, LPVOID, BOOL}; extern "system" { pub fn GetProcessHeap() -> HANDLE; pub fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID; pub fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID) -> BOOL; } } #[cfg(windows)] pub fn main() { let heap = unsafe { kernel32::GetProcessHeap() }; let mem = unsafe { kernel32::HeapAlloc(heap, 0, 100) }; assert!(mem!= 0); let res = unsafe { kernel32::HeapFree(heap, 0, mem) }; assert!(res!= 0); } #[cfg(not(windows))] pub fn main() { }
// // 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
random_line_split
x86stdcall2.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. pub type HANDLE = u32; pub type DWORD = u32; pub type SIZE_T = u32; pub type LPVOID = uint; pub type BOOL = u8; #[cfg(windows)] mod kernel32 { use super::{HANDLE, DWORD, SIZE_T, LPVOID, BOOL}; extern "system" { pub fn GetProcessHeap() -> HANDLE; pub fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID; pub fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID) -> BOOL; } } #[cfg(windows)] pub fn main() { let heap = unsafe { kernel32::GetProcessHeap() }; let mem = unsafe { kernel32::HeapAlloc(heap, 0, 100) }; assert!(mem!= 0); let res = unsafe { kernel32::HeapFree(heap, 0, mem) }; assert!(res!= 0); } #[cfg(not(windows))] pub fn main()
{ }
identifier_body
main.rs
mod graph; mod index_type; use std::io::{BufReader, BufRead}; use std::fs::File; use std::str::FromStr; use std::fmt::Debug; use std::result::Result; use graph::{MDGraph, WeightType, Unweighted}; use index_type::{IndexType, NodeIndex, EdgeIndex, DefIndex}; fn read_sgf<NodeWt, EdgeWt, NodeIx, EdgeIx, R, I>(rd: &mut R) -> MDGraph<NodeWt, EdgeWt, NodeIx, EdgeIx> where NodeWt: WeightType + FromStr<Err = I>, EdgeWt: WeightType + FromStr<Err = I>, NodeIx: IndexType, EdgeIx: IndexType, I: Debug, R: BufRead
} // // Some("u") => { // false // } // _ => { panic!("Invalid format"); } }; let num_nodes: usize = match m.next() { Some(ns) => { ns.parse().unwrap() } _ => { panic!("Invalid format"); } }; let num_edges: usize = match m.next() { Some(ns) => { ns.parse().unwrap() } _ => { panic!("Invalid format"); } }; meta = Some((directed, num_nodes, num_edges)); graph.reserve_nodes(num_nodes); graph.reserve_edges(num_edges); let _ = graph.add_nodes(num_nodes); } else { let mut i = line.splitn(2, '|'); let (node_id, node_weight) = match i.next() { Some(ns) => { let mut it = ns.splitn(2, ":"); let node_id: usize = it.next().unwrap().parse().unwrap(); let node_weight: Option<NodeWt> = it.next().map(|s| s.parse().unwrap()); (node_id, node_weight) } _ => { panic!("Invalid format"); } }; if let Some(nw) = node_weight { *graph.get_node_weight_mut(NodeIndex::new(node_id)) = nw; } let edge_s = i.next().unwrap(); for es in edge_s.split(',') { let mut it = es.splitn(2, ":"); let target_id: usize = it.next() .unwrap() .parse() .unwrap(); let edge_weight: Option<EdgeWt> = it.next() .map(|s| s.parse::<EdgeWt>().unwrap()); match edge_weight { Some(ew) => { let _ = graph.add_edge_with_weight(NodeIndex::new(node_id), NodeIndex::new(target_id), ew); } None => { let _ = graph.add_edge(NodeIndex::new(node_id), NodeIndex::new(target_id)); } } } } } assert!(meta.unwrap().1 == graph.node_count()); assert!(meta.unwrap().2 == graph.edge_count()); return graph; } fn main() { let f = File::open("er_100_0_1.sgf").unwrap(); let mut f = BufReader::new(f); // let graph: MDGraph<f32, f32> = read_sgf(&mut f); let graph: MDGraph = read_sgf(&mut f); println!("{:?}", graph); }
{ let mut meta: Option<(bool, usize, usize)> = None; let mut graph = MDGraph::new(); for line in rd.lines() { let line = line.unwrap(); let line = line.trim(); if line.starts_with("#") { // skip comment continue; } if meta.is_none() { // First line is meta let mut m = line.split_whitespace(); let directed = match m.next() { Some("d") => { true
identifier_body
main.rs
mod graph; mod index_type; use std::io::{BufReader, BufRead}; use std::fs::File; use std::str::FromStr; use std::fmt::Debug; use std::result::Result; use graph::{MDGraph, WeightType, Unweighted}; use index_type::{IndexType, NodeIndex, EdgeIndex, DefIndex}; fn
<NodeWt, EdgeWt, NodeIx, EdgeIx, R, I>(rd: &mut R) -> MDGraph<NodeWt, EdgeWt, NodeIx, EdgeIx> where NodeWt: WeightType + FromStr<Err = I>, EdgeWt: WeightType + FromStr<Err = I>, NodeIx: IndexType, EdgeIx: IndexType, I: Debug, R: BufRead { let mut meta: Option<(bool, usize, usize)> = None; let mut graph = MDGraph::new(); for line in rd.lines() { let line = line.unwrap(); let line = line.trim(); if line.starts_with("#") { // skip comment continue; } if meta.is_none() { // First line is meta let mut m = line.split_whitespace(); let directed = match m.next() { Some("d") => { true } // // Some("u") => { // false // } // _ => { panic!("Invalid format"); } }; let num_nodes: usize = match m.next() { Some(ns) => { ns.parse().unwrap() } _ => { panic!("Invalid format"); } }; let num_edges: usize = match m.next() { Some(ns) => { ns.parse().unwrap() } _ => { panic!("Invalid format"); } }; meta = Some((directed, num_nodes, num_edges)); graph.reserve_nodes(num_nodes); graph.reserve_edges(num_edges); let _ = graph.add_nodes(num_nodes); } else { let mut i = line.splitn(2, '|'); let (node_id, node_weight) = match i.next() { Some(ns) => { let mut it = ns.splitn(2, ":"); let node_id: usize = it.next().unwrap().parse().unwrap(); let node_weight: Option<NodeWt> = it.next().map(|s| s.parse().unwrap()); (node_id, node_weight) } _ => { panic!("Invalid format"); } }; if let Some(nw) = node_weight { *graph.get_node_weight_mut(NodeIndex::new(node_id)) = nw; } let edge_s = i.next().unwrap(); for es in edge_s.split(',') { let mut it = es.splitn(2, ":"); let target_id: usize = it.next() .unwrap() .parse() .unwrap(); let edge_weight: Option<EdgeWt> = it.next() .map(|s| s.parse::<EdgeWt>().unwrap()); match edge_weight { Some(ew) => { let _ = graph.add_edge_with_weight(NodeIndex::new(node_id), NodeIndex::new(target_id), ew); } None => { let _ = graph.add_edge(NodeIndex::new(node_id), NodeIndex::new(target_id)); } } } } } assert!(meta.unwrap().1 == graph.node_count()); assert!(meta.unwrap().2 == graph.edge_count()); return graph; } fn main() { let f = File::open("er_100_0_1.sgf").unwrap(); let mut f = BufReader::new(f); // let graph: MDGraph<f32, f32> = read_sgf(&mut f); let graph: MDGraph = read_sgf(&mut f); println!("{:?}", graph); }
read_sgf
identifier_name
main.rs
mod graph; mod index_type; use std::io::{BufReader, BufRead}; use std::fs::File; use std::str::FromStr; use std::fmt::Debug; use std::result::Result; use graph::{MDGraph, WeightType, Unweighted}; use index_type::{IndexType, NodeIndex, EdgeIndex, DefIndex}; fn read_sgf<NodeWt, EdgeWt, NodeIx, EdgeIx, R, I>(rd: &mut R) -> MDGraph<NodeWt, EdgeWt, NodeIx, EdgeIx> where NodeWt: WeightType + FromStr<Err = I>, EdgeWt: WeightType + FromStr<Err = I>, NodeIx: IndexType, EdgeIx: IndexType, I: Debug, R: BufRead { let mut meta: Option<(bool, usize, usize)> = None; let mut graph = MDGraph::new(); for line in rd.lines() { let line = line.unwrap(); let line = line.trim(); if line.starts_with("#") { // skip comment continue; } if meta.is_none() { // First line is meta let mut m = line.split_whitespace(); let directed = match m.next() { Some("d") => { true } // // Some("u") => { // false // } // _ => { panic!("Invalid format"); } }; let num_nodes: usize = match m.next() { Some(ns) => { ns.parse().unwrap() } _ => { panic!("Invalid format"); } }; let num_edges: usize = match m.next() { Some(ns) => { ns.parse().unwrap() } _ => { panic!("Invalid format"); } }; meta = Some((directed, num_nodes, num_edges)); graph.reserve_nodes(num_nodes); graph.reserve_edges(num_edges); let _ = graph.add_nodes(num_nodes); } else { let mut i = line.splitn(2, '|'); let (node_id, node_weight) = match i.next() { Some(ns) =>
_ => { panic!("Invalid format"); } }; if let Some(nw) = node_weight { *graph.get_node_weight_mut(NodeIndex::new(node_id)) = nw; } let edge_s = i.next().unwrap(); for es in edge_s.split(',') { let mut it = es.splitn(2, ":"); let target_id: usize = it.next() .unwrap() .parse() .unwrap(); let edge_weight: Option<EdgeWt> = it.next() .map(|s| s.parse::<EdgeWt>().unwrap()); match edge_weight { Some(ew) => { let _ = graph.add_edge_with_weight(NodeIndex::new(node_id), NodeIndex::new(target_id), ew); } None => { let _ = graph.add_edge(NodeIndex::new(node_id), NodeIndex::new(target_id)); } } } } } assert!(meta.unwrap().1 == graph.node_count()); assert!(meta.unwrap().2 == graph.edge_count()); return graph; } fn main() { let f = File::open("er_100_0_1.sgf").unwrap(); let mut f = BufReader::new(f); // let graph: MDGraph<f32, f32> = read_sgf(&mut f); let graph: MDGraph = read_sgf(&mut f); println!("{:?}", graph); }
{ let mut it = ns.splitn(2, ":"); let node_id: usize = it.next().unwrap().parse().unwrap(); let node_weight: Option<NodeWt> = it.next().map(|s| s.parse().unwrap()); (node_id, node_weight) }
conditional_block
main.rs
mod graph; mod index_type; use std::io::{BufReader, BufRead}; use std::fs::File; use std::str::FromStr; use std::fmt::Debug; use std::result::Result; use graph::{MDGraph, WeightType, Unweighted}; use index_type::{IndexType, NodeIndex, EdgeIndex, DefIndex}; fn read_sgf<NodeWt, EdgeWt, NodeIx, EdgeIx, R, I>(rd: &mut R) -> MDGraph<NodeWt, EdgeWt, NodeIx, EdgeIx> where NodeWt: WeightType + FromStr<Err = I>, EdgeWt: WeightType + FromStr<Err = I>, NodeIx: IndexType, EdgeIx: IndexType, I: Debug, R: BufRead { let mut meta: Option<(bool, usize, usize)> = None; let mut graph = MDGraph::new(); for line in rd.lines() { let line = line.unwrap();
} if meta.is_none() { // First line is meta let mut m = line.split_whitespace(); let directed = match m.next() { Some("d") => { true } // // Some("u") => { // false // } // _ => { panic!("Invalid format"); } }; let num_nodes: usize = match m.next() { Some(ns) => { ns.parse().unwrap() } _ => { panic!("Invalid format"); } }; let num_edges: usize = match m.next() { Some(ns) => { ns.parse().unwrap() } _ => { panic!("Invalid format"); } }; meta = Some((directed, num_nodes, num_edges)); graph.reserve_nodes(num_nodes); graph.reserve_edges(num_edges); let _ = graph.add_nodes(num_nodes); } else { let mut i = line.splitn(2, '|'); let (node_id, node_weight) = match i.next() { Some(ns) => { let mut it = ns.splitn(2, ":"); let node_id: usize = it.next().unwrap().parse().unwrap(); let node_weight: Option<NodeWt> = it.next().map(|s| s.parse().unwrap()); (node_id, node_weight) } _ => { panic!("Invalid format"); } }; if let Some(nw) = node_weight { *graph.get_node_weight_mut(NodeIndex::new(node_id)) = nw; } let edge_s = i.next().unwrap(); for es in edge_s.split(',') { let mut it = es.splitn(2, ":"); let target_id: usize = it.next() .unwrap() .parse() .unwrap(); let edge_weight: Option<EdgeWt> = it.next() .map(|s| s.parse::<EdgeWt>().unwrap()); match edge_weight { Some(ew) => { let _ = graph.add_edge_with_weight(NodeIndex::new(node_id), NodeIndex::new(target_id), ew); } None => { let _ = graph.add_edge(NodeIndex::new(node_id), NodeIndex::new(target_id)); } } } } } assert!(meta.unwrap().1 == graph.node_count()); assert!(meta.unwrap().2 == graph.edge_count()); return graph; } fn main() { let f = File::open("er_100_0_1.sgf").unwrap(); let mut f = BufReader::new(f); // let graph: MDGraph<f32, f32> = read_sgf(&mut f); let graph: MDGraph = read_sgf(&mut f); println!("{:?}", graph); }
let line = line.trim(); if line.starts_with("#") { // skip comment continue;
random_line_split
saddle-points.rs
extern crate saddle_points; use saddle_points::*; #[test] fn test_identify_single_saddle_point() { let input = vec![vec![9, 8, 7], vec![5, 3, 2], vec![6, 6, 7]]; assert_eq!(vec![(1, 0)], find_saddle_points(&input)); } #[test] #[ignore] fn
() { let input = vec![vec![], vec![], vec![]]; let expected: Vec<(usize, usize)> = Vec::new(); assert_eq!(expected, find_saddle_points(&input)); } #[test] #[ignore] fn test_identify_lack_of_saddle_point() { let input = vec![vec![1, 2, 3], vec![3, 1, 2], vec![2, 3, 1]]; let expected: Vec<(usize, usize)> = Vec::new(); assert_eq!(expected, find_saddle_points(&input)); } #[test] #[ignore] fn test_multiple_saddle_point() { let input = vec![vec![4, 5, 4], vec![3, 5, 5], vec![1, 5, 4]]; assert_eq!(vec![(0, 1), (1, 1), (2, 1)], find_saddle_points(&input)); } #[test] #[ignore] fn test_identify_bottom_right_saddle_point() { let input = vec![vec![8, 7, 9], vec![6, 7, 6], vec![3, 2, 5]]; assert_eq!(vec![(2, 2)], find_saddle_points(&input)); } #[test] #[ignore] fn test_non_square_matrix_high() { let input = vec![vec![1, 5], vec![3, 6], vec![2, 7], vec![3, 8]]; assert_eq!(vec![(0, 1)], find_saddle_points(&input)); } #[test] #[ignore] fn test_non_square_matrix_wide() { let input = vec![vec![8, 7, 10, 7, 9], vec![8, 7, 13, 7, 9]]; assert_eq!(vec![(0, 2)], find_saddle_points(&input)); } #[test] #[ignore] fn test_vector_matrix() { let input = vec![vec![1], vec![3], vec![2], vec![3]]; assert_eq!(vec![(0, 0)], find_saddle_points(&input)); }
test_identify_empty_matrix
identifier_name
saddle-points.rs
extern crate saddle_points; use saddle_points::*; #[test] fn test_identify_single_saddle_point() { let input = vec![vec![9, 8, 7], vec![5, 3, 2], vec![6, 6, 7]]; assert_eq!(vec![(1, 0)], find_saddle_points(&input)); } #[test] #[ignore] fn test_identify_empty_matrix() { let input = vec![vec![], vec![], vec![]]; let expected: Vec<(usize, usize)> = Vec::new(); assert_eq!(expected, find_saddle_points(&input)); } #[test] #[ignore] fn test_identify_lack_of_saddle_point() { let input = vec![vec![1, 2, 3], vec![3, 1, 2], vec![2, 3, 1]]; let expected: Vec<(usize, usize)> = Vec::new(); assert_eq!(expected, find_saddle_points(&input)); } #[test] #[ignore] fn test_multiple_saddle_point() { let input = vec![vec![4, 5, 4], vec![3, 5, 5], vec![1, 5, 4]]; assert_eq!(vec![(0, 1), (1, 1), (2, 1)], find_saddle_points(&input)); } #[test] #[ignore] fn test_identify_bottom_right_saddle_point() { let input = vec![vec![8, 7, 9], vec![6, 7, 6], vec![3, 2, 5]]; assert_eq!(vec![(2, 2)], find_saddle_points(&input)); } #[test] #[ignore] fn test_non_square_matrix_high() { let input = vec![vec![1, 5], vec![3, 6], vec![2, 7], vec![3, 8]]; assert_eq!(vec![(0, 1)], find_saddle_points(&input)); } #[test] #[ignore] fn test_non_square_matrix_wide()
#[test] #[ignore] fn test_vector_matrix() { let input = vec![vec![1], vec![3], vec![2], vec![3]]; assert_eq!(vec![(0, 0)], find_saddle_points(&input)); }
{ let input = vec![vec![8, 7, 10, 7, 9], vec![8, 7, 13, 7, 9]]; assert_eq!(vec![(0, 2)], find_saddle_points(&input)); }
identifier_body
saddle-points.rs
extern crate saddle_points; use saddle_points::*; #[test] fn test_identify_single_saddle_point() { let input = vec![vec![9, 8, 7], vec![5, 3, 2], vec![6, 6, 7]]; assert_eq!(vec![(1, 0)], find_saddle_points(&input)); } #[test] #[ignore] fn test_identify_empty_matrix() { let input = vec![vec![], vec![], vec![]]; let expected: Vec<(usize, usize)> = Vec::new(); assert_eq!(expected, find_saddle_points(&input)); } #[test] #[ignore] fn test_identify_lack_of_saddle_point() { let input = vec![vec![1, 2, 3], vec![3, 1, 2], vec![2, 3, 1]]; let expected: Vec<(usize, usize)> = Vec::new(); assert_eq!(expected, find_saddle_points(&input)); } #[test] #[ignore]
} #[test] #[ignore] fn test_identify_bottom_right_saddle_point() { let input = vec![vec![8, 7, 9], vec![6, 7, 6], vec![3, 2, 5]]; assert_eq!(vec![(2, 2)], find_saddle_points(&input)); } #[test] #[ignore] fn test_non_square_matrix_high() { let input = vec![vec![1, 5], vec![3, 6], vec![2, 7], vec![3, 8]]; assert_eq!(vec![(0, 1)], find_saddle_points(&input)); } #[test] #[ignore] fn test_non_square_matrix_wide() { let input = vec![vec![8, 7, 10, 7, 9], vec![8, 7, 13, 7, 9]]; assert_eq!(vec![(0, 2)], find_saddle_points(&input)); } #[test] #[ignore] fn test_vector_matrix() { let input = vec![vec![1], vec![3], vec![2], vec![3]]; assert_eq!(vec![(0, 0)], find_saddle_points(&input)); }
fn test_multiple_saddle_point() { let input = vec![vec![4, 5, 4], vec![3, 5, 5], vec![1, 5, 4]]; assert_eq!(vec![(0, 1), (1, 1), (2, 1)], find_saddle_points(&input));
random_line_split
closure.rs
important that we be able to locate the closure data *without // knowing the kind of data that is being bound*. This can be tricky // because the alignment requirements of the bound data affects the // alignment requires of the closure_data struct as a whole. However, // right now this is a non-issue in any case, because the size of the // rust_opaque_box header is always a multiple of 16-bytes, which is // the maximum alignment requirement we ever have to worry about. // // The only reason alignment matters is that, in order to learn what data // is bound, we would normally first load the type descriptors: but their // location is ultimately depend on their content! There is, however, a // workaround. We can load the tydesc from the rust_opaque_box, which // describes the closure_data struct and has self-contained derived type // descriptors, and read the alignment from there. It's just annoying to // do. Hopefully should this ever become an issue we'll have monomorphized // and type descriptors will all be a bad dream. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pub struct EnvValue { action: ast::CaptureClause, datum: Datum<Lvalue> } impl EnvValue { pub fn to_string(&self, ccx: &CrateContext) -> String { format!("{}({})", self.action, self.datum.to_string(ccx)) } } // Given a closure ty, emits a corresponding tuple ty pub fn mk_closure_tys(tcx: &ty::ctxt, bound_values: &[EnvValue]) -> ty::t { // determine the types of the values in the env. Note that this // is the actual types that will be stored in the map, not the // logical types as the user sees them, so by-ref upvars must be // converted to ptrs. let bound_tys = bound_values.iter().map(|bv| { match bv.action { ast::CaptureByValue => bv.datum.ty, ast::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty) } }).collect(); let cdata_ty = ty::mk_tup(tcx, bound_tys); debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty)); return cdata_ty; } fn tuplify_box_ty(tcx: &ty::ctxt, t: ty::t) -> ty::t { let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8()); ty::mk_tup(tcx, vec!(ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t)) } fn allocate_cbox<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, store: ty::TraitStore, cdata_ty: ty::t) -> Result<'blk, 'tcx> { let _icx = push_ctxt("closure::allocate_cbox"); let tcx = bcx.tcx(); // Allocate and initialize the box: let cbox_ty = tuplify_box_ty(tcx, cdata_ty); match store { ty::UniqTraitStore => { malloc_raw_dyn_proc(bcx, cbox_ty) } ty::RegionTraitStore(..) => { let llbox = alloc_ty(bcx, cbox_ty, "__closure"); Result::new(bcx, llbox) } } } pub struct ClosureResult<'blk, 'tcx: 'blk> { llbox: ValueRef, // llvalue of ptr to closure cdata_ty: ty::t, // type of the closure data bcx: Block<'blk, 'tcx> // final bcx } // Given a block context and a list of tydescs and values to bind // construct a closure out of them. If copying is true, it is a // heap allocated closure that copies the upvars into environment. // Otherwise, it is stack allocated and copies pointers to the upvars. pub fn store_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, bound_values: Vec<EnvValue>, store: ty::TraitStore) -> ClosureResult<'blk, 'tcx> { let _icx = push_ctxt("closure::store_environment"); let ccx = bcx.ccx(); let tcx = ccx.tcx(); // compute the type of the closure let cdata_ty = mk_closure_tys(tcx, bound_values.as_slice()); // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a // tuple. This could be a ptr in uniq or a box or on stack, // whatever. let cbox_ty = tuplify_box_ty(tcx, cdata_ty); let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable}); let llboxptr_ty = type_of(ccx, cboxptr_ty); // If there are no bound values, no point in allocating anything. if bound_values.is_empty() { return ClosureResult {llbox: C_null(llboxptr_ty), cdata_ty: cdata_ty, bcx: bcx}; } // allocate closure in the heap let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty); let llbox = PointerCast(bcx, llbox, llboxptr_ty); debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty)); // Copy expr values into boxed bindings. let mut bcx = bcx; for (i, bv) in bound_values.into_iter().enumerate() { debug!("Copy {} into closure", bv.to_string(ccx)); if ccx.sess().asm_comments() { add_comment(bcx, format!("Copy {} into closure", bv.to_string(ccx)).as_slice()); } let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]); match bv.action { ast::CaptureByValue => { bcx = bv.datum.store_to(bcx, bound_data); } ast::CaptureByRef => { Store(bcx, bv.datum.to_llref(), bound_data); } } } ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx } } // Given a context and a list of upvars, build a closure. This just // collects the upvars and packages them up for store_environment. fn build_closure<'blk, 'tcx>(bcx0: Block<'blk, 'tcx>, freevar_mode: ast::CaptureClause, freevars: &Vec<ty::Freevar>, store: ty::TraitStore) -> ClosureResult<'blk, 'tcx> { let _icx = push_ctxt("closure::build_closure"); // If we need to, package up the iterator body to call let bcx = bcx0; // Package up the captured upvars let mut env_vals = Vec::new(); for freevar in freevars.iter() { let datum = expr::trans_local_var(bcx, freevar.def); env_vals.push(EnvValue {action: freevar_mode, datum: datum}); } store_environment(bcx, env_vals, store) } // Given an enclosing block context, a new function context, a closure type, // and a list of upvars, generate code to load and populate the environment // with the upvars and type descriptors. fn load_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, cdata_ty: ty::t, freevars: &Vec<ty::Freevar>, store: ty::TraitStore) -> Block<'blk, 'tcx> { let _icx = push_ctxt("closure::load_environment"); // Don't bother to create the block if there's nothing to load if freevars.len() == 0 { return bcx; } // Load a pointer to the closure data, skipping over the box header: let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap()); // Store the pointer to closure data in an alloca for debug info because that's what the // llvm.dbg.declare intrinsic expects let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo { let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr"); Store(bcx, llcdata, alloc); Some(alloc) } else { None }; // Populate the upvars from the environment let mut i = 0u; for freevar in freevars.iter() { let mut upvarptr = GEPi(bcx, llcdata, [0u, i]); match store { ty::RegionTraitStore(..) => { upvarptr = Load(bcx, upvarptr); } ty::UniqTraitStore => {} } let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr); for &env_pointer_alloca in env_pointer_alloca.iter() { debuginfo::create_captured_var_metadata( bcx, def_id.node, cdata_ty, env_pointer_alloca, i, store, freevar.span); } i += 1u; } bcx } fn load_unboxed_closure_environment<'blk, 'tcx>( bcx: Block<'blk, 'tcx>, arg_scope_id: ScopeId, freevar_mode: ast::CaptureClause, freevars: &Vec<ty::Freevar>, closure_id: ast::DefId) -> Block<'blk, 'tcx> { let _icx = push_ctxt("closure::load_environment"); if freevars.len() == 0 { return bcx } // Special case for small by-value selfs. let self_type = self_type_for_unboxed_closure(bcx.ccx(), closure_id); let kind = kind_for_unboxed_closure(bcx.ccx(), closure_id); let llenv = if kind == ty::FnOnceUnboxedClosureKind && !arg_is_indirect(bcx.ccx(), self_type) { let datum = rvalue_scratch_datum(bcx, self_type, "unboxed_closure_env"); store_ty(bcx, bcx.fcx.llenv.unwrap(), datum.val, self_type); assert!(freevars.len() <= 1); datum.val } else { bcx.fcx.llenv.unwrap() }; for (i, freevar) in freevars.iter().enumerate() { let mut upvar_ptr = GEPi(bcx, llenv, [0, i]); if freevar_mode == ast::CaptureByRef { upvar_ptr = Load(bcx, upvar_ptr); } let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr); if kind == ty::FnOnceUnboxedClosureKind && freevar_mode == ast::CaptureByValue { bcx.fcx.schedule_drop_mem(arg_scope_id, upvar_ptr, node_id_type(bcx, def_id.node)) } } bcx } fn fill_fn_pair(bcx: Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) { Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code])); let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx())); Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box])); } pub fn trans_expr_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, store: ty::TraitStore, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> Block<'blk, 'tcx> { /*! * * Translates the body of a closure expression. * * - `store` * - `decl` * - `body` * - `id`: The id of the closure expression. * - `cap_clause`: information about captured variables, if any. * - `dest`: where to write the closure value, which must be a (fn ptr, env) pair */ let _icx = push_ctxt("closure::trans_expr_fn"); let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { return bcx; // closure construction is non-side-effecting } }; let ccx = bcx.ccx(); let tcx = bcx.tcx(); let fty = node_id_type(bcx, id); let s = tcx.map.with_path(id, |path| { mangle_internal_name_by_path_and_seq(path, "closure") }); let llfn = decl_internal_rust_fn(ccx, fty, s.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); let freevar_mode = tcx.capture_mode(id); let freevars: Vec<ty::Freevar> = ty::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect()); let ClosureResult { llbox, cdata_ty, bcx } = build_closure(bcx, freevar_mode, &freevars, store); trans_closure(ccx, decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(fty), ty::ty_fn_ret(fty), ty::ty_fn_abi(fty), true, NotUnboxedClosure, |bcx, _| load_environment(bcx, cdata_ty, &freevars, store)); fill_fn_pair(bcx, dest_addr, llfn, llbox); bcx } /// Returns the LLVM function declaration for an unboxed closure, creating it /// if necessary. If the ID does not correspond to a closure ID, returns None. pub fn get_or_create_declaration_if_unboxed_closure(ccx: &CrateContext, closure_id: ast::DefId) -> Option<ValueRef> { if!ccx.tcx().unboxed_closures.borrow().contains_key(&closure_id) { // Not an unboxed closure. return None } match ccx.unboxed_closure_vals().borrow().find(&closure_id) { Some(llfn) =>
None => {} } let function_type = ty::mk_unboxed_closure(ccx.tcx(), closure_id, ty::ReStatic); let symbol = ccx.tcx().map.with_path(closure_id.node, |path| { mangle_internal_name_by_path_and_seq(path, "unboxed_closure") }); let llfn = decl_internal_rust_fn(ccx, function_type, symbol.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \ closure {} (type {})", closure_id, ccx.tn().type_to_string(val_ty(llfn))); ccx.unboxed_closure_vals().borrow_mut().insert(closure_id, llfn); Some(llfn) } pub fn trans_unboxed_closure<'blk, 'tcx>( mut bcx: Block<'blk, 'tcx>, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> Block<'blk, 'tcx> { let _icx = push_ctxt("closure::trans_unboxed_closure"); debug!("trans_unboxed_closure()"); let closure_id = ast_util::local_def(id); let llfn = get_or_create_declaration_if_unboxed_closure( bcx.ccx(), closure_id).unwrap(); let unboxed_closures = bcx.tcx().unboxed_closures.borrow(); let function_type = unboxed_closures.get(&closure_id) .closure_type .clone(); let function_type = ty::mk_closure(bcx.tcx(), function_type); let freevars: Vec<ty::Freevar> = ty::with_freevars(bcx.tcx(), id, |fv| fv.iter().map(|&fv| fv).collect()); let freevars_ptr = &freevars; let freevar_mode = bcx.tcx().capture_mode(id); trans_closure(bcx.ccx(), decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(function_type), ty::ty_fn_ret(function_type), ty::ty_fn_abi(function_type), true, IsUnboxedClosure, |bcx, arg_scope| { load_unboxed_closure_environment(bcx, arg_scope, freevar_mode, freevars_ptr, closure_id) }); // Don't hoist this to the top of the function. It's perfectly legitimate // to have a zero-size unboxed closure (in which case dest will be // `Ignore`) and we must still generate the closure body. let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { debug!("trans_unboxed_closure() ignoring result"); return bcx } }; let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id)); // Create the closure. for (i, freevar) in freevars_ptr.iter().enumerate() { let datum = expr::trans_local_var(bcx, freevar.def); let upvar_slot_dest = adt::trans_field_ptr(bcx, &*repr,
{ debug!("get_or_create_declaration_if_unboxed_closure(): found \ closure"); return Some(*llfn) }
conditional_block
closure.rs
important that we be able to locate the closure data *without // knowing the kind of data that is being bound*. This can be tricky // because the alignment requirements of the bound data affects the // alignment requires of the closure_data struct as a whole. However, // right now this is a non-issue in any case, because the size of the // rust_opaque_box header is always a multiple of 16-bytes, which is // the maximum alignment requirement we ever have to worry about. // // The only reason alignment matters is that, in order to learn what data // is bound, we would normally first load the type descriptors: but their // location is ultimately depend on their content! There is, however, a // workaround. We can load the tydesc from the rust_opaque_box, which // describes the closure_data struct and has self-contained derived type // descriptors, and read the alignment from there. It's just annoying to // do. Hopefully should this ever become an issue we'll have monomorphized // and type descriptors will all be a bad dream. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pub struct EnvValue { action: ast::CaptureClause, datum: Datum<Lvalue> } impl EnvValue { pub fn
(&self, ccx: &CrateContext) -> String { format!("{}({})", self.action, self.datum.to_string(ccx)) } } // Given a closure ty, emits a corresponding tuple ty pub fn mk_closure_tys(tcx: &ty::ctxt, bound_values: &[EnvValue]) -> ty::t { // determine the types of the values in the env. Note that this // is the actual types that will be stored in the map, not the // logical types as the user sees them, so by-ref upvars must be // converted to ptrs. let bound_tys = bound_values.iter().map(|bv| { match bv.action { ast::CaptureByValue => bv.datum.ty, ast::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty) } }).collect(); let cdata_ty = ty::mk_tup(tcx, bound_tys); debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty)); return cdata_ty; } fn tuplify_box_ty(tcx: &ty::ctxt, t: ty::t) -> ty::t { let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8()); ty::mk_tup(tcx, vec!(ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t)) } fn allocate_cbox<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, store: ty::TraitStore, cdata_ty: ty::t) -> Result<'blk, 'tcx> { let _icx = push_ctxt("closure::allocate_cbox"); let tcx = bcx.tcx(); // Allocate and initialize the box: let cbox_ty = tuplify_box_ty(tcx, cdata_ty); match store { ty::UniqTraitStore => { malloc_raw_dyn_proc(bcx, cbox_ty) } ty::RegionTraitStore(..) => { let llbox = alloc_ty(bcx, cbox_ty, "__closure"); Result::new(bcx, llbox) } } } pub struct ClosureResult<'blk, 'tcx: 'blk> { llbox: ValueRef, // llvalue of ptr to closure cdata_ty: ty::t, // type of the closure data bcx: Block<'blk, 'tcx> // final bcx } // Given a block context and a list of tydescs and values to bind // construct a closure out of them. If copying is true, it is a // heap allocated closure that copies the upvars into environment. // Otherwise, it is stack allocated and copies pointers to the upvars. pub fn store_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, bound_values: Vec<EnvValue>, store: ty::TraitStore) -> ClosureResult<'blk, 'tcx> { let _icx = push_ctxt("closure::store_environment"); let ccx = bcx.ccx(); let tcx = ccx.tcx(); // compute the type of the closure let cdata_ty = mk_closure_tys(tcx, bound_values.as_slice()); // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a // tuple. This could be a ptr in uniq or a box or on stack, // whatever. let cbox_ty = tuplify_box_ty(tcx, cdata_ty); let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable}); let llboxptr_ty = type_of(ccx, cboxptr_ty); // If there are no bound values, no point in allocating anything. if bound_values.is_empty() { return ClosureResult {llbox: C_null(llboxptr_ty), cdata_ty: cdata_ty, bcx: bcx}; } // allocate closure in the heap let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty); let llbox = PointerCast(bcx, llbox, llboxptr_ty); debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty)); // Copy expr values into boxed bindings. let mut bcx = bcx; for (i, bv) in bound_values.into_iter().enumerate() { debug!("Copy {} into closure", bv.to_string(ccx)); if ccx.sess().asm_comments() { add_comment(bcx, format!("Copy {} into closure", bv.to_string(ccx)).as_slice()); } let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]); match bv.action { ast::CaptureByValue => { bcx = bv.datum.store_to(bcx, bound_data); } ast::CaptureByRef => { Store(bcx, bv.datum.to_llref(), bound_data); } } } ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx } } // Given a context and a list of upvars, build a closure. This just // collects the upvars and packages them up for store_environment. fn build_closure<'blk, 'tcx>(bcx0: Block<'blk, 'tcx>, freevar_mode: ast::CaptureClause, freevars: &Vec<ty::Freevar>, store: ty::TraitStore) -> ClosureResult<'blk, 'tcx> { let _icx = push_ctxt("closure::build_closure"); // If we need to, package up the iterator body to call let bcx = bcx0; // Package up the captured upvars let mut env_vals = Vec::new(); for freevar in freevars.iter() { let datum = expr::trans_local_var(bcx, freevar.def); env_vals.push(EnvValue {action: freevar_mode, datum: datum}); } store_environment(bcx, env_vals, store) } // Given an enclosing block context, a new function context, a closure type, // and a list of upvars, generate code to load and populate the environment // with the upvars and type descriptors. fn load_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, cdata_ty: ty::t, freevars: &Vec<ty::Freevar>, store: ty::TraitStore) -> Block<'blk, 'tcx> { let _icx = push_ctxt("closure::load_environment"); // Don't bother to create the block if there's nothing to load if freevars.len() == 0 { return bcx; } // Load a pointer to the closure data, skipping over the box header: let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap()); // Store the pointer to closure data in an alloca for debug info because that's what the // llvm.dbg.declare intrinsic expects let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo { let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr"); Store(bcx, llcdata, alloc); Some(alloc) } else { None }; // Populate the upvars from the environment let mut i = 0u; for freevar in freevars.iter() { let mut upvarptr = GEPi(bcx, llcdata, [0u, i]); match store { ty::RegionTraitStore(..) => { upvarptr = Load(bcx, upvarptr); } ty::UniqTraitStore => {} } let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr); for &env_pointer_alloca in env_pointer_alloca.iter() { debuginfo::create_captured_var_metadata( bcx, def_id.node, cdata_ty, env_pointer_alloca, i, store, freevar.span); } i += 1u; } bcx } fn load_unboxed_closure_environment<'blk, 'tcx>( bcx: Block<'blk, 'tcx>, arg_scope_id: ScopeId, freevar_mode: ast::CaptureClause, freevars: &Vec<ty::Freevar>, closure_id: ast::DefId) -> Block<'blk, 'tcx> { let _icx = push_ctxt("closure::load_environment"); if freevars.len() == 0 { return bcx } // Special case for small by-value selfs. let self_type = self_type_for_unboxed_closure(bcx.ccx(), closure_id); let kind = kind_for_unboxed_closure(bcx.ccx(), closure_id); let llenv = if kind == ty::FnOnceUnboxedClosureKind && !arg_is_indirect(bcx.ccx(), self_type) { let datum = rvalue_scratch_datum(bcx, self_type, "unboxed_closure_env"); store_ty(bcx, bcx.fcx.llenv.unwrap(), datum.val, self_type); assert!(freevars.len() <= 1); datum.val } else { bcx.fcx.llenv.unwrap() }; for (i, freevar) in freevars.iter().enumerate() { let mut upvar_ptr = GEPi(bcx, llenv, [0, i]); if freevar_mode == ast::CaptureByRef { upvar_ptr = Load(bcx, upvar_ptr); } let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr); if kind == ty::FnOnceUnboxedClosureKind && freevar_mode == ast::CaptureByValue { bcx.fcx.schedule_drop_mem(arg_scope_id, upvar_ptr, node_id_type(bcx, def_id.node)) } } bcx } fn fill_fn_pair(bcx: Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) { Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code])); let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx())); Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box])); } pub fn trans_expr_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, store: ty::TraitStore, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> Block<'blk, 'tcx> { /*! * * Translates the body of a closure expression. * * - `store` * - `decl` * - `body` * - `id`: The id of the closure expression. * - `cap_clause`: information about captured variables, if any. * - `dest`: where to write the closure value, which must be a (fn ptr, env) pair */ let _icx = push_ctxt("closure::trans_expr_fn"); let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { return bcx; // closure construction is non-side-effecting } }; let ccx = bcx.ccx(); let tcx = bcx.tcx(); let fty = node_id_type(bcx, id); let s = tcx.map.with_path(id, |path| { mangle_internal_name_by_path_and_seq(path, "closure") }); let llfn = decl_internal_rust_fn(ccx, fty, s.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); let freevar_mode = tcx.capture_mode(id); let freevars: Vec<ty::Freevar> = ty::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect()); let ClosureResult { llbox, cdata_ty, bcx } = build_closure(bcx, freevar_mode, &freevars, store); trans_closure(ccx, decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(fty), ty::ty_fn_ret(fty), ty::ty_fn_abi(fty), true, NotUnboxedClosure, |bcx, _| load_environment(bcx, cdata_ty, &freevars, store)); fill_fn_pair(bcx, dest_addr, llfn, llbox); bcx } /// Returns the LLVM function declaration for an unboxed closure, creating it /// if necessary. If the ID does not correspond to a closure ID, returns None. pub fn get_or_create_declaration_if_unboxed_closure(ccx: &CrateContext, closure_id: ast::DefId) -> Option<ValueRef> { if!ccx.tcx().unboxed_closures.borrow().contains_key(&closure_id) { // Not an unboxed closure. return None } match ccx.unboxed_closure_vals().borrow().find(&closure_id) { Some(llfn) => { debug!("get_or_create_declaration_if_unboxed_closure(): found \ closure"); return Some(*llfn) } None => {} } let function_type = ty::mk_unboxed_closure(ccx.tcx(), closure_id, ty::ReStatic); let symbol = ccx.tcx().map.with_path(closure_id.node, |path| { mangle_internal_name_by_path_and_seq(path, "unboxed_closure") }); let llfn = decl_internal_rust_fn(ccx, function_type, symbol.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \ closure {} (type {})", closure_id, ccx.tn().type_to_string(val_ty(llfn))); ccx.unboxed_closure_vals().borrow_mut().insert(closure_id, llfn); Some(llfn) } pub fn trans_unboxed_closure<'blk, 'tcx>( mut bcx: Block<'blk, 'tcx>, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> Block<'blk, 'tcx> { let _icx = push_ctxt("closure::trans_unboxed_closure"); debug!("trans_unboxed_closure()"); let closure_id = ast_util::local_def(id); let llfn = get_or_create_declaration_if_unboxed_closure( bcx.ccx(), closure_id).unwrap(); let unboxed_closures = bcx.tcx().unboxed_closures.borrow(); let function_type = unboxed_closures.get(&closure_id) .closure_type .clone(); let function_type = ty::mk_closure(bcx.tcx(), function_type); let freevars: Vec<ty::Freevar> = ty::with_freevars(bcx.tcx(), id, |fv| fv.iter().map(|&fv| fv).collect()); let freevars_ptr = &freevars; let freevar_mode = bcx.tcx().capture_mode(id); trans_closure(bcx.ccx(), decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(function_type), ty::ty_fn_ret(function_type), ty::ty_fn_abi(function_type), true, IsUnboxedClosure, |bcx, arg_scope| { load_unboxed_closure_environment(bcx, arg_scope, freevar_mode, freevars_ptr, closure_id) }); // Don't hoist this to the top of the function. It's perfectly legitimate // to have a zero-size unboxed closure (in which case dest will be // `Ignore`) and we must still generate the closure body. let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { debug!("trans_unboxed_closure() ignoring result"); return bcx } }; let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id)); // Create the closure. for (i, freevar) in freevars_ptr.iter().enumerate() { let datum = expr::trans_local_var(bcx, freevar.def); let upvar_slot_dest = adt::trans_field_ptr(bcx, &*repr,
to_string
identifier_name
closure.rs
important that we be able to locate the closure data *without // knowing the kind of data that is being bound*. This can be tricky // because the alignment requirements of the bound data affects the // alignment requires of the closure_data struct as a whole. However, // right now this is a non-issue in any case, because the size of the // rust_opaque_box header is always a multiple of 16-bytes, which is // the maximum alignment requirement we ever have to worry about. // // The only reason alignment matters is that, in order to learn what data // is bound, we would normally first load the type descriptors: but their // location is ultimately depend on their content! There is, however, a // workaround. We can load the tydesc from the rust_opaque_box, which // describes the closure_data struct and has self-contained derived type // descriptors, and read the alignment from there. It's just annoying to // do. Hopefully should this ever become an issue we'll have monomorphized // and type descriptors will all be a bad dream. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pub struct EnvValue { action: ast::CaptureClause, datum: Datum<Lvalue> } impl EnvValue { pub fn to_string(&self, ccx: &CrateContext) -> String { format!("{}({})", self.action, self.datum.to_string(ccx)) } } // Given a closure ty, emits a corresponding tuple ty pub fn mk_closure_tys(tcx: &ty::ctxt, bound_values: &[EnvValue]) -> ty::t
fn tuplify_box_ty(tcx: &ty::ctxt, t: ty::t) -> ty::t { let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8()); ty::mk_tup(tcx, vec!(ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t)) } fn allocate_cbox<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, store: ty::TraitStore, cdata_ty: ty::t) -> Result<'blk, 'tcx> { let _icx = push_ctxt("closure::allocate_cbox"); let tcx = bcx.tcx(); // Allocate and initialize the box: let cbox_ty = tuplify_box_ty(tcx, cdata_ty); match store { ty::UniqTraitStore => { malloc_raw_dyn_proc(bcx, cbox_ty) } ty::RegionTraitStore(..) => { let llbox = alloc_ty(bcx, cbox_ty, "__closure"); Result::new(bcx, llbox) } } } pub struct ClosureResult<'blk, 'tcx: 'blk> { llbox: ValueRef, // llvalue of ptr to closure cdata_ty: ty::t, // type of the closure data bcx: Block<'blk, 'tcx> // final bcx } // Given a block context and a list of tydescs and values to bind // construct a closure out of them. If copying is true, it is a // heap allocated closure that copies the upvars into environment. // Otherwise, it is stack allocated and copies pointers to the upvars. pub fn store_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, bound_values: Vec<EnvValue>, store: ty::TraitStore) -> ClosureResult<'blk, 'tcx> { let _icx = push_ctxt("closure::store_environment"); let ccx = bcx.ccx(); let tcx = ccx.tcx(); // compute the type of the closure let cdata_ty = mk_closure_tys(tcx, bound_values.as_slice()); // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a // tuple. This could be a ptr in uniq or a box or on stack, // whatever. let cbox_ty = tuplify_box_ty(tcx, cdata_ty); let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable}); let llboxptr_ty = type_of(ccx, cboxptr_ty); // If there are no bound values, no point in allocating anything. if bound_values.is_empty() { return ClosureResult {llbox: C_null(llboxptr_ty), cdata_ty: cdata_ty, bcx: bcx}; } // allocate closure in the heap let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty); let llbox = PointerCast(bcx, llbox, llboxptr_ty); debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty)); // Copy expr values into boxed bindings. let mut bcx = bcx; for (i, bv) in bound_values.into_iter().enumerate() { debug!("Copy {} into closure", bv.to_string(ccx)); if ccx.sess().asm_comments() { add_comment(bcx, format!("Copy {} into closure", bv.to_string(ccx)).as_slice()); } let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]); match bv.action { ast::CaptureByValue => { bcx = bv.datum.store_to(bcx, bound_data); } ast::CaptureByRef => { Store(bcx, bv.datum.to_llref(), bound_data); } } } ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx } } // Given a context and a list of upvars, build a closure. This just // collects the upvars and packages them up for store_environment. fn build_closure<'blk, 'tcx>(bcx0: Block<'blk, 'tcx>, freevar_mode: ast::CaptureClause, freevars: &Vec<ty::Freevar>, store: ty::TraitStore) -> ClosureResult<'blk, 'tcx> { let _icx = push_ctxt("closure::build_closure"); // If we need to, package up the iterator body to call let bcx = bcx0; // Package up the captured upvars let mut env_vals = Vec::new(); for freevar in freevars.iter() { let datum = expr::trans_local_var(bcx, freevar.def); env_vals.push(EnvValue {action: freevar_mode, datum: datum}); } store_environment(bcx, env_vals, store) } // Given an enclosing block context, a new function context, a closure type, // and a list of upvars, generate code to load and populate the environment // with the upvars and type descriptors. fn load_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, cdata_ty: ty::t, freevars: &Vec<ty::Freevar>, store: ty::TraitStore) -> Block<'blk, 'tcx> { let _icx = push_ctxt("closure::load_environment"); // Don't bother to create the block if there's nothing to load if freevars.len() == 0 { return bcx; } // Load a pointer to the closure data, skipping over the box header: let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap()); // Store the pointer to closure data in an alloca for debug info because that's what the // llvm.dbg.declare intrinsic expects let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo { let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr"); Store(bcx, llcdata, alloc); Some(alloc) } else { None }; // Populate the upvars from the environment let mut i = 0u; for freevar in freevars.iter() { let mut upvarptr = GEPi(bcx, llcdata, [0u, i]); match store { ty::RegionTraitStore(..) => { upvarptr = Load(bcx, upvarptr); } ty::UniqTraitStore => {} } let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr); for &env_pointer_alloca in env_pointer_alloca.iter() { debuginfo::create_captured_var_metadata( bcx, def_id.node, cdata_ty, env_pointer_alloca, i, store, freevar.span); } i += 1u; } bcx } fn load_unboxed_closure_environment<'blk, 'tcx>( bcx: Block<'blk, 'tcx>, arg_scope_id: ScopeId, freevar_mode: ast::CaptureClause, freevars: &Vec<ty::Freevar>, closure_id: ast::DefId) -> Block<'blk, 'tcx> { let _icx = push_ctxt("closure::load_environment"); if freevars.len() == 0 { return bcx } // Special case for small by-value selfs. let self_type = self_type_for_unboxed_closure(bcx.ccx(), closure_id); let kind = kind_for_unboxed_closure(bcx.ccx(), closure_id); let llenv = if kind == ty::FnOnceUnboxedClosureKind && !arg_is_indirect(bcx.ccx(), self_type) { let datum = rvalue_scratch_datum(bcx, self_type, "unboxed_closure_env"); store_ty(bcx, bcx.fcx.llenv.unwrap(), datum.val, self_type); assert!(freevars.len() <= 1); datum.val } else { bcx.fcx.llenv.unwrap() }; for (i, freevar) in freevars.iter().enumerate() { let mut upvar_ptr = GEPi(bcx, llenv, [0, i]); if freevar_mode == ast::CaptureByRef { upvar_ptr = Load(bcx, upvar_ptr); } let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr); if kind == ty::FnOnceUnboxedClosureKind && freevar_mode == ast::CaptureByValue { bcx.fcx.schedule_drop_mem(arg_scope_id, upvar_ptr, node_id_type(bcx, def_id.node)) } } bcx } fn fill_fn_pair(bcx: Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) { Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code])); let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx())); Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box])); } pub fn trans_expr_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, store: ty::TraitStore, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> Block<'blk, 'tcx> { /*! * * Translates the body of a closure expression. * * - `store` * - `decl` * - `body` * - `id`: The id of the closure expression. * - `cap_clause`: information about captured variables, if any. * - `dest`: where to write the closure value, which must be a (fn ptr, env) pair */ let _icx = push_ctxt("closure::trans_expr_fn"); let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { return bcx; // closure construction is non-side-effecting } }; let ccx = bcx.ccx(); let tcx = bcx.tcx(); let fty = node_id_type(bcx, id); let s = tcx.map.with_path(id, |path| { mangle_internal_name_by_path_and_seq(path, "closure") }); let llfn = decl_internal_rust_fn(ccx, fty, s.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); let freevar_mode = tcx.capture_mode(id); let freevars: Vec<ty::Freevar> = ty::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect()); let ClosureResult { llbox, cdata_ty, bcx } = build_closure(bcx, freevar_mode, &freevars, store); trans_closure(ccx, decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(fty), ty::ty_fn_ret(fty), ty::ty_fn_abi(fty), true, NotUnboxedClosure, |bcx, _| load_environment(bcx, cdata_ty, &freevars, store)); fill_fn_pair(bcx, dest_addr, llfn, llbox); bcx } /// Returns the LLVM function declaration for an unboxed closure, creating it /// if necessary. If the ID does not correspond to a closure ID, returns None. pub fn get_or_create_declaration_if_unboxed_closure(ccx: &CrateContext, closure_id: ast::DefId) -> Option<ValueRef> { if!ccx.tcx().unboxed_closures.borrow().contains_key(&closure_id) { // Not an unboxed closure. return None } match ccx.unboxed_closure_vals().borrow().find(&closure_id) { Some(llfn) => { debug!("get_or_create_declaration_if_unboxed_closure(): found \ closure"); return Some(*llfn) } None => {} } let function_type = ty::mk_unboxed_closure(ccx.tcx(), closure_id, ty::ReStatic); let symbol = ccx.tcx().map.with_path(closure_id.node, |path| { mangle_internal_name_by_path_and_seq(path, "unboxed_closure") }); let llfn = decl_internal_rust_fn(ccx, function_type, symbol.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \ closure {} (type {})", closure_id, ccx.tn().type_to_string(val_ty(llfn))); ccx.unboxed_closure_vals().borrow_mut().insert(closure_id, llfn); Some(llfn) } pub fn trans_unboxed_closure<'blk, 'tcx>( mut bcx: Block<'blk, 'tcx>, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> Block<'blk, 'tcx> { let _icx = push_ctxt("closure::trans_unboxed_closure"); debug!("trans_unboxed_closure()"); let closure_id = ast_util::local_def(id); let llfn = get_or_create_declaration_if_unboxed_closure( bcx.ccx(), closure_id).unwrap(); let unboxed_closures = bcx.tcx().unboxed_closures.borrow(); let function_type = unboxed_closures.get(&closure_id) .closure_type .clone(); let function_type = ty::mk_closure(bcx.tcx(), function_type); let freevars: Vec<ty::Freevar> = ty::with_freevars(bcx.tcx(), id, |fv| fv.iter().map(|&fv| fv).collect()); let freevars_ptr = &freevars; let freevar_mode = bcx.tcx().capture_mode(id); trans_closure(bcx.ccx(), decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(function_type), ty::ty_fn_ret(function_type), ty::ty_fn_abi(function_type), true, IsUnboxedClosure, |bcx, arg_scope| { load_unboxed_closure_environment(bcx, arg_scope, freevar_mode, freevars_ptr, closure_id) }); // Don't hoist this to the top of the function. It's perfectly legitimate // to have a zero-size unboxed closure (in which case dest will be // `Ignore`) and we must still generate the closure body. let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { debug!("trans_unboxed_closure() ignoring result"); return bcx } }; let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id)); // Create the closure. for (i, freevar) in freevars_ptr.iter().enumerate() { let datum = expr::trans_local_var(bcx, freevar.def); let upvar_slot_dest = adt::trans_field_ptr(bcx, &*repr,
{ // determine the types of the values in the env. Note that this // is the actual types that will be stored in the map, not the // logical types as the user sees them, so by-ref upvars must be // converted to ptrs. let bound_tys = bound_values.iter().map(|bv| { match bv.action { ast::CaptureByValue => bv.datum.ty, ast::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty) } }).collect(); let cdata_ty = ty::mk_tup(tcx, bound_tys); debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty)); return cdata_ty; }
identifier_body
closure.rs
// // But sometimes, such as when cloning or freeing a closure, we need // to know the full information. That is where the type descriptor // that defines the closure comes in handy. We can use its take and // drop glue functions to allocate/free data as needed. // // ## Subtleties concerning alignment ## // // It is important that we be able to locate the closure data *without // knowing the kind of data that is being bound*. This can be tricky // because the alignment requirements of the bound data affects the // alignment requires of the closure_data struct as a whole. However, // right now this is a non-issue in any case, because the size of the // rust_opaque_box header is always a multiple of 16-bytes, which is // the maximum alignment requirement we ever have to worry about. // // The only reason alignment matters is that, in order to learn what data // is bound, we would normally first load the type descriptors: but their // location is ultimately depend on their content! There is, however, a // workaround. We can load the tydesc from the rust_opaque_box, which // describes the closure_data struct and has self-contained derived type // descriptors, and read the alignment from there. It's just annoying to // do. Hopefully should this ever become an issue we'll have monomorphized // and type descriptors will all be a bad dream. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pub struct EnvValue { action: ast::CaptureClause, datum: Datum<Lvalue> } impl EnvValue { pub fn to_string(&self, ccx: &CrateContext) -> String { format!("{}({})", self.action, self.datum.to_string(ccx)) } } // Given a closure ty, emits a corresponding tuple ty pub fn mk_closure_tys(tcx: &ty::ctxt, bound_values: &[EnvValue]) -> ty::t { // determine the types of the values in the env. Note that this // is the actual types that will be stored in the map, not the // logical types as the user sees them, so by-ref upvars must be // converted to ptrs. let bound_tys = bound_values.iter().map(|bv| { match bv.action { ast::CaptureByValue => bv.datum.ty, ast::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty) } }).collect(); let cdata_ty = ty::mk_tup(tcx, bound_tys); debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty)); return cdata_ty; } fn tuplify_box_ty(tcx: &ty::ctxt, t: ty::t) -> ty::t { let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8()); ty::mk_tup(tcx, vec!(ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t)) } fn allocate_cbox<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, store: ty::TraitStore, cdata_ty: ty::t) -> Result<'blk, 'tcx> { let _icx = push_ctxt("closure::allocate_cbox"); let tcx = bcx.tcx(); // Allocate and initialize the box: let cbox_ty = tuplify_box_ty(tcx, cdata_ty); match store { ty::UniqTraitStore => { malloc_raw_dyn_proc(bcx, cbox_ty) } ty::RegionTraitStore(..) => { let llbox = alloc_ty(bcx, cbox_ty, "__closure"); Result::new(bcx, llbox) } } } pub struct ClosureResult<'blk, 'tcx: 'blk> { llbox: ValueRef, // llvalue of ptr to closure cdata_ty: ty::t, // type of the closure data bcx: Block<'blk, 'tcx> // final bcx } // Given a block context and a list of tydescs and values to bind // construct a closure out of them. If copying is true, it is a // heap allocated closure that copies the upvars into environment. // Otherwise, it is stack allocated and copies pointers to the upvars. pub fn store_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, bound_values: Vec<EnvValue>, store: ty::TraitStore) -> ClosureResult<'blk, 'tcx> { let _icx = push_ctxt("closure::store_environment"); let ccx = bcx.ccx(); let tcx = ccx.tcx(); // compute the type of the closure let cdata_ty = mk_closure_tys(tcx, bound_values.as_slice()); // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a // tuple. This could be a ptr in uniq or a box or on stack, // whatever. let cbox_ty = tuplify_box_ty(tcx, cdata_ty); let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable}); let llboxptr_ty = type_of(ccx, cboxptr_ty); // If there are no bound values, no point in allocating anything. if bound_values.is_empty() { return ClosureResult {llbox: C_null(llboxptr_ty), cdata_ty: cdata_ty, bcx: bcx}; } // allocate closure in the heap let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty); let llbox = PointerCast(bcx, llbox, llboxptr_ty); debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty)); // Copy expr values into boxed bindings. let mut bcx = bcx; for (i, bv) in bound_values.into_iter().enumerate() { debug!("Copy {} into closure", bv.to_string(ccx)); if ccx.sess().asm_comments() { add_comment(bcx, format!("Copy {} into closure", bv.to_string(ccx)).as_slice()); } let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]); match bv.action { ast::CaptureByValue => { bcx = bv.datum.store_to(bcx, bound_data); } ast::CaptureByRef => { Store(bcx, bv.datum.to_llref(), bound_data); } } } ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx } } // Given a context and a list of upvars, build a closure. This just // collects the upvars and packages them up for store_environment. fn build_closure<'blk, 'tcx>(bcx0: Block<'blk, 'tcx>, freevar_mode: ast::CaptureClause, freevars: &Vec<ty::Freevar>, store: ty::TraitStore) -> ClosureResult<'blk, 'tcx> { let _icx = push_ctxt("closure::build_closure"); // If we need to, package up the iterator body to call let bcx = bcx0; // Package up the captured upvars let mut env_vals = Vec::new(); for freevar in freevars.iter() { let datum = expr::trans_local_var(bcx, freevar.def); env_vals.push(EnvValue {action: freevar_mode, datum: datum}); } store_environment(bcx, env_vals, store) } // Given an enclosing block context, a new function context, a closure type, // and a list of upvars, generate code to load and populate the environment // with the upvars and type descriptors. fn load_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, cdata_ty: ty::t, freevars: &Vec<ty::Freevar>, store: ty::TraitStore) -> Block<'blk, 'tcx> { let _icx = push_ctxt("closure::load_environment"); // Don't bother to create the block if there's nothing to load if freevars.len() == 0 { return bcx; } // Load a pointer to the closure data, skipping over the box header: let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap()); // Store the pointer to closure data in an alloca for debug info because that's what the // llvm.dbg.declare intrinsic expects let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo { let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr"); Store(bcx, llcdata, alloc); Some(alloc) } else { None }; // Populate the upvars from the environment let mut i = 0u; for freevar in freevars.iter() { let mut upvarptr = GEPi(bcx, llcdata, [0u, i]); match store { ty::RegionTraitStore(..) => { upvarptr = Load(bcx, upvarptr); } ty::UniqTraitStore => {} } let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr); for &env_pointer_alloca in env_pointer_alloca.iter() { debuginfo::create_captured_var_metadata( bcx, def_id.node, cdata_ty, env_pointer_alloca, i, store, freevar.span); } i += 1u; } bcx } fn load_unboxed_closure_environment<'blk, 'tcx>( bcx: Block<'blk, 'tcx>, arg_scope_id: ScopeId, freevar_mode: ast::CaptureClause, freevars: &Vec<ty::Freevar>, closure_id: ast::DefId) -> Block<'blk, 'tcx> { let _icx = push_ctxt("closure::load_environment"); if freevars.len() == 0 { return bcx } // Special case for small by-value selfs. let self_type = self_type_for_unboxed_closure(bcx.ccx(), closure_id); let kind = kind_for_unboxed_closure(bcx.ccx(), closure_id); let llenv = if kind == ty::FnOnceUnboxedClosureKind && !arg_is_indirect(bcx.ccx(), self_type) { let datum = rvalue_scratch_datum(bcx, self_type, "unboxed_closure_env"); store_ty(bcx, bcx.fcx.llenv.unwrap(), datum.val, self_type); assert!(freevars.len() <= 1); datum.val } else { bcx.fcx.llenv.unwrap() }; for (i, freevar) in freevars.iter().enumerate() { let mut upvar_ptr = GEPi(bcx, llenv, [0, i]); if freevar_mode == ast::CaptureByRef { upvar_ptr = Load(bcx, upvar_ptr); } let def_id = freevar.def.def_id(); bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr); if kind == ty::FnOnceUnboxedClosureKind && freevar_mode == ast::CaptureByValue { bcx.fcx.schedule_drop_mem(arg_scope_id, upvar_ptr, node_id_type(bcx, def_id.node)) } } bcx } fn fill_fn_pair(bcx: Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) { Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code])); let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx())); Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box])); } pub fn trans_expr_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, store: ty::TraitStore, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> Block<'blk, 'tcx> { /*! * * Translates the body of a closure expression. * * - `store` * - `decl` * - `body` * - `id`: The id of the closure expression. * - `cap_clause`: information about captured variables, if any. * - `dest`: where to write the closure value, which must be a (fn ptr, env) pair */ let _icx = push_ctxt("closure::trans_expr_fn"); let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { return bcx; // closure construction is non-side-effecting } }; let ccx = bcx.ccx(); let tcx = bcx.tcx(); let fty = node_id_type(bcx, id); let s = tcx.map.with_path(id, |path| { mangle_internal_name_by_path_and_seq(path, "closure") }); let llfn = decl_internal_rust_fn(ccx, fty, s.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); let freevar_mode = tcx.capture_mode(id); let freevars: Vec<ty::Freevar> = ty::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect()); let ClosureResult { llbox, cdata_ty, bcx } = build_closure(bcx, freevar_mode, &freevars, store); trans_closure(ccx, decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(fty), ty::ty_fn_ret(fty), ty::ty_fn_abi(fty), true, NotUnboxedClosure, |bcx, _| load_environment(bcx, cdata_ty, &freevars, store)); fill_fn_pair(bcx, dest_addr, llfn, llbox); bcx } /// Returns the LLVM function declaration for an unboxed closure, creating it /// if necessary. If the ID does not correspond to a closure ID, returns None. pub fn get_or_create_declaration_if_unboxed_closure(ccx: &CrateContext, closure_id: ast::DefId) -> Option<ValueRef> { if!ccx.tcx().unboxed_closures.borrow().contains_key(&closure_id) { // Not an unboxed closure. return None } match ccx.unboxed_closure_vals().borrow().find(&closure_id) { Some(llfn) => { debug!("get_or_create_declaration_if_unboxed_closure(): found \ closure"); return Some(*llfn) } None => {} } let function_type = ty::mk_unboxed_closure(ccx.tcx(), closure_id, ty::ReStatic); let symbol = ccx.tcx().map.with_path(closure_id.node, |path| { mangle_internal_name_by_path_and_seq(path, "unboxed_closure") }); let llfn = decl_internal_rust_fn(ccx, function_type, symbol.as_slice()); // set an inline hint for all closures set_inline_hint(llfn); debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \ closure {} (type {})", closure_id, ccx.tn().type_to_string(val_ty(llfn))); ccx.unboxed_closure_vals().borrow_mut().insert(closure_id, llfn); Some(llfn) } pub fn trans_unboxed_closure<'blk, 'tcx>( mut bcx: Block<'blk, 'tcx>, decl: &ast::FnDecl, body: &ast::Block, id: ast::NodeId, dest: expr::Dest) -> Block<'blk, 'tcx> { let _icx = push_ctxt("closure::trans_unboxed_closure"); debug!("trans_unboxed_closure()"); let closure_id = ast_util::local_def(id); let llfn = get_or_create_declaration_if_unboxed_closure( bcx.ccx(), closure_id).unwrap(); let unboxed_closures = bcx.tcx().unboxed_closures.borrow(); let function_type = unboxed_closures.get(&closure_id) .closure_type .clone(); let function_type = ty::mk_closure(bcx.tcx(), function_type); let freevars: Vec<ty::Freevar> = ty::with_freevars(bcx.tcx(), id, |fv| fv.iter().map(|&fv| fv).collect()); let freevars_ptr = &freevars; let freevar_mode = bcx.tcx().capture_mode(id); trans_closure(bcx.ccx(), decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_args(function_type), ty::ty_fn_ret(function_type), ty::ty_fn_abi(function_type), true, IsUnboxedClosure, |bcx, arg_scope| { load_unboxed_closure_environment(bcx, arg_scope, freevar_mode, freevars_ptr, closure_id) }); // Don't hoist this to the top of the function. It's perfectly legitimate // to have a zero-size unboxed closure (in which case dest will be // `Ignore`) and we must still generate the closure body. let dest_addr = match dest { expr::SaveIn(p) => p, expr::Ignore => { debug!("trans_unboxed_closure() ignoring result"); return bcx } }; let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id)); // Create the closure. for (i, freevar) in freevars_ptr.iter().enumerate() { let datum = expr::trans_local_var(bcx, freevar.def);
// by ptr. The routine Type::at_box().ptr_to() returns an appropriate // type for such an opaque closure; it allows access to the box fields, // but not the closure_data itself.
random_line_split
gdl90.rs
9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, ]; const HEARTBEAT_FREQ: u16 = 1; const OWNSHIP_FREQ: u16 = 2; const MAX_STALE_SECS: u64 = 6; // do not report data more than 6 sec old pub struct GDL90 { ownship_valid: bool, heartbeat_counter: u32, ownship_counter: u32, /// true if Pressure altitude source exists pres_alt_valid: bool, } impl Protocol for GDL90 { fn run(&mut self, handle: &mut Pushable<Payload>, i: ChainedIter) { let clock = handle.get_clock(); self.ownship_counter += 1; self.heartbeat_counter += 1; for e in i { match *e { Report::Ownship(ref o) => { if self.ownship_counter >= (handle.get_frequency() / OWNSHIP_FREQ) as u32 { self.ownship_counter = 0; self.ownship_valid = o.valid; if o.pressure_altitude.is_some() { self.pres_alt_valid = true; } handle.push_data(GDL90::generate_ownship(o)); handle.push_data(GDL90::generate_ownship_geometric_altitude(o)); } } Report::Traffic(ref o) => { // throttle for Target type is done at traffic processor handle.push_data(GDL90::generate_traffic(o, clock, self.pres_alt_valid)); } Report::FISB(ref o) => handle.push_data(GDL90::generate_uplink(o)), _ => {} } } if self.heartbeat_counter == (handle.get_frequency() / HEARTBEAT_FREQ) as u32 { self.heartbeat_counter = 0; let utc = handle.get_utc(); handle.push_data(self.generate_heartbeat(&utc)); handle.push_data(GDL90::generate_foreflight_id()); } } } impl GDL90 { fn generate_heartbeat(&self, utc: &Tm) -> Payload { let mut buf = [0_u8; 7 + 2]; // incl CRC field buf[0] = 0x00; // type = heartbeat buf[1] = 0x11; // UAT Initialized + ATC Services talkback if self.ownship_valid { buf[1] |= 0x80; } let midnight_utc = Tm { tm_hour: 0, tm_min: 0, tm_sec: 0, ..*utc }; let delta = (*utc - midnight_utc).num_seconds(); buf[2] = ((delta & 0x10000) >> 9) as u8 | 0x01; // MSB + UTC OK buf[3] = (delta & 0xFF) as u8; buf[4] = ((delta & 0xFF00) >> 8) as u8; Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_foreflight_id() -> Payload { // see: https://www.foreflight.com/connect/spec/ let mut buf = [0_u8; 39 + 2]; // incl CRC field buf[0] = 0x65; // type = FF buf[1] = 0x00; // sub ID = 0 buf[2] = 0x01; // version = 1 for i in 3..11 { buf[i] = 0xFF; // serial = invalid } buf[11] = 'P' as u8; buf[12] = 'i' as u8; buf[13] = 't' as u8; buf[14] = 'o' as u8; buf[15] = 't' as u8; buf[20] = 'P' as u8; buf[21] = 'i' as u8; buf[22] = 't' as u8; buf[23] = 'o' as u8; buf[24] = 't' as u8; // datum is WGS-84 ellipsoid buf[38] = 0x00; Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_uplink(e: &FISBData) -> Payload { let mut buf = [0_u8; 436 + 2]; // incl CRC field buf[0] = 0x07; // type = uplink buf[1] = 0xFF; buf[2] = 0xFF; buf[3] = 0xFF; &buf[4..436].clone_from_slice(&e.payload); Payload { queueable: true, payload: GDL90::prepare_payload(&mut buf), } } fn generate_ownship_geometric_altitude(e: &Ownship) -> Payload { let mut buf = [0_u8; 5 + 2]; // incl CRC field buf[0] = 0x0B; // type = ownship geometric let alt = (e.hae_altitude / 5) as i16; buf[1] = (alt >> 8) as u8; buf[2] = (alt & 0x00FF) as u8; buf[3] = 0x00; buf[4] = 0x0A; // No Vertical Warning, VFOM = 10 meters Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_ownship(e: &Ownship) -> Payload { let mut buf = [0_u8; 28 + 2]; // incl CRC field buf[0] = 0x0A; buf[1] = 0x01; // alert status = false, identity = ADS-B with Self-assigned address buf[2] = 0xF0; // self-assigned address buf[3] = 0x00; buf[4] = 0x00; // latitude let (lat1, lat2, lat3) = latlon_to_gdl90(e.lat); buf[5] = lat1; buf[6] = lat2; buf[7] = lat3; // longitude let (lon1, lon2, lon3) = latlon_to_gdl90(e.lon); buf[8] = lon1; buf[9] = lon2; buf[10] = lon3; // altitude if let Some(alt) = e.pressure_altitude { let alt = alt_to_gdl90(alt as f32); buf[11] = ((alt & 0xFF0) >> 4) as u8; buf[12] = (((alt & 0x00F) << 4) | 0x09) as u8; // Airborne + True Track } else { buf[11] = 0xFF; buf[12] = 0xF9; // Airborne + True Track } buf[13] = (e.nic << 4) & 0xF0 | e.nacp & 0x0F; let gs = e.gs.round() as u16; let vs = 0x800_u16; // "no vertical rate available" buf[14] = ((gs & 0xFF0) >> 4) as u8; buf[15] = (((gs & 0x00F) << 4) | ((vs & 0x0F00) >> 8)) as u8; buf[16] = (vs & 0xFF) as u8; buf[17] = crs_to_gdl90(e.true_track); buf[18] = 0x01; // Light (ICAO) < 15 500 lbs buf[19] = 'P' as u8; buf[20] = 'i' as u8; buf[21] = 't' as u8; buf[22] = 'o' as u8; buf[23] = 't' as u8; Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf),
buf[0] = 0x14; buf[1] = match e.addr.1 { AddressType::ADSBICAO | AddressType::ADSRICAO => 0, AddressType::ADSBOther | AddressType::ADSROther => 1, AddressType::TISBICAO => 2, AddressType::TISBOther => 3, _ => 3, // unknown }; buf[2] = ((0xFF0000 & e.addr.0) >> 16) as u8; // address buf[3] = ((0x00FF00 & e.addr.0) >> 8) as u8; buf[4] = (0x0000FF & e.addr.0) as u8; // latitude if let Some(((lat, lon), i)) = e.lat_lon { if (clock - i).as_secs() <= MAX_STALE_SECS { let (lat1, lat2, lat3) = latlon_to_gdl90(lat); buf[5] = lat1; buf[6] = lat2; buf[7] = lat3; // longitude let (lon1, lon2, lon3) = latlon_to_gdl90(lon); buf[8] = lon1; buf[9] = lon2; buf[10] = lon3; if let Some(nic) = e.nic { buf[13] |= (nic << 4) & 0xF0; } } } // altitude if let Some((alt, typ, i)) = e.altitude { if (clock - i).as_secs() <= MAX_STALE_SECS { let mut corrected_alt = alt; // if ownship pressure altitude is NOT available, use MSL and attempt to correct it // using GNSS delta if needed if!pres_alt_valid && typ == AltitudeType::Baro { // GDL90 wants pres altitude, try to calculate it from GNSS altitude // if correction is available // Note: GDL90 wants pressure altitude here, // but FF currently uses MSL altitude from // ownship geometric report when calculating altitude // difference, this is to correct Baro altitude // to MSL so that the calculation will be as accurate as possible if let Some(delta) = e.gnss_delta { corrected_alt += delta; } } else if pres_alt_valid && typ == AltitudeType::GNSS { if let Some(delta) = e.gnss_delta { corrected_alt -= delta; } } let alt = alt_to_gdl90(corrected_alt as f32); buf[11] = ((alt & 0xFF0) >> 4) as u8; buf[12] = ((alt & 0x00F) << 4) as u8; } } else { // invalid altitude buf[11] = 0xFF; buf[12] = 0xF0; } if let Some((_, typ, i)) = e.heading { if (clock - i).as_secs() <= MAX_STALE_SECS { match typ { HeadingType::True => buf[12] |= 0x01, HeadingType::Mag => buf[12] |= 0x02, } } } if e.on_ground!= Some(true) { buf[12] |= 0x08; // airborne // if unknown, assume airborne } if let Some(nacp) = e.nacp { buf[13] |= nacp & 0x0F; } // velocity unavailable by default buf[14] = 0xFF; buf[15] = 0xF0; if let Some((spd, _, i)) = e.speed { if (clock - i).as_secs() <= MAX_STALE_SECS { buf[14] = ((spd & 0xFF0) >> 4) as u8; buf[15] = ((spd & 0x00F) << 4) as u8; } } if let Some((vs, i)) = e.vs { if (clock - i).as_secs() <= MAX_STALE_SECS { let vs = (vs as f32 / 64_f32).round() as i16; // see p. 21 buf[15] |= ((vs & 0xF00) >> 8) as u8; buf[16] = (vs & 0xFF) as u8; } else { buf[15] |= 0x08; // no vs } } else { buf[15] |= 0x08; // no vs } if let Some((hdg, _, _)) = e.heading { // valid flag set above buf[17] = crs_to_gdl90(hdg as f32); } if let Some(cat) = e.category { buf[18] = cat; } // insert traffic source buf[19] = match e.source { TrafficSource::UAT => 'u', TrafficSource::ES => 'e', } as u8; buf[20] = match e.addr.1 { AddressType::ADSBICAO | AddressType::ADSBOther => 'a', AddressType::ADSRICAO | AddressType::ADSROther => 'r', AddressType::TISBICAO | AddressType::TISBOther => 't', _ => 'x', } as u8; if let Some(ref cs) = e.callsign { for (i, c) in cs.chars().take(6).enumerate() { buf[21 + i] = c as u8; } } else if let Some(sq) = e.squawk { // squawk available? let squawk_str = format!("{:04}", sq); // 0 padded debug_assert!(squawk_str.len() == 4); let squawk_str = squawk_str.as_bytes(); buf[21] = squawk_str[0]; buf[22] = squawk_str[1]; buf[23] = squawk_str[2]; buf[24] = squawk_str[3]; } if let Some(sq) = e.squawk { if sq == 7700 || sq == 7600 || sq == 7500 { buf[27] = 0x10; // emergency aircraft } } Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } /// Given a buffer containing everything between "Flag Bytes" (see p. 5) /// with the CRC field space allocated but left empty for calculation fn prepare_payload(buf: &mut [u8]) -> Vec<u8> { let len = buf.len() - 2; let crc = buf.iter() .take(len) .scan(0_u16, |crc, b| { *crc = CRC16_TABLE[(*crc >> 8) as usize] ^ (*crc << 8) ^ (*b as u16); Some(*crc) }) .last() .unwrap(); buf[len] = (crc & 0xFF) as u8; buf[len + 1] = (crc >> 8) as u8; // len + CRC (2 bytes) + 2 Flag Bytes + some stuffing bits (don't know yet) let mut tmp = Vec::with_capacity(len + 4); tmp.push(0x7E); for b in buf { if *b == 0x7E || *b == 0x7D { tmp.push(0x7D); tmp.push(*b ^ 0x20); } else { tmp.push(*b); } } tmp.push(0x7E); tmp } } impl GDL90 { pub fn new() -> Box<Protocol> { Box::new(GDL90 { ownship_valid: false, heartbeat_counter: 0, ownship_counter: 0, pres_alt_valid: false, }) } } /// Given coordinate in degrees, return the GDL 90 formatted byte sequence /// From: https://github.com/cyoung/stratux/blob/master/main/gen_gdl90.go#L206 fn latlon_to_gdl90(mut d: f32) -> (u8, u8, u8) { d /= LON_LAT_RESOLUTION; let wk = d.round() as i32; ( ((wk & 0xFF0000) >> 16) as u8, ((wk & 0x00FF00) >> 8) as u8, (wk & 0x0000FF) as u8, ) } fn alt_to_gdl90(mut a: f32) -> u16 { if a < -1000_f32 || a > 101350_f32 { 0xFFF } else {
} } fn generate_traffic(e: &Target, clock: Instant, pres_alt_valid: bool) -> Payload { let mut buf = [0_u8; 28 + 2]; // incl CRC field
random_line_split
gdl90.rs
D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, ]; const HEARTBEAT_FREQ: u16 = 1; const OWNSHIP_FREQ: u16 = 2; const MAX_STALE_SECS: u64 = 6; // do not report data more than 6 sec old pub struct GDL90 { ownship_valid: bool, heartbeat_counter: u32, ownship_counter: u32, /// true if Pressure altitude source exists pres_alt_valid: bool, } impl Protocol for GDL90 { fn run(&mut self, handle: &mut Pushable<Payload>, i: ChainedIter) { let clock = handle.get_clock(); self.ownship_counter += 1; self.heartbeat_counter += 1; for e in i { match *e { Report::Ownship(ref o) => { if self.ownship_counter >= (handle.get_frequency() / OWNSHIP_FREQ) as u32 { self.ownship_counter = 0; self.ownship_valid = o.valid; if o.pressure_altitude.is_some() { self.pres_alt_valid = true; } handle.push_data(GDL90::generate_ownship(o)); handle.push_data(GDL90::generate_ownship_geometric_altitude(o)); } } Report::Traffic(ref o) => { // throttle for Target type is done at traffic processor handle.push_data(GDL90::generate_traffic(o, clock, self.pres_alt_valid)); } Report::FISB(ref o) => handle.push_data(GDL90::generate_uplink(o)), _ => {} } } if self.heartbeat_counter == (handle.get_frequency() / HEARTBEAT_FREQ) as u32 { self.heartbeat_counter = 0; let utc = handle.get_utc(); handle.push_data(self.generate_heartbeat(&utc)); handle.push_data(GDL90::generate_foreflight_id()); } } } impl GDL90 { fn generate_heartbeat(&self, utc: &Tm) -> Payload { let mut buf = [0_u8; 7 + 2]; // incl CRC field buf[0] = 0x00; // type = heartbeat buf[1] = 0x11; // UAT Initialized + ATC Services talkback if self.ownship_valid { buf[1] |= 0x80; } let midnight_utc = Tm { tm_hour: 0, tm_min: 0, tm_sec: 0, ..*utc }; let delta = (*utc - midnight_utc).num_seconds(); buf[2] = ((delta & 0x10000) >> 9) as u8 | 0x01; // MSB + UTC OK buf[3] = (delta & 0xFF) as u8; buf[4] = ((delta & 0xFF00) >> 8) as u8; Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_foreflight_id() -> Payload { // see: https://www.foreflight.com/connect/spec/ let mut buf = [0_u8; 39 + 2]; // incl CRC field buf[0] = 0x65; // type = FF buf[1] = 0x00; // sub ID = 0 buf[2] = 0x01; // version = 1 for i in 3..11 { buf[i] = 0xFF; // serial = invalid } buf[11] = 'P' as u8; buf[12] = 'i' as u8; buf[13] = 't' as u8; buf[14] = 'o' as u8; buf[15] = 't' as u8; buf[20] = 'P' as u8; buf[21] = 'i' as u8; buf[22] = 't' as u8; buf[23] = 'o' as u8; buf[24] = 't' as u8; // datum is WGS-84 ellipsoid buf[38] = 0x00; Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_uplink(e: &FISBData) -> Payload { let mut buf = [0_u8; 436 + 2]; // incl CRC field buf[0] = 0x07; // type = uplink buf[1] = 0xFF; buf[2] = 0xFF; buf[3] = 0xFF; &buf[4..436].clone_from_slice(&e.payload); Payload { queueable: true, payload: GDL90::prepare_payload(&mut buf), } } fn generate_ownship_geometric_altitude(e: &Ownship) -> Payload { let mut buf = [0_u8; 5 + 2]; // incl CRC field buf[0] = 0x0B; // type = ownship geometric let alt = (e.hae_altitude / 5) as i16; buf[1] = (alt >> 8) as u8; buf[2] = (alt & 0x00FF) as u8; buf[3] = 0x00; buf[4] = 0x0A; // No Vertical Warning, VFOM = 10 meters Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_ownship(e: &Ownship) -> Payload { let mut buf = [0_u8; 28 + 2]; // incl CRC field buf[0] = 0x0A; buf[1] = 0x01; // alert status = false, identity = ADS-B with Self-assigned address buf[2] = 0xF0; // self-assigned address buf[3] = 0x00; buf[4] = 0x00; // latitude let (lat1, lat2, lat3) = latlon_to_gdl90(e.lat); buf[5] = lat1; buf[6] = lat2; buf[7] = lat3; // longitude let (lon1, lon2, lon3) = latlon_to_gdl90(e.lon); buf[8] = lon1; buf[9] = lon2; buf[10] = lon3; // altitude if let Some(alt) = e.pressure_altitude { let alt = alt_to_gdl90(alt as f32); buf[11] = ((alt & 0xFF0) >> 4) as u8; buf[12] = (((alt & 0x00F) << 4) | 0x09) as u8; // Airborne + True Track } else { buf[11] = 0xFF; buf[12] = 0xF9; // Airborne + True Track } buf[13] = (e.nic << 4) & 0xF0 | e.nacp & 0x0F; let gs = e.gs.round() as u16; let vs = 0x800_u16; // "no vertical rate available" buf[14] = ((gs & 0xFF0) >> 4) as u8; buf[15] = (((gs & 0x00F) << 4) | ((vs & 0x0F00) >> 8)) as u8; buf[16] = (vs & 0xFF) as u8; buf[17] = crs_to_gdl90(e.true_track); buf[18] = 0x01; // Light (ICAO) < 15 500 lbs buf[19] = 'P' as u8; buf[20] = 'i' as u8; buf[21] = 't' as u8; buf[22] = 'o' as u8; buf[23] = 't' as u8; Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_traffic(e: &Target, clock: Instant, pres_alt_valid: bool) -> Payload { let mut buf = [0_u8; 28 + 2]; // incl CRC field buf[0] = 0x14; buf[1] = match e.addr.1 { AddressType::ADSBICAO | AddressType::ADSRICAO => 0, AddressType::ADSBOther | AddressType::ADSROther => 1, AddressType::TISBICAO => 2, AddressType::TISBOther => 3, _ => 3, // unknown }; buf[2] = ((0xFF0000 & e.addr.0) >> 16) as u8; // address buf[3] = ((0x00FF00 & e.addr.0) >> 8) as u8; buf[4] = (0x0000FF & e.addr.0) as u8; // latitude if let Some(((lat, lon), i)) = e.lat_lon { if (clock - i).as_secs() <= MAX_STALE_SECS { let (lat1, lat2, lat3) = latlon_to_gdl90(lat); buf[5] = lat1; buf[6] = lat2; buf[7] = lat3; // longitude let (lon1, lon2, lon3) = latlon_to_gdl90(lon); buf[8] = lon1; buf[9] = lon2; buf[10] = lon3; if let Some(nic) = e.nic { buf[13] |= (nic << 4) & 0xF0; } } } // altitude if let Some((alt, typ, i)) = e.altitude { if (clock - i).as_secs() <= MAX_STALE_SECS { let mut corrected_alt = alt; // if ownship pressure altitude is NOT available, use MSL and attempt to correct it // using GNSS delta if needed if!pres_alt_valid && typ == AltitudeType::Baro { // GDL90 wants pres altitude, try to calculate it from GNSS altitude // if correction is available // Note: GDL90 wants pressure altitude here, // but FF currently uses MSL altitude from // ownship geometric report when calculating altitude // difference, this is to correct Baro altitude // to MSL so that the calculation will be as accurate as possible if let Some(delta) = e.gnss_delta { corrected_alt += delta; } } else if pres_alt_valid && typ == AltitudeType::GNSS { if let Some(delta) = e.gnss_delta { corrected_alt -= delta; } } let alt = alt_to_gdl90(corrected_alt as f32); buf[11] = ((alt & 0xFF0) >> 4) as u8; buf[12] = ((alt & 0x00F) << 4) as u8; } } else { // invalid altitude buf[11] = 0xFF; buf[12] = 0xF0; } if let Some((_, typ, i)) = e.heading { if (clock - i).as_secs() <= MAX_STALE_SECS { match typ { HeadingType::True => buf[12] |= 0x01, HeadingType::Mag => buf[12] |= 0x02, } } } if e.on_ground!= Some(true) { buf[12] |= 0x08; // airborne // if unknown, assume airborne } if let Some(nacp) = e.nacp { buf[13] |= nacp & 0x0F; } // velocity unavailable by default buf[14] = 0xFF; buf[15] = 0xF0; if let Some((spd, _, i)) = e.speed { if (clock - i).as_secs() <= MAX_STALE_SECS { buf[14] = ((spd & 0xFF0) >> 4) as u8; buf[15] = ((spd & 0x00F) << 4) as u8; } } if let Some((vs, i)) = e.vs { if (clock - i).as_secs() <= MAX_STALE_SECS { let vs = (vs as f32 / 64_f32).round() as i16; // see p. 21 buf[15] |= ((vs & 0xF00) >> 8) as u8; buf[16] = (vs & 0xFF) as u8; } else { buf[15] |= 0x08; // no vs } } else { buf[15] |= 0x08; // no vs } if let Some((hdg, _, _)) = e.heading { // valid flag set above buf[17] = crs_to_gdl90(hdg as f32); } if let Some(cat) = e.category { buf[18] = cat; } // insert traffic source buf[19] = match e.source { TrafficSource::UAT => 'u', TrafficSource::ES => 'e', } as u8; buf[20] = match e.addr.1 { AddressType::ADSBICAO | AddressType::ADSBOther => 'a', AddressType::ADSRICAO | AddressType::ADSROther => 'r', AddressType::TISBICAO | AddressType::TISBOther => 't', _ => 'x', } as u8; if let Some(ref cs) = e.callsign { for (i, c) in cs.chars().take(6).enumerate() { buf[21 + i] = c as u8; } } else if let Some(sq) = e.squawk { // squawk available? let squawk_str = format!("{:04}", sq); // 0 padded debug_assert!(squawk_str.len() == 4); let squawk_str = squawk_str.as_bytes(); buf[21] = squawk_str[0]; buf[22] = squawk_str[1]; buf[23] = squawk_str[2]; buf[24] = squawk_str[3]; } if let Some(sq) = e.squawk { if sq == 7700 || sq == 7600 || sq == 7500 { buf[27] = 0x10; // emergency aircraft } } Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } /// Given a buffer containing everything between "Flag Bytes" (see p. 5) /// with the CRC field space allocated but left empty for calculation fn prepare_payload(buf: &mut [u8]) -> Vec<u8> { let len = buf.len() - 2; let crc = buf.iter() .take(len) .scan(0_u16, |crc, b| { *crc = CRC16_TABLE[(*crc >> 8) as usize] ^ (*crc << 8) ^ (*b as u16); Some(*crc) }) .last() .unwrap(); buf[len] = (crc & 0xFF) as u8; buf[len + 1] = (crc >> 8) as u8; // len + CRC (2 bytes) + 2 Flag Bytes + some stuffing bits (don't know yet) let mut tmp = Vec::with_capacity(len + 4); tmp.push(0x7E); for b in buf { if *b == 0x7E || *b == 0x7D { tmp.push(0x7D); tmp.push(*b ^ 0x20); } else { tmp.push(*b); } } tmp.push(0x7E); tmp } } impl GDL90 { pub fn new() -> Box<Protocol> { Box::new(GDL90 { ownship_valid: false, heartbeat_counter: 0, ownship_counter: 0, pres_alt_valid: false, }) } } /// Given coordinate in degrees, return the GDL 90 formatted byte sequence /// From: https://github.com/cyoung/stratux/blob/master/main/gen_gdl90.go#L206 fn
(mut d: f32) -> (u8, u8, u8) { d /= LON_LAT_RESOLUTION; let wk = d.round() as i32; ( ((wk & 0xFF0000) >> 16) as u8, ((wk & 0x00FF00) >> 8) as u8, (wk & 0x0000FF) as u8, ) } fn alt_to_gdl90(mut a: f32) -> u16 { if a < -1000_f32 || a > 101350_f32 { 0xFFF } else
latlon_to_gdl90
identifier_name
gdl90.rs
D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, ]; const HEARTBEAT_FREQ: u16 = 1; const OWNSHIP_FREQ: u16 = 2; const MAX_STALE_SECS: u64 = 6; // do not report data more than 6 sec old pub struct GDL90 { ownship_valid: bool, heartbeat_counter: u32, ownship_counter: u32, /// true if Pressure altitude source exists pres_alt_valid: bool, } impl Protocol for GDL90 { fn run(&mut self, handle: &mut Pushable<Payload>, i: ChainedIter) { let clock = handle.get_clock(); self.ownship_counter += 1; self.heartbeat_counter += 1; for e in i { match *e { Report::Ownship(ref o) => { if self.ownship_counter >= (handle.get_frequency() / OWNSHIP_FREQ) as u32 { self.ownship_counter = 0; self.ownship_valid = o.valid; if o.pressure_altitude.is_some() { self.pres_alt_valid = true; } handle.push_data(GDL90::generate_ownship(o)); handle.push_data(GDL90::generate_ownship_geometric_altitude(o)); } } Report::Traffic(ref o) => { // throttle for Target type is done at traffic processor handle.push_data(GDL90::generate_traffic(o, clock, self.pres_alt_valid)); } Report::FISB(ref o) => handle.push_data(GDL90::generate_uplink(o)), _ => {} } } if self.heartbeat_counter == (handle.get_frequency() / HEARTBEAT_FREQ) as u32
} } impl GDL90 { fn generate_heartbeat(&self, utc: &Tm) -> Payload { let mut buf = [0_u8; 7 + 2]; // incl CRC field buf[0] = 0x00; // type = heartbeat buf[1] = 0x11; // UAT Initialized + ATC Services talkback if self.ownship_valid { buf[1] |= 0x80; } let midnight_utc = Tm { tm_hour: 0, tm_min: 0, tm_sec: 0, ..*utc }; let delta = (*utc - midnight_utc).num_seconds(); buf[2] = ((delta & 0x10000) >> 9) as u8 | 0x01; // MSB + UTC OK buf[3] = (delta & 0xFF) as u8; buf[4] = ((delta & 0xFF00) >> 8) as u8; Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_foreflight_id() -> Payload { // see: https://www.foreflight.com/connect/spec/ let mut buf = [0_u8; 39 + 2]; // incl CRC field buf[0] = 0x65; // type = FF buf[1] = 0x00; // sub ID = 0 buf[2] = 0x01; // version = 1 for i in 3..11 { buf[i] = 0xFF; // serial = invalid } buf[11] = 'P' as u8; buf[12] = 'i' as u8; buf[13] = 't' as u8; buf[14] = 'o' as u8; buf[15] = 't' as u8; buf[20] = 'P' as u8; buf[21] = 'i' as u8; buf[22] = 't' as u8; buf[23] = 'o' as u8; buf[24] = 't' as u8; // datum is WGS-84 ellipsoid buf[38] = 0x00; Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_uplink(e: &FISBData) -> Payload { let mut buf = [0_u8; 436 + 2]; // incl CRC field buf[0] = 0x07; // type = uplink buf[1] = 0xFF; buf[2] = 0xFF; buf[3] = 0xFF; &buf[4..436].clone_from_slice(&e.payload); Payload { queueable: true, payload: GDL90::prepare_payload(&mut buf), } } fn generate_ownship_geometric_altitude(e: &Ownship) -> Payload { let mut buf = [0_u8; 5 + 2]; // incl CRC field buf[0] = 0x0B; // type = ownship geometric let alt = (e.hae_altitude / 5) as i16; buf[1] = (alt >> 8) as u8; buf[2] = (alt & 0x00FF) as u8; buf[3] = 0x00; buf[4] = 0x0A; // No Vertical Warning, VFOM = 10 meters Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_ownship(e: &Ownship) -> Payload { let mut buf = [0_u8; 28 + 2]; // incl CRC field buf[0] = 0x0A; buf[1] = 0x01; // alert status = false, identity = ADS-B with Self-assigned address buf[2] = 0xF0; // self-assigned address buf[3] = 0x00; buf[4] = 0x00; // latitude let (lat1, lat2, lat3) = latlon_to_gdl90(e.lat); buf[5] = lat1; buf[6] = lat2; buf[7] = lat3; // longitude let (lon1, lon2, lon3) = latlon_to_gdl90(e.lon); buf[8] = lon1; buf[9] = lon2; buf[10] = lon3; // altitude if let Some(alt) = e.pressure_altitude { let alt = alt_to_gdl90(alt as f32); buf[11] = ((alt & 0xFF0) >> 4) as u8; buf[12] = (((alt & 0x00F) << 4) | 0x09) as u8; // Airborne + True Track } else { buf[11] = 0xFF; buf[12] = 0xF9; // Airborne + True Track } buf[13] = (e.nic << 4) & 0xF0 | e.nacp & 0x0F; let gs = e.gs.round() as u16; let vs = 0x800_u16; // "no vertical rate available" buf[14] = ((gs & 0xFF0) >> 4) as u8; buf[15] = (((gs & 0x00F) << 4) | ((vs & 0x0F00) >> 8)) as u8; buf[16] = (vs & 0xFF) as u8; buf[17] = crs_to_gdl90(e.true_track); buf[18] = 0x01; // Light (ICAO) < 15 500 lbs buf[19] = 'P' as u8; buf[20] = 'i' as u8; buf[21] = 't' as u8; buf[22] = 'o' as u8; buf[23] = 't' as u8; Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_traffic(e: &Target, clock: Instant, pres_alt_valid: bool) -> Payload { let mut buf = [0_u8; 28 + 2]; // incl CRC field buf[0] = 0x14; buf[1] = match e.addr.1 { AddressType::ADSBICAO | AddressType::ADSRICAO => 0, AddressType::ADSBOther | AddressType::ADSROther => 1, AddressType::TISBICAO => 2, AddressType::TISBOther => 3, _ => 3, // unknown }; buf[2] = ((0xFF0000 & e.addr.0) >> 16) as u8; // address buf[3] = ((0x00FF00 & e.addr.0) >> 8) as u8; buf[4] = (0x0000FF & e.addr.0) as u8; // latitude if let Some(((lat, lon), i)) = e.lat_lon { if (clock - i).as_secs() <= MAX_STALE_SECS { let (lat1, lat2, lat3) = latlon_to_gdl90(lat); buf[5] = lat1; buf[6] = lat2; buf[7] = lat3; // longitude let (lon1, lon2, lon3) = latlon_to_gdl90(lon); buf[8] = lon1; buf[9] = lon2; buf[10] = lon3; if let Some(nic) = e.nic { buf[13] |= (nic << 4) & 0xF0; } } } // altitude if let Some((alt, typ, i)) = e.altitude { if (clock - i).as_secs() <= MAX_STALE_SECS { let mut corrected_alt = alt; // if ownship pressure altitude is NOT available, use MSL and attempt to correct it // using GNSS delta if needed if!pres_alt_valid && typ == AltitudeType::Baro { // GDL90 wants pres altitude, try to calculate it from GNSS altitude // if correction is available // Note: GDL90 wants pressure altitude here, // but FF currently uses MSL altitude from // ownship geometric report when calculating altitude // difference, this is to correct Baro altitude // to MSL so that the calculation will be as accurate as possible if let Some(delta) = e.gnss_delta { corrected_alt += delta; } } else if pres_alt_valid && typ == AltitudeType::GNSS { if let Some(delta) = e.gnss_delta { corrected_alt -= delta; } } let alt = alt_to_gdl90(corrected_alt as f32); buf[11] = ((alt & 0xFF0) >> 4) as u8; buf[12] = ((alt & 0x00F) << 4) as u8; } } else { // invalid altitude buf[11] = 0xFF; buf[12] = 0xF0; } if let Some((_, typ, i)) = e.heading { if (clock - i).as_secs() <= MAX_STALE_SECS { match typ { HeadingType::True => buf[12] |= 0x01, HeadingType::Mag => buf[12] |= 0x02, } } } if e.on_ground!= Some(true) { buf[12] |= 0x08; // airborne // if unknown, assume airborne } if let Some(nacp) = e.nacp { buf[13] |= nacp & 0x0F; } // velocity unavailable by default buf[14] = 0xFF; buf[15] = 0xF0; if let Some((spd, _, i)) = e.speed { if (clock - i).as_secs() <= MAX_STALE_SECS { buf[14] = ((spd & 0xFF0) >> 4) as u8; buf[15] = ((spd & 0x00F) << 4) as u8; } } if let Some((vs, i)) = e.vs { if (clock - i).as_secs() <= MAX_STALE_SECS { let vs = (vs as f32 / 64_f32).round() as i16; // see p. 21 buf[15] |= ((vs & 0xF00) >> 8) as u8; buf[16] = (vs & 0xFF) as u8; } else { buf[15] |= 0x08; // no vs } } else { buf[15] |= 0x08; // no vs } if let Some((hdg, _, _)) = e.heading { // valid flag set above buf[17] = crs_to_gdl90(hdg as f32); } if let Some(cat) = e.category { buf[18] = cat; } // insert traffic source buf[19] = match e.source { TrafficSource::UAT => 'u', TrafficSource::ES => 'e', } as u8; buf[20] = match e.addr.1 { AddressType::ADSBICAO | AddressType::ADSBOther => 'a', AddressType::ADSRICAO | AddressType::ADSROther => 'r', AddressType::TISBICAO | AddressType::TISBOther => 't', _ => 'x', } as u8; if let Some(ref cs) = e.callsign { for (i, c) in cs.chars().take(6).enumerate() { buf[21 + i] = c as u8; } } else if let Some(sq) = e.squawk { // squawk available? let squawk_str = format!("{:04}", sq); // 0 padded debug_assert!(squawk_str.len() == 4); let squawk_str = squawk_str.as_bytes(); buf[21] = squawk_str[0]; buf[22] = squawk_str[1]; buf[23] = squawk_str[2]; buf[24] = squawk_str[3]; } if let Some(sq) = e.squawk { if sq == 7700 || sq == 7600 || sq == 7500 { buf[27] = 0x10; // emergency aircraft } } Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } /// Given a buffer containing everything between "Flag Bytes" (see p. 5) /// with the CRC field space allocated but left empty for calculation fn prepare_payload(buf: &mut [u8]) -> Vec<u8> { let len = buf.len() - 2; let crc = buf.iter() .take(len) .scan(0_u16, |crc, b| { *crc = CRC16_TABLE[(*crc >> 8) as usize] ^ (*crc << 8) ^ (*b as u16); Some(*crc) }) .last() .unwrap(); buf[len] = (crc & 0xFF) as u8; buf[len + 1] = (crc >> 8) as u8; // len + CRC (2 bytes) + 2 Flag Bytes + some stuffing bits (don't know yet) let mut tmp = Vec::with_capacity(len + 4); tmp.push(0x7E); for b in buf { if *b == 0x7E || *b == 0x7D { tmp.push(0x7D); tmp.push(*b ^ 0x20); } else { tmp.push(*b); } } tmp.push(0x7E); tmp } } impl GDL90 { pub fn new() -> Box<Protocol> { Box::new(GDL90 { ownship_valid: false, heartbeat_counter: 0, ownship_counter: 0, pres_alt_valid: false, }) } } /// Given coordinate in degrees, return the GDL 90 formatted byte sequence /// From: https://github.com/cyoung/stratux/blob/master/main/gen_gdl90.go#L206 fn latlon_to_gdl90(mut d: f32) -> (u8, u8, u8) { d /= LON_LAT_RESOLUTION; let wk = d.round() as i32; ( ((wk & 0xFF0000) >> 16) as u8, ((wk & 0x00FF00) >> 8) as u8, (wk & 0x0000FF) as u8, ) } fn alt_to_gdl90(mut a: f32) -> u16 { if a < -1000_f32 || a > 101350_f32 { 0xFFF } else
{ self.heartbeat_counter = 0; let utc = handle.get_utc(); handle.push_data(self.generate_heartbeat(&utc)); handle.push_data(GDL90::generate_foreflight_id()); }
conditional_block
gdl90.rs
D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, ]; const HEARTBEAT_FREQ: u16 = 1; const OWNSHIP_FREQ: u16 = 2; const MAX_STALE_SECS: u64 = 6; // do not report data more than 6 sec old pub struct GDL90 { ownship_valid: bool, heartbeat_counter: u32, ownship_counter: u32, /// true if Pressure altitude source exists pres_alt_valid: bool, } impl Protocol for GDL90 { fn run(&mut self, handle: &mut Pushable<Payload>, i: ChainedIter) { let clock = handle.get_clock(); self.ownship_counter += 1; self.heartbeat_counter += 1; for e in i { match *e { Report::Ownship(ref o) => { if self.ownship_counter >= (handle.get_frequency() / OWNSHIP_FREQ) as u32 { self.ownship_counter = 0; self.ownship_valid = o.valid; if o.pressure_altitude.is_some() { self.pres_alt_valid = true; } handle.push_data(GDL90::generate_ownship(o)); handle.push_data(GDL90::generate_ownship_geometric_altitude(o)); } } Report::Traffic(ref o) => { // throttle for Target type is done at traffic processor handle.push_data(GDL90::generate_traffic(o, clock, self.pres_alt_valid)); } Report::FISB(ref o) => handle.push_data(GDL90::generate_uplink(o)), _ => {} } } if self.heartbeat_counter == (handle.get_frequency() / HEARTBEAT_FREQ) as u32 { self.heartbeat_counter = 0; let utc = handle.get_utc(); handle.push_data(self.generate_heartbeat(&utc)); handle.push_data(GDL90::generate_foreflight_id()); } } } impl GDL90 { fn generate_heartbeat(&self, utc: &Tm) -> Payload { let mut buf = [0_u8; 7 + 2]; // incl CRC field buf[0] = 0x00; // type = heartbeat buf[1] = 0x11; // UAT Initialized + ATC Services talkback if self.ownship_valid { buf[1] |= 0x80; } let midnight_utc = Tm { tm_hour: 0, tm_min: 0, tm_sec: 0, ..*utc }; let delta = (*utc - midnight_utc).num_seconds(); buf[2] = ((delta & 0x10000) >> 9) as u8 | 0x01; // MSB + UTC OK buf[3] = (delta & 0xFF) as u8; buf[4] = ((delta & 0xFF00) >> 8) as u8; Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_foreflight_id() -> Payload { // see: https://www.foreflight.com/connect/spec/ let mut buf = [0_u8; 39 + 2]; // incl CRC field buf[0] = 0x65; // type = FF buf[1] = 0x00; // sub ID = 0 buf[2] = 0x01; // version = 1 for i in 3..11 { buf[i] = 0xFF; // serial = invalid } buf[11] = 'P' as u8; buf[12] = 'i' as u8; buf[13] = 't' as u8; buf[14] = 'o' as u8; buf[15] = 't' as u8; buf[20] = 'P' as u8; buf[21] = 'i' as u8; buf[22] = 't' as u8; buf[23] = 'o' as u8; buf[24] = 't' as u8; // datum is WGS-84 ellipsoid buf[38] = 0x00; Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_uplink(e: &FISBData) -> Payload { let mut buf = [0_u8; 436 + 2]; // incl CRC field buf[0] = 0x07; // type = uplink buf[1] = 0xFF; buf[2] = 0xFF; buf[3] = 0xFF; &buf[4..436].clone_from_slice(&e.payload); Payload { queueable: true, payload: GDL90::prepare_payload(&mut buf), } } fn generate_ownship_geometric_altitude(e: &Ownship) -> Payload { let mut buf = [0_u8; 5 + 2]; // incl CRC field buf[0] = 0x0B; // type = ownship geometric let alt = (e.hae_altitude / 5) as i16; buf[1] = (alt >> 8) as u8; buf[2] = (alt & 0x00FF) as u8; buf[3] = 0x00; buf[4] = 0x0A; // No Vertical Warning, VFOM = 10 meters Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_ownship(e: &Ownship) -> Payload { let mut buf = [0_u8; 28 + 2]; // incl CRC field buf[0] = 0x0A; buf[1] = 0x01; // alert status = false, identity = ADS-B with Self-assigned address buf[2] = 0xF0; // self-assigned address buf[3] = 0x00; buf[4] = 0x00; // latitude let (lat1, lat2, lat3) = latlon_to_gdl90(e.lat); buf[5] = lat1; buf[6] = lat2; buf[7] = lat3; // longitude let (lon1, lon2, lon3) = latlon_to_gdl90(e.lon); buf[8] = lon1; buf[9] = lon2; buf[10] = lon3; // altitude if let Some(alt) = e.pressure_altitude { let alt = alt_to_gdl90(alt as f32); buf[11] = ((alt & 0xFF0) >> 4) as u8; buf[12] = (((alt & 0x00F) << 4) | 0x09) as u8; // Airborne + True Track } else { buf[11] = 0xFF; buf[12] = 0xF9; // Airborne + True Track } buf[13] = (e.nic << 4) & 0xF0 | e.nacp & 0x0F; let gs = e.gs.round() as u16; let vs = 0x800_u16; // "no vertical rate available" buf[14] = ((gs & 0xFF0) >> 4) as u8; buf[15] = (((gs & 0x00F) << 4) | ((vs & 0x0F00) >> 8)) as u8; buf[16] = (vs & 0xFF) as u8; buf[17] = crs_to_gdl90(e.true_track); buf[18] = 0x01; // Light (ICAO) < 15 500 lbs buf[19] = 'P' as u8; buf[20] = 'i' as u8; buf[21] = 't' as u8; buf[22] = 'o' as u8; buf[23] = 't' as u8; Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } fn generate_traffic(e: &Target, clock: Instant, pres_alt_valid: bool) -> Payload { let mut buf = [0_u8; 28 + 2]; // incl CRC field buf[0] = 0x14; buf[1] = match e.addr.1 { AddressType::ADSBICAO | AddressType::ADSRICAO => 0, AddressType::ADSBOther | AddressType::ADSROther => 1, AddressType::TISBICAO => 2, AddressType::TISBOther => 3, _ => 3, // unknown }; buf[2] = ((0xFF0000 & e.addr.0) >> 16) as u8; // address buf[3] = ((0x00FF00 & e.addr.0) >> 8) as u8; buf[4] = (0x0000FF & e.addr.0) as u8; // latitude if let Some(((lat, lon), i)) = e.lat_lon { if (clock - i).as_secs() <= MAX_STALE_SECS { let (lat1, lat2, lat3) = latlon_to_gdl90(lat); buf[5] = lat1; buf[6] = lat2; buf[7] = lat3; // longitude let (lon1, lon2, lon3) = latlon_to_gdl90(lon); buf[8] = lon1; buf[9] = lon2; buf[10] = lon3; if let Some(nic) = e.nic { buf[13] |= (nic << 4) & 0xF0; } } } // altitude if let Some((alt, typ, i)) = e.altitude { if (clock - i).as_secs() <= MAX_STALE_SECS { let mut corrected_alt = alt; // if ownship pressure altitude is NOT available, use MSL and attempt to correct it // using GNSS delta if needed if!pres_alt_valid && typ == AltitudeType::Baro { // GDL90 wants pres altitude, try to calculate it from GNSS altitude // if correction is available // Note: GDL90 wants pressure altitude here, // but FF currently uses MSL altitude from // ownship geometric report when calculating altitude // difference, this is to correct Baro altitude // to MSL so that the calculation will be as accurate as possible if let Some(delta) = e.gnss_delta { corrected_alt += delta; } } else if pres_alt_valid && typ == AltitudeType::GNSS { if let Some(delta) = e.gnss_delta { corrected_alt -= delta; } } let alt = alt_to_gdl90(corrected_alt as f32); buf[11] = ((alt & 0xFF0) >> 4) as u8; buf[12] = ((alt & 0x00F) << 4) as u8; } } else { // invalid altitude buf[11] = 0xFF; buf[12] = 0xF0; } if let Some((_, typ, i)) = e.heading { if (clock - i).as_secs() <= MAX_STALE_SECS { match typ { HeadingType::True => buf[12] |= 0x01, HeadingType::Mag => buf[12] |= 0x02, } } } if e.on_ground!= Some(true) { buf[12] |= 0x08; // airborne // if unknown, assume airborne } if let Some(nacp) = e.nacp { buf[13] |= nacp & 0x0F; } // velocity unavailable by default buf[14] = 0xFF; buf[15] = 0xF0; if let Some((spd, _, i)) = e.speed { if (clock - i).as_secs() <= MAX_STALE_SECS { buf[14] = ((spd & 0xFF0) >> 4) as u8; buf[15] = ((spd & 0x00F) << 4) as u8; } } if let Some((vs, i)) = e.vs { if (clock - i).as_secs() <= MAX_STALE_SECS { let vs = (vs as f32 / 64_f32).round() as i16; // see p. 21 buf[15] |= ((vs & 0xF00) >> 8) as u8; buf[16] = (vs & 0xFF) as u8; } else { buf[15] |= 0x08; // no vs } } else { buf[15] |= 0x08; // no vs } if let Some((hdg, _, _)) = e.heading { // valid flag set above buf[17] = crs_to_gdl90(hdg as f32); } if let Some(cat) = e.category { buf[18] = cat; } // insert traffic source buf[19] = match e.source { TrafficSource::UAT => 'u', TrafficSource::ES => 'e', } as u8; buf[20] = match e.addr.1 { AddressType::ADSBICAO | AddressType::ADSBOther => 'a', AddressType::ADSRICAO | AddressType::ADSROther => 'r', AddressType::TISBICAO | AddressType::TISBOther => 't', _ => 'x', } as u8; if let Some(ref cs) = e.callsign { for (i, c) in cs.chars().take(6).enumerate() { buf[21 + i] = c as u8; } } else if let Some(sq) = e.squawk { // squawk available? let squawk_str = format!("{:04}", sq); // 0 padded debug_assert!(squawk_str.len() == 4); let squawk_str = squawk_str.as_bytes(); buf[21] = squawk_str[0]; buf[22] = squawk_str[1]; buf[23] = squawk_str[2]; buf[24] = squawk_str[3]; } if let Some(sq) = e.squawk { if sq == 7700 || sq == 7600 || sq == 7500 { buf[27] = 0x10; // emergency aircraft } } Payload { queueable: false, payload: GDL90::prepare_payload(&mut buf), } } /// Given a buffer containing everything between "Flag Bytes" (see p. 5) /// with the CRC field space allocated but left empty for calculation fn prepare_payload(buf: &mut [u8]) -> Vec<u8>
if *b == 0x7E || *b == 0x7D { tmp.push(0x7D); tmp.push(*b ^ 0x20); } else { tmp.push(*b); } } tmp.push(0x7E); tmp } } impl GDL90 { pub fn new() -> Box<Protocol> { Box::new(GDL90 { ownship_valid: false, heartbeat_counter: 0, ownship_counter: 0, pres_alt_valid: false, }) } } /// Given coordinate in degrees, return the GDL 90 formatted byte sequence /// From: https://github.com/cyoung/stratux/blob/master/main/gen_gdl90.go#L206 fn latlon_to_gdl90(mut d: f32) -> (u8, u8, u8) { d /= LON_LAT_RESOLUTION; let wk = d.round() as i32; ( ((wk & 0xFF0000) >> 16) as u8, ((wk & 0x00FF00) >> 8) as u8, (wk & 0x0000FF) as u8, ) } fn alt_to_gdl90(mut a: f32) -> u16 { if a < -1000_f32 || a > 101350_f32 { 0xFFF } else
{ let len = buf.len() - 2; let crc = buf.iter() .take(len) .scan(0_u16, |crc, b| { *crc = CRC16_TABLE[(*crc >> 8) as usize] ^ (*crc << 8) ^ (*b as u16); Some(*crc) }) .last() .unwrap(); buf[len] = (crc & 0xFF) as u8; buf[len + 1] = (crc >> 8) as u8; // len + CRC (2 bytes) + 2 Flag Bytes + some stuffing bits (don't know yet) let mut tmp = Vec::with_capacity(len + 4); tmp.push(0x7E); for b in buf {
identifier_body
unique-send-2.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. use core::comm::*; fn child(c: &SharedChan<~uint>, i: uint) { c.send(~i); } pub fn main() { let (p, ch) = stream(); let ch = SharedChan(ch); let n = 100u; let mut expected = 0u; for uint::range(0u, n) |i| { let ch = ch.clone(); task::spawn(|| child(&ch, i) ); expected += i; }
let mut actual = 0u; for uint::range(0u, n) |_i| { let j = p.recv(); actual += *j; } assert!(expected == actual); }
random_line_split
unique-send-2.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. use core::comm::*; fn child(c: &SharedChan<~uint>, i: uint) { c.send(~i); } pub fn
() { let (p, ch) = stream(); let ch = SharedChan(ch); let n = 100u; let mut expected = 0u; for uint::range(0u, n) |i| { let ch = ch.clone(); task::spawn(|| child(&ch, i) ); expected += i; } let mut actual = 0u; for uint::range(0u, n) |_i| { let j = p.recv(); actual += *j; } assert!(expected == actual); }
main
identifier_name
unique-send-2.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. use core::comm::*; fn child(c: &SharedChan<~uint>, i: uint)
pub fn main() { let (p, ch) = stream(); let ch = SharedChan(ch); let n = 100u; let mut expected = 0u; for uint::range(0u, n) |i| { let ch = ch.clone(); task::spawn(|| child(&ch, i) ); expected += i; } let mut actual = 0u; for uint::range(0u, n) |_i| { let j = p.recv(); actual += *j; } assert!(expected == actual); }
{ c.send(~i); }
identifier_body
lib.rs
// ================================================================= // // * WARNING * // // This file is generated! // // Changes made to this file will be overwritten. If changes are // required to the generated code, the service_crategen project // must be updated to generate the changes. // // ================================================================= #![doc( html_logo_url = "https://raw.githubusercontent.com/rusoto/rusoto/master/assets/logo-square.png"
mod custom; mod generated; pub use custom::*; pub use generated::*;
)] //! <p>AWS Cloud Map lets you configure public DNS, private DNS, or HTTP namespaces that your microservice applications run in. When an instance of the service becomes available, you can call the AWS Cloud Map API to register the instance with AWS Cloud Map. For public or private DNS namespaces, AWS Cloud Map automatically creates DNS records and an optional health check. Clients that submit public or private DNS queries, or HTTP requests, for the service receive an answer that contains up to eight healthy records. </p> //! //! If you're using the service, you're probably looking for [ServiceDiscoveryClient](struct.ServiceDiscoveryClient.html) and [ServiceDiscovery](trait.ServiceDiscovery.html).
random_line_split
storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::StorageMethods; use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast}; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::event::{EventBubbles, EventCancelable}; use dom::storageevent::StorageEvent; use dom::urlhelper::UrlHelper; use ipc_channel::ipc; use net_traits::storage_task::{StorageTask, StorageTaskMsg, StorageType}; use page::IterablePage; use script_task::{ScriptTask, MainThreadRunnable, MainThreadScriptMsg}; use std::borrow::ToOwned; use std::sync::mpsc::channel; use url::Url; use util::str::DOMString; #[dom_struct] pub struct Storage { reflector_: Reflector, global: GlobalField, storage_type: StorageType } impl Storage { fn new_inherited(global: &GlobalRef, storage_type: StorageType) -> Storage { Storage { reflector_: Reflector::new(), global: GlobalField::from_rooted(global), storage_type: storage_type } } pub fn new(global: &GlobalRef, storage_type: StorageType) -> Root<Storage> { reflect_dom_object(box Storage::new_inherited(global, storage_type), *global, StorageBinding::Wrap) } fn get_url(&self) -> Url { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.get_url() } fn get_storage_task(&self) -> StorageTask { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.as_window().storage_task() } } impl StorageMethods for Storage { // https://html.spec.whatwg.org/multipage/#dom-storage-length fn Length(&self) -> u32 { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Length(sender, self.get_url(), self.storage_type)).unwrap(); receiver.recv().unwrap() as u32 } // https://html.spec.whatwg.org/multipage/#dom-storage-key fn Key(&self, index: u32) -> Option<DOMString> { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Key(sender, self.get_url(), self.storage_type, index)).unwrap(); receiver.recv().unwrap() } // https://html.spec.whatwg.org/multipage/#dom-storage-getitem fn GetItem(&self, name: DOMString) -> Option<DOMString> { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::GetItem(sender, self.get_url(), self.storage_type, name); self.get_storage_task().send(msg).unwrap(); receiver.recv().unwrap() } // https://html.spec.whatwg.org/multipage/#dom-storage-setitem fn SetItem(&self, name: DOMString, value: DOMString) { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::SetItem(sender, self.get_url(), self.storage_type, name.clone(), value.clone()); self.get_storage_task().send(msg).unwrap(); let (changed, old_value) = receiver.recv().unwrap(); if changed { self.broadcast_change_notification(Some(name), old_value, Some(value)); } } // https://html.spec.whatwg.org/multipage/#dom-storage-removeitem fn RemoveItem(&self, name: DOMString) { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone()); self.get_storage_task().send(msg).unwrap(); if let Some(old_value) = receiver.recv().unwrap() { self.broadcast_change_notification(Some(name), Some(old_value), None); } } // https://html.spec.whatwg.org/multipage/#dom-storage-clear fn Clear(&self) { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Clear(sender, self.get_url(), self.storage_type)).unwrap(); if receiver.recv().unwrap() { self.broadcast_change_notification(None, None, None); } } // check-tidy: no specs after this line fn NamedGetter(&self, name: DOMString, found: &mut bool) -> Option<DOMString> { let item = self.GetItem(name); *found = item.is_some(); item } fn NamedSetter(&self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn
(&self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn NamedDeleter(&self, name: DOMString) { self.RemoveItem(name); } fn SupportedPropertyNames(&self) -> Vec<DOMString> { // FIXME: unimplemented (https://github.com/servo/servo/issues/7273) vec![] } } impl Storage { /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification fn broadcast_change_notification(&self, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>) { let global_root = self.global.root(); let global_ref = global_root.r(); let main_script_chan = global_ref.as_window().main_thread_script_chan(); let script_chan = global_ref.script_chan(); let trusted_storage = Trusted::new(global_ref.get_cx(), self, script_chan.clone()); main_script_chan.send(MainThreadScriptMsg::MainThreadRunnableMsg( box StorageEventRunnable::new(trusted_storage, key, old_value, new_value))).unwrap(); } } pub struct StorageEventRunnable { element: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString> } impl StorageEventRunnable { fn new(storage: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>) -> StorageEventRunnable { StorageEventRunnable { element: storage, key: key, old_value: old_value, new_value: new_value } } } impl MainThreadRunnable for StorageEventRunnable { fn handler(self: Box<StorageEventRunnable>, script_task: &ScriptTask) { let this = *self; let storage_root = this.element.root(); let storage = storage_root.r(); let global_root = storage.global.root(); let global_ref = global_root.r(); let ev_window = global_ref.as_window(); let ev_url = storage.get_url(); let storage_event = StorageEvent::new( global_ref, "storage".to_owned(), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, this.key, this.old_value, this.new_value, ev_url.to_string(), Some(storage) ); let event = EventCast::from_ref(storage_event.r()); let root_page = script_task.root_page(); for it_page in root_page.iter() { let it_window_root = it_page.window(); let it_window = it_window_root.r(); assert!(UrlHelper::SameOrigin(&ev_url, &it_window.get_url())); // TODO: Such a Document object is not necessarily fully active, but events fired on such // objects are ignored by the event loop until the Document becomes fully active again. if ev_window.pipeline()!= it_window.pipeline() { let target = EventTargetCast::from_ref(it_window); event.fire(target); } } } }
NamedCreator
identifier_name
storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::StorageMethods; use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast}; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::event::{EventBubbles, EventCancelable}; use dom::storageevent::StorageEvent; use dom::urlhelper::UrlHelper; use ipc_channel::ipc; use net_traits::storage_task::{StorageTask, StorageTaskMsg, StorageType}; use page::IterablePage; use script_task::{ScriptTask, MainThreadRunnable, MainThreadScriptMsg}; use std::borrow::ToOwned; use std::sync::mpsc::channel; use url::Url; use util::str::DOMString; #[dom_struct] pub struct Storage { reflector_: Reflector, global: GlobalField, storage_type: StorageType } impl Storage { fn new_inherited(global: &GlobalRef, storage_type: StorageType) -> Storage { Storage { reflector_: Reflector::new(), global: GlobalField::from_rooted(global), storage_type: storage_type } }
reflect_dom_object(box Storage::new_inherited(global, storage_type), *global, StorageBinding::Wrap) } fn get_url(&self) -> Url { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.get_url() } fn get_storage_task(&self) -> StorageTask { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.as_window().storage_task() } } impl StorageMethods for Storage { // https://html.spec.whatwg.org/multipage/#dom-storage-length fn Length(&self) -> u32 { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Length(sender, self.get_url(), self.storage_type)).unwrap(); receiver.recv().unwrap() as u32 } // https://html.spec.whatwg.org/multipage/#dom-storage-key fn Key(&self, index: u32) -> Option<DOMString> { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Key(sender, self.get_url(), self.storage_type, index)).unwrap(); receiver.recv().unwrap() } // https://html.spec.whatwg.org/multipage/#dom-storage-getitem fn GetItem(&self, name: DOMString) -> Option<DOMString> { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::GetItem(sender, self.get_url(), self.storage_type, name); self.get_storage_task().send(msg).unwrap(); receiver.recv().unwrap() } // https://html.spec.whatwg.org/multipage/#dom-storage-setitem fn SetItem(&self, name: DOMString, value: DOMString) { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::SetItem(sender, self.get_url(), self.storage_type, name.clone(), value.clone()); self.get_storage_task().send(msg).unwrap(); let (changed, old_value) = receiver.recv().unwrap(); if changed { self.broadcast_change_notification(Some(name), old_value, Some(value)); } } // https://html.spec.whatwg.org/multipage/#dom-storage-removeitem fn RemoveItem(&self, name: DOMString) { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone()); self.get_storage_task().send(msg).unwrap(); if let Some(old_value) = receiver.recv().unwrap() { self.broadcast_change_notification(Some(name), Some(old_value), None); } } // https://html.spec.whatwg.org/multipage/#dom-storage-clear fn Clear(&self) { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Clear(sender, self.get_url(), self.storage_type)).unwrap(); if receiver.recv().unwrap() { self.broadcast_change_notification(None, None, None); } } // check-tidy: no specs after this line fn NamedGetter(&self, name: DOMString, found: &mut bool) -> Option<DOMString> { let item = self.GetItem(name); *found = item.is_some(); item } fn NamedSetter(&self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn NamedCreator(&self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn NamedDeleter(&self, name: DOMString) { self.RemoveItem(name); } fn SupportedPropertyNames(&self) -> Vec<DOMString> { // FIXME: unimplemented (https://github.com/servo/servo/issues/7273) vec![] } } impl Storage { /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification fn broadcast_change_notification(&self, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>) { let global_root = self.global.root(); let global_ref = global_root.r(); let main_script_chan = global_ref.as_window().main_thread_script_chan(); let script_chan = global_ref.script_chan(); let trusted_storage = Trusted::new(global_ref.get_cx(), self, script_chan.clone()); main_script_chan.send(MainThreadScriptMsg::MainThreadRunnableMsg( box StorageEventRunnable::new(trusted_storage, key, old_value, new_value))).unwrap(); } } pub struct StorageEventRunnable { element: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString> } impl StorageEventRunnable { fn new(storage: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>) -> StorageEventRunnable { StorageEventRunnable { element: storage, key: key, old_value: old_value, new_value: new_value } } } impl MainThreadRunnable for StorageEventRunnable { fn handler(self: Box<StorageEventRunnable>, script_task: &ScriptTask) { let this = *self; let storage_root = this.element.root(); let storage = storage_root.r(); let global_root = storage.global.root(); let global_ref = global_root.r(); let ev_window = global_ref.as_window(); let ev_url = storage.get_url(); let storage_event = StorageEvent::new( global_ref, "storage".to_owned(), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, this.key, this.old_value, this.new_value, ev_url.to_string(), Some(storage) ); let event = EventCast::from_ref(storage_event.r()); let root_page = script_task.root_page(); for it_page in root_page.iter() { let it_window_root = it_page.window(); let it_window = it_window_root.r(); assert!(UrlHelper::SameOrigin(&ev_url, &it_window.get_url())); // TODO: Such a Document object is not necessarily fully active, but events fired on such // objects are ignored by the event loop until the Document becomes fully active again. if ev_window.pipeline()!= it_window.pipeline() { let target = EventTargetCast::from_ref(it_window); event.fire(target); } } } }
pub fn new(global: &GlobalRef, storage_type: StorageType) -> Root<Storage> {
random_line_split
storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::StorageMethods; use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast}; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::event::{EventBubbles, EventCancelable}; use dom::storageevent::StorageEvent; use dom::urlhelper::UrlHelper; use ipc_channel::ipc; use net_traits::storage_task::{StorageTask, StorageTaskMsg, StorageType}; use page::IterablePage; use script_task::{ScriptTask, MainThreadRunnable, MainThreadScriptMsg}; use std::borrow::ToOwned; use std::sync::mpsc::channel; use url::Url; use util::str::DOMString; #[dom_struct] pub struct Storage { reflector_: Reflector, global: GlobalField, storage_type: StorageType } impl Storage { fn new_inherited(global: &GlobalRef, storage_type: StorageType) -> Storage { Storage { reflector_: Reflector::new(), global: GlobalField::from_rooted(global), storage_type: storage_type } } pub fn new(global: &GlobalRef, storage_type: StorageType) -> Root<Storage> { reflect_dom_object(box Storage::new_inherited(global, storage_type), *global, StorageBinding::Wrap) } fn get_url(&self) -> Url { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.get_url() } fn get_storage_task(&self) -> StorageTask { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.as_window().storage_task() } } impl StorageMethods for Storage { // https://html.spec.whatwg.org/multipage/#dom-storage-length fn Length(&self) -> u32 { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Length(sender, self.get_url(), self.storage_type)).unwrap(); receiver.recv().unwrap() as u32 } // https://html.spec.whatwg.org/multipage/#dom-storage-key fn Key(&self, index: u32) -> Option<DOMString> { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Key(sender, self.get_url(), self.storage_type, index)).unwrap(); receiver.recv().unwrap() } // https://html.spec.whatwg.org/multipage/#dom-storage-getitem fn GetItem(&self, name: DOMString) -> Option<DOMString> { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::GetItem(sender, self.get_url(), self.storage_type, name); self.get_storage_task().send(msg).unwrap(); receiver.recv().unwrap() } // https://html.spec.whatwg.org/multipage/#dom-storage-setitem fn SetItem(&self, name: DOMString, value: DOMString) { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::SetItem(sender, self.get_url(), self.storage_type, name.clone(), value.clone()); self.get_storage_task().send(msg).unwrap(); let (changed, old_value) = receiver.recv().unwrap(); if changed { self.broadcast_change_notification(Some(name), old_value, Some(value)); } } // https://html.spec.whatwg.org/multipage/#dom-storage-removeitem fn RemoveItem(&self, name: DOMString) { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone()); self.get_storage_task().send(msg).unwrap(); if let Some(old_value) = receiver.recv().unwrap()
} // https://html.spec.whatwg.org/multipage/#dom-storage-clear fn Clear(&self) { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Clear(sender, self.get_url(), self.storage_type)).unwrap(); if receiver.recv().unwrap() { self.broadcast_change_notification(None, None, None); } } // check-tidy: no specs after this line fn NamedGetter(&self, name: DOMString, found: &mut bool) -> Option<DOMString> { let item = self.GetItem(name); *found = item.is_some(); item } fn NamedSetter(&self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn NamedCreator(&self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn NamedDeleter(&self, name: DOMString) { self.RemoveItem(name); } fn SupportedPropertyNames(&self) -> Vec<DOMString> { // FIXME: unimplemented (https://github.com/servo/servo/issues/7273) vec![] } } impl Storage { /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification fn broadcast_change_notification(&self, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>) { let global_root = self.global.root(); let global_ref = global_root.r(); let main_script_chan = global_ref.as_window().main_thread_script_chan(); let script_chan = global_ref.script_chan(); let trusted_storage = Trusted::new(global_ref.get_cx(), self, script_chan.clone()); main_script_chan.send(MainThreadScriptMsg::MainThreadRunnableMsg( box StorageEventRunnable::new(trusted_storage, key, old_value, new_value))).unwrap(); } } pub struct StorageEventRunnable { element: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString> } impl StorageEventRunnable { fn new(storage: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>) -> StorageEventRunnable { StorageEventRunnable { element: storage, key: key, old_value: old_value, new_value: new_value } } } impl MainThreadRunnable for StorageEventRunnable { fn handler(self: Box<StorageEventRunnable>, script_task: &ScriptTask) { let this = *self; let storage_root = this.element.root(); let storage = storage_root.r(); let global_root = storage.global.root(); let global_ref = global_root.r(); let ev_window = global_ref.as_window(); let ev_url = storage.get_url(); let storage_event = StorageEvent::new( global_ref, "storage".to_owned(), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, this.key, this.old_value, this.new_value, ev_url.to_string(), Some(storage) ); let event = EventCast::from_ref(storage_event.r()); let root_page = script_task.root_page(); for it_page in root_page.iter() { let it_window_root = it_page.window(); let it_window = it_window_root.r(); assert!(UrlHelper::SameOrigin(&ev_url, &it_window.get_url())); // TODO: Such a Document object is not necessarily fully active, but events fired on such // objects are ignored by the event loop until the Document becomes fully active again. if ev_window.pipeline()!= it_window.pipeline() { let target = EventTargetCast::from_ref(it_window); event.fire(target); } } } }
{ self.broadcast_change_notification(Some(name), Some(old_value), None); }
conditional_block
storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::StorageMethods; use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast}; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::event::{EventBubbles, EventCancelable}; use dom::storageevent::StorageEvent; use dom::urlhelper::UrlHelper; use ipc_channel::ipc; use net_traits::storage_task::{StorageTask, StorageTaskMsg, StorageType}; use page::IterablePage; use script_task::{ScriptTask, MainThreadRunnable, MainThreadScriptMsg}; use std::borrow::ToOwned; use std::sync::mpsc::channel; use url::Url; use util::str::DOMString; #[dom_struct] pub struct Storage { reflector_: Reflector, global: GlobalField, storage_type: StorageType } impl Storage { fn new_inherited(global: &GlobalRef, storage_type: StorageType) -> Storage { Storage { reflector_: Reflector::new(), global: GlobalField::from_rooted(global), storage_type: storage_type } } pub fn new(global: &GlobalRef, storage_type: StorageType) -> Root<Storage> { reflect_dom_object(box Storage::new_inherited(global, storage_type), *global, StorageBinding::Wrap) } fn get_url(&self) -> Url { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.get_url() } fn get_storage_task(&self) -> StorageTask { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.as_window().storage_task() } } impl StorageMethods for Storage { // https://html.spec.whatwg.org/multipage/#dom-storage-length fn Length(&self) -> u32 { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Length(sender, self.get_url(), self.storage_type)).unwrap(); receiver.recv().unwrap() as u32 } // https://html.spec.whatwg.org/multipage/#dom-storage-key fn Key(&self, index: u32) -> Option<DOMString> { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Key(sender, self.get_url(), self.storage_type, index)).unwrap(); receiver.recv().unwrap() } // https://html.spec.whatwg.org/multipage/#dom-storage-getitem fn GetItem(&self, name: DOMString) -> Option<DOMString> { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::GetItem(sender, self.get_url(), self.storage_type, name); self.get_storage_task().send(msg).unwrap(); receiver.recv().unwrap() } // https://html.spec.whatwg.org/multipage/#dom-storage-setitem fn SetItem(&self, name: DOMString, value: DOMString) { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::SetItem(sender, self.get_url(), self.storage_type, name.clone(), value.clone()); self.get_storage_task().send(msg).unwrap(); let (changed, old_value) = receiver.recv().unwrap(); if changed { self.broadcast_change_notification(Some(name), old_value, Some(value)); } } // https://html.spec.whatwg.org/multipage/#dom-storage-removeitem fn RemoveItem(&self, name: DOMString)
// https://html.spec.whatwg.org/multipage/#dom-storage-clear fn Clear(&self) { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Clear(sender, self.get_url(), self.storage_type)).unwrap(); if receiver.recv().unwrap() { self.broadcast_change_notification(None, None, None); } } // check-tidy: no specs after this line fn NamedGetter(&self, name: DOMString, found: &mut bool) -> Option<DOMString> { let item = self.GetItem(name); *found = item.is_some(); item } fn NamedSetter(&self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn NamedCreator(&self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn NamedDeleter(&self, name: DOMString) { self.RemoveItem(name); } fn SupportedPropertyNames(&self) -> Vec<DOMString> { // FIXME: unimplemented (https://github.com/servo/servo/issues/7273) vec![] } } impl Storage { /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification fn broadcast_change_notification(&self, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>) { let global_root = self.global.root(); let global_ref = global_root.r(); let main_script_chan = global_ref.as_window().main_thread_script_chan(); let script_chan = global_ref.script_chan(); let trusted_storage = Trusted::new(global_ref.get_cx(), self, script_chan.clone()); main_script_chan.send(MainThreadScriptMsg::MainThreadRunnableMsg( box StorageEventRunnable::new(trusted_storage, key, old_value, new_value))).unwrap(); } } pub struct StorageEventRunnable { element: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString> } impl StorageEventRunnable { fn new(storage: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>) -> StorageEventRunnable { StorageEventRunnable { element: storage, key: key, old_value: old_value, new_value: new_value } } } impl MainThreadRunnable for StorageEventRunnable { fn handler(self: Box<StorageEventRunnable>, script_task: &ScriptTask) { let this = *self; let storage_root = this.element.root(); let storage = storage_root.r(); let global_root = storage.global.root(); let global_ref = global_root.r(); let ev_window = global_ref.as_window(); let ev_url = storage.get_url(); let storage_event = StorageEvent::new( global_ref, "storage".to_owned(), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, this.key, this.old_value, this.new_value, ev_url.to_string(), Some(storage) ); let event = EventCast::from_ref(storage_event.r()); let root_page = script_task.root_page(); for it_page in root_page.iter() { let it_window_root = it_page.window(); let it_window = it_window_root.r(); assert!(UrlHelper::SameOrigin(&ev_url, &it_window.get_url())); // TODO: Such a Document object is not necessarily fully active, but events fired on such // objects are ignored by the event loop until the Document becomes fully active again. if ev_window.pipeline()!= it_window.pipeline() { let target = EventTargetCast::from_ref(it_window); event.fire(target); } } } }
{ let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone()); self.get_storage_task().send(msg).unwrap(); if let Some(old_value) = receiver.recv().unwrap() { self.broadcast_change_notification(Some(name), Some(old_value), None); } }
identifier_body
tree.rs
/// Async server-side trees use std::{ops, fmt, mem}; use dbus::tree::{Factory, Tree, MethodType, DataType, MTFn, Method, MethodInfo, MethodErr}; use dbus::{Member, Message, Connection}; use std::marker::PhantomData; use std::cell::RefCell; use futures::{IntoFuture, Future, Poll, Stream, Async}; use std::ffi::CString; pub trait ADataType: fmt::Debug + Sized + Default { type ObjectPath: fmt::Debug; type Property: fmt::Debug; type Interface: fmt::Debug + Default; type Method: fmt::Debug + Default; type Signal: fmt::Debug; } #[derive(Debug, Default)] /// A Tree that allows both synchronous and asynchronous methods. pub struct ATree<D: ADataType>(RefCell<Option<AMethodResult>>, PhantomData<*const D>); impl<D: ADataType> ATree<D> { pub fn
() -> Self { Default::default() } fn push(&self, a: AMethodResult) { let mut z = self.0.borrow_mut(); assert!(z.is_none(), "Same message handled twice"); *z = Some(a); } } impl<D: ADataType> DataType for ATree<D> { type Tree = ATree<D>; type ObjectPath = D::ObjectPath; type Property = D::Property; type Interface = D::Interface; type Method = D::Method; type Signal = D::Signal; } impl ADataType for () { type ObjectPath = (); type Property = (); type Interface = (); type Method = (); type Signal = (); } /// A Tree factory that allows both synchronous and asynchronous methods. pub struct AFactory<M: MethodType<D>, D: DataType = ()>(Factory<M, D>); impl AFactory<MTFn<()>, ()> { pub fn new_afn<D: ADataType>() -> AFactory<MTFn<ATree<D>>, ATree<D>> { AFactory(Factory::new_fn()) } } impl<M: MethodType<D>, D: DataType> ops::Deref for AFactory<M, D> { type Target = Factory<M, D>; fn deref(&self) -> &Self::Target { &self.0 } } impl<D: ADataType> AFactory<MTFn<ATree<D>>, ATree<D>> { /// Creates an async method, for methods whose result cannot be returned immediately. /// /// The method handler supplied to amethod returns a future, which resolves into the method result. /// See the tokio_server example for some hints on how to use it. pub fn amethod<H, R, T>(&self, t: T, data: D::Method, handler: H) -> Method<MTFn<ATree<D>>, ATree<D>> where H:'static + Fn(&MethodInfo<MTFn<ATree<D>>, ATree<D>>) -> R, T: Into<Member<'static>>, R:'static + IntoFuture<Item=Vec<Message>, Error=MethodErr> { self.0.method(t, data, move |minfo| { let r = handler(minfo); minfo.tree.get_data().push(AMethodResult::new(r)); Ok(Vec::new()) }) } } /// A Future method result /// /// When method results cannot be returned right away, the AMethodResult holds it temporarily struct AMethodResult(Box<Future<Item=Vec<Message>, Error=MethodErr>>, Option<Message>); impl fmt::Debug for AMethodResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "AMethodResult({:?})", self.1) } } impl AMethodResult { fn new<F:'static + IntoFuture<Item=Vec<Message>, Error=MethodErr>>(f: F) -> Self { AMethodResult(Box::new(f.into_future()), None) } } impl Future for AMethodResult { type Item = Vec<Message>; type Error = MethodErr; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { self.0.poll() } } #[derive(Debug)] /// Creates a filter for incoming messages, that handles messages in the tree. /// /// See the tokio_server example for some hints on how to use it. pub struct ATreeServer<C,T,D,S> where C: ops::Deref<Target=Connection>, T: ops::Deref<Target=Tree<MTFn<ATree<D>>, ATree<D>>>, D: ADataType { conn: C, tree: T, stream: S, pendingresults: Vec<AMethodResult>, } impl<C,T,D,S> ATreeServer<C,T,D,S> where C: ops::Deref<Target=Connection>, T: ops::Deref<Target=Tree<MTFn<ATree<D>>, ATree<D>>>, S: Stream<Item=Message, Error=()>, D: ADataType { pub fn new(c: C, t: T, stream: S) -> Self { ATreeServer { conn: c, tree: t, stream: stream, pendingresults: vec![] } } fn spawn_method_results(&mut self, msg: Message) { let v = self.tree.get_data().0.borrow_mut().take(); if let Some(mut r) = v { if r.1.is_none() { r.1 = Some(msg); }; // println!("Pushing {:?}", r); self.pendingresults.push(r); } } fn check_pending_results(&mut self) { let v = mem::replace(&mut self.pendingresults, vec!()); self.pendingresults = v.into_iter().filter_map(|mut mr| { let z = mr.poll(); // println!("Polling {:?} returned {:?}", mr, z); match z { Ok(Async::NotReady) => Some(mr), Ok(Async::Ready(t)) => { for msg in t { self.conn.send(msg).expect("D-Bus send error"); }; None }, Err(e) => { let m = mr.1.take().unwrap(); let msg = m.error(&e.errorname(), &CString::new(e.description()).unwrap()); self.conn.send(msg).expect("D-Bus send error"); None } } }).collect(); } } impl<C,T,D,S> Stream for ATreeServer<C,T,D,S> where C: ops::Deref<Target=Connection>, T: ops::Deref<Target=Tree<MTFn<ATree<D>>, ATree<D>>>, S: Stream<Item=Message, Error=()>, D: ADataType { type Item = Message; type Error = (); fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { loop { self.check_pending_results(); let z = self.stream.poll(); if let Ok(Async::Ready(Some(m))) = z { // println!("treeserver {:?}", m); let hh = self.tree.handle(&m); // println!("hh: {:?}", hh); if let Some(v) = hh { self.spawn_method_results(m); for msg in v { self.conn.send(msg)?; } // We consumed the message. Poll again } else { return Ok(Async::Ready(Some(m))) } } else { return z } } } }
new
identifier_name
tree.rs
/// Async server-side trees use std::{ops, fmt, mem}; use dbus::tree::{Factory, Tree, MethodType, DataType, MTFn, Method, MethodInfo, MethodErr}; use dbus::{Member, Message, Connection}; use std::marker::PhantomData; use std::cell::RefCell; use futures::{IntoFuture, Future, Poll, Stream, Async}; use std::ffi::CString; pub trait ADataType: fmt::Debug + Sized + Default { type ObjectPath: fmt::Debug; type Property: fmt::Debug; type Interface: fmt::Debug + Default; type Method: fmt::Debug + Default; type Signal: fmt::Debug; } #[derive(Debug, Default)] /// A Tree that allows both synchronous and asynchronous methods. pub struct ATree<D: ADataType>(RefCell<Option<AMethodResult>>, PhantomData<*const D>); impl<D: ADataType> ATree<D> { pub fn new() -> Self { Default::default() } fn push(&self, a: AMethodResult) { let mut z = self.0.borrow_mut(); assert!(z.is_none(), "Same message handled twice"); *z = Some(a); } } impl<D: ADataType> DataType for ATree<D> { type Tree = ATree<D>; type ObjectPath = D::ObjectPath; type Property = D::Property; type Interface = D::Interface; type Method = D::Method; type Signal = D::Signal; } impl ADataType for () { type ObjectPath = (); type Property = (); type Interface = (); type Method = (); type Signal = (); } /// A Tree factory that allows both synchronous and asynchronous methods. pub struct AFactory<M: MethodType<D>, D: DataType = ()>(Factory<M, D>); impl AFactory<MTFn<()>, ()> { pub fn new_afn<D: ADataType>() -> AFactory<MTFn<ATree<D>>, ATree<D>> { AFactory(Factory::new_fn()) } } impl<M: MethodType<D>, D: DataType> ops::Deref for AFactory<M, D> { type Target = Factory<M, D>; fn deref(&self) -> &Self::Target { &self.0 } } impl<D: ADataType> AFactory<MTFn<ATree<D>>, ATree<D>> { /// Creates an async method, for methods whose result cannot be returned immediately. /// /// The method handler supplied to amethod returns a future, which resolves into the method result. /// See the tokio_server example for some hints on how to use it. pub fn amethod<H, R, T>(&self, t: T, data: D::Method, handler: H) -> Method<MTFn<ATree<D>>, ATree<D>> where H:'static + Fn(&MethodInfo<MTFn<ATree<D>>, ATree<D>>) -> R, T: Into<Member<'static>>, R:'static + IntoFuture<Item=Vec<Message>, Error=MethodErr> { self.0.method(t, data, move |minfo| { let r = handler(minfo); minfo.tree.get_data().push(AMethodResult::new(r)); Ok(Vec::new()) }) } } /// A Future method result /// /// When method results cannot be returned right away, the AMethodResult holds it temporarily struct AMethodResult(Box<Future<Item=Vec<Message>, Error=MethodErr>>, Option<Message>); impl fmt::Debug for AMethodResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "AMethodResult({:?})", self.1) } } impl AMethodResult { fn new<F:'static + IntoFuture<Item=Vec<Message>, Error=MethodErr>>(f: F) -> Self { AMethodResult(Box::new(f.into_future()), None) } } impl Future for AMethodResult { type Item = Vec<Message>; type Error = MethodErr; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { self.0.poll() } } #[derive(Debug)] /// Creates a filter for incoming messages, that handles messages in the tree. /// /// See the tokio_server example for some hints on how to use it. pub struct ATreeServer<C,T,D,S> where C: ops::Deref<Target=Connection>, T: ops::Deref<Target=Tree<MTFn<ATree<D>>, ATree<D>>>, D: ADataType { conn: C, tree: T, stream: S, pendingresults: Vec<AMethodResult>, } impl<C,T,D,S> ATreeServer<C,T,D,S> where C: ops::Deref<Target=Connection>, T: ops::Deref<Target=Tree<MTFn<ATree<D>>, ATree<D>>>, S: Stream<Item=Message, Error=()>, D: ADataType { pub fn new(c: C, t: T, stream: S) -> Self { ATreeServer { conn: c, tree: t, stream: stream, pendingresults: vec![] } } fn spawn_method_results(&mut self, msg: Message) { let v = self.tree.get_data().0.borrow_mut().take(); if let Some(mut r) = v { if r.1.is_none() { r.1 = Some(msg); }; // println!("Pushing {:?}", r); self.pendingresults.push(r); } } fn check_pending_results(&mut self) { let v = mem::replace(&mut self.pendingresults, vec!()); self.pendingresults = v.into_iter().filter_map(|mut mr| { let z = mr.poll(); // println!("Polling {:?} returned {:?}", mr, z); match z { Ok(Async::NotReady) => Some(mr), Ok(Async::Ready(t)) => { for msg in t { self.conn.send(msg).expect("D-Bus send error"); }; None }, Err(e) => { let m = mr.1.take().unwrap(); let msg = m.error(&e.errorname(), &CString::new(e.description()).unwrap()); self.conn.send(msg).expect("D-Bus send error"); None } } }).collect(); } } impl<C,T,D,S> Stream for ATreeServer<C,T,D,S> where C: ops::Deref<Target=Connection>, T: ops::Deref<Target=Tree<MTFn<ATree<D>>, ATree<D>>>, S: Stream<Item=Message, Error=()>, D: ADataType { type Item = Message; type Error = (); fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { loop { self.check_pending_results(); let z = self.stream.poll(); if let Ok(Async::Ready(Some(m))) = z { // println!("treeserver {:?}", m); let hh = self.tree.handle(&m); // println!("hh: {:?}", hh); if let Some(v) = hh
else { return Ok(Async::Ready(Some(m))) } } else { return z } } } }
{ self.spawn_method_results(m); for msg in v { self.conn.send(msg)?; } // We consumed the message. Poll again }
conditional_block
tree.rs
/// Async server-side trees use std::{ops, fmt, mem}; use dbus::tree::{Factory, Tree, MethodType, DataType, MTFn, Method, MethodInfo, MethodErr}; use dbus::{Member, Message, Connection}; use std::marker::PhantomData; use std::cell::RefCell; use futures::{IntoFuture, Future, Poll, Stream, Async}; use std::ffi::CString;
type ObjectPath: fmt::Debug; type Property: fmt::Debug; type Interface: fmt::Debug + Default; type Method: fmt::Debug + Default; type Signal: fmt::Debug; } #[derive(Debug, Default)] /// A Tree that allows both synchronous and asynchronous methods. pub struct ATree<D: ADataType>(RefCell<Option<AMethodResult>>, PhantomData<*const D>); impl<D: ADataType> ATree<D> { pub fn new() -> Self { Default::default() } fn push(&self, a: AMethodResult) { let mut z = self.0.borrow_mut(); assert!(z.is_none(), "Same message handled twice"); *z = Some(a); } } impl<D: ADataType> DataType for ATree<D> { type Tree = ATree<D>; type ObjectPath = D::ObjectPath; type Property = D::Property; type Interface = D::Interface; type Method = D::Method; type Signal = D::Signal; } impl ADataType for () { type ObjectPath = (); type Property = (); type Interface = (); type Method = (); type Signal = (); } /// A Tree factory that allows both synchronous and asynchronous methods. pub struct AFactory<M: MethodType<D>, D: DataType = ()>(Factory<M, D>); impl AFactory<MTFn<()>, ()> { pub fn new_afn<D: ADataType>() -> AFactory<MTFn<ATree<D>>, ATree<D>> { AFactory(Factory::new_fn()) } } impl<M: MethodType<D>, D: DataType> ops::Deref for AFactory<M, D> { type Target = Factory<M, D>; fn deref(&self) -> &Self::Target { &self.0 } } impl<D: ADataType> AFactory<MTFn<ATree<D>>, ATree<D>> { /// Creates an async method, for methods whose result cannot be returned immediately. /// /// The method handler supplied to amethod returns a future, which resolves into the method result. /// See the tokio_server example for some hints on how to use it. pub fn amethod<H, R, T>(&self, t: T, data: D::Method, handler: H) -> Method<MTFn<ATree<D>>, ATree<D>> where H:'static + Fn(&MethodInfo<MTFn<ATree<D>>, ATree<D>>) -> R, T: Into<Member<'static>>, R:'static + IntoFuture<Item=Vec<Message>, Error=MethodErr> { self.0.method(t, data, move |minfo| { let r = handler(minfo); minfo.tree.get_data().push(AMethodResult::new(r)); Ok(Vec::new()) }) } } /// A Future method result /// /// When method results cannot be returned right away, the AMethodResult holds it temporarily struct AMethodResult(Box<Future<Item=Vec<Message>, Error=MethodErr>>, Option<Message>); impl fmt::Debug for AMethodResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "AMethodResult({:?})", self.1) } } impl AMethodResult { fn new<F:'static + IntoFuture<Item=Vec<Message>, Error=MethodErr>>(f: F) -> Self { AMethodResult(Box::new(f.into_future()), None) } } impl Future for AMethodResult { type Item = Vec<Message>; type Error = MethodErr; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { self.0.poll() } } #[derive(Debug)] /// Creates a filter for incoming messages, that handles messages in the tree. /// /// See the tokio_server example for some hints on how to use it. pub struct ATreeServer<C,T,D,S> where C: ops::Deref<Target=Connection>, T: ops::Deref<Target=Tree<MTFn<ATree<D>>, ATree<D>>>, D: ADataType { conn: C, tree: T, stream: S, pendingresults: Vec<AMethodResult>, } impl<C,T,D,S> ATreeServer<C,T,D,S> where C: ops::Deref<Target=Connection>, T: ops::Deref<Target=Tree<MTFn<ATree<D>>, ATree<D>>>, S: Stream<Item=Message, Error=()>, D: ADataType { pub fn new(c: C, t: T, stream: S) -> Self { ATreeServer { conn: c, tree: t, stream: stream, pendingresults: vec![] } } fn spawn_method_results(&mut self, msg: Message) { let v = self.tree.get_data().0.borrow_mut().take(); if let Some(mut r) = v { if r.1.is_none() { r.1 = Some(msg); }; // println!("Pushing {:?}", r); self.pendingresults.push(r); } } fn check_pending_results(&mut self) { let v = mem::replace(&mut self.pendingresults, vec!()); self.pendingresults = v.into_iter().filter_map(|mut mr| { let z = mr.poll(); // println!("Polling {:?} returned {:?}", mr, z); match z { Ok(Async::NotReady) => Some(mr), Ok(Async::Ready(t)) => { for msg in t { self.conn.send(msg).expect("D-Bus send error"); }; None }, Err(e) => { let m = mr.1.take().unwrap(); let msg = m.error(&e.errorname(), &CString::new(e.description()).unwrap()); self.conn.send(msg).expect("D-Bus send error"); None } } }).collect(); } } impl<C,T,D,S> Stream for ATreeServer<C,T,D,S> where C: ops::Deref<Target=Connection>, T: ops::Deref<Target=Tree<MTFn<ATree<D>>, ATree<D>>>, S: Stream<Item=Message, Error=()>, D: ADataType { type Item = Message; type Error = (); fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { loop { self.check_pending_results(); let z = self.stream.poll(); if let Ok(Async::Ready(Some(m))) = z { // println!("treeserver {:?}", m); let hh = self.tree.handle(&m); // println!("hh: {:?}", hh); if let Some(v) = hh { self.spawn_method_results(m); for msg in v { self.conn.send(msg)?; } // We consumed the message. Poll again } else { return Ok(Async::Ready(Some(m))) } } else { return z } } } }
pub trait ADataType: fmt::Debug + Sized + Default {
random_line_split
env.rs
use std::cell::RefCell; use analysis; use config::Config; use config::gobjects::GStatus; use library::*; use version::Version; pub struct
{ pub library: Library, pub config: Config, pub namespaces: analysis::namespaces::Info, pub symbols: RefCell<analysis::symbols::Info>, pub class_hierarchy: analysis::class_hierarchy::Info, } impl Env { #[inline] pub fn type_(&self, tid: TypeId) -> &Type { self.library.type_(tid) } pub fn type_status(&self, name: &str) -> GStatus { self.config.objects.get(name).map(|o| o.status) .unwrap_or(Default::default()) } pub fn type_status_sys(&self, name: &str) -> GStatus { self.config.objects.get(name).map(|o| o.status) .unwrap_or(GStatus::Generate) } pub fn is_totally_deprecated(&self, deprecated_version: Option<Version>) -> bool { match deprecated_version { Some(version) if version <= self.config.min_cfg_version => self.config.deprecate_by_min_version, _ => false, } } }
Env
identifier_name
env.rs
use std::cell::RefCell; use analysis; use config::Config; use config::gobjects::GStatus;
pub library: Library, pub config: Config, pub namespaces: analysis::namespaces::Info, pub symbols: RefCell<analysis::symbols::Info>, pub class_hierarchy: analysis::class_hierarchy::Info, } impl Env { #[inline] pub fn type_(&self, tid: TypeId) -> &Type { self.library.type_(tid) } pub fn type_status(&self, name: &str) -> GStatus { self.config.objects.get(name).map(|o| o.status) .unwrap_or(Default::default()) } pub fn type_status_sys(&self, name: &str) -> GStatus { self.config.objects.get(name).map(|o| o.status) .unwrap_or(GStatus::Generate) } pub fn is_totally_deprecated(&self, deprecated_version: Option<Version>) -> bool { match deprecated_version { Some(version) if version <= self.config.min_cfg_version => self.config.deprecate_by_min_version, _ => false, } } }
use library::*; use version::Version; pub struct Env {
random_line_split
env.rs
use std::cell::RefCell; use analysis; use config::Config; use config::gobjects::GStatus; use library::*; use version::Version; pub struct Env { pub library: Library, pub config: Config, pub namespaces: analysis::namespaces::Info, pub symbols: RefCell<analysis::symbols::Info>, pub class_hierarchy: analysis::class_hierarchy::Info, } impl Env { #[inline] pub fn type_(&self, tid: TypeId) -> &Type { self.library.type_(tid) } pub fn type_status(&self, name: &str) -> GStatus
pub fn type_status_sys(&self, name: &str) -> GStatus { self.config.objects.get(name).map(|o| o.status) .unwrap_or(GStatus::Generate) } pub fn is_totally_deprecated(&self, deprecated_version: Option<Version>) -> bool { match deprecated_version { Some(version) if version <= self.config.min_cfg_version => self.config.deprecate_by_min_version, _ => false, } } }
{ self.config.objects.get(name).map(|o| o.status) .unwrap_or(Default::default()) }
identifier_body
hamming_numbers_alt.rs
// Implements http://rosettacode.org/wiki/Hamming_numbers // alternate version: uses a more efficient representation of Hamming numbers: // instead of storing them as BigUint directly, it stores the three exponents // i, j and k for 2^i * 3^j * 5 ^k and the logarithm of the number for comparisons #![allow(unused_attributes)] extern crate num; use hamming_numbers::{Hamming, HammingNumber}; use num::pow; use num::traits::One; use num::bigint::{BigUint, ToBigUint}; use std::ops::Mul; use std::cmp::Ordering; use std::cmp::Ordering::{Less, Equal, Greater}; mod hamming_numbers; #[cfg(not(test))] fn main() { // capacity of the queue currently needs to be a power of 2 because of a bug with VecDeque let hamming : Hamming<HammingTriple> = Hamming::new(128); for (idx, h) in hamming.enumerate().take(1_000_000) { match idx + 1 { 1...20 => print!("{} ", h.to_biguint().unwrap()), i @ 1691 | i @ 1_000_000 => println!("\n{}th number: {}", i, h.to_biguint().unwrap()), _ => continue } } } // we store these to calculate the ln of a hamming number pub const LN_2: f64 = 0.693147180559945309417232121458176568075500134360255254120680_f64; pub const LN_3: f64 = 1.098612288668109691395245236922525704647490557822749451734694_f64; pub const LN_5: f64 = 1.609437912434100374600759333226187639525601354268517721912647_f64; // more space-efficient representation of a Hamming number. // A Hamming number is 2^i * 3^j * 5^k; // instead of storing it directly as a BigUint // we store the powers i, j and k and calculate the // result as a BigUint only when we need it. // we also store the logarithm for quicker comparisons, using this property // of logarithms: ln(2^i * 3^j * 5^k) = i*ln2 + j*ln3 + k*ln5 #[derive(Debug, Copy)] pub struct HammingTriple { pow_2: usize, pow_3: usize, pow_5: usize, ln: f64 } impl Mul for HammingTriple { type Output = HammingTriple; fn mul(self, other: HammingTriple) -> HammingTriple { HammingTriple{ pow_2: self.pow_2 + other.pow_2, pow_3: self.pow_3 + other.pow_3, pow_5: self.pow_5 + other.pow_5, ln: self.ln + other.ln } } } impl One for HammingTriple { // 1 as an HammingNumber is 2^0 * 3^0 * 5^0 // ln(1) = 0 fn one() -> HammingTriple { HammingTriple::new(0, 0, 0) } } impl HammingNumber for HammingTriple { fn multipliers() -> (HammingTriple, HammingTriple, HammingTriple) { (HammingTriple { pow_2: 1, pow_3: 0, pow_5: 0, ln: LN_2 }, HammingTriple { pow_2: 0, pow_3: 1, pow_5: 0, ln: LN_3 }, HammingTriple { pow_2: 0, pow_3: 0, pow_5: 1, ln: LN_5 }) } } impl ToBigUint for HammingTriple { // calculate the value as a BigUint fn to_biguint(&self) -> Option<BigUint> { Some(pow(2u8.to_biguint().unwrap(), self.pow_2) * pow(3u8.to_biguint().unwrap(), self.pow_3) * pow(5u8.to_biguint().unwrap(), self.pow_5)) } } impl HammingTriple { fn new(pow_2: usize, pow_3: usize, pow_5: usize) -> HammingTriple { HammingTriple { pow_2: pow_2, pow_3: pow_3, pow_5: pow_5, ln: (pow_2 as f64) * LN_2 + (pow_3 as f64) * LN_3 + (pow_5 as f64) * LN_5 } } } impl Clone for HammingTriple { /// Return a deep copy of the value. #[inline] fn
(&self) -> HammingTriple { *self } } impl PartialEq for HammingTriple { fn eq(&self, other: &HammingTriple) -> bool { self.pow_2 == other.pow_2 && self.pow_3 == other.pow_3 && self.pow_5 == other.pow_5 } } impl Eq for HammingTriple {} impl PartialOrd for HammingTriple { fn partial_cmp(&self, other: &HammingTriple) -> Option<Ordering> { if self == other { Some(Equal) } else if self.pow_2 >= other.pow_2 && self.pow_3 >= other.pow_3 && self.pow_5 >= other.pow_5 { Some(Greater) } else if self.pow_2 <= other.pow_2 && self.pow_3 <= other.pow_3 && self.pow_5 <= other.pow_5 { Some(Less) } else if self.ln > other.ln { Some(Greater) } else if self.ln < other.ln { Some(Less) } else { None } } } impl Ord for HammingTriple { fn cmp(&self, other: &HammingTriple) -> Ordering { // as a last resort we need to calculate the BigUint values and compare them. // This should be rare. The reason is that for very big values floating point precision // could make hamming_1.ln == hamming_2.ln even if the two numbers are actually different self.partial_cmp(other).unwrap_or_else( || self.to_biguint().unwrap().cmp(&other.to_biguint().unwrap()) ) } } #[test] fn hamming_iter() { let mut hamming = Hamming::<HammingTriple>::new(20); assert!(hamming.nth(19).unwrap().to_biguint() == 36u8.to_biguint()); } #[test] fn hamming_iter_1million() { let mut hamming = Hamming::<HammingTriple>::new(128); // one-million-th hamming number has index 999_999 because indexes are zero-based assert_eq!(hamming.nth(999_999).unwrap().to_biguint(), "519312780448388736089589843750000000000000000000000000000000000000000000000000000000" .parse::<BigUint>().ok() ); }
clone
identifier_name
hamming_numbers_alt.rs
// Implements http://rosettacode.org/wiki/Hamming_numbers // alternate version: uses a more efficient representation of Hamming numbers: // instead of storing them as BigUint directly, it stores the three exponents // i, j and k for 2^i * 3^j * 5 ^k and the logarithm of the number for comparisons #![allow(unused_attributes)] extern crate num; use hamming_numbers::{Hamming, HammingNumber}; use num::pow; use num::traits::One; use num::bigint::{BigUint, ToBigUint}; use std::ops::Mul; use std::cmp::Ordering; use std::cmp::Ordering::{Less, Equal, Greater}; mod hamming_numbers; #[cfg(not(test))] fn main() { // capacity of the queue currently needs to be a power of 2 because of a bug with VecDeque let hamming : Hamming<HammingTriple> = Hamming::new(128); for (idx, h) in hamming.enumerate().take(1_000_000) { match idx + 1 { 1...20 => print!("{} ", h.to_biguint().unwrap()), i @ 1691 | i @ 1_000_000 => println!("\n{}th number: {}", i, h.to_biguint().unwrap()), _ => continue } } } // we store these to calculate the ln of a hamming number pub const LN_2: f64 = 0.693147180559945309417232121458176568075500134360255254120680_f64; pub const LN_3: f64 = 1.098612288668109691395245236922525704647490557822749451734694_f64; pub const LN_5: f64 = 1.609437912434100374600759333226187639525601354268517721912647_f64; // more space-efficient representation of a Hamming number. // A Hamming number is 2^i * 3^j * 5^k; // instead of storing it directly as a BigUint // we store the powers i, j and k and calculate the // result as a BigUint only when we need it. // we also store the logarithm for quicker comparisons, using this property // of logarithms: ln(2^i * 3^j * 5^k) = i*ln2 + j*ln3 + k*ln5 #[derive(Debug, Copy)] pub struct HammingTriple { pow_2: usize, pow_3: usize, pow_5: usize, ln: f64 } impl Mul for HammingTriple { type Output = HammingTriple; fn mul(self, other: HammingTriple) -> HammingTriple { HammingTriple{ pow_2: self.pow_2 + other.pow_2, pow_3: self.pow_3 + other.pow_3, pow_5: self.pow_5 + other.pow_5, ln: self.ln + other.ln } } } impl One for HammingTriple { // 1 as an HammingNumber is 2^0 * 3^0 * 5^0 // ln(1) = 0 fn one() -> HammingTriple { HammingTriple::new(0, 0, 0) } } impl HammingNumber for HammingTriple { fn multipliers() -> (HammingTriple, HammingTriple, HammingTriple) { (HammingTriple { pow_2: 1, pow_3: 0, pow_5: 0, ln: LN_2 }, HammingTriple { pow_2: 0, pow_3: 1, pow_5: 0, ln: LN_3 }, HammingTriple { pow_2: 0, pow_3: 0, pow_5: 1, ln: LN_5 }) } } impl ToBigUint for HammingTriple { // calculate the value as a BigUint fn to_biguint(&self) -> Option<BigUint>
} impl HammingTriple { fn new(pow_2: usize, pow_3: usize, pow_5: usize) -> HammingTriple { HammingTriple { pow_2: pow_2, pow_3: pow_3, pow_5: pow_5, ln: (pow_2 as f64) * LN_2 + (pow_3 as f64) * LN_3 + (pow_5 as f64) * LN_5 } } } impl Clone for HammingTriple { /// Return a deep copy of the value. #[inline] fn clone(&self) -> HammingTriple { *self } } impl PartialEq for HammingTriple { fn eq(&self, other: &HammingTriple) -> bool { self.pow_2 == other.pow_2 && self.pow_3 == other.pow_3 && self.pow_5 == other.pow_5 } } impl Eq for HammingTriple {} impl PartialOrd for HammingTriple { fn partial_cmp(&self, other: &HammingTriple) -> Option<Ordering> { if self == other { Some(Equal) } else if self.pow_2 >= other.pow_2 && self.pow_3 >= other.pow_3 && self.pow_5 >= other.pow_5 { Some(Greater) } else if self.pow_2 <= other.pow_2 && self.pow_3 <= other.pow_3 && self.pow_5 <= other.pow_5 { Some(Less) } else if self.ln > other.ln { Some(Greater) } else if self.ln < other.ln { Some(Less) } else { None } } } impl Ord for HammingTriple { fn cmp(&self, other: &HammingTriple) -> Ordering { // as a last resort we need to calculate the BigUint values and compare them. // This should be rare. The reason is that for very big values floating point precision // could make hamming_1.ln == hamming_2.ln even if the two numbers are actually different self.partial_cmp(other).unwrap_or_else( || self.to_biguint().unwrap().cmp(&other.to_biguint().unwrap()) ) } } #[test] fn hamming_iter() { let mut hamming = Hamming::<HammingTriple>::new(20); assert!(hamming.nth(19).unwrap().to_biguint() == 36u8.to_biguint()); } #[test] fn hamming_iter_1million() { let mut hamming = Hamming::<HammingTriple>::new(128); // one-million-th hamming number has index 999_999 because indexes are zero-based assert_eq!(hamming.nth(999_999).unwrap().to_biguint(), "519312780448388736089589843750000000000000000000000000000000000000000000000000000000" .parse::<BigUint>().ok() ); }
{ Some(pow(2u8.to_biguint().unwrap(), self.pow_2) * pow(3u8.to_biguint().unwrap(), self.pow_3) * pow(5u8.to_biguint().unwrap(), self.pow_5)) }
identifier_body
hamming_numbers_alt.rs
// Implements http://rosettacode.org/wiki/Hamming_numbers // alternate version: uses a more efficient representation of Hamming numbers: // instead of storing them as BigUint directly, it stores the three exponents // i, j and k for 2^i * 3^j * 5 ^k and the logarithm of the number for comparisons #![allow(unused_attributes)] extern crate num; use hamming_numbers::{Hamming, HammingNumber}; use num::pow; use num::traits::One; use num::bigint::{BigUint, ToBigUint}; use std::ops::Mul; use std::cmp::Ordering; use std::cmp::Ordering::{Less, Equal, Greater}; mod hamming_numbers; #[cfg(not(test))] fn main() { // capacity of the queue currently needs to be a power of 2 because of a bug with VecDeque let hamming : Hamming<HammingTriple> = Hamming::new(128); for (idx, h) in hamming.enumerate().take(1_000_000) { match idx + 1 { 1...20 => print!("{} ", h.to_biguint().unwrap()), i @ 1691 | i @ 1_000_000 => println!("\n{}th number: {}", i, h.to_biguint().unwrap()), _ => continue } } } // we store these to calculate the ln of a hamming number pub const LN_2: f64 = 0.693147180559945309417232121458176568075500134360255254120680_f64; pub const LN_3: f64 = 1.098612288668109691395245236922525704647490557822749451734694_f64; pub const LN_5: f64 = 1.609437912434100374600759333226187639525601354268517721912647_f64; // more space-efficient representation of a Hamming number. // A Hamming number is 2^i * 3^j * 5^k; // instead of storing it directly as a BigUint // we store the powers i, j and k and calculate the // result as a BigUint only when we need it. // we also store the logarithm for quicker comparisons, using this property // of logarithms: ln(2^i * 3^j * 5^k) = i*ln2 + j*ln3 + k*ln5 #[derive(Debug, Copy)] pub struct HammingTriple { pow_2: usize, pow_3: usize, pow_5: usize, ln: f64 } impl Mul for HammingTriple { type Output = HammingTriple; fn mul(self, other: HammingTriple) -> HammingTriple { HammingTriple{ pow_2: self.pow_2 + other.pow_2,
} } impl One for HammingTriple { // 1 as an HammingNumber is 2^0 * 3^0 * 5^0 // ln(1) = 0 fn one() -> HammingTriple { HammingTriple::new(0, 0, 0) } } impl HammingNumber for HammingTriple { fn multipliers() -> (HammingTriple, HammingTriple, HammingTriple) { (HammingTriple { pow_2: 1, pow_3: 0, pow_5: 0, ln: LN_2 }, HammingTriple { pow_2: 0, pow_3: 1, pow_5: 0, ln: LN_3 }, HammingTriple { pow_2: 0, pow_3: 0, pow_5: 1, ln: LN_5 }) } } impl ToBigUint for HammingTriple { // calculate the value as a BigUint fn to_biguint(&self) -> Option<BigUint> { Some(pow(2u8.to_biguint().unwrap(), self.pow_2) * pow(3u8.to_biguint().unwrap(), self.pow_3) * pow(5u8.to_biguint().unwrap(), self.pow_5)) } } impl HammingTriple { fn new(pow_2: usize, pow_3: usize, pow_5: usize) -> HammingTriple { HammingTriple { pow_2: pow_2, pow_3: pow_3, pow_5: pow_5, ln: (pow_2 as f64) * LN_2 + (pow_3 as f64) * LN_3 + (pow_5 as f64) * LN_5 } } } impl Clone for HammingTriple { /// Return a deep copy of the value. #[inline] fn clone(&self) -> HammingTriple { *self } } impl PartialEq for HammingTriple { fn eq(&self, other: &HammingTriple) -> bool { self.pow_2 == other.pow_2 && self.pow_3 == other.pow_3 && self.pow_5 == other.pow_5 } } impl Eq for HammingTriple {} impl PartialOrd for HammingTriple { fn partial_cmp(&self, other: &HammingTriple) -> Option<Ordering> { if self == other { Some(Equal) } else if self.pow_2 >= other.pow_2 && self.pow_3 >= other.pow_3 && self.pow_5 >= other.pow_5 { Some(Greater) } else if self.pow_2 <= other.pow_2 && self.pow_3 <= other.pow_3 && self.pow_5 <= other.pow_5 { Some(Less) } else if self.ln > other.ln { Some(Greater) } else if self.ln < other.ln { Some(Less) } else { None } } } impl Ord for HammingTriple { fn cmp(&self, other: &HammingTriple) -> Ordering { // as a last resort we need to calculate the BigUint values and compare them. // This should be rare. The reason is that for very big values floating point precision // could make hamming_1.ln == hamming_2.ln even if the two numbers are actually different self.partial_cmp(other).unwrap_or_else( || self.to_biguint().unwrap().cmp(&other.to_biguint().unwrap()) ) } } #[test] fn hamming_iter() { let mut hamming = Hamming::<HammingTriple>::new(20); assert!(hamming.nth(19).unwrap().to_biguint() == 36u8.to_biguint()); } #[test] fn hamming_iter_1million() { let mut hamming = Hamming::<HammingTriple>::new(128); // one-million-th hamming number has index 999_999 because indexes are zero-based assert_eq!(hamming.nth(999_999).unwrap().to_biguint(), "519312780448388736089589843750000000000000000000000000000000000000000000000000000000" .parse::<BigUint>().ok() ); }
pow_3: self.pow_3 + other.pow_3, pow_5: self.pow_5 + other.pow_5, ln: self.ln + other.ln }
random_line_split
unboxed-closures-wrong-trait.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(lang_items, overloaded_calls, unboxed_closures)] fn c<F:Fn(int, int) -> int>(f: F) -> int { f(5, 6) } fn
() { let z: int = 7; assert_eq!(c(|&mut: x: int, y| x + y + z), 10); //~^ ERROR not implemented }
main
identifier_name
unboxed-closures-wrong-trait.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(lang_items, overloaded_calls, unboxed_closures)] fn c<F:Fn(int, int) -> int>(f: F) -> int { f(5, 6) } fn main() { let z: int = 7; assert_eq!(c(|&mut: x: int, y| x + y + z), 10); //~^ ERROR not implemented }
// // 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
random_line_split
unboxed-closures-wrong-trait.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(lang_items, overloaded_calls, unboxed_closures)] fn c<F:Fn(int, int) -> int>(f: F) -> int
fn main() { let z: int = 7; assert_eq!(c(|&mut: x: int, y| x + y + z), 10); //~^ ERROR not implemented }
{ f(5, 6) }
identifier_body
bench_acquire.rs
//! Benchmark the overhead that the synchronization of `OnceCell::get` causes. //! We do some other operations that write to memory to get an imprecise but somewhat realistic //! measurement. use once_cell::sync::OnceCell; use std::sync::atomic::{AtomicUsize, Ordering}; const N_THREADS: usize = 16; const N_ROUNDS: usize = 1_000_000; static CELL: OnceCell<usize> = OnceCell::new(); static OTHER: AtomicUsize = AtomicUsize::new(0); fn main() { let start = std::time::Instant::now(); let threads = (0..N_THREADS).map(|i| std::thread::spawn(move || thread_main(i))).collect::<Vec<_>>(); for thread in threads { thread.join().unwrap(); } println!("{:?}", start.elapsed()); println!("{:?}", OTHER.load(Ordering::Relaxed)); } #[inline(never)] fn thread_main(i: usize) { // The operations we do here don't really matter, as long as we do multiple writes, and // everything is messy enough to prevent the compiler from optimizing the loop away. let mut data = [i; 128]; let mut accum = 0usize; for _ in 0..N_ROUNDS { let _value = CELL.get_or_init(|| i + 1); let k = OTHER.fetch_add(data[accum & 0x7F] as usize, Ordering::Relaxed);
*j = (*j).wrapping_add(accum); accum = accum.wrapping_add(k); } } }
for j in data.iter_mut() {
random_line_split
bench_acquire.rs
//! Benchmark the overhead that the synchronization of `OnceCell::get` causes. //! We do some other operations that write to memory to get an imprecise but somewhat realistic //! measurement. use once_cell::sync::OnceCell; use std::sync::atomic::{AtomicUsize, Ordering}; const N_THREADS: usize = 16; const N_ROUNDS: usize = 1_000_000; static CELL: OnceCell<usize> = OnceCell::new(); static OTHER: AtomicUsize = AtomicUsize::new(0); fn main() { let start = std::time::Instant::now(); let threads = (0..N_THREADS).map(|i| std::thread::spawn(move || thread_main(i))).collect::<Vec<_>>(); for thread in threads { thread.join().unwrap(); } println!("{:?}", start.elapsed()); println!("{:?}", OTHER.load(Ordering::Relaxed)); } #[inline(never)] fn thread_main(i: usize)
{ // The operations we do here don't really matter, as long as we do multiple writes, and // everything is messy enough to prevent the compiler from optimizing the loop away. let mut data = [i; 128]; let mut accum = 0usize; for _ in 0..N_ROUNDS { let _value = CELL.get_or_init(|| i + 1); let k = OTHER.fetch_add(data[accum & 0x7F] as usize, Ordering::Relaxed); for j in data.iter_mut() { *j = (*j).wrapping_add(accum); accum = accum.wrapping_add(k); } } }
identifier_body
bench_acquire.rs
//! Benchmark the overhead that the synchronization of `OnceCell::get` causes. //! We do some other operations that write to memory to get an imprecise but somewhat realistic //! measurement. use once_cell::sync::OnceCell; use std::sync::atomic::{AtomicUsize, Ordering}; const N_THREADS: usize = 16; const N_ROUNDS: usize = 1_000_000; static CELL: OnceCell<usize> = OnceCell::new(); static OTHER: AtomicUsize = AtomicUsize::new(0); fn main() { let start = std::time::Instant::now(); let threads = (0..N_THREADS).map(|i| std::thread::spawn(move || thread_main(i))).collect::<Vec<_>>(); for thread in threads { thread.join().unwrap(); } println!("{:?}", start.elapsed()); println!("{:?}", OTHER.load(Ordering::Relaxed)); } #[inline(never)] fn
(i: usize) { // The operations we do here don't really matter, as long as we do multiple writes, and // everything is messy enough to prevent the compiler from optimizing the loop away. let mut data = [i; 128]; let mut accum = 0usize; for _ in 0..N_ROUNDS { let _value = CELL.get_or_init(|| i + 1); let k = OTHER.fetch_add(data[accum & 0x7F] as usize, Ordering::Relaxed); for j in data.iter_mut() { *j = (*j).wrapping_add(accum); accum = accum.wrapping_add(k); } } }
thread_main
identifier_name
comments.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. pub use self::CommentStyle::*; use ast; use codemap::{BytePos, CharPos, CodeMap, Pos}; use diagnostic; use parse::lexer::{is_whitespace, Reader}; use parse::lexer::{StringReader, TokenAndSpan}; use parse::lexer::is_block_doc_comment; use parse::lexer; use print::pprust; use std::io::Read; use std::str; use std::usize; #[derive(Clone, Copy, PartialEq)] pub enum CommentStyle { /// No code on either side of each line of the comment Isolated, /// Code exists to the left of the comment Trailing, /// Code before /* foo */ and after the comment Mixed, /// Just a manual blank line "\n\n", for layout BlankLine, } #[derive(Clone)] pub struct Comment { pub style: CommentStyle, pub lines: Vec<String>, pub pos: BytePos, } pub fn is_doc_comment(s: &str) -> bool { (s.starts_with("///") && super::is_doc_comment(s)) || s.starts_with("//!") || (s.starts_with("/**") && is_block_doc_comment(s)) || s.starts_with("/*!") } pub fn doc_comment_style(comment: &str) -> ast::AttrStyle { assert!(is_doc_comment(comment)); if comment.starts_with("//!") || comment.starts_with("/*!") { ast::AttrInner } else { ast::AttrOuter } } pub fn strip_doc_comment_decoration(comment: &str) -> String { /// remove whitespace-only lines from the start/end of lines fn vertical_trim(lines: Vec<String>) -> Vec<String> { let mut i = 0; let mut j = lines.len(); // first line of all-stars should be omitted if lines.len() > 0 && lines[0].chars().all(|c| c == '*') { i += 1; } while i < j && lines[i].trim().is_empty() { i += 1; } // like the first, a last line of all stars should be omitted if j > i && lines[j - 1] .chars() .skip(1) .all(|c| c == '*') { j -= 1; } while j > i && lines[j - 1].trim().is_empty() { j -= 1; } lines[i..j].iter().cloned().collect() } /// remove a "[ \t]*\*" block from each line, if possible fn horizontal_trim(lines: Vec<String> ) -> Vec<String> { let mut i = usize::MAX; let mut can_trim = true; let mut first = true; for line in &lines { for (j, c) in line.chars().enumerate() { if j > i ||!"* \t".contains(c) { can_trim = false; break; } if c == '*' { if first { i = j; first = false; } else if i!= j { can_trim = false; } break; } } if i > line.len() { can_trim = false; } if!can_trim { break; } } if can_trim { lines.iter().map(|line| { (&line[i + 1..line.len()]).to_string() }).collect() } else { lines } } // one-line comments lose their prefix const ONELINERS: &'static [&'static str] = &["///!", "///", "//!", "//"]; for prefix in ONELINERS { if comment.starts_with(*prefix) { return (&comment[prefix.len()..]).to_string(); } } if comment.starts_with("/*") { let lines = comment[3..comment.len() - 2] .lines_any() .map(|s| s.to_string()) .collect::<Vec<String> >(); let lines = vertical_trim(lines); let lines = horizontal_trim(lines); return lines.connect("\n"); } panic!("not a doc-comment: {}", comment); } fn push_blank_line_comment(rdr: &StringReader, comments: &mut Vec<Comment>) { debug!(">>> blank-line comment"); comments.push(Comment { style: BlankLine, lines: Vec::new(), pos: rdr.last_pos, }); } fn consume_whitespace_counting_blank_lines(rdr: &mut StringReader, comments: &mut Vec<Comment>) { while is_whitespace(rdr.curr) &&!rdr.is_eof() { if rdr.col == CharPos(0) && rdr.curr_is('\n') { push_blank_line_comment(rdr, &mut *comments); } rdr.bump(); } } fn read_shebang_comment(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment>) { debug!(">>> shebang comment"); let p = rdr.last_pos; debug!("<<< shebang comment"); comments.push(Comment { style: if code_to_the_left { Trailing } else { Isolated }, lines: vec!(rdr.read_one_line_comment()), pos: p }); } fn read_line_comments(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment>) { debug!(">>> line comments"); let p = rdr.last_pos; let mut lines: Vec<String> = Vec::new(); while rdr.curr_is('/') && rdr.nextch_is('/') { let line = rdr.read_one_line_comment(); debug!("{}", line); // Doc comments are not put in comments. if is_doc_comment(&line[..]) { break; } lines.push(line); rdr.consume_non_eol_whitespace(); } debug!("<<< line comments"); if!lines.is_empty() { comments.push(Comment { style: if code_to_the_left { Trailing } else { Isolated }, lines: lines, pos: p }); } } /// Returns None if the first col chars of s contain a non-whitespace char. /// Otherwise returns Some(k) where k is first char offset after that leading /// whitespace. Note k may be outside bounds of s. fn all_whitespace(s: &str, col: CharPos) -> Option<usize> { let len = s.len(); let mut col = col.to_usize(); let mut cursor: usize = 0; while col > 0 && cursor < len { let r: str::CharRange = s.char_range_at(cursor); if!r.ch.is_whitespace() { return None; } cursor = r.next; col -= 1; } return Some(cursor); } fn trim_whitespace_prefix_and_push_line(lines: &mut Vec<String>, s: String, col: CharPos) { let len = s.len(); let s1 = match all_whitespace(&s[..], col) { Some(col) => { if col < len { (&s[col..len]).to_string() } else { "".to_string() } } None => s, }; debug!("pushing line: {}", s1); lines.push(s1); } fn read_block_comment(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment> ) { debug!(">>> block comment"); let p = rdr.last_pos; let mut lines: Vec<String> = Vec::new(); let col = rdr.col; rdr.bump(); rdr.bump(); let mut curr_line = String::from_str("/*"); // doc-comments are not really comments, they are attributes if (rdr.curr_is('*') &&!rdr.nextch_is('*')) || rdr.curr_is('!') { while!(rdr.curr_is('*') && rdr.nextch_is('/')) &&!rdr.is_eof() { curr_line.push(rdr.curr.unwrap()); rdr.bump(); } if!rdr.is_eof() { curr_line.push_str("*/"); rdr.bump(); rdr.bump(); } if is_block_doc_comment(&curr_line[..]) { return } assert!(!curr_line.contains('\n')); lines.push(curr_line); } else { let mut level: isize = 1; while level > 0 { debug!("=== block comment level {}", level); if rdr.is_eof() { rdr.fatal("unterminated block comment"); } if rdr.curr_is('\n') { trim_whitespace_prefix_and_push_line(&mut lines,
curr_line.push(rdr.curr.unwrap()); if rdr.curr_is('/') && rdr.nextch_is('*') { rdr.bump(); rdr.bump(); curr_line.push('*'); level += 1; } else { if rdr.curr_is('*') && rdr.nextch_is('/') { rdr.bump(); rdr.bump(); curr_line.push('/'); level -= 1; } else { rdr.bump(); } } } } if curr_line.len()!= 0 { trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col); } } let mut style = if code_to_the_left { Trailing } else { Isolated }; rdr.consume_non_eol_whitespace(); if!rdr.is_eof() &&!rdr.curr_is('\n') && lines.len() == 1 { style = Mixed; } debug!("<<< block comment"); comments.push(Comment {style: style, lines: lines, pos: p}); } fn consume_comment(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment> ) { debug!(">>> consume comment"); if rdr.curr_is('/') && rdr.nextch_is('/') { read_line_comments(rdr, code_to_the_left, comments); } else if rdr.curr_is('/') && rdr.nextch_is('*') { read_block_comment(rdr, code_to_the_left, comments); } else if rdr.curr_is('#') && rdr.nextch_is('!') { read_shebang_comment(rdr, code_to_the_left, comments); } else { panic!(); } debug!("<<< consume comment"); } #[derive(Clone)] pub struct Literal { pub lit: String, pub pos: BytePos, } // it appears this function is called only from pprust... that's // probably not a good thing. pub fn gather_comments_and_literals(span_diagnostic: &diagnostic::SpanHandler, path: String, srdr: &mut Read) -> (Vec<Comment>, Vec<Literal>) { let mut src = Vec::new(); srdr.read_to_end(&mut src).unwrap(); let src = String::from_utf8(src).unwrap(); let cm = CodeMap::new(); let filemap = cm.new_filemap(path, src); let mut rdr = lexer::StringReader::new_raw(span_diagnostic, filemap); let mut comments: Vec<Comment> = Vec::new(); let mut literals: Vec<Literal> = Vec::new(); let mut first_read: bool = true; while!rdr.is_eof() { loop { let mut code_to_the_left =!first_read; rdr.consume_non_eol_whitespace(); if rdr.curr_is('\n') { code_to_the_left = false; consume_whitespace_counting_blank_lines(&mut rdr, &mut comments); } while rdr.peeking_at_comment() { consume_comment(&mut rdr, code_to_the_left, &mut comments); consume_whitespace_counting_blank_lines(&mut rdr, &mut comments); } break; } let bstart = rdr.last_pos; rdr.next_token(); //discard, and look ahead; we're working with internal state let TokenAndSpan { tok, sp } = rdr.peek(); if tok.is_lit() { rdr.with_str_from(bstart, |s| { debug!("tok lit: {}", s); literals.push(Literal {lit: s.to_string(), pos: sp.lo}); }) } else { debug!("tok: {}", pprust::token_to_string(&tok)); } first_read = false; } (comments, literals) } #[cfg(test)] mod test { use super::*; #[test] fn test_block_doc_comment_1() { let comment = "/**\n * Test \n ** Test\n * Test\n*/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " Test \n* Test\n Test"); } #[test] fn test_block_doc_comment_2() { let comment = "/**\n * Test\n * Test\n*/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " Test\n Test"); } #[test] fn test_block_doc_comment_3() { let comment = "/**\n let a: *i32;\n *a = 5;\n*/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " let a: *i32;\n *a = 5;"); } #[test] fn test_block_doc_comment_4() { let comment = "/*******************\n test\n *********************/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " test"); } #[test] fn test_line_doc_comment() { let stripped = strip_doc_comment_decoration("/// test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("///! test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("// test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("// test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("///test"); assert_eq!(stripped, "test"); let stripped = strip_doc_comment_decoration("///!test"); assert_eq!(stripped, "test"); let stripped = strip_doc_comment_decoration("//test"); assert_eq!(stripped, "test"); } }
curr_line, col); curr_line = String::new(); rdr.bump(); } else {
random_line_split
comments.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. pub use self::CommentStyle::*; use ast; use codemap::{BytePos, CharPos, CodeMap, Pos}; use diagnostic; use parse::lexer::{is_whitespace, Reader}; use parse::lexer::{StringReader, TokenAndSpan}; use parse::lexer::is_block_doc_comment; use parse::lexer; use print::pprust; use std::io::Read; use std::str; use std::usize; #[derive(Clone, Copy, PartialEq)] pub enum CommentStyle { /// No code on either side of each line of the comment Isolated, /// Code exists to the left of the comment Trailing, /// Code before /* foo */ and after the comment Mixed, /// Just a manual blank line "\n\n", for layout BlankLine, } #[derive(Clone)] pub struct Comment { pub style: CommentStyle, pub lines: Vec<String>, pub pos: BytePos, } pub fn is_doc_comment(s: &str) -> bool { (s.starts_with("///") && super::is_doc_comment(s)) || s.starts_with("//!") || (s.starts_with("/**") && is_block_doc_comment(s)) || s.starts_with("/*!") } pub fn doc_comment_style(comment: &str) -> ast::AttrStyle { assert!(is_doc_comment(comment)); if comment.starts_with("//!") || comment.starts_with("/*!") { ast::AttrInner } else { ast::AttrOuter } } pub fn strip_doc_comment_decoration(comment: &str) -> String { /// remove whitespace-only lines from the start/end of lines fn vertical_trim(lines: Vec<String>) -> Vec<String> { let mut i = 0; let mut j = lines.len(); // first line of all-stars should be omitted if lines.len() > 0 && lines[0].chars().all(|c| c == '*')
while i < j && lines[i].trim().is_empty() { i += 1; } // like the first, a last line of all stars should be omitted if j > i && lines[j - 1] .chars() .skip(1) .all(|c| c == '*') { j -= 1; } while j > i && lines[j - 1].trim().is_empty() { j -= 1; } lines[i..j].iter().cloned().collect() } /// remove a "[ \t]*\*" block from each line, if possible fn horizontal_trim(lines: Vec<String> ) -> Vec<String> { let mut i = usize::MAX; let mut can_trim = true; let mut first = true; for line in &lines { for (j, c) in line.chars().enumerate() { if j > i ||!"* \t".contains(c) { can_trim = false; break; } if c == '*' { if first { i = j; first = false; } else if i!= j { can_trim = false; } break; } } if i > line.len() { can_trim = false; } if!can_trim { break; } } if can_trim { lines.iter().map(|line| { (&line[i + 1..line.len()]).to_string() }).collect() } else { lines } } // one-line comments lose their prefix const ONELINERS: &'static [&'static str] = &["///!", "///", "//!", "//"]; for prefix in ONELINERS { if comment.starts_with(*prefix) { return (&comment[prefix.len()..]).to_string(); } } if comment.starts_with("/*") { let lines = comment[3..comment.len() - 2] .lines_any() .map(|s| s.to_string()) .collect::<Vec<String> >(); let lines = vertical_trim(lines); let lines = horizontal_trim(lines); return lines.connect("\n"); } panic!("not a doc-comment: {}", comment); } fn push_blank_line_comment(rdr: &StringReader, comments: &mut Vec<Comment>) { debug!(">>> blank-line comment"); comments.push(Comment { style: BlankLine, lines: Vec::new(), pos: rdr.last_pos, }); } fn consume_whitespace_counting_blank_lines(rdr: &mut StringReader, comments: &mut Vec<Comment>) { while is_whitespace(rdr.curr) &&!rdr.is_eof() { if rdr.col == CharPos(0) && rdr.curr_is('\n') { push_blank_line_comment(rdr, &mut *comments); } rdr.bump(); } } fn read_shebang_comment(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment>) { debug!(">>> shebang comment"); let p = rdr.last_pos; debug!("<<< shebang comment"); comments.push(Comment { style: if code_to_the_left { Trailing } else { Isolated }, lines: vec!(rdr.read_one_line_comment()), pos: p }); } fn read_line_comments(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment>) { debug!(">>> line comments"); let p = rdr.last_pos; let mut lines: Vec<String> = Vec::new(); while rdr.curr_is('/') && rdr.nextch_is('/') { let line = rdr.read_one_line_comment(); debug!("{}", line); // Doc comments are not put in comments. if is_doc_comment(&line[..]) { break; } lines.push(line); rdr.consume_non_eol_whitespace(); } debug!("<<< line comments"); if!lines.is_empty() { comments.push(Comment { style: if code_to_the_left { Trailing } else { Isolated }, lines: lines, pos: p }); } } /// Returns None if the first col chars of s contain a non-whitespace char. /// Otherwise returns Some(k) where k is first char offset after that leading /// whitespace. Note k may be outside bounds of s. fn all_whitespace(s: &str, col: CharPos) -> Option<usize> { let len = s.len(); let mut col = col.to_usize(); let mut cursor: usize = 0; while col > 0 && cursor < len { let r: str::CharRange = s.char_range_at(cursor); if!r.ch.is_whitespace() { return None; } cursor = r.next; col -= 1; } return Some(cursor); } fn trim_whitespace_prefix_and_push_line(lines: &mut Vec<String>, s: String, col: CharPos) { let len = s.len(); let s1 = match all_whitespace(&s[..], col) { Some(col) => { if col < len { (&s[col..len]).to_string() } else { "".to_string() } } None => s, }; debug!("pushing line: {}", s1); lines.push(s1); } fn read_block_comment(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment> ) { debug!(">>> block comment"); let p = rdr.last_pos; let mut lines: Vec<String> = Vec::new(); let col = rdr.col; rdr.bump(); rdr.bump(); let mut curr_line = String::from_str("/*"); // doc-comments are not really comments, they are attributes if (rdr.curr_is('*') &&!rdr.nextch_is('*')) || rdr.curr_is('!') { while!(rdr.curr_is('*') && rdr.nextch_is('/')) &&!rdr.is_eof() { curr_line.push(rdr.curr.unwrap()); rdr.bump(); } if!rdr.is_eof() { curr_line.push_str("*/"); rdr.bump(); rdr.bump(); } if is_block_doc_comment(&curr_line[..]) { return } assert!(!curr_line.contains('\n')); lines.push(curr_line); } else { let mut level: isize = 1; while level > 0 { debug!("=== block comment level {}", level); if rdr.is_eof() { rdr.fatal("unterminated block comment"); } if rdr.curr_is('\n') { trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col); curr_line = String::new(); rdr.bump(); } else { curr_line.push(rdr.curr.unwrap()); if rdr.curr_is('/') && rdr.nextch_is('*') { rdr.bump(); rdr.bump(); curr_line.push('*'); level += 1; } else { if rdr.curr_is('*') && rdr.nextch_is('/') { rdr.bump(); rdr.bump(); curr_line.push('/'); level -= 1; } else { rdr.bump(); } } } } if curr_line.len()!= 0 { trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col); } } let mut style = if code_to_the_left { Trailing } else { Isolated }; rdr.consume_non_eol_whitespace(); if!rdr.is_eof() &&!rdr.curr_is('\n') && lines.len() == 1 { style = Mixed; } debug!("<<< block comment"); comments.push(Comment {style: style, lines: lines, pos: p}); } fn consume_comment(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment> ) { debug!(">>> consume comment"); if rdr.curr_is('/') && rdr.nextch_is('/') { read_line_comments(rdr, code_to_the_left, comments); } else if rdr.curr_is('/') && rdr.nextch_is('*') { read_block_comment(rdr, code_to_the_left, comments); } else if rdr.curr_is('#') && rdr.nextch_is('!') { read_shebang_comment(rdr, code_to_the_left, comments); } else { panic!(); } debug!("<<< consume comment"); } #[derive(Clone)] pub struct Literal { pub lit: String, pub pos: BytePos, } // it appears this function is called only from pprust... that's // probably not a good thing. pub fn gather_comments_and_literals(span_diagnostic: &diagnostic::SpanHandler, path: String, srdr: &mut Read) -> (Vec<Comment>, Vec<Literal>) { let mut src = Vec::new(); srdr.read_to_end(&mut src).unwrap(); let src = String::from_utf8(src).unwrap(); let cm = CodeMap::new(); let filemap = cm.new_filemap(path, src); let mut rdr = lexer::StringReader::new_raw(span_diagnostic, filemap); let mut comments: Vec<Comment> = Vec::new(); let mut literals: Vec<Literal> = Vec::new(); let mut first_read: bool = true; while!rdr.is_eof() { loop { let mut code_to_the_left =!first_read; rdr.consume_non_eol_whitespace(); if rdr.curr_is('\n') { code_to_the_left = false; consume_whitespace_counting_blank_lines(&mut rdr, &mut comments); } while rdr.peeking_at_comment() { consume_comment(&mut rdr, code_to_the_left, &mut comments); consume_whitespace_counting_blank_lines(&mut rdr, &mut comments); } break; } let bstart = rdr.last_pos; rdr.next_token(); //discard, and look ahead; we're working with internal state let TokenAndSpan { tok, sp } = rdr.peek(); if tok.is_lit() { rdr.with_str_from(bstart, |s| { debug!("tok lit: {}", s); literals.push(Literal {lit: s.to_string(), pos: sp.lo}); }) } else { debug!("tok: {}", pprust::token_to_string(&tok)); } first_read = false; } (comments, literals) } #[cfg(test)] mod test { use super::*; #[test] fn test_block_doc_comment_1() { let comment = "/**\n * Test \n ** Test\n * Test\n*/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " Test \n* Test\n Test"); } #[test] fn test_block_doc_comment_2() { let comment = "/**\n * Test\n * Test\n*/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " Test\n Test"); } #[test] fn test_block_doc_comment_3() { let comment = "/**\n let a: *i32;\n *a = 5;\n*/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " let a: *i32;\n *a = 5;"); } #[test] fn test_block_doc_comment_4() { let comment = "/*******************\n test\n *********************/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " test"); } #[test] fn test_line_doc_comment() { let stripped = strip_doc_comment_decoration("/// test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("///! test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("// test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("// test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("///test"); assert_eq!(stripped, "test"); let stripped = strip_doc_comment_decoration("///!test"); assert_eq!(stripped, "test"); let stripped = strip_doc_comment_decoration("//test"); assert_eq!(stripped, "test"); } }
{ i += 1; }
conditional_block
comments.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. pub use self::CommentStyle::*; use ast; use codemap::{BytePos, CharPos, CodeMap, Pos}; use diagnostic; use parse::lexer::{is_whitespace, Reader}; use parse::lexer::{StringReader, TokenAndSpan}; use parse::lexer::is_block_doc_comment; use parse::lexer; use print::pprust; use std::io::Read; use std::str; use std::usize; #[derive(Clone, Copy, PartialEq)] pub enum CommentStyle { /// No code on either side of each line of the comment Isolated, /// Code exists to the left of the comment Trailing, /// Code before /* foo */ and after the comment Mixed, /// Just a manual blank line "\n\n", for layout BlankLine, } #[derive(Clone)] pub struct Comment { pub style: CommentStyle, pub lines: Vec<String>, pub pos: BytePos, } pub fn is_doc_comment(s: &str) -> bool { (s.starts_with("///") && super::is_doc_comment(s)) || s.starts_with("//!") || (s.starts_with("/**") && is_block_doc_comment(s)) || s.starts_with("/*!") } pub fn doc_comment_style(comment: &str) -> ast::AttrStyle { assert!(is_doc_comment(comment)); if comment.starts_with("//!") || comment.starts_with("/*!") { ast::AttrInner } else { ast::AttrOuter } } pub fn strip_doc_comment_decoration(comment: &str) -> String { /// remove whitespace-only lines from the start/end of lines fn vertical_trim(lines: Vec<String>) -> Vec<String> { let mut i = 0; let mut j = lines.len(); // first line of all-stars should be omitted if lines.len() > 0 && lines[0].chars().all(|c| c == '*') { i += 1; } while i < j && lines[i].trim().is_empty() { i += 1; } // like the first, a last line of all stars should be omitted if j > i && lines[j - 1] .chars() .skip(1) .all(|c| c == '*') { j -= 1; } while j > i && lines[j - 1].trim().is_empty() { j -= 1; } lines[i..j].iter().cloned().collect() } /// remove a "[ \t]*\*" block from each line, if possible fn horizontal_trim(lines: Vec<String> ) -> Vec<String> { let mut i = usize::MAX; let mut can_trim = true; let mut first = true; for line in &lines { for (j, c) in line.chars().enumerate() { if j > i ||!"* \t".contains(c) { can_trim = false; break; } if c == '*' { if first { i = j; first = false; } else if i!= j { can_trim = false; } break; } } if i > line.len() { can_trim = false; } if!can_trim { break; } } if can_trim { lines.iter().map(|line| { (&line[i + 1..line.len()]).to_string() }).collect() } else { lines } } // one-line comments lose their prefix const ONELINERS: &'static [&'static str] = &["///!", "///", "//!", "//"]; for prefix in ONELINERS { if comment.starts_with(*prefix) { return (&comment[prefix.len()..]).to_string(); } } if comment.starts_with("/*") { let lines = comment[3..comment.len() - 2] .lines_any() .map(|s| s.to_string()) .collect::<Vec<String> >(); let lines = vertical_trim(lines); let lines = horizontal_trim(lines); return lines.connect("\n"); } panic!("not a doc-comment: {}", comment); } fn push_blank_line_comment(rdr: &StringReader, comments: &mut Vec<Comment>) { debug!(">>> blank-line comment"); comments.push(Comment { style: BlankLine, lines: Vec::new(), pos: rdr.last_pos, }); } fn consume_whitespace_counting_blank_lines(rdr: &mut StringReader, comments: &mut Vec<Comment>)
fn read_shebang_comment(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment>) { debug!(">>> shebang comment"); let p = rdr.last_pos; debug!("<<< shebang comment"); comments.push(Comment { style: if code_to_the_left { Trailing } else { Isolated }, lines: vec!(rdr.read_one_line_comment()), pos: p }); } fn read_line_comments(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment>) { debug!(">>> line comments"); let p = rdr.last_pos; let mut lines: Vec<String> = Vec::new(); while rdr.curr_is('/') && rdr.nextch_is('/') { let line = rdr.read_one_line_comment(); debug!("{}", line); // Doc comments are not put in comments. if is_doc_comment(&line[..]) { break; } lines.push(line); rdr.consume_non_eol_whitespace(); } debug!("<<< line comments"); if!lines.is_empty() { comments.push(Comment { style: if code_to_the_left { Trailing } else { Isolated }, lines: lines, pos: p }); } } /// Returns None if the first col chars of s contain a non-whitespace char. /// Otherwise returns Some(k) where k is first char offset after that leading /// whitespace. Note k may be outside bounds of s. fn all_whitespace(s: &str, col: CharPos) -> Option<usize> { let len = s.len(); let mut col = col.to_usize(); let mut cursor: usize = 0; while col > 0 && cursor < len { let r: str::CharRange = s.char_range_at(cursor); if!r.ch.is_whitespace() { return None; } cursor = r.next; col -= 1; } return Some(cursor); } fn trim_whitespace_prefix_and_push_line(lines: &mut Vec<String>, s: String, col: CharPos) { let len = s.len(); let s1 = match all_whitespace(&s[..], col) { Some(col) => { if col < len { (&s[col..len]).to_string() } else { "".to_string() } } None => s, }; debug!("pushing line: {}", s1); lines.push(s1); } fn read_block_comment(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment> ) { debug!(">>> block comment"); let p = rdr.last_pos; let mut lines: Vec<String> = Vec::new(); let col = rdr.col; rdr.bump(); rdr.bump(); let mut curr_line = String::from_str("/*"); // doc-comments are not really comments, they are attributes if (rdr.curr_is('*') &&!rdr.nextch_is('*')) || rdr.curr_is('!') { while!(rdr.curr_is('*') && rdr.nextch_is('/')) &&!rdr.is_eof() { curr_line.push(rdr.curr.unwrap()); rdr.bump(); } if!rdr.is_eof() { curr_line.push_str("*/"); rdr.bump(); rdr.bump(); } if is_block_doc_comment(&curr_line[..]) { return } assert!(!curr_line.contains('\n')); lines.push(curr_line); } else { let mut level: isize = 1; while level > 0 { debug!("=== block comment level {}", level); if rdr.is_eof() { rdr.fatal("unterminated block comment"); } if rdr.curr_is('\n') { trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col); curr_line = String::new(); rdr.bump(); } else { curr_line.push(rdr.curr.unwrap()); if rdr.curr_is('/') && rdr.nextch_is('*') { rdr.bump(); rdr.bump(); curr_line.push('*'); level += 1; } else { if rdr.curr_is('*') && rdr.nextch_is('/') { rdr.bump(); rdr.bump(); curr_line.push('/'); level -= 1; } else { rdr.bump(); } } } } if curr_line.len()!= 0 { trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col); } } let mut style = if code_to_the_left { Trailing } else { Isolated }; rdr.consume_non_eol_whitespace(); if!rdr.is_eof() &&!rdr.curr_is('\n') && lines.len() == 1 { style = Mixed; } debug!("<<< block comment"); comments.push(Comment {style: style, lines: lines, pos: p}); } fn consume_comment(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment> ) { debug!(">>> consume comment"); if rdr.curr_is('/') && rdr.nextch_is('/') { read_line_comments(rdr, code_to_the_left, comments); } else if rdr.curr_is('/') && rdr.nextch_is('*') { read_block_comment(rdr, code_to_the_left, comments); } else if rdr.curr_is('#') && rdr.nextch_is('!') { read_shebang_comment(rdr, code_to_the_left, comments); } else { panic!(); } debug!("<<< consume comment"); } #[derive(Clone)] pub struct Literal { pub lit: String, pub pos: BytePos, } // it appears this function is called only from pprust... that's // probably not a good thing. pub fn gather_comments_and_literals(span_diagnostic: &diagnostic::SpanHandler, path: String, srdr: &mut Read) -> (Vec<Comment>, Vec<Literal>) { let mut src = Vec::new(); srdr.read_to_end(&mut src).unwrap(); let src = String::from_utf8(src).unwrap(); let cm = CodeMap::new(); let filemap = cm.new_filemap(path, src); let mut rdr = lexer::StringReader::new_raw(span_diagnostic, filemap); let mut comments: Vec<Comment> = Vec::new(); let mut literals: Vec<Literal> = Vec::new(); let mut first_read: bool = true; while!rdr.is_eof() { loop { let mut code_to_the_left =!first_read; rdr.consume_non_eol_whitespace(); if rdr.curr_is('\n') { code_to_the_left = false; consume_whitespace_counting_blank_lines(&mut rdr, &mut comments); } while rdr.peeking_at_comment() { consume_comment(&mut rdr, code_to_the_left, &mut comments); consume_whitespace_counting_blank_lines(&mut rdr, &mut comments); } break; } let bstart = rdr.last_pos; rdr.next_token(); //discard, and look ahead; we're working with internal state let TokenAndSpan { tok, sp } = rdr.peek(); if tok.is_lit() { rdr.with_str_from(bstart, |s| { debug!("tok lit: {}", s); literals.push(Literal {lit: s.to_string(), pos: sp.lo}); }) } else { debug!("tok: {}", pprust::token_to_string(&tok)); } first_read = false; } (comments, literals) } #[cfg(test)] mod test { use super::*; #[test] fn test_block_doc_comment_1() { let comment = "/**\n * Test \n ** Test\n * Test\n*/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " Test \n* Test\n Test"); } #[test] fn test_block_doc_comment_2() { let comment = "/**\n * Test\n * Test\n*/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " Test\n Test"); } #[test] fn test_block_doc_comment_3() { let comment = "/**\n let a: *i32;\n *a = 5;\n*/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " let a: *i32;\n *a = 5;"); } #[test] fn test_block_doc_comment_4() { let comment = "/*******************\n test\n *********************/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " test"); } #[test] fn test_line_doc_comment() { let stripped = strip_doc_comment_decoration("/// test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("///! test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("// test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("// test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("///test"); assert_eq!(stripped, "test"); let stripped = strip_doc_comment_decoration("///!test"); assert_eq!(stripped, "test"); let stripped = strip_doc_comment_decoration("//test"); assert_eq!(stripped, "test"); } }
{ while is_whitespace(rdr.curr) && !rdr.is_eof() { if rdr.col == CharPos(0) && rdr.curr_is('\n') { push_blank_line_comment(rdr, &mut *comments); } rdr.bump(); } }
identifier_body
comments.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. pub use self::CommentStyle::*; use ast; use codemap::{BytePos, CharPos, CodeMap, Pos}; use diagnostic; use parse::lexer::{is_whitespace, Reader}; use parse::lexer::{StringReader, TokenAndSpan}; use parse::lexer::is_block_doc_comment; use parse::lexer; use print::pprust; use std::io::Read; use std::str; use std::usize; #[derive(Clone, Copy, PartialEq)] pub enum CommentStyle { /// No code on either side of each line of the comment Isolated, /// Code exists to the left of the comment Trailing, /// Code before /* foo */ and after the comment Mixed, /// Just a manual blank line "\n\n", for layout BlankLine, } #[derive(Clone)] pub struct Comment { pub style: CommentStyle, pub lines: Vec<String>, pub pos: BytePos, } pub fn is_doc_comment(s: &str) -> bool { (s.starts_with("///") && super::is_doc_comment(s)) || s.starts_with("//!") || (s.starts_with("/**") && is_block_doc_comment(s)) || s.starts_with("/*!") } pub fn doc_comment_style(comment: &str) -> ast::AttrStyle { assert!(is_doc_comment(comment)); if comment.starts_with("//!") || comment.starts_with("/*!") { ast::AttrInner } else { ast::AttrOuter } } pub fn strip_doc_comment_decoration(comment: &str) -> String { /// remove whitespace-only lines from the start/end of lines fn vertical_trim(lines: Vec<String>) -> Vec<String> { let mut i = 0; let mut j = lines.len(); // first line of all-stars should be omitted if lines.len() > 0 && lines[0].chars().all(|c| c == '*') { i += 1; } while i < j && lines[i].trim().is_empty() { i += 1; } // like the first, a last line of all stars should be omitted if j > i && lines[j - 1] .chars() .skip(1) .all(|c| c == '*') { j -= 1; } while j > i && lines[j - 1].trim().is_empty() { j -= 1; } lines[i..j].iter().cloned().collect() } /// remove a "[ \t]*\*" block from each line, if possible fn horizontal_trim(lines: Vec<String> ) -> Vec<String> { let mut i = usize::MAX; let mut can_trim = true; let mut first = true; for line in &lines { for (j, c) in line.chars().enumerate() { if j > i ||!"* \t".contains(c) { can_trim = false; break; } if c == '*' { if first { i = j; first = false; } else if i!= j { can_trim = false; } break; } } if i > line.len() { can_trim = false; } if!can_trim { break; } } if can_trim { lines.iter().map(|line| { (&line[i + 1..line.len()]).to_string() }).collect() } else { lines } } // one-line comments lose their prefix const ONELINERS: &'static [&'static str] = &["///!", "///", "//!", "//"]; for prefix in ONELINERS { if comment.starts_with(*prefix) { return (&comment[prefix.len()..]).to_string(); } } if comment.starts_with("/*") { let lines = comment[3..comment.len() - 2] .lines_any() .map(|s| s.to_string()) .collect::<Vec<String> >(); let lines = vertical_trim(lines); let lines = horizontal_trim(lines); return lines.connect("\n"); } panic!("not a doc-comment: {}", comment); } fn push_blank_line_comment(rdr: &StringReader, comments: &mut Vec<Comment>) { debug!(">>> blank-line comment"); comments.push(Comment { style: BlankLine, lines: Vec::new(), pos: rdr.last_pos, }); } fn consume_whitespace_counting_blank_lines(rdr: &mut StringReader, comments: &mut Vec<Comment>) { while is_whitespace(rdr.curr) &&!rdr.is_eof() { if rdr.col == CharPos(0) && rdr.curr_is('\n') { push_blank_line_comment(rdr, &mut *comments); } rdr.bump(); } } fn read_shebang_comment(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment>) { debug!(">>> shebang comment"); let p = rdr.last_pos; debug!("<<< shebang comment"); comments.push(Comment { style: if code_to_the_left { Trailing } else { Isolated }, lines: vec!(rdr.read_one_line_comment()), pos: p }); } fn read_line_comments(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment>) { debug!(">>> line comments"); let p = rdr.last_pos; let mut lines: Vec<String> = Vec::new(); while rdr.curr_is('/') && rdr.nextch_is('/') { let line = rdr.read_one_line_comment(); debug!("{}", line); // Doc comments are not put in comments. if is_doc_comment(&line[..]) { break; } lines.push(line); rdr.consume_non_eol_whitespace(); } debug!("<<< line comments"); if!lines.is_empty() { comments.push(Comment { style: if code_to_the_left { Trailing } else { Isolated }, lines: lines, pos: p }); } } /// Returns None if the first col chars of s contain a non-whitespace char. /// Otherwise returns Some(k) where k is first char offset after that leading /// whitespace. Note k may be outside bounds of s. fn all_whitespace(s: &str, col: CharPos) -> Option<usize> { let len = s.len(); let mut col = col.to_usize(); let mut cursor: usize = 0; while col > 0 && cursor < len { let r: str::CharRange = s.char_range_at(cursor); if!r.ch.is_whitespace() { return None; } cursor = r.next; col -= 1; } return Some(cursor); } fn trim_whitespace_prefix_and_push_line(lines: &mut Vec<String>, s: String, col: CharPos) { let len = s.len(); let s1 = match all_whitespace(&s[..], col) { Some(col) => { if col < len { (&s[col..len]).to_string() } else { "".to_string() } } None => s, }; debug!("pushing line: {}", s1); lines.push(s1); } fn read_block_comment(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment> ) { debug!(">>> block comment"); let p = rdr.last_pos; let mut lines: Vec<String> = Vec::new(); let col = rdr.col; rdr.bump(); rdr.bump(); let mut curr_line = String::from_str("/*"); // doc-comments are not really comments, they are attributes if (rdr.curr_is('*') &&!rdr.nextch_is('*')) || rdr.curr_is('!') { while!(rdr.curr_is('*') && rdr.nextch_is('/')) &&!rdr.is_eof() { curr_line.push(rdr.curr.unwrap()); rdr.bump(); } if!rdr.is_eof() { curr_line.push_str("*/"); rdr.bump(); rdr.bump(); } if is_block_doc_comment(&curr_line[..]) { return } assert!(!curr_line.contains('\n')); lines.push(curr_line); } else { let mut level: isize = 1; while level > 0 { debug!("=== block comment level {}", level); if rdr.is_eof() { rdr.fatal("unterminated block comment"); } if rdr.curr_is('\n') { trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col); curr_line = String::new(); rdr.bump(); } else { curr_line.push(rdr.curr.unwrap()); if rdr.curr_is('/') && rdr.nextch_is('*') { rdr.bump(); rdr.bump(); curr_line.push('*'); level += 1; } else { if rdr.curr_is('*') && rdr.nextch_is('/') { rdr.bump(); rdr.bump(); curr_line.push('/'); level -= 1; } else { rdr.bump(); } } } } if curr_line.len()!= 0 { trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col); } } let mut style = if code_to_the_left { Trailing } else { Isolated }; rdr.consume_non_eol_whitespace(); if!rdr.is_eof() &&!rdr.curr_is('\n') && lines.len() == 1 { style = Mixed; } debug!("<<< block comment"); comments.push(Comment {style: style, lines: lines, pos: p}); } fn consume_comment(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment> ) { debug!(">>> consume comment"); if rdr.curr_is('/') && rdr.nextch_is('/') { read_line_comments(rdr, code_to_the_left, comments); } else if rdr.curr_is('/') && rdr.nextch_is('*') { read_block_comment(rdr, code_to_the_left, comments); } else if rdr.curr_is('#') && rdr.nextch_is('!') { read_shebang_comment(rdr, code_to_the_left, comments); } else { panic!(); } debug!("<<< consume comment"); } #[derive(Clone)] pub struct Literal { pub lit: String, pub pos: BytePos, } // it appears this function is called only from pprust... that's // probably not a good thing. pub fn gather_comments_and_literals(span_diagnostic: &diagnostic::SpanHandler, path: String, srdr: &mut Read) -> (Vec<Comment>, Vec<Literal>) { let mut src = Vec::new(); srdr.read_to_end(&mut src).unwrap(); let src = String::from_utf8(src).unwrap(); let cm = CodeMap::new(); let filemap = cm.new_filemap(path, src); let mut rdr = lexer::StringReader::new_raw(span_diagnostic, filemap); let mut comments: Vec<Comment> = Vec::new(); let mut literals: Vec<Literal> = Vec::new(); let mut first_read: bool = true; while!rdr.is_eof() { loop { let mut code_to_the_left =!first_read; rdr.consume_non_eol_whitespace(); if rdr.curr_is('\n') { code_to_the_left = false; consume_whitespace_counting_blank_lines(&mut rdr, &mut comments); } while rdr.peeking_at_comment() { consume_comment(&mut rdr, code_to_the_left, &mut comments); consume_whitespace_counting_blank_lines(&mut rdr, &mut comments); } break; } let bstart = rdr.last_pos; rdr.next_token(); //discard, and look ahead; we're working with internal state let TokenAndSpan { tok, sp } = rdr.peek(); if tok.is_lit() { rdr.with_str_from(bstart, |s| { debug!("tok lit: {}", s); literals.push(Literal {lit: s.to_string(), pos: sp.lo}); }) } else { debug!("tok: {}", pprust::token_to_string(&tok)); } first_read = false; } (comments, literals) } #[cfg(test)] mod test { use super::*; #[test] fn test_block_doc_comment_1() { let comment = "/**\n * Test \n ** Test\n * Test\n*/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " Test \n* Test\n Test"); } #[test] fn test_block_doc_comment_2() { let comment = "/**\n * Test\n * Test\n*/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " Test\n Test"); } #[test] fn
() { let comment = "/**\n let a: *i32;\n *a = 5;\n*/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " let a: *i32;\n *a = 5;"); } #[test] fn test_block_doc_comment_4() { let comment = "/*******************\n test\n *********************/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " test"); } #[test] fn test_line_doc_comment() { let stripped = strip_doc_comment_decoration("/// test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("///! test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("// test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("// test"); assert_eq!(stripped, " test"); let stripped = strip_doc_comment_decoration("///test"); assert_eq!(stripped, "test"); let stripped = strip_doc_comment_decoration("///!test"); assert_eq!(stripped, "test"); let stripped = strip_doc_comment_decoration("//test"); assert_eq!(stripped, "test"); } }
test_block_doc_comment_3
identifier_name
q_sigma.rs
use crate::{ domains::Transition, fa::StateActionUpdate, policies::EnumerablePolicy, utils::argmaxima, Enumerable, Function, Handler, Parameterised, }; use rand::thread_rng; use std::{collections::VecDeque, ops::Index}; struct BackupEntry<S> { pub s: S, pub a: usize, pub q: f64, pub residual: f64, pub sigma: f64, pub pi: f64, pub mu: f64, } struct Backup<S> { n_steps: usize, entries: VecDeque<BackupEntry<S>>, } impl<S> Backup<S> { pub fn new(n_steps: usize) -> Backup<S> { Backup { n_steps, entries: VecDeque::new(), } }
pub fn push(&mut self, entry: BackupEntry<S>) { self.entries.push_back(entry); } pub fn clear(&mut self) { self.entries.clear(); } pub fn propagate(&self, gamma: f64) -> (f64, f64) { let mut g = self.entries[0].q; let mut z = 1.0; let mut isr = 1.0; for k in 0..self.n_steps { let b1 = &self.entries[k]; let b2 = &self.entries[k + 1]; g += z * b1.residual; z *= gamma * ((1.0 - b1.sigma) * b2.pi + b2.sigma); isr *= 1.0 - b1.sigma + b1.sigma * b1.pi / b1.mu; } (isr, g) } } /// General multi-step temporal-difference learning algorithm. /// /// # Parameters /// - `sigma` varies the degree of sampling, yielding classical learning /// algorithms as special cases: /// * `0` - `ExpectedSARSA` | `TreeBackup` /// * `1` - `SARSA` /// /// # References /// - Sutton, R. S. and Barto, A. G. (2017). Reinforcement Learning: An /// Introduction (2nd ed.). Manuscript in preparation. /// - De Asis, K., Hernandez-Garcia, J. F., Holland, G. Z., & Sutton, R. S. /// (2017). Multi-step Reinforcement Learning: A Unifying Algorithm. arXiv /// preprint arXiv:1703.01327. #[derive(Parameterised)] pub struct QSigma<S, Q, P> { #[weights] pub q_func: Q, pub policy: P, pub alpha: f64, pub gamma: f64, pub sigma: f64, backup: Backup<S>, } impl<S, Q, P> QSigma<S, Q, P> { pub fn new(q_func: Q, policy: P, alpha: f64, gamma: f64, sigma: f64, n_steps: usize) -> Self { QSigma { q_func, policy, alpha, gamma, sigma, backup: Backup::new(n_steps), } } } impl<S, Q, P> QSigma<S, Q, P> { fn update_backup(&mut self, entry: BackupEntry<S>) -> Option<Result<Q::Response, Q::Error>> where Q: for<'s, 'a> Function<(&'s S, &'a usize), Output = f64>, Q: Handler<StateActionUpdate<S, usize, f64>>, { self.backup.push(entry); if self.backup.len() >= self.backup.n_steps { let (isr, g) = self.backup.propagate(self.gamma); let anchor = self.backup.pop().unwrap(); let qsa = self.q_func.evaluate((&anchor.s, &anchor.a)); Some(self.q_func.handle(StateActionUpdate { state: anchor.s, action: anchor.a, error: self.alpha * isr * (g - qsa), })) } else { None } } } impl<'m, S, Q, P> Handler<&'m Transition<S, usize>> for QSigma<S, Q, P> where S: Clone, Q: Enumerable<(&'m S,)> + for<'s, 'a> Function<(&'s S, &'a usize), Output = f64> + Handler<StateActionUpdate<S, usize, f64>>, P: EnumerablePolicy<&'m S>, <Q as Function<(&'m S,)>>::Output: Index<usize, Output = f64> + IntoIterator<Item = f64>, <<Q as Function<(&'m S,)>>::Output as IntoIterator>::IntoIter: ExactSizeIterator, <P as Function<(&'m S,)>>::Output: Index<usize, Output = f64> + IntoIterator<Item = f64>, <<P as Function<(&'m S,)>>::Output as IntoIterator>::IntoIter: ExactSizeIterator, { type Response = Option<Q::Response>; type Error = Q::Error; fn handle(&mut self, t: &'m Transition<S, usize>) -> Result<Self::Response, Self::Error> { let s = t.from.state(); let qa = self.q_func.evaluate_index((s,), t.action); let res = if t.terminated() { let res = self.update_backup(BackupEntry { s: s.clone(), a: t.action, q: qa, residual: t.reward - qa, sigma: self.sigma, pi: 0.0, mu: 1.0, }); self.backup.clear(); res } else { let ns = t.to.state(); let na = self.policy.sample(&mut thread_rng(), ns); let nqs = self.q_func.evaluate((ns,)); let nqsna = nqs[na]; let (na_max, exp_nqs) = argmaxima(nqs.into_iter()); let pi = if na_max.contains(&na) { 1.0 / na_max.len() as f64 } else { 0.0 }; let mu = self.policy.evaluate((ns, na)); let residual = t.reward + self.gamma * (self.sigma * nqsna + (1.0 - self.sigma) * exp_nqs) - qa; self.update_backup(BackupEntry { s: s.clone(), a: t.action, q: qa, residual: residual, sigma: self.sigma, pi: pi, mu: mu, }) }; res.transpose() } }
pub fn len(&self) -> usize { self.entries.len() } pub fn pop(&mut self) -> Option<BackupEntry<S>> { self.entries.pop_front() }
random_line_split
q_sigma.rs
use crate::{ domains::Transition, fa::StateActionUpdate, policies::EnumerablePolicy, utils::argmaxima, Enumerable, Function, Handler, Parameterised, }; use rand::thread_rng; use std::{collections::VecDeque, ops::Index}; struct BackupEntry<S> { pub s: S, pub a: usize, pub q: f64, pub residual: f64, pub sigma: f64, pub pi: f64, pub mu: f64, } struct Backup<S> { n_steps: usize, entries: VecDeque<BackupEntry<S>>, } impl<S> Backup<S> { pub fn new(n_steps: usize) -> Backup<S> { Backup { n_steps, entries: VecDeque::new(), } } pub fn len(&self) -> usize { self.entries.len() } pub fn pop(&mut self) -> Option<BackupEntry<S>> { self.entries.pop_front() } pub fn push(&mut self, entry: BackupEntry<S>) { self.entries.push_back(entry); } pub fn clear(&mut self) { self.entries.clear(); } pub fn propagate(&self, gamma: f64) -> (f64, f64) { let mut g = self.entries[0].q; let mut z = 1.0; let mut isr = 1.0; for k in 0..self.n_steps { let b1 = &self.entries[k]; let b2 = &self.entries[k + 1]; g += z * b1.residual; z *= gamma * ((1.0 - b1.sigma) * b2.pi + b2.sigma); isr *= 1.0 - b1.sigma + b1.sigma * b1.pi / b1.mu; } (isr, g) } } /// General multi-step temporal-difference learning algorithm. /// /// # Parameters /// - `sigma` varies the degree of sampling, yielding classical learning /// algorithms as special cases: /// * `0` - `ExpectedSARSA` | `TreeBackup` /// * `1` - `SARSA` /// /// # References /// - Sutton, R. S. and Barto, A. G. (2017). Reinforcement Learning: An /// Introduction (2nd ed.). Manuscript in preparation. /// - De Asis, K., Hernandez-Garcia, J. F., Holland, G. Z., & Sutton, R. S. /// (2017). Multi-step Reinforcement Learning: A Unifying Algorithm. arXiv /// preprint arXiv:1703.01327. #[derive(Parameterised)] pub struct QSigma<S, Q, P> { #[weights] pub q_func: Q, pub policy: P, pub alpha: f64, pub gamma: f64, pub sigma: f64, backup: Backup<S>, } impl<S, Q, P> QSigma<S, Q, P> { pub fn new(q_func: Q, policy: P, alpha: f64, gamma: f64, sigma: f64, n_steps: usize) -> Self { QSigma { q_func, policy, alpha, gamma, sigma, backup: Backup::new(n_steps), } } } impl<S, Q, P> QSigma<S, Q, P> { fn update_backup(&mut self, entry: BackupEntry<S>) -> Option<Result<Q::Response, Q::Error>> where Q: for<'s, 'a> Function<(&'s S, &'a usize), Output = f64>, Q: Handler<StateActionUpdate<S, usize, f64>>, { self.backup.push(entry); if self.backup.len() >= self.backup.n_steps { let (isr, g) = self.backup.propagate(self.gamma); let anchor = self.backup.pop().unwrap(); let qsa = self.q_func.evaluate((&anchor.s, &anchor.a)); Some(self.q_func.handle(StateActionUpdate { state: anchor.s, action: anchor.a, error: self.alpha * isr * (g - qsa), })) } else { None } } } impl<'m, S, Q, P> Handler<&'m Transition<S, usize>> for QSigma<S, Q, P> where S: Clone, Q: Enumerable<(&'m S,)> + for<'s, 'a> Function<(&'s S, &'a usize), Output = f64> + Handler<StateActionUpdate<S, usize, f64>>, P: EnumerablePolicy<&'m S>, <Q as Function<(&'m S,)>>::Output: Index<usize, Output = f64> + IntoIterator<Item = f64>, <<Q as Function<(&'m S,)>>::Output as IntoIterator>::IntoIter: ExactSizeIterator, <P as Function<(&'m S,)>>::Output: Index<usize, Output = f64> + IntoIterator<Item = f64>, <<P as Function<(&'m S,)>>::Output as IntoIterator>::IntoIter: ExactSizeIterator, { type Response = Option<Q::Response>; type Error = Q::Error; fn handle(&mut self, t: &'m Transition<S, usize>) -> Result<Self::Response, Self::Error> { let s = t.from.state(); let qa = self.q_func.evaluate_index((s,), t.action); let res = if t.terminated() { let res = self.update_backup(BackupEntry { s: s.clone(), a: t.action, q: qa, residual: t.reward - qa, sigma: self.sigma, pi: 0.0, mu: 1.0, }); self.backup.clear(); res } else { let ns = t.to.state(); let na = self.policy.sample(&mut thread_rng(), ns); let nqs = self.q_func.evaluate((ns,)); let nqsna = nqs[na]; let (na_max, exp_nqs) = argmaxima(nqs.into_iter()); let pi = if na_max.contains(&na) { 1.0 / na_max.len() as f64 } else
; let mu = self.policy.evaluate((ns, na)); let residual = t.reward + self.gamma * (self.sigma * nqsna + (1.0 - self.sigma) * exp_nqs) - qa; self.update_backup(BackupEntry { s: s.clone(), a: t.action, q: qa, residual: residual, sigma: self.sigma, pi: pi, mu: mu, }) }; res.transpose() } }
{ 0.0 }
conditional_block
q_sigma.rs
use crate::{ domains::Transition, fa::StateActionUpdate, policies::EnumerablePolicy, utils::argmaxima, Enumerable, Function, Handler, Parameterised, }; use rand::thread_rng; use std::{collections::VecDeque, ops::Index}; struct
<S> { pub s: S, pub a: usize, pub q: f64, pub residual: f64, pub sigma: f64, pub pi: f64, pub mu: f64, } struct Backup<S> { n_steps: usize, entries: VecDeque<BackupEntry<S>>, } impl<S> Backup<S> { pub fn new(n_steps: usize) -> Backup<S> { Backup { n_steps, entries: VecDeque::new(), } } pub fn len(&self) -> usize { self.entries.len() } pub fn pop(&mut self) -> Option<BackupEntry<S>> { self.entries.pop_front() } pub fn push(&mut self, entry: BackupEntry<S>) { self.entries.push_back(entry); } pub fn clear(&mut self) { self.entries.clear(); } pub fn propagate(&self, gamma: f64) -> (f64, f64) { let mut g = self.entries[0].q; let mut z = 1.0; let mut isr = 1.0; for k in 0..self.n_steps { let b1 = &self.entries[k]; let b2 = &self.entries[k + 1]; g += z * b1.residual; z *= gamma * ((1.0 - b1.sigma) * b2.pi + b2.sigma); isr *= 1.0 - b1.sigma + b1.sigma * b1.pi / b1.mu; } (isr, g) } } /// General multi-step temporal-difference learning algorithm. /// /// # Parameters /// - `sigma` varies the degree of sampling, yielding classical learning /// algorithms as special cases: /// * `0` - `ExpectedSARSA` | `TreeBackup` /// * `1` - `SARSA` /// /// # References /// - Sutton, R. S. and Barto, A. G. (2017). Reinforcement Learning: An /// Introduction (2nd ed.). Manuscript in preparation. /// - De Asis, K., Hernandez-Garcia, J. F., Holland, G. Z., & Sutton, R. S. /// (2017). Multi-step Reinforcement Learning: A Unifying Algorithm. arXiv /// preprint arXiv:1703.01327. #[derive(Parameterised)] pub struct QSigma<S, Q, P> { #[weights] pub q_func: Q, pub policy: P, pub alpha: f64, pub gamma: f64, pub sigma: f64, backup: Backup<S>, } impl<S, Q, P> QSigma<S, Q, P> { pub fn new(q_func: Q, policy: P, alpha: f64, gamma: f64, sigma: f64, n_steps: usize) -> Self { QSigma { q_func, policy, alpha, gamma, sigma, backup: Backup::new(n_steps), } } } impl<S, Q, P> QSigma<S, Q, P> { fn update_backup(&mut self, entry: BackupEntry<S>) -> Option<Result<Q::Response, Q::Error>> where Q: for<'s, 'a> Function<(&'s S, &'a usize), Output = f64>, Q: Handler<StateActionUpdate<S, usize, f64>>, { self.backup.push(entry); if self.backup.len() >= self.backup.n_steps { let (isr, g) = self.backup.propagate(self.gamma); let anchor = self.backup.pop().unwrap(); let qsa = self.q_func.evaluate((&anchor.s, &anchor.a)); Some(self.q_func.handle(StateActionUpdate { state: anchor.s, action: anchor.a, error: self.alpha * isr * (g - qsa), })) } else { None } } } impl<'m, S, Q, P> Handler<&'m Transition<S, usize>> for QSigma<S, Q, P> where S: Clone, Q: Enumerable<(&'m S,)> + for<'s, 'a> Function<(&'s S, &'a usize), Output = f64> + Handler<StateActionUpdate<S, usize, f64>>, P: EnumerablePolicy<&'m S>, <Q as Function<(&'m S,)>>::Output: Index<usize, Output = f64> + IntoIterator<Item = f64>, <<Q as Function<(&'m S,)>>::Output as IntoIterator>::IntoIter: ExactSizeIterator, <P as Function<(&'m S,)>>::Output: Index<usize, Output = f64> + IntoIterator<Item = f64>, <<P as Function<(&'m S,)>>::Output as IntoIterator>::IntoIter: ExactSizeIterator, { type Response = Option<Q::Response>; type Error = Q::Error; fn handle(&mut self, t: &'m Transition<S, usize>) -> Result<Self::Response, Self::Error> { let s = t.from.state(); let qa = self.q_func.evaluate_index((s,), t.action); let res = if t.terminated() { let res = self.update_backup(BackupEntry { s: s.clone(), a: t.action, q: qa, residual: t.reward - qa, sigma: self.sigma, pi: 0.0, mu: 1.0, }); self.backup.clear(); res } else { let ns = t.to.state(); let na = self.policy.sample(&mut thread_rng(), ns); let nqs = self.q_func.evaluate((ns,)); let nqsna = nqs[na]; let (na_max, exp_nqs) = argmaxima(nqs.into_iter()); let pi = if na_max.contains(&na) { 1.0 / na_max.len() as f64 } else { 0.0 }; let mu = self.policy.evaluate((ns, na)); let residual = t.reward + self.gamma * (self.sigma * nqsna + (1.0 - self.sigma) * exp_nqs) - qa; self.update_backup(BackupEntry { s: s.clone(), a: t.action, q: qa, residual: residual, sigma: self.sigma, pi: pi, mu: mu, }) }; res.transpose() } }
BackupEntry
identifier_name
q_sigma.rs
use crate::{ domains::Transition, fa::StateActionUpdate, policies::EnumerablePolicy, utils::argmaxima, Enumerable, Function, Handler, Parameterised, }; use rand::thread_rng; use std::{collections::VecDeque, ops::Index}; struct BackupEntry<S> { pub s: S, pub a: usize, pub q: f64, pub residual: f64, pub sigma: f64, pub pi: f64, pub mu: f64, } struct Backup<S> { n_steps: usize, entries: VecDeque<BackupEntry<S>>, } impl<S> Backup<S> { pub fn new(n_steps: usize) -> Backup<S> { Backup { n_steps, entries: VecDeque::new(), } } pub fn len(&self) -> usize { self.entries.len() } pub fn pop(&mut self) -> Option<BackupEntry<S>> { self.entries.pop_front() } pub fn push(&mut self, entry: BackupEntry<S>)
pub fn clear(&mut self) { self.entries.clear(); } pub fn propagate(&self, gamma: f64) -> (f64, f64) { let mut g = self.entries[0].q; let mut z = 1.0; let mut isr = 1.0; for k in 0..self.n_steps { let b1 = &self.entries[k]; let b2 = &self.entries[k + 1]; g += z * b1.residual; z *= gamma * ((1.0 - b1.sigma) * b2.pi + b2.sigma); isr *= 1.0 - b1.sigma + b1.sigma * b1.pi / b1.mu; } (isr, g) } } /// General multi-step temporal-difference learning algorithm. /// /// # Parameters /// - `sigma` varies the degree of sampling, yielding classical learning /// algorithms as special cases: /// * `0` - `ExpectedSARSA` | `TreeBackup` /// * `1` - `SARSA` /// /// # References /// - Sutton, R. S. and Barto, A. G. (2017). Reinforcement Learning: An /// Introduction (2nd ed.). Manuscript in preparation. /// - De Asis, K., Hernandez-Garcia, J. F., Holland, G. Z., & Sutton, R. S. /// (2017). Multi-step Reinforcement Learning: A Unifying Algorithm. arXiv /// preprint arXiv:1703.01327. #[derive(Parameterised)] pub struct QSigma<S, Q, P> { #[weights] pub q_func: Q, pub policy: P, pub alpha: f64, pub gamma: f64, pub sigma: f64, backup: Backup<S>, } impl<S, Q, P> QSigma<S, Q, P> { pub fn new(q_func: Q, policy: P, alpha: f64, gamma: f64, sigma: f64, n_steps: usize) -> Self { QSigma { q_func, policy, alpha, gamma, sigma, backup: Backup::new(n_steps), } } } impl<S, Q, P> QSigma<S, Q, P> { fn update_backup(&mut self, entry: BackupEntry<S>) -> Option<Result<Q::Response, Q::Error>> where Q: for<'s, 'a> Function<(&'s S, &'a usize), Output = f64>, Q: Handler<StateActionUpdate<S, usize, f64>>, { self.backup.push(entry); if self.backup.len() >= self.backup.n_steps { let (isr, g) = self.backup.propagate(self.gamma); let anchor = self.backup.pop().unwrap(); let qsa = self.q_func.evaluate((&anchor.s, &anchor.a)); Some(self.q_func.handle(StateActionUpdate { state: anchor.s, action: anchor.a, error: self.alpha * isr * (g - qsa), })) } else { None } } } impl<'m, S, Q, P> Handler<&'m Transition<S, usize>> for QSigma<S, Q, P> where S: Clone, Q: Enumerable<(&'m S,)> + for<'s, 'a> Function<(&'s S, &'a usize), Output = f64> + Handler<StateActionUpdate<S, usize, f64>>, P: EnumerablePolicy<&'m S>, <Q as Function<(&'m S,)>>::Output: Index<usize, Output = f64> + IntoIterator<Item = f64>, <<Q as Function<(&'m S,)>>::Output as IntoIterator>::IntoIter: ExactSizeIterator, <P as Function<(&'m S,)>>::Output: Index<usize, Output = f64> + IntoIterator<Item = f64>, <<P as Function<(&'m S,)>>::Output as IntoIterator>::IntoIter: ExactSizeIterator, { type Response = Option<Q::Response>; type Error = Q::Error; fn handle(&mut self, t: &'m Transition<S, usize>) -> Result<Self::Response, Self::Error> { let s = t.from.state(); let qa = self.q_func.evaluate_index((s,), t.action); let res = if t.terminated() { let res = self.update_backup(BackupEntry { s: s.clone(), a: t.action, q: qa, residual: t.reward - qa, sigma: self.sigma, pi: 0.0, mu: 1.0, }); self.backup.clear(); res } else { let ns = t.to.state(); let na = self.policy.sample(&mut thread_rng(), ns); let nqs = self.q_func.evaluate((ns,)); let nqsna = nqs[na]; let (na_max, exp_nqs) = argmaxima(nqs.into_iter()); let pi = if na_max.contains(&na) { 1.0 / na_max.len() as f64 } else { 0.0 }; let mu = self.policy.evaluate((ns, na)); let residual = t.reward + self.gamma * (self.sigma * nqsna + (1.0 - self.sigma) * exp_nqs) - qa; self.update_backup(BackupEntry { s: s.clone(), a: t.action, q: qa, residual: residual, sigma: self.sigma, pi: pi, mu: mu, }) }; res.transpose() } }
{ self.entries.push_back(entry); }
identifier_body
lib.rs
#![warn(missing_docs)] //! A `Pinboard` is a shared, mutable, eventually consistent, lock-free data-structure. This //! allows multiple threads to communicate in a decoupled way by publishing data to the pinboard //! which other threads can then read in an eventually consistent way. //! //! This is not a silver bullet though, there are various limitations of `Pinboard` that trade off //! the nice behaviour described above. //! //! * Eventual consistency: //! * Writes from one thread are not guaranteed to be seen by reads from another thread //! * Writes from one thread can overwrite writes from another thread //! * No in-place mutation: //! * The only write primitive completely overwrites the data on the `Pinboard` //! * Requires `Clone`: //! * All reads return a clone of the data, decoupling the lifetime of the read value from the //! data stored in the global reference. extern crate crossbeam_epoch as epoch; use epoch::{Atomic, Owned, Shared, pin}; use std::sync::atomic::Ordering::*; /// An instance of a `Pinboard`, holds a shared, mutable, eventually-consistent reference to a `T`. pub struct Pinboard<T: Clone +'static>(Atomic<T>); impl<T: Clone +'static> Pinboard<T> { /// Create a new `Pinboard` instance holding the given value. pub fn new(t: T) -> Pinboard<T> { let t = Owned::new(t); let p = Pinboard::default(); p.0.store(t, Release); p } /// Create a new, empty `Pinboard` pub fn new_empty() -> Self { Pinboard(Atomic::null()) } /// Update the value stored in the `Pinboard`. pub fn set(&self, t: T) { let guard = pin(); let t = Owned::new(t); let t = self.0.swap(t, AcqRel, &guard); unsafe { if!t.is_null() { guard.defer_unchecked(move || drop(t.into_owned())); } } } /// Clear out the `Pinboard` so it's no longer holding any data. pub fn clear(&self) { let guard = pin(); let t = self.0.swap(Shared::null(), AcqRel, &guard); unsafe { if!t.is_null() { guard.defer_unchecked(move || drop(t.into_owned())); } } } /// Get a copy of the latest (well, recent) version of the posted data. pub fn read(&self) -> Option<T> { let guard = pin(); unsafe { let t = self.0.load(Acquire, &guard); if t.is_null() { None } else { Some(t.deref().clone()) } } } } impl<T: Clone +'static> Default for Pinboard<T> { fn default() -> Pinboard<T> { Self::new_empty() } } impl<T: Clone +'static> Drop for Pinboard<T> { fn drop(&mut self) { // Make sure any stored data is marked for deletion self.clear(); } } impl<T: Clone +'static> From<Option<T>> for Pinboard<T> { fn from(src: Option<T>) -> Pinboard<T> { src.map(Pinboard::new).unwrap_or_default() } } /// An wrapper around a `Pinboard` which provides the guarantee it is never empty. pub struct NonEmptyPinboard<T: Clone +'static>(Pinboard<T>); impl<T: Clone +'static> NonEmptyPinboard<T> { /// Create a new `NonEmptyPinboard` instance holding the given value. pub fn new(t: T) -> NonEmptyPinboard<T> { NonEmptyPinboard(Pinboard::new(t)) } /// Update the value stored in the `NonEmptyPinboard`. #[inline] pub fn set(&self, t: T) { self.0.set(t) } /// Get a copy of the latest (well, recent) version of the posted data. #[inline] pub fn read(&self) -> T { // Unwrap the option returned by the inner `Pinboard`. This will never panic, because it's // impossible for this `Pinboard` to be empty (though it's not possible to prove this to the // compiler). match self.0.read() { Some(t) => t, None => unreachable!("Inner pointer was unexpectedly null"), } } } macro_rules! debuggable { ($struct:ident, $trait:ident) => { impl<T: Clone +'static> ::std::fmt::$trait for $struct<T> where T: ::std::fmt::$trait { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { write!(f, "{}(", stringify!($struct))?; ::std::fmt::$trait::fmt(&self.read(), f)?; write!(f, ")") } } } } debuggable!(Pinboard, Debug); debuggable!(NonEmptyPinboard, Debug); debuggable!(NonEmptyPinboard, Binary); debuggable!(NonEmptyPinboard, Display); debuggable!(NonEmptyPinboard, LowerExp); debuggable!(NonEmptyPinboard, LowerHex); debuggable!(NonEmptyPinboard, Octal); debuggable!(NonEmptyPinboard, Pointer); debuggable!(NonEmptyPinboard, UpperExp); debuggable!(NonEmptyPinboard, UpperHex); #[cfg(test)] mod tests { extern crate crossbeam; use super::*; use std::fmt::Display; fn consume<T: Clone + Display>(t: &Pinboard<T>) { loop { match t.read() { Some(_) => {} None => break, } std::thread::sleep(std::time::Duration::from_millis(1)); } } fn produce(t: &Pinboard<u32>) { for i in 1..100 { t.set(i); std::thread::sleep(std::time::Duration::from_millis(2)); } t.clear(); } fn check_debug<T: ::std::fmt::Debug>(_: T) {} #[test] fn it_works() { let t = Pinboard::<u32>::default(); assert_eq!(None, t.read()); t.set(3); assert_eq!(Some(3), t.read()); t.clear(); assert_eq!(None, t.read()); } #[test] fn single_producer_single_consumer() { let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); }).unwrap(); } #[test] fn multi_producer_single_consumer()
#[test] fn single_producer_multi_consumer() { let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); }).unwrap(); } #[test] fn multi_producer_multi_consumer() { let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); }).unwrap(); } #[test] fn non_empty_pinboard() { let t = NonEmptyPinboard::<u32>::new(3); assert_eq!(3, t.read()); t.set(4); assert_eq!(4, t.read()); } #[test] fn debuggable() { let t = Pinboard::<i32>::new(3); check_debug(t); let t = NonEmptyPinboard::<i32>::new(2); check_debug(t); } }
{ let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); }).unwrap(); }
identifier_body
lib.rs
#![warn(missing_docs)] //! A `Pinboard` is a shared, mutable, eventually consistent, lock-free data-structure. This //! allows multiple threads to communicate in a decoupled way by publishing data to the pinboard //! which other threads can then read in an eventually consistent way. //! //! This is not a silver bullet though, there are various limitations of `Pinboard` that trade off //! the nice behaviour described above. //! //! * Eventual consistency: //! * Writes from one thread are not guaranteed to be seen by reads from another thread //! * Writes from one thread can overwrite writes from another thread //! * No in-place mutation: //! * The only write primitive completely overwrites the data on the `Pinboard` //! * Requires `Clone`: //! * All reads return a clone of the data, decoupling the lifetime of the read value from the //! data stored in the global reference.
use std::sync::atomic::Ordering::*; /// An instance of a `Pinboard`, holds a shared, mutable, eventually-consistent reference to a `T`. pub struct Pinboard<T: Clone +'static>(Atomic<T>); impl<T: Clone +'static> Pinboard<T> { /// Create a new `Pinboard` instance holding the given value. pub fn new(t: T) -> Pinboard<T> { let t = Owned::new(t); let p = Pinboard::default(); p.0.store(t, Release); p } /// Create a new, empty `Pinboard` pub fn new_empty() -> Self { Pinboard(Atomic::null()) } /// Update the value stored in the `Pinboard`. pub fn set(&self, t: T) { let guard = pin(); let t = Owned::new(t); let t = self.0.swap(t, AcqRel, &guard); unsafe { if!t.is_null() { guard.defer_unchecked(move || drop(t.into_owned())); } } } /// Clear out the `Pinboard` so it's no longer holding any data. pub fn clear(&self) { let guard = pin(); let t = self.0.swap(Shared::null(), AcqRel, &guard); unsafe { if!t.is_null() { guard.defer_unchecked(move || drop(t.into_owned())); } } } /// Get a copy of the latest (well, recent) version of the posted data. pub fn read(&self) -> Option<T> { let guard = pin(); unsafe { let t = self.0.load(Acquire, &guard); if t.is_null() { None } else { Some(t.deref().clone()) } } } } impl<T: Clone +'static> Default for Pinboard<T> { fn default() -> Pinboard<T> { Self::new_empty() } } impl<T: Clone +'static> Drop for Pinboard<T> { fn drop(&mut self) { // Make sure any stored data is marked for deletion self.clear(); } } impl<T: Clone +'static> From<Option<T>> for Pinboard<T> { fn from(src: Option<T>) -> Pinboard<T> { src.map(Pinboard::new).unwrap_or_default() } } /// An wrapper around a `Pinboard` which provides the guarantee it is never empty. pub struct NonEmptyPinboard<T: Clone +'static>(Pinboard<T>); impl<T: Clone +'static> NonEmptyPinboard<T> { /// Create a new `NonEmptyPinboard` instance holding the given value. pub fn new(t: T) -> NonEmptyPinboard<T> { NonEmptyPinboard(Pinboard::new(t)) } /// Update the value stored in the `NonEmptyPinboard`. #[inline] pub fn set(&self, t: T) { self.0.set(t) } /// Get a copy of the latest (well, recent) version of the posted data. #[inline] pub fn read(&self) -> T { // Unwrap the option returned by the inner `Pinboard`. This will never panic, because it's // impossible for this `Pinboard` to be empty (though it's not possible to prove this to the // compiler). match self.0.read() { Some(t) => t, None => unreachable!("Inner pointer was unexpectedly null"), } } } macro_rules! debuggable { ($struct:ident, $trait:ident) => { impl<T: Clone +'static> ::std::fmt::$trait for $struct<T> where T: ::std::fmt::$trait { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { write!(f, "{}(", stringify!($struct))?; ::std::fmt::$trait::fmt(&self.read(), f)?; write!(f, ")") } } } } debuggable!(Pinboard, Debug); debuggable!(NonEmptyPinboard, Debug); debuggable!(NonEmptyPinboard, Binary); debuggable!(NonEmptyPinboard, Display); debuggable!(NonEmptyPinboard, LowerExp); debuggable!(NonEmptyPinboard, LowerHex); debuggable!(NonEmptyPinboard, Octal); debuggable!(NonEmptyPinboard, Pointer); debuggable!(NonEmptyPinboard, UpperExp); debuggable!(NonEmptyPinboard, UpperHex); #[cfg(test)] mod tests { extern crate crossbeam; use super::*; use std::fmt::Display; fn consume<T: Clone + Display>(t: &Pinboard<T>) { loop { match t.read() { Some(_) => {} None => break, } std::thread::sleep(std::time::Duration::from_millis(1)); } } fn produce(t: &Pinboard<u32>) { for i in 1..100 { t.set(i); std::thread::sleep(std::time::Duration::from_millis(2)); } t.clear(); } fn check_debug<T: ::std::fmt::Debug>(_: T) {} #[test] fn it_works() { let t = Pinboard::<u32>::default(); assert_eq!(None, t.read()); t.set(3); assert_eq!(Some(3), t.read()); t.clear(); assert_eq!(None, t.read()); } #[test] fn single_producer_single_consumer() { let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); }).unwrap(); } #[test] fn multi_producer_single_consumer() { let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); }).unwrap(); } #[test] fn single_producer_multi_consumer() { let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); }).unwrap(); } #[test] fn multi_producer_multi_consumer() { let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); }).unwrap(); } #[test] fn non_empty_pinboard() { let t = NonEmptyPinboard::<u32>::new(3); assert_eq!(3, t.read()); t.set(4); assert_eq!(4, t.read()); } #[test] fn debuggable() { let t = Pinboard::<i32>::new(3); check_debug(t); let t = NonEmptyPinboard::<i32>::new(2); check_debug(t); } }
extern crate crossbeam_epoch as epoch; use epoch::{Atomic, Owned, Shared, pin};
random_line_split
lib.rs
#![warn(missing_docs)] //! A `Pinboard` is a shared, mutable, eventually consistent, lock-free data-structure. This //! allows multiple threads to communicate in a decoupled way by publishing data to the pinboard //! which other threads can then read in an eventually consistent way. //! //! This is not a silver bullet though, there are various limitations of `Pinboard` that trade off //! the nice behaviour described above. //! //! * Eventual consistency: //! * Writes from one thread are not guaranteed to be seen by reads from another thread //! * Writes from one thread can overwrite writes from another thread //! * No in-place mutation: //! * The only write primitive completely overwrites the data on the `Pinboard` //! * Requires `Clone`: //! * All reads return a clone of the data, decoupling the lifetime of the read value from the //! data stored in the global reference. extern crate crossbeam_epoch as epoch; use epoch::{Atomic, Owned, Shared, pin}; use std::sync::atomic::Ordering::*; /// An instance of a `Pinboard`, holds a shared, mutable, eventually-consistent reference to a `T`. pub struct Pinboard<T: Clone +'static>(Atomic<T>); impl<T: Clone +'static> Pinboard<T> { /// Create a new `Pinboard` instance holding the given value. pub fn new(t: T) -> Pinboard<T> { let t = Owned::new(t); let p = Pinboard::default(); p.0.store(t, Release); p } /// Create a new, empty `Pinboard` pub fn new_empty() -> Self { Pinboard(Atomic::null()) } /// Update the value stored in the `Pinboard`. pub fn set(&self, t: T) { let guard = pin(); let t = Owned::new(t); let t = self.0.swap(t, AcqRel, &guard); unsafe { if!t.is_null() { guard.defer_unchecked(move || drop(t.into_owned())); } } } /// Clear out the `Pinboard` so it's no longer holding any data. pub fn clear(&self) { let guard = pin(); let t = self.0.swap(Shared::null(), AcqRel, &guard); unsafe { if!t.is_null() { guard.defer_unchecked(move || drop(t.into_owned())); } } } /// Get a copy of the latest (well, recent) version of the posted data. pub fn read(&self) -> Option<T> { let guard = pin(); unsafe { let t = self.0.load(Acquire, &guard); if t.is_null() { None } else { Some(t.deref().clone()) } } } } impl<T: Clone +'static> Default for Pinboard<T> { fn default() -> Pinboard<T> { Self::new_empty() } } impl<T: Clone +'static> Drop for Pinboard<T> { fn drop(&mut self) { // Make sure any stored data is marked for deletion self.clear(); } } impl<T: Clone +'static> From<Option<T>> for Pinboard<T> { fn from(src: Option<T>) -> Pinboard<T> { src.map(Pinboard::new).unwrap_or_default() } } /// An wrapper around a `Pinboard` which provides the guarantee it is never empty. pub struct NonEmptyPinboard<T: Clone +'static>(Pinboard<T>); impl<T: Clone +'static> NonEmptyPinboard<T> { /// Create a new `NonEmptyPinboard` instance holding the given value. pub fn new(t: T) -> NonEmptyPinboard<T> { NonEmptyPinboard(Pinboard::new(t)) } /// Update the value stored in the `NonEmptyPinboard`. #[inline] pub fn set(&self, t: T) { self.0.set(t) } /// Get a copy of the latest (well, recent) version of the posted data. #[inline] pub fn read(&self) -> T { // Unwrap the option returned by the inner `Pinboard`. This will never panic, because it's // impossible for this `Pinboard` to be empty (though it's not possible to prove this to the // compiler). match self.0.read() { Some(t) => t, None => unreachable!("Inner pointer was unexpectedly null"), } } } macro_rules! debuggable { ($struct:ident, $trait:ident) => { impl<T: Clone +'static> ::std::fmt::$trait for $struct<T> where T: ::std::fmt::$trait { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { write!(f, "{}(", stringify!($struct))?; ::std::fmt::$trait::fmt(&self.read(), f)?; write!(f, ")") } } } } debuggable!(Pinboard, Debug); debuggable!(NonEmptyPinboard, Debug); debuggable!(NonEmptyPinboard, Binary); debuggable!(NonEmptyPinboard, Display); debuggable!(NonEmptyPinboard, LowerExp); debuggable!(NonEmptyPinboard, LowerHex); debuggable!(NonEmptyPinboard, Octal); debuggable!(NonEmptyPinboard, Pointer); debuggable!(NonEmptyPinboard, UpperExp); debuggable!(NonEmptyPinboard, UpperHex); #[cfg(test)] mod tests { extern crate crossbeam; use super::*; use std::fmt::Display; fn
<T: Clone + Display>(t: &Pinboard<T>) { loop { match t.read() { Some(_) => {} None => break, } std::thread::sleep(std::time::Duration::from_millis(1)); } } fn produce(t: &Pinboard<u32>) { for i in 1..100 { t.set(i); std::thread::sleep(std::time::Duration::from_millis(2)); } t.clear(); } fn check_debug<T: ::std::fmt::Debug>(_: T) {} #[test] fn it_works() { let t = Pinboard::<u32>::default(); assert_eq!(None, t.read()); t.set(3); assert_eq!(Some(3), t.read()); t.clear(); assert_eq!(None, t.read()); } #[test] fn single_producer_single_consumer() { let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); }).unwrap(); } #[test] fn multi_producer_single_consumer() { let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); }).unwrap(); } #[test] fn single_producer_multi_consumer() { let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); }).unwrap(); } #[test] fn multi_producer_multi_consumer() { let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); }).unwrap(); } #[test] fn non_empty_pinboard() { let t = NonEmptyPinboard::<u32>::new(3); assert_eq!(3, t.read()); t.set(4); assert_eq!(4, t.read()); } #[test] fn debuggable() { let t = Pinboard::<i32>::new(3); check_debug(t); let t = NonEmptyPinboard::<i32>::new(2); check_debug(t); } }
consume
identifier_name
htmllabelelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::activation::{Activatable, ActivationSource, synthetic_click_activation}; use dom::bindings::codegen::Bindings::HTMLLabelElementBinding; use dom::bindings::codegen::Bindings::HTMLLabelElementBinding::HTMLLabelElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::event::Event; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::htmlformelement::{FormControl, HTMLFormElement}; use dom::node::{document_from_node, Node}; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; use style::attr::AttrValue; #[dom_struct] pub struct HTMLLabelElement { htmlelement: HTMLElement, } impl HTMLLabelElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLLabelElement { HTMLLabelElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLLabelElement> { Node::reflect_node(box HTMLLabelElement::new_inherited(localName, prefix, document), document, HTMLLabelElementBinding::Wrap) } } impl Activatable for HTMLLabelElement { fn as_element(&self) -> &Element { self.upcast::<Element>() } fn is_instance_activatable(&self) -> bool { true } // https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps // https://html.spec.whatwg.org/multipage/#the-button-element:activation-behavior fn pre_click_activation(&self) { }
fn canceled_activation(&self) { } // https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps fn activation_behavior(&self, _event: &Event, _target: &EventTarget) { if let Some(e) = self.GetControl() { let elem = e.upcast::<Element>(); synthetic_click_activation(elem, false, false, false, false, ActivationSource::NotFromClick); } } // https://html.spec.whatwg.org/multipage/#implicit-submission fn implicit_submission(&self, _ctrlKey: bool, _shiftKey: bool, _altKey: bool, _metaKey: bool) { //FIXME: Investigate and implement implicit submission for label elements // Issue filed at https://github.com/servo/servo/issues/8263 } } impl HTMLLabelElementMethods for HTMLLabelElement { // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } // https://html.spec.whatwg.org/multipage/#dom-label-htmlfor make_getter!(HtmlFor, "for"); // https://html.spec.whatwg.org/multipage/#dom-label-htmlfor make_atomic_setter!(SetHtmlFor, "for"); // https://html.spec.whatwg.org/multipage/#dom-label-control fn GetControl(&self) -> Option<Root<HTMLElement>> { if!self.upcast::<Node>().is_in_doc() { return None; } let for_attr = match self.upcast::<Element>().get_attribute(&ns!(), &atom!("for")) { Some(for_attr) => for_attr, None => return self.first_labelable_descendant(), }; let for_value = for_attr.value(); document_from_node(self).get_element_by_id(for_value.as_atom()) .and_then(Root::downcast::<HTMLElement>) .into_iter() .filter(|e| e.is_labelable_element()) .next() } } impl VirtualMethods for HTMLLabelElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("for") => AttrValue::from_atomic(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } } impl HTMLLabelElement { pub fn first_labelable_descendant(&self) -> Option<Root<HTMLElement>> { self.upcast::<Node>() .traverse_preorder() .filter_map(Root::downcast::<HTMLElement>) .filter(|elem| elem.is_labelable_element()) .next() } } impl FormControl for HTMLLabelElement {}
// https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
random_line_split
htmllabelelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::activation::{Activatable, ActivationSource, synthetic_click_activation}; use dom::bindings::codegen::Bindings::HTMLLabelElementBinding; use dom::bindings::codegen::Bindings::HTMLLabelElementBinding::HTMLLabelElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::event::Event; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::htmlformelement::{FormControl, HTMLFormElement}; use dom::node::{document_from_node, Node}; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; use style::attr::AttrValue; #[dom_struct] pub struct HTMLLabelElement { htmlelement: HTMLElement, } impl HTMLLabelElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLLabelElement { HTMLLabelElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLLabelElement> { Node::reflect_node(box HTMLLabelElement::new_inherited(localName, prefix, document), document, HTMLLabelElementBinding::Wrap) } } impl Activatable for HTMLLabelElement { fn as_element(&self) -> &Element { self.upcast::<Element>() } fn is_instance_activatable(&self) -> bool { true } // https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps // https://html.spec.whatwg.org/multipage/#the-button-element:activation-behavior fn pre_click_activation(&self) { } // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps fn canceled_activation(&self) { } // https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps fn activation_behavior(&self, _event: &Event, _target: &EventTarget)
// https://html.spec.whatwg.org/multipage/#implicit-submission fn implicit_submission(&self, _ctrlKey: bool, _shiftKey: bool, _altKey: bool, _metaKey: bool) { //FIXME: Investigate and implement implicit submission for label elements // Issue filed at https://github.com/servo/servo/issues/8263 } } impl HTMLLabelElementMethods for HTMLLabelElement { // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } // https://html.spec.whatwg.org/multipage/#dom-label-htmlfor make_getter!(HtmlFor, "for"); // https://html.spec.whatwg.org/multipage/#dom-label-htmlfor make_atomic_setter!(SetHtmlFor, "for"); // https://html.spec.whatwg.org/multipage/#dom-label-control fn GetControl(&self) -> Option<Root<HTMLElement>> { if!self.upcast::<Node>().is_in_doc() { return None; } let for_attr = match self.upcast::<Element>().get_attribute(&ns!(), &atom!("for")) { Some(for_attr) => for_attr, None => return self.first_labelable_descendant(), }; let for_value = for_attr.value(); document_from_node(self).get_element_by_id(for_value.as_atom()) .and_then(Root::downcast::<HTMLElement>) .into_iter() .filter(|e| e.is_labelable_element()) .next() } } impl VirtualMethods for HTMLLabelElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("for") => AttrValue::from_atomic(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } } impl HTMLLabelElement { pub fn first_labelable_descendant(&self) -> Option<Root<HTMLElement>> { self.upcast::<Node>() .traverse_preorder() .filter_map(Root::downcast::<HTMLElement>) .filter(|elem| elem.is_labelable_element()) .next() } } impl FormControl for HTMLLabelElement {}
{ if let Some(e) = self.GetControl() { let elem = e.upcast::<Element>(); synthetic_click_activation(elem, false, false, false, false, ActivationSource::NotFromClick); } }
identifier_body
htmllabelelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::activation::{Activatable, ActivationSource, synthetic_click_activation}; use dom::bindings::codegen::Bindings::HTMLLabelElementBinding; use dom::bindings::codegen::Bindings::HTMLLabelElementBinding::HTMLLabelElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::event::Event; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::htmlformelement::{FormControl, HTMLFormElement}; use dom::node::{document_from_node, Node}; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; use style::attr::AttrValue; #[dom_struct] pub struct HTMLLabelElement { htmlelement: HTMLElement, } impl HTMLLabelElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLLabelElement { HTMLLabelElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLLabelElement> { Node::reflect_node(box HTMLLabelElement::new_inherited(localName, prefix, document), document, HTMLLabelElementBinding::Wrap) } } impl Activatable for HTMLLabelElement { fn as_element(&self) -> &Element { self.upcast::<Element>() } fn is_instance_activatable(&self) -> bool { true } // https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps // https://html.spec.whatwg.org/multipage/#the-button-element:activation-behavior fn pre_click_activation(&self) { } // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps fn canceled_activation(&self) { } // https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps fn activation_behavior(&self, _event: &Event, _target: &EventTarget) { if let Some(e) = self.GetControl() { let elem = e.upcast::<Element>(); synthetic_click_activation(elem, false, false, false, false, ActivationSource::NotFromClick); } } // https://html.spec.whatwg.org/multipage/#implicit-submission fn implicit_submission(&self, _ctrlKey: bool, _shiftKey: bool, _altKey: bool, _metaKey: bool) { //FIXME: Investigate and implement implicit submission for label elements // Issue filed at https://github.com/servo/servo/issues/8263 } } impl HTMLLabelElementMethods for HTMLLabelElement { // https://html.spec.whatwg.org/multipage/#dom-fae-form fn
(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } // https://html.spec.whatwg.org/multipage/#dom-label-htmlfor make_getter!(HtmlFor, "for"); // https://html.spec.whatwg.org/multipage/#dom-label-htmlfor make_atomic_setter!(SetHtmlFor, "for"); // https://html.spec.whatwg.org/multipage/#dom-label-control fn GetControl(&self) -> Option<Root<HTMLElement>> { if!self.upcast::<Node>().is_in_doc() { return None; } let for_attr = match self.upcast::<Element>().get_attribute(&ns!(), &atom!("for")) { Some(for_attr) => for_attr, None => return self.first_labelable_descendant(), }; let for_value = for_attr.value(); document_from_node(self).get_element_by_id(for_value.as_atom()) .and_then(Root::downcast::<HTMLElement>) .into_iter() .filter(|e| e.is_labelable_element()) .next() } } impl VirtualMethods for HTMLLabelElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("for") => AttrValue::from_atomic(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } } impl HTMLLabelElement { pub fn first_labelable_descendant(&self) -> Option<Root<HTMLElement>> { self.upcast::<Node>() .traverse_preorder() .filter_map(Root::downcast::<HTMLElement>) .filter(|elem| elem.is_labelable_element()) .next() } } impl FormControl for HTMLLabelElement {}
GetForm
identifier_name
htmltitleelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLTitleElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLTitleElementBinding::HTMLTitleElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::{ChildrenMutation, Node}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLTitleElement { htmlelement: HTMLElement, } impl HTMLTitleElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLTitleElement { HTMLTitleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLTitleElement> { Node::reflect_node( Box::new(HTMLTitleElement::new_inherited( local_name, prefix, document, )), document, HTMLTitleElementBinding::Wrap, ) } } impl HTMLTitleElementMethods for HTMLTitleElement { // https://html.spec.whatwg.org/multipage/#dom-title-text fn Text(&self) -> DOMString { self.upcast::<Node>().child_text_content() } // https://html.spec.whatwg.org/multipage/#dom-title-text fn SetText(&self, value: DOMString) { self.upcast::<Node>().SetTextContent(Some(value)) } } impl VirtualMethods for HTMLTitleElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } let node = self.upcast::<Node>(); if node.is_in_doc() { node.owner_doc().title_changed(); } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type()
let node = self.upcast::<Node>(); if tree_in_doc { node.owner_doc().title_changed(); } } }
{ s.bind_to_tree(tree_in_doc); }
conditional_block
htmltitleelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLTitleElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLTitleElementBinding::HTMLTitleElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::{ChildrenMutation, Node}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLTitleElement { htmlelement: HTMLElement, } impl HTMLTitleElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLTitleElement { HTMLTitleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLTitleElement> { Node::reflect_node( Box::new(HTMLTitleElement::new_inherited( local_name, prefix, document, )), document, HTMLTitleElementBinding::Wrap, ) } } impl HTMLTitleElementMethods for HTMLTitleElement { // https://html.spec.whatwg.org/multipage/#dom-title-text fn Text(&self) -> DOMString { self.upcast::<Node>().child_text_content() } // https://html.spec.whatwg.org/multipage/#dom-title-text fn SetText(&self, value: DOMString) { self.upcast::<Node>().SetTextContent(Some(value)) } } impl VirtualMethods for HTMLTitleElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn
(&self, mutation: &ChildrenMutation) { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } let node = self.upcast::<Node>(); if node.is_in_doc() { node.owner_doc().title_changed(); } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } let node = self.upcast::<Node>(); if tree_in_doc { node.owner_doc().title_changed(); } } }
children_changed
identifier_name
htmltitleelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLTitleElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLTitleElementBinding::HTMLTitleElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot;
use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLTitleElement { htmlelement: HTMLElement, } impl HTMLTitleElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLTitleElement { HTMLTitleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLTitleElement> { Node::reflect_node( Box::new(HTMLTitleElement::new_inherited( local_name, prefix, document, )), document, HTMLTitleElementBinding::Wrap, ) } } impl HTMLTitleElementMethods for HTMLTitleElement { // https://html.spec.whatwg.org/multipage/#dom-title-text fn Text(&self) -> DOMString { self.upcast::<Node>().child_text_content() } // https://html.spec.whatwg.org/multipage/#dom-title-text fn SetText(&self, value: DOMString) { self.upcast::<Node>().SetTextContent(Some(value)) } } impl VirtualMethods for HTMLTitleElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } let node = self.upcast::<Node>(); if node.is_in_doc() { node.owner_doc().title_changed(); } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } let node = self.upcast::<Node>(); if tree_in_doc { node.owner_doc().title_changed(); } } }
use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::{ChildrenMutation, Node};
random_line_split
htmltitleelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLTitleElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLTitleElementBinding::HTMLTitleElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::{ChildrenMutation, Node}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLTitleElement { htmlelement: HTMLElement, } impl HTMLTitleElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLTitleElement { HTMLTitleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLTitleElement>
} impl HTMLTitleElementMethods for HTMLTitleElement { // https://html.spec.whatwg.org/multipage/#dom-title-text fn Text(&self) -> DOMString { self.upcast::<Node>().child_text_content() } // https://html.spec.whatwg.org/multipage/#dom-title-text fn SetText(&self, value: DOMString) { self.upcast::<Node>().SetTextContent(Some(value)) } } impl VirtualMethods for HTMLTitleElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } let node = self.upcast::<Node>(); if node.is_in_doc() { node.owner_doc().title_changed(); } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } let node = self.upcast::<Node>(); if tree_in_doc { node.owner_doc().title_changed(); } } }
{ Node::reflect_node( Box::new(HTMLTitleElement::new_inherited( local_name, prefix, document, )), document, HTMLTitleElementBinding::Wrap, ) }
identifier_body
vec.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-test // compile-flags:-Z extra-debug-info // debugger:set print pretty off // debugger:break 29 // debugger:run // debugger:print a // check:$1 = {1, 2, 3} // debugger:print b.vec[0] // check:$2 = 4 // debugger:print c->boxed.data[1] // check:$3 = 8 // debugger:print d->boxed.data[2] // check:$4 = 12 fn
() { let a = [1, 2, 3]; let b = &[4, 5, 6]; let c = @[7, 8, 9]; let d = ~[10, 11, 12]; let _z = 0; }
main
identifier_name
vec.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-test // compile-flags:-Z extra-debug-info // debugger:set print pretty off // debugger:break 29 // debugger:run // debugger:print a // check:$1 = {1, 2, 3} // debugger:print b.vec[0] // check:$2 = 4 // debugger:print c->boxed.data[1] // check:$3 = 8 // debugger:print d->boxed.data[2] // check:$4 = 12 fn main()
{ let a = [1, 2, 3]; let b = &[4, 5, 6]; let c = @[7, 8, 9]; let d = ~[10, 11, 12]; let _z = 0; }
identifier_body
vec.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-test // compile-flags:-Z extra-debug-info // debugger:set print pretty off // debugger:break 29 // debugger:run // debugger:print a // check:$1 = {1, 2, 3} // debugger:print b.vec[0] // check:$2 = 4 // debugger:print c->boxed.data[1] // check:$3 = 8 // debugger:print d->boxed.data[2] // check:$4 = 12 fn main() { let a = [1, 2, 3]; let b = &[4, 5, 6]; let c = @[7, 8, 9]; let d = ~[10, 11, 12]; let _z = 0;
}
random_line_split
main.rs
use itertools::Itertools; use std::fs; use std::io::{Read, Write}; use std::str; const PHF_SRC: &str = "\ // A stripped down `phf` crate fork. // // https://github.com/sfackler/rust-phf struct Map<V:'static> { pub key: u64, pub disps: &'static [(u32, u32)], pub entries: &'static[(&'static str, V)], } impl<V: PartialEq> Map<V> { fn get(&self, key: &str) -> Option<&V> { use std::borrow::Borrow; let hash = hash(key, self.key); let index = get_index(hash, &*self.disps, self.entries.len()); let entry = &self.entries[index as usize]; let b = entry.0.borrow(); if b == key { Some(&entry.1) } else { None } } fn key(&self, value: &V) -> &'static str { self.entries.iter().find(|kv| kv.1 == *value).unwrap().0 } } #[inline] fn hash(x: &str, key: u64) -> u64 { use std::hash::Hasher; let mut hasher = siphasher::sip::SipHasher13::new_with_keys(0, key); hasher.write(x.as_bytes()); hasher.finish() } #[inline] fn get_index(hash: u64, disps: &[(u32, u32)], len: usize) -> u32 { let (g, f1, f2) = split(hash); let (d1, d2) = disps[(g % (disps.len() as u32)) as usize]; displace(f1, f2, d1, d2) % (len as u32) } #[inline] fn split(hash: u64) -> (u32, u32, u32) { const BITS: u32 = 21; const MASK: u64 = (1 << BITS) - 1; ((hash & MASK) as u32, ((hash >> BITS) & MASK) as u32, ((hash >> (2 * BITS)) & MASK) as u32) } #[inline] fn displace(f1: u32, f2: u32, d1: u32, d2: u32) -> u32 { d2 + f1 * d1 + f2 }"; fn main() { if let Err(e) = gen() { println!("{:?}", e); std::process::exit(1); } } fn gen() -> Result<(), Box<dyn std::error::Error>> { let f = &mut fs::File::create("../src/names.rs")?; writeln!(f, "// This file is autogenerated. Do not edit it!")?; writeln!(f, "// See./codegen for details.\n")?; writeln!(f, "use std::fmt;\n")?; gen_map( "elements.txt", "ElementId", "ELEMENTS", "List of all SVG elements.", f, )?; gen_map( "attributes.txt", "AttributeId", "ATTRIBUTES", "List of all SVG attributes.", f, )?; writeln!(f, "{}", PHF_SRC)?; Ok(()) } fn gen_map( spec_path: &str, enum_name: &str, map_name: &str, doc: &str, f: &mut fs::File, ) -> Result<(), Box<dyn std::error::Error>> { let mut spec = String::new(); fs::File::open(spec_path)?.read_to_string(&mut spec)?; let names: Vec<&str> = spec.split('\n').filter(|s|!s.is_empty()).collect(); let joined_names = names.iter().map(|n| to_enum_name(n)).join(",\n "); let mut map = phf_codegen::Map::new(); for name in &names { map.entry(*name, &format!("{}::{}", enum_name, to_enum_name(name))); } let mut map_data = Vec::new(); map.build(&mut map_data)?; let map_data = String::from_utf8(map_data)?; let map_data = map_data.replace("::phf::Map", "Map"); let map_data = map_data.replace("::phf::Slice::Static(", ""); let map_data = map_data.replace("]),", "],"); writeln!(f, "/// {}", doc)?; writeln!(f, "#[derive(Copy,Clone,Eq,PartialEq,Ord,PartialOrd,Hash)]")?; writeln!(f, "#[allow(missing_docs)]")?; writeln!(f, "pub enum {} {{", enum_name)?; writeln!(f, " {}", joined_names)?; writeln!(f, "}}\n")?; writeln!(f, "static {}: Map<{}> = {};\n", map_name, enum_name, map_data)?; writeln!(f, "impl {} {{", enum_name)?; writeln!(f, " /// Parses `{}` from a string.", enum_name)?; writeln!(f, " pub fn from_str(text: &str) -> Option<{}> {{", enum_name)?; writeln!(f, " {}.get(text).cloned()", map_name)?; writeln!(f, " }}")?; writeln!(f, "")?; writeln!(f, " /// Returns an original string.")?; writeln!(f, " pub fn as_str(&self) -> &'static str {{")?; writeln!(f, " {}.key(self)", map_name)?; writeln!(f, " }}")?; writeln!(f, "}}\n")?; writeln!(f, "impl fmt::Debug for {} {{", enum_name)?; writeln!(f, " fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{")?; writeln!(f, " write!(f, \"{{}}\", self.as_str())")?; writeln!(f, " }}")?; writeln!(f, "}}\n")?; writeln!(f, "impl fmt::Display for {} {{", enum_name)?; writeln!(f, " fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{")?; writeln!(f, " write!(f, \"{{}}\", self.as_str())")?; writeln!(f, " }}")?; writeln!(f, "}}")?; writeln!(f, "")?; Ok(()) } // some-string -> SomeString // some_string -> SomeString // some:string -> SomeString // 100 -> N100 fn
(name: &str) -> String { let mut change_case = false; let mut s = String::with_capacity(name.len()); for (idx, c) in name.chars().enumerate() { if idx == 0 { if c.is_digit(10) { s.push('N'); s.push(c); } else { s.push(c.to_uppercase().next().unwrap()); } continue; } if c == '-' || c == '_' || c == ':' { change_case = true; continue; } if change_case { s.push(c.to_uppercase().next().unwrap()); change_case = false; } else { s.push(c); } } s }
to_enum_name
identifier_name
main.rs
use itertools::Itertools; use std::fs; use std::io::{Read, Write}; use std::str; const PHF_SRC: &str = "\ // A stripped down `phf` crate fork. // // https://github.com/sfackler/rust-phf struct Map<V:'static> { pub key: u64, pub disps: &'static [(u32, u32)], pub entries: &'static[(&'static str, V)], } impl<V: PartialEq> Map<V> { fn get(&self, key: &str) -> Option<&V> { use std::borrow::Borrow; let hash = hash(key, self.key); let index = get_index(hash, &*self.disps, self.entries.len()); let entry = &self.entries[index as usize]; let b = entry.0.borrow(); if b == key { Some(&entry.1) } else { None } } fn key(&self, value: &V) -> &'static str { self.entries.iter().find(|kv| kv.1 == *value).unwrap().0 } } #[inline] fn hash(x: &str, key: u64) -> u64 { use std::hash::Hasher; let mut hasher = siphasher::sip::SipHasher13::new_with_keys(0, key); hasher.write(x.as_bytes()); hasher.finish() } #[inline] fn get_index(hash: u64, disps: &[(u32, u32)], len: usize) -> u32 { let (g, f1, f2) = split(hash); let (d1, d2) = disps[(g % (disps.len() as u32)) as usize]; displace(f1, f2, d1, d2) % (len as u32) } #[inline] fn split(hash: u64) -> (u32, u32, u32) { const BITS: u32 = 21; const MASK: u64 = (1 << BITS) - 1; ((hash & MASK) as u32, ((hash >> BITS) & MASK) as u32, ((hash >> (2 * BITS)) & MASK) as u32) } #[inline] fn displace(f1: u32, f2: u32, d1: u32, d2: u32) -> u32 { d2 + f1 * d1 + f2 }"; fn main() { if let Err(e) = gen() { println!("{:?}", e); std::process::exit(1); } } fn gen() -> Result<(), Box<dyn std::error::Error>> { let f = &mut fs::File::create("../src/names.rs")?; writeln!(f, "// This file is autogenerated. Do not edit it!")?; writeln!(f, "// See./codegen for details.\n")?; writeln!(f, "use std::fmt;\n")?; gen_map( "elements.txt", "ElementId", "ELEMENTS", "List of all SVG elements.", f, )?; gen_map( "attributes.txt", "AttributeId", "ATTRIBUTES", "List of all SVG attributes.", f, )?; writeln!(f, "{}", PHF_SRC)?; Ok(()) } fn gen_map( spec_path: &str, enum_name: &str, map_name: &str, doc: &str, f: &mut fs::File, ) -> Result<(), Box<dyn std::error::Error>> { let mut spec = String::new(); fs::File::open(spec_path)?.read_to_string(&mut spec)?; let names: Vec<&str> = spec.split('\n').filter(|s|!s.is_empty()).collect(); let joined_names = names.iter().map(|n| to_enum_name(n)).join(",\n "); let mut map = phf_codegen::Map::new(); for name in &names { map.entry(*name, &format!("{}::{}", enum_name, to_enum_name(name))); } let mut map_data = Vec::new(); map.build(&mut map_data)?; let map_data = String::from_utf8(map_data)?; let map_data = map_data.replace("::phf::Map", "Map"); let map_data = map_data.replace("::phf::Slice::Static(", ""); let map_data = map_data.replace("]),", "],"); writeln!(f, "/// {}", doc)?; writeln!(f, "#[derive(Copy,Clone,Eq,PartialEq,Ord,PartialOrd,Hash)]")?; writeln!(f, "#[allow(missing_docs)]")?; writeln!(f, "pub enum {} {{", enum_name)?; writeln!(f, " {}", joined_names)?; writeln!(f, "}}\n")?; writeln!(f, "static {}: Map<{}> = {};\n", map_name, enum_name, map_data)?; writeln!(f, "impl {} {{", enum_name)?; writeln!(f, " /// Parses `{}` from a string.", enum_name)?; writeln!(f, " pub fn from_str(text: &str) -> Option<{}> {{", enum_name)?; writeln!(f, " {}.get(text).cloned()", map_name)?; writeln!(f, " }}")?; writeln!(f, "")?; writeln!(f, " /// Returns an original string.")?; writeln!(f, " pub fn as_str(&self) -> &'static str {{")?; writeln!(f, " {}.key(self)", map_name)?; writeln!(f, " }}")?; writeln!(f, "}}\n")?; writeln!(f, "impl fmt::Debug for {} {{", enum_name)?; writeln!(f, " fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{")?; writeln!(f, " write!(f, \"{{}}\", self.as_str())")?; writeln!(f, " }}")?; writeln!(f, "}}\n")?; writeln!(f, "impl fmt::Display for {} {{", enum_name)?; writeln!(f, " fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{")?; writeln!(f, " write!(f, \"{{}}\", self.as_str())")?; writeln!(f, " }}")?; writeln!(f, "}}")?; writeln!(f, "")?; Ok(()) } // some-string -> SomeString // some_string -> SomeString // some:string -> SomeString // 100 -> N100 fn to_enum_name(name: &str) -> String { let mut change_case = false; let mut s = String::with_capacity(name.len()); for (idx, c) in name.chars().enumerate() { if idx == 0 { if c.is_digit(10) { s.push('N'); s.push(c); } else { s.push(c.to_uppercase().next().unwrap()); } continue; } if c == '-' || c == '_' || c == ':' { change_case = true; continue; } if change_case { s.push(c.to_uppercase().next().unwrap()); change_case = false; } else
} s }
{ s.push(c); }
conditional_block
main.rs
use itertools::Itertools; use std::fs; use std::io::{Read, Write}; use std::str; const PHF_SRC: &str = "\ // A stripped down `phf` crate fork. // // https://github.com/sfackler/rust-phf struct Map<V:'static> { pub key: u64, pub disps: &'static [(u32, u32)], pub entries: &'static[(&'static str, V)], } impl<V: PartialEq> Map<V> { fn get(&self, key: &str) -> Option<&V> { use std::borrow::Borrow; let hash = hash(key, self.key); let index = get_index(hash, &*self.disps, self.entries.len()); let entry = &self.entries[index as usize]; let b = entry.0.borrow(); if b == key { Some(&entry.1) } else { None } } fn key(&self, value: &V) -> &'static str { self.entries.iter().find(|kv| kv.1 == *value).unwrap().0 } }
#[inline] fn hash(x: &str, key: u64) -> u64 { use std::hash::Hasher; let mut hasher = siphasher::sip::SipHasher13::new_with_keys(0, key); hasher.write(x.as_bytes()); hasher.finish() } #[inline] fn get_index(hash: u64, disps: &[(u32, u32)], len: usize) -> u32 { let (g, f1, f2) = split(hash); let (d1, d2) = disps[(g % (disps.len() as u32)) as usize]; displace(f1, f2, d1, d2) % (len as u32) } #[inline] fn split(hash: u64) -> (u32, u32, u32) { const BITS: u32 = 21; const MASK: u64 = (1 << BITS) - 1; ((hash & MASK) as u32, ((hash >> BITS) & MASK) as u32, ((hash >> (2 * BITS)) & MASK) as u32) } #[inline] fn displace(f1: u32, f2: u32, d1: u32, d2: u32) -> u32 { d2 + f1 * d1 + f2 }"; fn main() { if let Err(e) = gen() { println!("{:?}", e); std::process::exit(1); } } fn gen() -> Result<(), Box<dyn std::error::Error>> { let f = &mut fs::File::create("../src/names.rs")?; writeln!(f, "// This file is autogenerated. Do not edit it!")?; writeln!(f, "// See./codegen for details.\n")?; writeln!(f, "use std::fmt;\n")?; gen_map( "elements.txt", "ElementId", "ELEMENTS", "List of all SVG elements.", f, )?; gen_map( "attributes.txt", "AttributeId", "ATTRIBUTES", "List of all SVG attributes.", f, )?; writeln!(f, "{}", PHF_SRC)?; Ok(()) } fn gen_map( spec_path: &str, enum_name: &str, map_name: &str, doc: &str, f: &mut fs::File, ) -> Result<(), Box<dyn std::error::Error>> { let mut spec = String::new(); fs::File::open(spec_path)?.read_to_string(&mut spec)?; let names: Vec<&str> = spec.split('\n').filter(|s|!s.is_empty()).collect(); let joined_names = names.iter().map(|n| to_enum_name(n)).join(",\n "); let mut map = phf_codegen::Map::new(); for name in &names { map.entry(*name, &format!("{}::{}", enum_name, to_enum_name(name))); } let mut map_data = Vec::new(); map.build(&mut map_data)?; let map_data = String::from_utf8(map_data)?; let map_data = map_data.replace("::phf::Map", "Map"); let map_data = map_data.replace("::phf::Slice::Static(", ""); let map_data = map_data.replace("]),", "],"); writeln!(f, "/// {}", doc)?; writeln!(f, "#[derive(Copy,Clone,Eq,PartialEq,Ord,PartialOrd,Hash)]")?; writeln!(f, "#[allow(missing_docs)]")?; writeln!(f, "pub enum {} {{", enum_name)?; writeln!(f, " {}", joined_names)?; writeln!(f, "}}\n")?; writeln!(f, "static {}: Map<{}> = {};\n", map_name, enum_name, map_data)?; writeln!(f, "impl {} {{", enum_name)?; writeln!(f, " /// Parses `{}` from a string.", enum_name)?; writeln!(f, " pub fn from_str(text: &str) -> Option<{}> {{", enum_name)?; writeln!(f, " {}.get(text).cloned()", map_name)?; writeln!(f, " }}")?; writeln!(f, "")?; writeln!(f, " /// Returns an original string.")?; writeln!(f, " pub fn as_str(&self) -> &'static str {{")?; writeln!(f, " {}.key(self)", map_name)?; writeln!(f, " }}")?; writeln!(f, "}}\n")?; writeln!(f, "impl fmt::Debug for {} {{", enum_name)?; writeln!(f, " fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{")?; writeln!(f, " write!(f, \"{{}}\", self.as_str())")?; writeln!(f, " }}")?; writeln!(f, "}}\n")?; writeln!(f, "impl fmt::Display for {} {{", enum_name)?; writeln!(f, " fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{")?; writeln!(f, " write!(f, \"{{}}\", self.as_str())")?; writeln!(f, " }}")?; writeln!(f, "}}")?; writeln!(f, "")?; Ok(()) } // some-string -> SomeString // some_string -> SomeString // some:string -> SomeString // 100 -> N100 fn to_enum_name(name: &str) -> String { let mut change_case = false; let mut s = String::with_capacity(name.len()); for (idx, c) in name.chars().enumerate() { if idx == 0 { if c.is_digit(10) { s.push('N'); s.push(c); } else { s.push(c.to_uppercase().next().unwrap()); } continue; } if c == '-' || c == '_' || c == ':' { change_case = true; continue; } if change_case { s.push(c.to_uppercase().next().unwrap()); change_case = false; } else { s.push(c); } } s }
random_line_split
main.rs
use itertools::Itertools; use std::fs; use std::io::{Read, Write}; use std::str; const PHF_SRC: &str = "\ // A stripped down `phf` crate fork. // // https://github.com/sfackler/rust-phf struct Map<V:'static> { pub key: u64, pub disps: &'static [(u32, u32)], pub entries: &'static[(&'static str, V)], } impl<V: PartialEq> Map<V> { fn get(&self, key: &str) -> Option<&V> { use std::borrow::Borrow; let hash = hash(key, self.key); let index = get_index(hash, &*self.disps, self.entries.len()); let entry = &self.entries[index as usize]; let b = entry.0.borrow(); if b == key { Some(&entry.1) } else { None } } fn key(&self, value: &V) -> &'static str { self.entries.iter().find(|kv| kv.1 == *value).unwrap().0 } } #[inline] fn hash(x: &str, key: u64) -> u64 { use std::hash::Hasher; let mut hasher = siphasher::sip::SipHasher13::new_with_keys(0, key); hasher.write(x.as_bytes()); hasher.finish() } #[inline] fn get_index(hash: u64, disps: &[(u32, u32)], len: usize) -> u32 { let (g, f1, f2) = split(hash); let (d1, d2) = disps[(g % (disps.len() as u32)) as usize]; displace(f1, f2, d1, d2) % (len as u32) } #[inline] fn split(hash: u64) -> (u32, u32, u32) { const BITS: u32 = 21; const MASK: u64 = (1 << BITS) - 1; ((hash & MASK) as u32, ((hash >> BITS) & MASK) as u32, ((hash >> (2 * BITS)) & MASK) as u32) } #[inline] fn displace(f1: u32, f2: u32, d1: u32, d2: u32) -> u32 { d2 + f1 * d1 + f2 }"; fn main() { if let Err(e) = gen() { println!("{:?}", e); std::process::exit(1); } } fn gen() -> Result<(), Box<dyn std::error::Error>>
"List of all SVG attributes.", f, )?; writeln!(f, "{}", PHF_SRC)?; Ok(()) } fn gen_map( spec_path: &str, enum_name: &str, map_name: &str, doc: &str, f: &mut fs::File, ) -> Result<(), Box<dyn std::error::Error>> { let mut spec = String::new(); fs::File::open(spec_path)?.read_to_string(&mut spec)?; let names: Vec<&str> = spec.split('\n').filter(|s|!s.is_empty()).collect(); let joined_names = names.iter().map(|n| to_enum_name(n)).join(",\n "); let mut map = phf_codegen::Map::new(); for name in &names { map.entry(*name, &format!("{}::{}", enum_name, to_enum_name(name))); } let mut map_data = Vec::new(); map.build(&mut map_data)?; let map_data = String::from_utf8(map_data)?; let map_data = map_data.replace("::phf::Map", "Map"); let map_data = map_data.replace("::phf::Slice::Static(", ""); let map_data = map_data.replace("]),", "],"); writeln!(f, "/// {}", doc)?; writeln!(f, "#[derive(Copy,Clone,Eq,PartialEq,Ord,PartialOrd,Hash)]")?; writeln!(f, "#[allow(missing_docs)]")?; writeln!(f, "pub enum {} {{", enum_name)?; writeln!(f, " {}", joined_names)?; writeln!(f, "}}\n")?; writeln!(f, "static {}: Map<{}> = {};\n", map_name, enum_name, map_data)?; writeln!(f, "impl {} {{", enum_name)?; writeln!(f, " /// Parses `{}` from a string.", enum_name)?; writeln!(f, " pub fn from_str(text: &str) -> Option<{}> {{", enum_name)?; writeln!(f, " {}.get(text).cloned()", map_name)?; writeln!(f, " }}")?; writeln!(f, "")?; writeln!(f, " /// Returns an original string.")?; writeln!(f, " pub fn as_str(&self) -> &'static str {{")?; writeln!(f, " {}.key(self)", map_name)?; writeln!(f, " }}")?; writeln!(f, "}}\n")?; writeln!(f, "impl fmt::Debug for {} {{", enum_name)?; writeln!(f, " fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{")?; writeln!(f, " write!(f, \"{{}}\", self.as_str())")?; writeln!(f, " }}")?; writeln!(f, "}}\n")?; writeln!(f, "impl fmt::Display for {} {{", enum_name)?; writeln!(f, " fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{")?; writeln!(f, " write!(f, \"{{}}\", self.as_str())")?; writeln!(f, " }}")?; writeln!(f, "}}")?; writeln!(f, "")?; Ok(()) } // some-string -> SomeString // some_string -> SomeString // some:string -> SomeString // 100 -> N100 fn to_enum_name(name: &str) -> String { let mut change_case = false; let mut s = String::with_capacity(name.len()); for (idx, c) in name.chars().enumerate() { if idx == 0 { if c.is_digit(10) { s.push('N'); s.push(c); } else { s.push(c.to_uppercase().next().unwrap()); } continue; } if c == '-' || c == '_' || c == ':' { change_case = true; continue; } if change_case { s.push(c.to_uppercase().next().unwrap()); change_case = false; } else { s.push(c); } } s }
{ let f = &mut fs::File::create("../src/names.rs")?; writeln!(f, "// This file is autogenerated. Do not edit it!")?; writeln!(f, "// See ./codegen for details.\n")?; writeln!(f, "use std::fmt;\n")?; gen_map( "elements.txt", "ElementId", "ELEMENTS", "List of all SVG elements.", f, )?; gen_map( "attributes.txt", "AttributeId", "ATTRIBUTES",
identifier_body
marisa-build.rs
// Copyright (c) 2010-2013, Susumu Yata // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifdef _WIN32 #include <fcntl.h> #include <io.h> #include <stdio.h> #endif // _WIN32 #include <cstdlib> #include <fstream> #include <iostream> #include <string> #include <marisa.h> #include "cmdopt.h" namespace { int param_num_tries = MARISA_DEFAULT_NUM_TRIES; marisa::TailMode param_tail_mode = MARISA_DEFAULT_TAIL; marisa::NodeOrder param_node_order = MARISA_DEFAULT_ORDER; marisa::CacheLevel param_cache_level = MARISA_DEFAULT_CACHE; const char *output_filename = NULL; void print_help(const char *cmd) { std::cerr << "Usage: " << cmd << " [OPTION]... [FILE]...\n\n" "Options:\n" " -n, --num-tries=[N] limit the number of tries" " [" << MARISA_MIN_NUM_TRIES << ", " << MARISA_MAX_NUM_TRIES << "] (default: 3)\n" " -t, --text-tail build a dictionary with text TAIL (default)\n" " -b, --binary-tail build a dictionary with binary TAIL\n" " -w, --weight-order arrange siblings in weight order (default)\n" " -l, --label-order arrange siblings in label order\n" " -c, --cache-level=[N] specify the cache size" " [1, 5] (default: 3)\n" " -o, --output=[FILE] write tries to FILE (default: stdout)\n" " -h, --help print this help\n" << std::endl; } void read_keys(std::istream &input, marisa::Keyset *keyset) { std::string line; while (std::getline(input, line)) { const std::string::size_type delim_pos = line.find_last_of('\t'); float weight = 1.0F; if (delim_pos!= line.npos) { char *end_of_value; weight = (float)std::strtod(&line[delim_pos + 1], &end_of_value); if (*end_of_value == '\0') { line.resize(delim_pos); } } keyset->push_back(line.c_str(), line.length(), weight); } } int build(const char * const *args, std::size_t num_args) { marisa::Keyset keyset; if (num_args == 0) try { read_keys(std::cin, &keyset); } catch (const marisa::Exception &ex) { std::cerr << ex.what() << ": failed to read keys" << std::endl; return 10; } for (std::size_t i = 0; i < num_args; ++i) try { std::ifstream input_file(args[i], std::ios::binary); if (!input_file)
read_keys(input_file, &keyset); } catch (const marisa::Exception &ex) { std::cerr << ex.what() << ": failed to read keys" << std::endl; return 12; } marisa::Trie trie; try { trie.build(keyset, param_num_tries | param_tail_mode | param_node_order | param_cache_level); } catch (const marisa::Exception &ex) { std::cerr << ex.what() << ": failed to build a dictionary" << std::endl; return 20; } std::cerr << "#keys: " << trie.num_keys() << std::endl; std::cerr << "#nodes: " << trie.num_nodes() << std::endl; std::cerr << "size: " << trie.io_size() << std::endl; if (output_filename!= NULL) { try { trie.save(output_filename); } catch (const marisa::Exception &ex) { std::cerr << ex.what() << ": failed to write a dictionary to file: " << output_filename << std::endl; return 30; } } else { #ifdef _WIN32 const int stdout_fileno = ::_fileno(stdout); if (stdout_fileno < 0) { std::cerr << "error: failed to get the file descriptor of " "standard output" << std::endl; return 31; } if (::_setmode(stdout_fileno, _O_BINARY) == -1) { std::cerr << "error: failed to set binary mode" << std::endl; return 32; } #endif // _WIN32 try { std::cout << trie; } catch (const marisa::Exception &ex) { std::cerr << ex.what() << ": failed to write a dictionary to standard output" << std::endl; return 33; } } return 0; } } // namespace int main(int argc, char *argv[]) { std::ios::sync_with_stdio(false); ::cmdopt_option long_options[] = { { "max-num-tries", 1, NULL, 'n' }, { "text-tail", 0, NULL, 't' }, { "binary-tail", 0, NULL, 'b' }, { "weight-order", 0, NULL, 'w' }, { "label-order", 0, NULL, 'l' }, { "cache-level", 1, NULL, 'c' }, { "output", 1, NULL, 'o' }, { "help", 0, NULL, 'h' }, { NULL, 0, NULL, 0 } }; ::cmdopt_t cmdopt; ::cmdopt_init(&cmdopt, argc, argv, "n:tbwlc:o:h", long_options); int label; while ((label = ::cmdopt_get(&cmdopt))!= -1) { switch (label) { case 'n': { char *end_of_value; const long value = std::strtol(cmdopt.optarg, &end_of_value, 10); if ((*end_of_value!= '\0') || (value <= 0) || (value > MARISA_MAX_NUM_TRIES)) { std::cerr << "error: option `-n' with an invalid argument: " << cmdopt.optarg << std::endl; return 1; } param_num_tries = (int)value; break; } case 't': { param_tail_mode = MARISA_TEXT_TAIL; break; } case 'b': { param_tail_mode = MARISA_BINARY_TAIL; break; } case 'w': { param_node_order = MARISA_WEIGHT_ORDER; break; } case 'l': { param_node_order = MARISA_LABEL_ORDER; break; } case 'c': { char *end_of_value; const long value = std::strtol(cmdopt.optarg, &end_of_value, 10); if ((*end_of_value!= '\0') || (value < 1) || (value > 5)) { std::cerr << "error: option `-c' with an invalid argument: " << cmdopt.optarg << std::endl; return 2; } else if (value == 1) { param_cache_level = MARISA_TINY_CACHE; } else if (value == 2) { param_cache_level = MARISA_SMALL_CACHE; } else if (value == 3) { param_cache_level = MARISA_NORMAL_CACHE; } else if (value == 4) { param_cache_level = MARISA_LARGE_CACHE; } else if (value == 5) { param_cache_level = MARISA_HUGE_CACHE; } break; } case 'o': { output_filename = cmdopt.optarg; break; } case 'h': { print_help(argv[0]); return 0; } default: { return 1; } } } return build(cmdopt.argv + cmdopt.optind, cmdopt.argc - cmdopt.optind); }
{ std::cerr << "error: failed to open: " << args[i] << std::endl; return 11; }
conditional_block
marisa-build.rs
// Copyright (c) 2010-2013, Susumu Yata // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifdef _WIN32 #include <fcntl.h> #include <io.h> #include <stdio.h> #endif // _WIN32 #include <cstdlib> #include <fstream> #include <iostream> #include <string> #include <marisa.h> #include "cmdopt.h" namespace { int param_num_tries = MARISA_DEFAULT_NUM_TRIES; marisa::TailMode param_tail_mode = MARISA_DEFAULT_TAIL; marisa::NodeOrder param_node_order = MARISA_DEFAULT_ORDER; marisa::CacheLevel param_cache_level = MARISA_DEFAULT_CACHE; const char *output_filename = NULL; void print_help(const char *cmd) { std::cerr << "Usage: " << cmd << " [OPTION]... [FILE]...\n\n" "Options:\n" " -n, --num-tries=[N] limit the number of tries" " [" << MARISA_MIN_NUM_TRIES << ", " << MARISA_MAX_NUM_TRIES << "] (default: 3)\n" " -t, --text-tail build a dictionary with text TAIL (default)\n" " -b, --binary-tail build a dictionary with binary TAIL\n" " -w, --weight-order arrange siblings in weight order (default)\n" " -l, --label-order arrange siblings in label order\n" " -c, --cache-level=[N] specify the cache size" " [1, 5] (default: 3)\n" " -o, --output=[FILE] write tries to FILE (default: stdout)\n" " -h, --help print this help\n" << std::endl; } void read_keys(std::istream &input, marisa::Keyset *keyset) { std::string line; while (std::getline(input, line)) { const std::string::size_type delim_pos = line.find_last_of('\t'); float weight = 1.0F; if (delim_pos!= line.npos) { char *end_of_value; weight = (float)std::strtod(&line[delim_pos + 1], &end_of_value); if (*end_of_value == '\0') { line.resize(delim_pos); } } keyset->push_back(line.c_str(), line.length(), weight); } } int build(const char * const *args, std::size_t num_args) { marisa::Keyset keyset; if (num_args == 0) try { read_keys(std::cin, &keyset); } catch (const marisa::Exception &ex) { std::cerr << ex.what() << ": failed to read keys" << std::endl; return 10; } for (std::size_t i = 0; i < num_args; ++i) try { std::ifstream input_file(args[i], std::ios::binary); if (!input_file) { std::cerr << "error: failed to open: " << args[i] << std::endl; return 11; } read_keys(input_file, &keyset); } catch (const marisa::Exception &ex) { std::cerr << ex.what() << ": failed to read keys" << std::endl; return 12; } marisa::Trie trie; try { trie.build(keyset, param_num_tries | param_tail_mode | param_node_order | param_cache_level); } catch (const marisa::Exception &ex) { std::cerr << ex.what() << ": failed to build a dictionary" << std::endl; return 20; } std::cerr << "#keys: " << trie.num_keys() << std::endl; std::cerr << "#nodes: " << trie.num_nodes() << std::endl; std::cerr << "size: " << trie.io_size() << std::endl; if (output_filename!= NULL) { try { trie.save(output_filename); } catch (const marisa::Exception &ex) { std::cerr << ex.what() << ": failed to write a dictionary to file: " << output_filename << std::endl; return 30; } } else { #ifdef _WIN32 const int stdout_fileno = ::_fileno(stdout); if (stdout_fileno < 0) { std::cerr << "error: failed to get the file descriptor of " "standard output" << std::endl; return 31; } if (::_setmode(stdout_fileno, _O_BINARY) == -1) { std::cerr << "error: failed to set binary mode" << std::endl; return 32; } #endif // _WIN32 try { std::cout << trie; } catch (const marisa::Exception &ex) { std::cerr << ex.what() << ": failed to write a dictionary to standard output" << std::endl; return 33; } } return 0; } } // namespace int main(int argc, char *argv[]) { std::ios::sync_with_stdio(false); ::cmdopt_option long_options[] = { { "max-num-tries", 1, NULL, 'n' }, { "text-tail", 0, NULL, 't' }, { "binary-tail", 0, NULL, 'b' }, { "weight-order", 0, NULL, 'w' }, { "label-order", 0, NULL, 'l' }, { "cache-level", 1, NULL, 'c' }, { "output", 1, NULL, 'o' }, { "help", 0, NULL, 'h' }, { NULL, 0, NULL, 0 } }; ::cmdopt_t cmdopt; ::cmdopt_init(&cmdopt, argc, argv, "n:tbwlc:o:h", long_options); int label; while ((label = ::cmdopt_get(&cmdopt))!= -1) { switch (label) { case 'n': { char *end_of_value; const long value = std::strtol(cmdopt.optarg, &end_of_value, 10); if ((*end_of_value!= '\0') || (value <= 0) || (value > MARISA_MAX_NUM_TRIES)) { std::cerr << "error: option `-n' with an invalid argument: " << cmdopt.optarg << std::endl; return 1; } param_num_tries = (int)value; break; } case 't': { param_tail_mode = MARISA_TEXT_TAIL; break; } case 'b': { param_tail_mode = MARISA_BINARY_TAIL; break; } case 'w': { param_node_order = MARISA_WEIGHT_ORDER; break; } case 'l': { param_node_order = MARISA_LABEL_ORDER; break; } case 'c': { char *end_of_value; const long value = std::strtol(cmdopt.optarg, &end_of_value, 10); if ((*end_of_value!= '\0') || (value < 1) || (value > 5)) { std::cerr << "error: option `-c' with an invalid argument: " << cmdopt.optarg << std::endl; return 2; } else if (value == 1) { param_cache_level = MARISA_TINY_CACHE; } else if (value == 2) { param_cache_level = MARISA_SMALL_CACHE; } else if (value == 3) { param_cache_level = MARISA_NORMAL_CACHE; } else if (value == 4) { param_cache_level = MARISA_LARGE_CACHE; } else if (value == 5) { param_cache_level = MARISA_HUGE_CACHE; } break; } case 'o': { output_filename = cmdopt.optarg; break; } case 'h': { print_help(argv[0]); return 0; } default: { return 1; } } } return build(cmdopt.argv + cmdopt.optind, cmdopt.argc - cmdopt.optind); }
random_line_split
trait-inheritance-overloading-simple.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. use std::cmp::Eq; trait MyNum : Eq { } #[deriving(Show)] struct MyInt { val: int } impl Eq for MyInt { fn eq(&self, other: &MyInt) -> bool { self.val == other.val } fn
(&self, other: &MyInt) -> bool {!self.eq(other) } } impl MyNum for MyInt {} fn f<T:MyNum>(x: T, y: T) -> bool { return x == y; } fn mi(v: int) -> MyInt { MyInt { val: v } } pub fn main() { let (x, y, z) = (mi(3), mi(5), mi(3)); assert!(x!= y); assert_eq!(x, z); }
ne
identifier_name
trait-inheritance-overloading-simple.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. use std::cmp::Eq; trait MyNum : Eq { } #[deriving(Show)] struct MyInt { val: int } impl Eq for MyInt { fn eq(&self, other: &MyInt) -> bool { self.val == other.val } fn ne(&self, other: &MyInt) -> bool {!self.eq(other) } } impl MyNum for MyInt {} fn f<T:MyNum>(x: T, y: T) -> bool
fn mi(v: int) -> MyInt { MyInt { val: v } } pub fn main() { let (x, y, z) = (mi(3), mi(5), mi(3)); assert!(x!= y); assert_eq!(x, z); }
{ return x == y; }
identifier_body
trait-inheritance-overloading-simple.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// except according to those terms. use std::cmp::Eq; trait MyNum : Eq { } #[deriving(Show)] struct MyInt { val: int } impl Eq for MyInt { fn eq(&self, other: &MyInt) -> bool { self.val == other.val } fn ne(&self, other: &MyInt) -> bool {!self.eq(other) } } impl MyNum for MyInt {} fn f<T:MyNum>(x: T, y: T) -> bool { return x == y; } fn mi(v: int) -> MyInt { MyInt { val: v } } pub fn main() { let (x, y, z) = (mi(3), mi(5), mi(3)); assert!(x!= y); assert_eq!(x, z); }
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
exponent.rs
use crate::digit_table::*; use core::ptr; #[cfg_attr(feature = "no-panic", inline)] pub unsafe fn write_exponent3(mut k: isize, mut result: *mut u8) -> usize { let sign = k < 0; if sign { *result = b'-'; result = result.offset(1); k = -k; } debug_assert!(k < 1000); if k >= 100 { *result = b'0' + (k / 100) as u8; k %= 100; let d = DIGIT_TABLE.get_unchecked(k as usize * 2); ptr::copy_nonoverlapping(d, result.offset(1), 2); sign as usize + 3 } else if k >= 10 { let d = DIGIT_TABLE.get_unchecked(k as usize * 2); ptr::copy_nonoverlapping(d, result, 2); sign as usize + 2 } else { *result = b'0' + k as u8; sign as usize + 1 } } #[cfg_attr(feature = "no-panic", inline)] pub unsafe fn write_exponent2(mut k: isize, mut result: *mut u8) -> usize
{ let sign = k < 0; if sign { *result = b'-'; result = result.offset(1); k = -k; } debug_assert!(k < 100); if k >= 10 { let d = DIGIT_TABLE.get_unchecked(k as usize * 2); ptr::copy_nonoverlapping(d, result, 2); sign as usize + 2 } else { *result = b'0' + k as u8; sign as usize + 1 } }
identifier_body
exponent.rs
use crate::digit_table::*; use core::ptr; #[cfg_attr(feature = "no-panic", inline)] pub unsafe fn write_exponent3(mut k: isize, mut result: *mut u8) -> usize { let sign = k < 0; if sign { *result = b'-'; result = result.offset(1); k = -k; } debug_assert!(k < 1000); if k >= 100 { *result = b'0' + (k / 100) as u8; k %= 100; let d = DIGIT_TABLE.get_unchecked(k as usize * 2); ptr::copy_nonoverlapping(d, result.offset(1), 2); sign as usize + 3 } else if k >= 10 { let d = DIGIT_TABLE.get_unchecked(k as usize * 2); ptr::copy_nonoverlapping(d, result, 2); sign as usize + 2 } else { *result = b'0' + k as u8; sign as usize + 1 } } #[cfg_attr(feature = "no-panic", inline)] pub unsafe fn write_exponent2(mut k: isize, mut result: *mut u8) -> usize { let sign = k < 0; if sign { *result = b'-'; result = result.offset(1); k = -k; } debug_assert!(k < 100); if k >= 10
else { *result = b'0' + k as u8; sign as usize + 1 } }
{ let d = DIGIT_TABLE.get_unchecked(k as usize * 2); ptr::copy_nonoverlapping(d, result, 2); sign as usize + 2 }
conditional_block
exponent.rs
use crate::digit_table::*; use core::ptr; #[cfg_attr(feature = "no-panic", inline)] pub unsafe fn write_exponent3(mut k: isize, mut result: *mut u8) -> usize { let sign = k < 0; if sign { *result = b'-'; result = result.offset(1); k = -k; } debug_assert!(k < 1000); if k >= 100 { *result = b'0' + (k / 100) as u8; k %= 100; let d = DIGIT_TABLE.get_unchecked(k as usize * 2); ptr::copy_nonoverlapping(d, result.offset(1), 2); sign as usize + 3 } else if k >= 10 { let d = DIGIT_TABLE.get_unchecked(k as usize * 2); ptr::copy_nonoverlapping(d, result, 2); sign as usize + 2 } else { *result = b'0' + k as u8; sign as usize + 1 } } #[cfg_attr(feature = "no-panic", inline)] pub unsafe fn write_exponent2(mut k: isize, mut result: *mut u8) -> usize { let sign = k < 0; if sign { *result = b'-'; result = result.offset(1); k = -k; } debug_assert!(k < 100); if k >= 10 {
} else { *result = b'0' + k as u8; sign as usize + 1 } }
let d = DIGIT_TABLE.get_unchecked(k as usize * 2); ptr::copy_nonoverlapping(d, result, 2); sign as usize + 2
random_line_split
exponent.rs
use crate::digit_table::*; use core::ptr; #[cfg_attr(feature = "no-panic", inline)] pub unsafe fn write_exponent3(mut k: isize, mut result: *mut u8) -> usize { let sign = k < 0; if sign { *result = b'-'; result = result.offset(1); k = -k; } debug_assert!(k < 1000); if k >= 100 { *result = b'0' + (k / 100) as u8; k %= 100; let d = DIGIT_TABLE.get_unchecked(k as usize * 2); ptr::copy_nonoverlapping(d, result.offset(1), 2); sign as usize + 3 } else if k >= 10 { let d = DIGIT_TABLE.get_unchecked(k as usize * 2); ptr::copy_nonoverlapping(d, result, 2); sign as usize + 2 } else { *result = b'0' + k as u8; sign as usize + 1 } } #[cfg_attr(feature = "no-panic", inline)] pub unsafe fn
(mut k: isize, mut result: *mut u8) -> usize { let sign = k < 0; if sign { *result = b'-'; result = result.offset(1); k = -k; } debug_assert!(k < 100); if k >= 10 { let d = DIGIT_TABLE.get_unchecked(k as usize * 2); ptr::copy_nonoverlapping(d, result, 2); sign as usize + 2 } else { *result = b'0' + k as u8; sign as usize + 1 } }
write_exponent2
identifier_name
ai.rs
// See LICENSE file for copyright and license details. use common::types::{Size2, ZInt, PlayerId, MapPos}; use game_state::{GameState}; use map::{distance}; use pathfinder::{MapPath, Pathfinder}; use dir::{Dir}; use unit::{Unit}; use db::{Db}; use core::{CoreEvent, Command, MoveMode, los}; pub struct Ai { id: PlayerId, state: GameState, pathfinder: Pathfinder, } impl Ai { pub fn new(id: &PlayerId, map_size: &Size2) -> Ai { Ai { id: id.clone(), state: GameState::new(map_size, id), pathfinder: Pathfinder::new(map_size), } } pub fn apply_event(&mut self, db: &Db, event: &CoreEvent) { self.state.apply_event(db, event); } // TODO: move fill_map here fn get_best_pos(&self) -> Option<MapPos> { let mut best_pos = None; let mut best_cost = None; for (_, enemy) in self.state.units() { if enemy.player_id == self.id { continue; } for i in 0.. 6 { let dir = Dir::from_int(i); let destination = Dir::get_neighbour_pos(&enemy.pos, &dir); if!self.state.map().is_inboard(&destination) { continue; } if self.state.is_tile_occupied(&destination) { continue; } let path = match self.pathfinder.get_path(&destination) { Some(path) => path, None => continue, }; let cost = path.total_cost().n; if let Some(ref mut best_cost) = best_cost { if *best_cost > cost { *best_cost = cost; best_pos = Some(destination.clone()); } } else { best_cost = Some(cost); best_pos = Some(destination.clone()); } } } best_pos } fn truncate_path(&self, path: MapPath, move_points: ZInt) -> MapPath { if path.total_cost().n <= move_points { return path; } let len = path.nodes().len(); for i in 1.. len { let cost = &path.nodes()[i].cost; if cost.n > move_points { let mut new_nodes = path.nodes().clone(); new_nodes.truncate(i); return MapPath::new(new_nodes); } } assert!(false); // TODO return path; } fn is_close_to_enemies(&self, db: &Db, unit: &Unit) -> bool { for (_, target) in self.state.units() { if target.player_id == self.id { continue; } let max_distance = db.unit_max_attack_dist(unit); if distance(&unit.pos, &target.pos) <= max_distance { return true; } } false } pub fn try_get_move_command(&mut self, db: &Db) -> Option<Command> { for (_, unit) in self.state.units() { if unit.player_id!= self.id { continue; } // println!("id: {}, ap: {}", unit.id.id, unit.attack_points); if unit.attack_points <= 0 { continue; } let unit_type = db.unit_type(&unit.type_id); for (_, target) in self.state.units() { if target.player_id == self.id { continue; } let max_distance = db.unit_max_attack_dist(unit); if distance(&unit.pos, &target.pos) > max_distance { continue; } if!los(self.state.map(), unit_type, &unit.pos, &target.pos) { continue; } return Some(Command::AttackUnit { attacker_id: unit.id.clone(), defender_id: target.id.clone(), }); } } None } pub fn try_get_attack_command(&mut self, db: &Db) -> Option<Command> { for (_, unit) in self.state.units() { if unit.player_id!= self.id { continue; } if self.is_close_to_enemies(db, unit) { continue; } self.pathfinder.fill_map(db, &self.state, unit); let destination = match self.get_best_pos() { Some(destination) => destination, None => continue, }; let path = match self.pathfinder.get_path(&destination) { Some(path) => path, None => continue, }; if unit.move_points == 0 { continue; } let path = self.truncate_path(path, unit.move_points); return Some(Command::Move { unit_id: unit.id.clone(), path: path, mode: MoveMode::Fast, }); } None } pub fn get_command(&mut self, db: &Db) -> Command { if let Some(cmd) = self.try_get_move_command(db) { cmd } else if let Some(cmd) = self.try_get_attack_command(db) { cmd } else { Command::EndTurn
} } } // vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
random_line_split
ai.rs
// See LICENSE file for copyright and license details. use common::types::{Size2, ZInt, PlayerId, MapPos}; use game_state::{GameState}; use map::{distance}; use pathfinder::{MapPath, Pathfinder}; use dir::{Dir}; use unit::{Unit}; use db::{Db}; use core::{CoreEvent, Command, MoveMode, los}; pub struct Ai { id: PlayerId, state: GameState, pathfinder: Pathfinder, } impl Ai { pub fn new(id: &PlayerId, map_size: &Size2) -> Ai { Ai { id: id.clone(), state: GameState::new(map_size, id), pathfinder: Pathfinder::new(map_size), } } pub fn apply_event(&mut self, db: &Db, event: &CoreEvent) { self.state.apply_event(db, event); } // TODO: move fill_map here fn get_best_pos(&self) -> Option<MapPos> { let mut best_pos = None; let mut best_cost = None; for (_, enemy) in self.state.units() { if enemy.player_id == self.id { continue; } for i in 0.. 6 { let dir = Dir::from_int(i); let destination = Dir::get_neighbour_pos(&enemy.pos, &dir); if!self.state.map().is_inboard(&destination) { continue; } if self.state.is_tile_occupied(&destination) { continue; } let path = match self.pathfinder.get_path(&destination) { Some(path) => path, None => continue, }; let cost = path.total_cost().n; if let Some(ref mut best_cost) = best_cost { if *best_cost > cost { *best_cost = cost; best_pos = Some(destination.clone()); } } else
} } best_pos } fn truncate_path(&self, path: MapPath, move_points: ZInt) -> MapPath { if path.total_cost().n <= move_points { return path; } let len = path.nodes().len(); for i in 1.. len { let cost = &path.nodes()[i].cost; if cost.n > move_points { let mut new_nodes = path.nodes().clone(); new_nodes.truncate(i); return MapPath::new(new_nodes); } } assert!(false); // TODO return path; } fn is_close_to_enemies(&self, db: &Db, unit: &Unit) -> bool { for (_, target) in self.state.units() { if target.player_id == self.id { continue; } let max_distance = db.unit_max_attack_dist(unit); if distance(&unit.pos, &target.pos) <= max_distance { return true; } } false } pub fn try_get_move_command(&mut self, db: &Db) -> Option<Command> { for (_, unit) in self.state.units() { if unit.player_id!= self.id { continue; } // println!("id: {}, ap: {}", unit.id.id, unit.attack_points); if unit.attack_points <= 0 { continue; } let unit_type = db.unit_type(&unit.type_id); for (_, target) in self.state.units() { if target.player_id == self.id { continue; } let max_distance = db.unit_max_attack_dist(unit); if distance(&unit.pos, &target.pos) > max_distance { continue; } if!los(self.state.map(), unit_type, &unit.pos, &target.pos) { continue; } return Some(Command::AttackUnit { attacker_id: unit.id.clone(), defender_id: target.id.clone(), }); } } None } pub fn try_get_attack_command(&mut self, db: &Db) -> Option<Command> { for (_, unit) in self.state.units() { if unit.player_id!= self.id { continue; } if self.is_close_to_enemies(db, unit) { continue; } self.pathfinder.fill_map(db, &self.state, unit); let destination = match self.get_best_pos() { Some(destination) => destination, None => continue, }; let path = match self.pathfinder.get_path(&destination) { Some(path) => path, None => continue, }; if unit.move_points == 0 { continue; } let path = self.truncate_path(path, unit.move_points); return Some(Command::Move { unit_id: unit.id.clone(), path: path, mode: MoveMode::Fast, }); } None } pub fn get_command(&mut self, db: &Db) -> Command { if let Some(cmd) = self.try_get_move_command(db) { cmd } else if let Some(cmd) = self.try_get_attack_command(db) { cmd } else { Command::EndTurn } } } // vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
{ best_cost = Some(cost); best_pos = Some(destination.clone()); }
conditional_block
ai.rs
// See LICENSE file for copyright and license details. use common::types::{Size2, ZInt, PlayerId, MapPos}; use game_state::{GameState}; use map::{distance}; use pathfinder::{MapPath, Pathfinder}; use dir::{Dir}; use unit::{Unit}; use db::{Db}; use core::{CoreEvent, Command, MoveMode, los}; pub struct
{ id: PlayerId, state: GameState, pathfinder: Pathfinder, } impl Ai { pub fn new(id: &PlayerId, map_size: &Size2) -> Ai { Ai { id: id.clone(), state: GameState::new(map_size, id), pathfinder: Pathfinder::new(map_size), } } pub fn apply_event(&mut self, db: &Db, event: &CoreEvent) { self.state.apply_event(db, event); } // TODO: move fill_map here fn get_best_pos(&self) -> Option<MapPos> { let mut best_pos = None; let mut best_cost = None; for (_, enemy) in self.state.units() { if enemy.player_id == self.id { continue; } for i in 0.. 6 { let dir = Dir::from_int(i); let destination = Dir::get_neighbour_pos(&enemy.pos, &dir); if!self.state.map().is_inboard(&destination) { continue; } if self.state.is_tile_occupied(&destination) { continue; } let path = match self.pathfinder.get_path(&destination) { Some(path) => path, None => continue, }; let cost = path.total_cost().n; if let Some(ref mut best_cost) = best_cost { if *best_cost > cost { *best_cost = cost; best_pos = Some(destination.clone()); } } else { best_cost = Some(cost); best_pos = Some(destination.clone()); } } } best_pos } fn truncate_path(&self, path: MapPath, move_points: ZInt) -> MapPath { if path.total_cost().n <= move_points { return path; } let len = path.nodes().len(); for i in 1.. len { let cost = &path.nodes()[i].cost; if cost.n > move_points { let mut new_nodes = path.nodes().clone(); new_nodes.truncate(i); return MapPath::new(new_nodes); } } assert!(false); // TODO return path; } fn is_close_to_enemies(&self, db: &Db, unit: &Unit) -> bool { for (_, target) in self.state.units() { if target.player_id == self.id { continue; } let max_distance = db.unit_max_attack_dist(unit); if distance(&unit.pos, &target.pos) <= max_distance { return true; } } false } pub fn try_get_move_command(&mut self, db: &Db) -> Option<Command> { for (_, unit) in self.state.units() { if unit.player_id!= self.id { continue; } // println!("id: {}, ap: {}", unit.id.id, unit.attack_points); if unit.attack_points <= 0 { continue; } let unit_type = db.unit_type(&unit.type_id); for (_, target) in self.state.units() { if target.player_id == self.id { continue; } let max_distance = db.unit_max_attack_dist(unit); if distance(&unit.pos, &target.pos) > max_distance { continue; } if!los(self.state.map(), unit_type, &unit.pos, &target.pos) { continue; } return Some(Command::AttackUnit { attacker_id: unit.id.clone(), defender_id: target.id.clone(), }); } } None } pub fn try_get_attack_command(&mut self, db: &Db) -> Option<Command> { for (_, unit) in self.state.units() { if unit.player_id!= self.id { continue; } if self.is_close_to_enemies(db, unit) { continue; } self.pathfinder.fill_map(db, &self.state, unit); let destination = match self.get_best_pos() { Some(destination) => destination, None => continue, }; let path = match self.pathfinder.get_path(&destination) { Some(path) => path, None => continue, }; if unit.move_points == 0 { continue; } let path = self.truncate_path(path, unit.move_points); return Some(Command::Move { unit_id: unit.id.clone(), path: path, mode: MoveMode::Fast, }); } None } pub fn get_command(&mut self, db: &Db) -> Command { if let Some(cmd) = self.try_get_move_command(db) { cmd } else if let Some(cmd) = self.try_get_attack_command(db) { cmd } else { Command::EndTurn } } } // vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
Ai
identifier_name
ai.rs
// See LICENSE file for copyright and license details. use common::types::{Size2, ZInt, PlayerId, MapPos}; use game_state::{GameState}; use map::{distance}; use pathfinder::{MapPath, Pathfinder}; use dir::{Dir}; use unit::{Unit}; use db::{Db}; use core::{CoreEvent, Command, MoveMode, los}; pub struct Ai { id: PlayerId, state: GameState, pathfinder: Pathfinder, } impl Ai { pub fn new(id: &PlayerId, map_size: &Size2) -> Ai { Ai { id: id.clone(), state: GameState::new(map_size, id), pathfinder: Pathfinder::new(map_size), } } pub fn apply_event(&mut self, db: &Db, event: &CoreEvent) { self.state.apply_event(db, event); } // TODO: move fill_map here fn get_best_pos(&self) -> Option<MapPos> { let mut best_pos = None; let mut best_cost = None; for (_, enemy) in self.state.units() { if enemy.player_id == self.id { continue; } for i in 0.. 6 { let dir = Dir::from_int(i); let destination = Dir::get_neighbour_pos(&enemy.pos, &dir); if!self.state.map().is_inboard(&destination) { continue; } if self.state.is_tile_occupied(&destination) { continue; } let path = match self.pathfinder.get_path(&destination) { Some(path) => path, None => continue, }; let cost = path.total_cost().n; if let Some(ref mut best_cost) = best_cost { if *best_cost > cost { *best_cost = cost; best_pos = Some(destination.clone()); } } else { best_cost = Some(cost); best_pos = Some(destination.clone()); } } } best_pos } fn truncate_path(&self, path: MapPath, move_points: ZInt) -> MapPath { if path.total_cost().n <= move_points { return path; } let len = path.nodes().len(); for i in 1.. len { let cost = &path.nodes()[i].cost; if cost.n > move_points { let mut new_nodes = path.nodes().clone(); new_nodes.truncate(i); return MapPath::new(new_nodes); } } assert!(false); // TODO return path; } fn is_close_to_enemies(&self, db: &Db, unit: &Unit) -> bool { for (_, target) in self.state.units() { if target.player_id == self.id { continue; } let max_distance = db.unit_max_attack_dist(unit); if distance(&unit.pos, &target.pos) <= max_distance { return true; } } false } pub fn try_get_move_command(&mut self, db: &Db) -> Option<Command> { for (_, unit) in self.state.units() { if unit.player_id!= self.id { continue; } // println!("id: {}, ap: {}", unit.id.id, unit.attack_points); if unit.attack_points <= 0 { continue; } let unit_type = db.unit_type(&unit.type_id); for (_, target) in self.state.units() { if target.player_id == self.id { continue; } let max_distance = db.unit_max_attack_dist(unit); if distance(&unit.pos, &target.pos) > max_distance { continue; } if!los(self.state.map(), unit_type, &unit.pos, &target.pos) { continue; } return Some(Command::AttackUnit { attacker_id: unit.id.clone(), defender_id: target.id.clone(), }); } } None } pub fn try_get_attack_command(&mut self, db: &Db) -> Option<Command> { for (_, unit) in self.state.units() { if unit.player_id!= self.id { continue; } if self.is_close_to_enemies(db, unit) { continue; } self.pathfinder.fill_map(db, &self.state, unit); let destination = match self.get_best_pos() { Some(destination) => destination, None => continue, }; let path = match self.pathfinder.get_path(&destination) { Some(path) => path, None => continue, }; if unit.move_points == 0 { continue; } let path = self.truncate_path(path, unit.move_points); return Some(Command::Move { unit_id: unit.id.clone(), path: path, mode: MoveMode::Fast, }); } None } pub fn get_command(&mut self, db: &Db) -> Command
} // vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
{ if let Some(cmd) = self.try_get_move_command(db) { cmd } else if let Some(cmd) = self.try_get_attack_command(db) { cmd } else { Command::EndTurn } }
identifier_body
main.rs
mod tokenizer; mod executor; use tokenizer::*; use executor::{execute, Numeric}; use std::collections::HashMap; use std::io::prelude::*; use std::io; fn main() { // contain all program variables let mut variables: HashMap<String, executor::Numeric> = HashMap::new(); // string to execute let mut buffer = String::new(); loop { print!(">> "); io::stdout().flush() .ok() .expect( "[error] Can't flush to stdout!" ); io::stdin().read_line(&mut buffer) .ok()
// split string to tokens let data = tokenizer::tokenize(buffer.trim()); // execute operation (check by exit flag) if execute(&mut variables, &data) { break; } // clean string buffer.clear(); } }
.expect( "[error] Can't read line from stdin!" ); // ignore null strings if buffer.trim().len() == 0 { continue; }
random_line_split
main.rs
mod tokenizer; mod executor; use tokenizer::*; use executor::{execute, Numeric}; use std::collections::HashMap; use std::io::prelude::*; use std::io; fn
() { // contain all program variables let mut variables: HashMap<String, executor::Numeric> = HashMap::new(); // string to execute let mut buffer = String::new(); loop { print!(">> "); io::stdout().flush() .ok() .expect( "[error] Can't flush to stdout!" ); io::stdin().read_line(&mut buffer) .ok() .expect( "[error] Can't read line from stdin!" ); // ignore null strings if buffer.trim().len() == 0 { continue; } // split string to tokens let data = tokenizer::tokenize(buffer.trim()); // execute operation (check by exit flag) if execute(&mut variables, &data) { break; } // clean string buffer.clear(); } }
main
identifier_name
main.rs
mod tokenizer; mod executor; use tokenizer::*; use executor::{execute, Numeric}; use std::collections::HashMap; use std::io::prelude::*; use std::io; fn main()
if execute(&mut variables, &data) { break; } // clean string buffer.clear(); } }
{ // contain all program variables let mut variables: HashMap<String, executor::Numeric> = HashMap::new(); // string to execute let mut buffer = String::new(); loop { print!(">> "); io::stdout().flush() .ok() .expect( "[error] Can't flush to stdout!" ); io::stdin().read_line(&mut buffer) .ok() .expect( "[error] Can't read line from stdin!" ); // ignore null strings if buffer.trim().len() == 0 { continue; } // split string to tokens let data = tokenizer::tokenize(buffer.trim()); // execute operation (check by exit flag)
identifier_body