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
messages_util.rs
// Copyright 2015 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. #[cfg(test)] pub mod test { use messages; use crust::Endpoint; use sodiumoxide::crypto; use rand::distributions::{IndependentSample, Range}; use rand::{random, thread_rng}; use types; use super::super::random_trait::Random; // TODO: Use IPv6 and non-TCP pub fn random_endpoint() -> Endpoint { use std::net::{Ipv4Addr, SocketAddrV4, SocketAddr}; Endpoint::Tcp(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(random::<u8>(), random::<u8>(), random::<u8>(), random::<u8>()), random::<u16>()))) } pub fn random_endpoints() -> Vec<Endpoint>
impl Random for messages::ConnectRequest { fn generate_random() -> messages::ConnectRequest { messages::ConnectRequest { local_endpoints: random_endpoints(), external_endpoints: random_endpoints(), requester_fob: Random::generate_random(), } } } impl Random for messages::ConnectResponse { fn generate_random() -> messages::ConnectResponse { messages::ConnectResponse { local_endpoints: random_endpoints(), external_endpoints: random_endpoints(), receiver_fob: Random::generate_random(), } } } }
{ let range = Range::new(1, 10); let mut rng = thread_rng(); let count = range.ind_sample(&mut rng); let mut endpoints = vec![]; for _ in 0..count { endpoints.push(random_endpoint()); } endpoints }
identifier_body
messages_util.rs
// Copyright 2015 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied.
// Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. #[cfg(test)] pub mod test { use messages; use crust::Endpoint; use sodiumoxide::crypto; use rand::distributions::{IndependentSample, Range}; use rand::{random, thread_rng}; use types; use super::super::random_trait::Random; // TODO: Use IPv6 and non-TCP pub fn random_endpoint() -> Endpoint { use std::net::{Ipv4Addr, SocketAddrV4, SocketAddr}; Endpoint::Tcp(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(random::<u8>(), random::<u8>(), random::<u8>(), random::<u8>()), random::<u16>()))) } pub fn random_endpoints() -> Vec<Endpoint> { let range = Range::new(1, 10); let mut rng = thread_rng(); let count = range.ind_sample(&mut rng); let mut endpoints = vec![]; for _ in 0..count { endpoints.push(random_endpoint()); } endpoints } impl Random for messages::ConnectRequest { fn generate_random() -> messages::ConnectRequest { messages::ConnectRequest { local_endpoints: random_endpoints(), external_endpoints: random_endpoints(), requester_fob: Random::generate_random(), } } } impl Random for messages::ConnectResponse { fn generate_random() -> messages::ConnectResponse { messages::ConnectResponse { local_endpoints: random_endpoints(), external_endpoints: random_endpoints(), receiver_fob: Random::generate_random(), } } } }
//
random_line_split
messages_util.rs
// Copyright 2015 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. #[cfg(test)] pub mod test { use messages; use crust::Endpoint; use sodiumoxide::crypto; use rand::distributions::{IndependentSample, Range}; use rand::{random, thread_rng}; use types; use super::super::random_trait::Random; // TODO: Use IPv6 and non-TCP pub fn
() -> Endpoint { use std::net::{Ipv4Addr, SocketAddrV4, SocketAddr}; Endpoint::Tcp(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(random::<u8>(), random::<u8>(), random::<u8>(), random::<u8>()), random::<u16>()))) } pub fn random_endpoints() -> Vec<Endpoint> { let range = Range::new(1, 10); let mut rng = thread_rng(); let count = range.ind_sample(&mut rng); let mut endpoints = vec![]; for _ in 0..count { endpoints.push(random_endpoint()); } endpoints } impl Random for messages::ConnectRequest { fn generate_random() -> messages::ConnectRequest { messages::ConnectRequest { local_endpoints: random_endpoints(), external_endpoints: random_endpoints(), requester_fob: Random::generate_random(), } } } impl Random for messages::ConnectResponse { fn generate_random() -> messages::ConnectResponse { messages::ConnectResponse { local_endpoints: random_endpoints(), external_endpoints: random_endpoints(), receiver_fob: Random::generate_random(), } } } }
random_endpoint
identifier_name
main.rs
use sendgrid::SGClient; use sendgrid::{Destination, Mail}; fn main()
.add_subject("Rust is rad") .add_html("<h1>Hello from SendGrid!</h1>") .add_from_name("Test") .add_header("x-cool".to_string(), "indeed") .add_x_smtpapi(&x_smtpapi); match sg.send(mail_info) { Err(err) => println!("Error: {}", err), Ok(body) => println!("Response: {:?}", body), }; }
{ let mut env_vars = std::env::vars(); let api_key_check = env_vars.find(|var| var.0 == "SENDGRID_API_KEY"); let api_key: String; match api_key_check { Some(key) => api_key = key.1, None => panic!("Must supply API key in environment variables to use!"), } let sg = SGClient::new(api_key); let mut x_smtpapi = String::new(); x_smtpapi.push_str(r#"{"unique_args":{"test":7}}"#); let mail_info = Mail::new() .add_to(Destination { address: "[email protected]", name: "you there", }) .add_from("[email protected]")
identifier_body
main.rs
use sendgrid::SGClient; use sendgrid::{Destination, Mail}; fn
() { let mut env_vars = std::env::vars(); let api_key_check = env_vars.find(|var| var.0 == "SENDGRID_API_KEY"); let api_key: String; match api_key_check { Some(key) => api_key = key.1, None => panic!("Must supply API key in environment variables to use!"), } let sg = SGClient::new(api_key); let mut x_smtpapi = String::new(); x_smtpapi.push_str(r#"{"unique_args":{"test":7}}"#); let mail_info = Mail::new() .add_to(Destination { address: "[email protected]", name: "you there", }) .add_from("[email protected]") .add_subject("Rust is rad") .add_html("<h1>Hello from SendGrid!</h1>") .add_from_name("Test") .add_header("x-cool".to_string(), "indeed") .add_x_smtpapi(&x_smtpapi); match sg.send(mail_info) { Err(err) => println!("Error: {}", err), Ok(body) => println!("Response: {:?}", body), }; }
main
identifier_name
main.rs
use sendgrid::SGClient; use sendgrid::{Destination, Mail}; fn main() {
let mut env_vars = std::env::vars(); let api_key_check = env_vars.find(|var| var.0 == "SENDGRID_API_KEY"); let api_key: String; match api_key_check { Some(key) => api_key = key.1, None => panic!("Must supply API key in environment variables to use!"), } let sg = SGClient::new(api_key); let mut x_smtpapi = String::new(); x_smtpapi.push_str(r#"{"unique_args":{"test":7}}"#); let mail_info = Mail::new() .add_to(Destination { address: "[email protected]", name: "you there", }) .add_from("[email protected]") .add_subject("Rust is rad") .add_html("<h1>Hello from SendGrid!</h1>") .add_from_name("Test") .add_header("x-cool".to_string(), "indeed") .add_x_smtpapi(&x_smtpapi); match sg.send(mail_info) { Err(err) => println!("Error: {}", err), Ok(body) => println!("Response: {:?}", body), }; }
random_line_split
logger.rs
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; struct Logger { log_level: Level, } impl Log for Logger { fn
(&self, metadata: &Metadata) -> bool { metadata.level() <= self.log_level } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { println!("[{:>5}@{}] {}", record.level(), record.target(), record.args()); } } fn flush(&self) {} } pub fn init(level: &str) -> Result<(), SetLoggerError> { if level!= "off" { let log_level = match level { "trace" => Level::Trace, "info" => Level::Info, "debug" => Level::Debug, "warn" => Level::Warn, "error" => Level::Error, _ => Level::Error, }; let logger = Logger { log_level }; log::set_boxed_logger(Box::new(logger)).map(|()| log::set_max_level(LevelFilter::Info)) } else { Ok(()) } }
enabled
identifier_name
logger.rs
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; struct Logger {
fn enabled(&self, metadata: &Metadata) -> bool { metadata.level() <= self.log_level } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { println!("[{:>5}@{}] {}", record.level(), record.target(), record.args()); } } fn flush(&self) {} } pub fn init(level: &str) -> Result<(), SetLoggerError> { if level!= "off" { let log_level = match level { "trace" => Level::Trace, "info" => Level::Info, "debug" => Level::Debug, "warn" => Level::Warn, "error" => Level::Error, _ => Level::Error, }; let logger = Logger { log_level }; log::set_boxed_logger(Box::new(logger)).map(|()| log::set_max_level(LevelFilter::Info)) } else { Ok(()) } }
log_level: Level, } impl Log for Logger {
random_line_split
logger.rs
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; struct Logger { log_level: Level, } impl Log for Logger { fn enabled(&self, metadata: &Metadata) -> bool
fn log(&self, record: &Record) { if self.enabled(record.metadata()) { println!("[{:>5}@{}] {}", record.level(), record.target(), record.args()); } } fn flush(&self) {} } pub fn init(level: &str) -> Result<(), SetLoggerError> { if level!= "off" { let log_level = match level { "trace" => Level::Trace, "info" => Level::Info, "debug" => Level::Debug, "warn" => Level::Warn, "error" => Level::Error, _ => Level::Error, }; let logger = Logger { log_level }; log::set_boxed_logger(Box::new(logger)).map(|()| log::set_max_level(LevelFilter::Info)) } else { Ok(()) } }
{ metadata.level() <= self.log_level }
identifier_body
text_run.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 app_units::Au; use font::{Font, FontHandleMethods, FontMetrics, ShapingFlags}; use font::{RunMetrics, ShapingOptions}; use platform::font_template::FontTemplateData; use range::Range; use std::cell::Cell; use std::cmp::{Ordering, max}; use std::slice::Iter; use std::sync::Arc; use style::str::char_is_whitespace; use text::glyph::{ByteIndex, GlyphStore}; use unicode_bidi as bidi; use webrender_api; use xi_unicode::LineBreakIterator; thread_local! { static INDEX_OF_FIRST_GLYPH_RUN_CACHE: Cell<Option<(*const TextRun, ByteIndex, usize)>> = Cell::new(None) } /// A single "paragraph" of text in one font size and style. #[derive(Clone, Deserialize, Serialize)] pub struct TextRun { /// The UTF-8 string represented by this text run. pub text: Arc<String>, pub font_template: Arc<FontTemplateData>, pub actual_pt_size: Au, pub font_metrics: FontMetrics, pub font_key: webrender_api::FontInstanceKey, /// The glyph runs that make up this text run. pub glyphs: Arc<Vec<GlyphRun>>, pub bidi_level: bidi::Level, pub extra_word_spacing: Au, } impl Drop for TextRun { fn drop(&mut self) { // Invalidate the glyph run cache if it was our text run that got freed. INDEX_OF_FIRST_GLYPH_RUN_CACHE.with(|index_of_first_glyph_run_cache| { if let Some((text_run_ptr, _, _)) = index_of_first_glyph_run_cache.get() { if text_run_ptr == (self as *const TextRun) { index_of_first_glyph_run_cache.set(None); } } }) } } /// A single series of glyphs within a text run. #[derive(Clone, Deserialize, Serialize)] pub struct GlyphRun { /// The glyphs. pub glyph_store: Arc<GlyphStore>, /// The byte range of characters in the containing run. pub range: Range<ByteIndex>, } pub struct NaturalWordSliceIterator<'a> { glyphs: &'a [GlyphRun], index: usize, range: Range<ByteIndex>, reverse: bool, } impl GlyphRun { fn compare(&self, key: &ByteIndex) -> Ordering { if *key < self.range.begin() { Ordering::Greater } else if *key >= self.range.end() { Ordering::Less } else { Ordering::Equal } } } /// A "slice" of a text run is a series of contiguous glyphs that all belong to the same glyph /// store. Line breaking strategies yield these. pub struct TextRunSlice<'a> { /// The glyph store that the glyphs in this slice belong to. pub glyphs: &'a GlyphStore, /// The byte index that this slice begins at, relative to the start of the *text run*. pub offset: ByteIndex, /// The range that these glyphs encompass, relative to the start of the *glyph store*. pub range: Range<ByteIndex>, } impl<'a> TextRunSlice<'a> { /// Returns the range that these glyphs encompass, relative to the start of the *text run*. #[inline] pub fn text_run_range(&self) -> Range<ByteIndex> { let mut range = self.range; range.shift_by(self.offset); range } } impl<'a> Iterator for NaturalWordSliceIterator<'a> { type Item = TextRunSlice<'a>; // inline(always) due to the inefficient rt failures messing up inline heuristics, I think. #[inline(always)] fn next(&mut self) -> Option<TextRunSlice<'a>> { let slice_glyphs; if self.reverse { if self.index == 0 { return None; } self.index -= 1; slice_glyphs = &self.glyphs[self.index]; } else { if self.index >= self.glyphs.len() { return None; } slice_glyphs = &self.glyphs[self.index]; self.index += 1; }
let mut byte_range = self.range.intersect(&slice_glyphs.range); let slice_range_begin = slice_glyphs.range.begin(); byte_range.shift_by(-slice_range_begin); if!byte_range.is_empty() { Some(TextRunSlice { glyphs: &*slice_glyphs.glyph_store, offset: slice_range_begin, range: byte_range, }) } else { None } } } pub struct CharacterSliceIterator<'a> { text: &'a str, glyph_run: Option<&'a GlyphRun>, glyph_run_iter: Iter<'a, GlyphRun>, range: Range<ByteIndex>, } impl<'a> Iterator for CharacterSliceIterator<'a> { type Item = TextRunSlice<'a>; // inline(always) due to the inefficient rt failures messing up inline heuristics, I think. #[inline(always)] fn next(&mut self) -> Option<TextRunSlice<'a>> { let glyph_run = self.glyph_run?; debug_assert!(!self.range.is_empty()); let byte_start = self.range.begin(); let byte_len = match self.text[byte_start.to_usize()..].chars().next() { Some(ch) => ByteIndex(ch.len_utf8() as isize), None => unreachable!() // XXX refactor? }; self.range.adjust_by(byte_len, -byte_len); if self.range.is_empty() { // We're done. self.glyph_run = None } else if self.range.intersect(&glyph_run.range).is_empty() { // Move on to the next glyph run. self.glyph_run = self.glyph_run_iter.next(); } let index_within_glyph_run = byte_start - glyph_run.range.begin(); Some(TextRunSlice { glyphs: &*glyph_run.glyph_store, offset: glyph_run.range.begin(), range: Range::new(index_within_glyph_run, byte_len), }) } } impl<'a> TextRun { pub fn new(font: &mut Font, text: String, options: &ShapingOptions, bidi_level: bidi::Level) -> TextRun { let glyphs = TextRun::break_and_shape(font, &text, options); TextRun { text: Arc::new(text), font_metrics: font.metrics.clone(), font_template: font.handle.template(), font_key: font.font_key, actual_pt_size: font.actual_pt_size, glyphs: Arc::new(glyphs), bidi_level: bidi_level, extra_word_spacing: Au(0), } } pub fn break_and_shape(font: &mut Font, text: &str, options: &ShapingOptions) -> Vec<GlyphRun> { let mut glyphs = vec!(); let mut slice = 0..0; for (idx, _is_hard_break) in LineBreakIterator::new(text) { // Extend the slice to the next UAX#14 line break opportunity. slice.end = idx; let word = &text[slice.clone()]; // Split off any trailing whitespace into a separate glyph run. let mut whitespace = slice.end..slice.end; if let Some((i, _)) = word.char_indices().rev() .take_while(|&(_, c)| char_is_whitespace(c)).last() { whitespace.start = slice.start + i; slice.end = whitespace.start; } else if idx!= text.len() && options.flags.contains(ShapingFlags::KEEP_ALL_FLAG) { // If there's no whitespace and word-break is set to // keep-all, try increasing the slice. continue; } if slice.len() > 0 { glyphs.push(GlyphRun { glyph_store: font.shape_text(&text[slice.clone()], options), range: Range::new(ByteIndex(slice.start as isize), ByteIndex(slice.len() as isize)), }); } if whitespace.len() > 0 { let mut options = options.clone(); options.flags.insert(ShapingFlags::IS_WHITESPACE_SHAPING_FLAG); glyphs.push(GlyphRun { glyph_store: font.shape_text(&text[whitespace.clone()], &options), range: Range::new(ByteIndex(whitespace.start as isize), ByteIndex(whitespace.len() as isize)), }); } slice.start = whitespace.end; } glyphs } pub fn ascent(&self) -> Au { self.font_metrics.ascent } pub fn descent(&self) -> Au { self.font_metrics.descent } pub fn advance_for_range(&self, range: &Range<ByteIndex>) -> Au { if range.is_empty() { return Au(0) } // TODO(Issue #199): alter advance direction for RTL // TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text self.natural_word_slices_in_range(range) .fold(Au(0), |advance, slice| { advance + slice.glyphs.advance_for_byte_range(&slice.range, self.extra_word_spacing) }) } pub fn metrics_for_range(&self, range: &Range<ByteIndex>) -> RunMetrics { RunMetrics::new(self.advance_for_range(range), self.font_metrics.ascent, self.font_metrics.descent) } pub fn metrics_for_slice(&self, glyphs: &GlyphStore, slice_range: &Range<ByteIndex>) -> RunMetrics { RunMetrics::new(glyphs.advance_for_byte_range(slice_range, self.extra_word_spacing), self.font_metrics.ascent, self.font_metrics.descent) } pub fn min_width_for_range(&self, range: &Range<ByteIndex>) -> Au { debug!("iterating outer range {:?}", range); self.natural_word_slices_in_range(range).fold(Au(0), |max_piece_width, slice| { debug!("iterated on {:?}[{:?}]", slice.offset, slice.range); max(max_piece_width, self.advance_for_range(&slice.range)) }) } pub fn minimum_splittable_inline_size(&self, range: &Range<ByteIndex>) -> Au { match self.natural_word_slices_in_range(range).next() { None => Au(0), Some(slice) => self.advance_for_range(&slice.range), } } /// Returns the index of the first glyph run containing the given character index. fn index_of_first_glyph_run_containing(&self, index: ByteIndex) -> Option<usize> { let self_ptr = self as *const TextRun; INDEX_OF_FIRST_GLYPH_RUN_CACHE.with(|index_of_first_glyph_run_cache| { if let Some((last_text_run, last_index, last_result)) = index_of_first_glyph_run_cache.get() { if last_text_run == self_ptr && last_index == index { return Some(last_result) } } if let Ok(result) = (&**self.glyphs).binary_search_by(|current| current.compare(&index)) { index_of_first_glyph_run_cache.set(Some((self_ptr, index, result))); Some(result) } else { None } }) } /// Returns the index in the range of the first glyph advancing over given advance pub fn range_index_of_advance(&self, range: &Range<ByteIndex>, advance: Au) -> usize { // TODO(Issue #199): alter advance direction for RTL // TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text let mut remaining = advance; self.natural_word_slices_in_range(range) .map(|slice| { let (slice_index, slice_advance) = slice.glyphs.range_index_of_advance(&slice.range, remaining, self.extra_word_spacing); remaining -= slice_advance; slice_index }) .sum() } /// Returns an iterator that will iterate over all slices of glyphs that represent natural /// words in the given range. pub fn natural_word_slices_in_range(&'a self, range: &Range<ByteIndex>) -> NaturalWordSliceIterator<'a> { let index = match self.index_of_first_glyph_run_containing(range.begin()) { None => self.glyphs.len(), Some(index) => index, }; NaturalWordSliceIterator { glyphs: &self.glyphs[..], index: index, range: *range, reverse: false, } } /// Returns an iterator that over natural word slices in visual order (left to right or /// right to left, depending on the bidirectional embedding level). pub fn natural_word_slices_in_visual_order(&'a self, range: &Range<ByteIndex>) -> NaturalWordSliceIterator<'a> { // Iterate in reverse order if bidi level is RTL. let reverse = self.bidi_level.is_rtl(); let index = if reverse { match self.index_of_first_glyph_run_containing(range.end() - ByteIndex(1)) { Some(i) => i + 1, // In reverse mode, index points one past the next element. None => 0 } } else { match self.index_of_first_glyph_run_containing(range.begin()) { Some(i) => i, None => self.glyphs.len() } }; NaturalWordSliceIterator { glyphs: &self.glyphs[..], index: index, range: *range, reverse: reverse, } } /// Returns an iterator that will iterate over all slices of glyphs that represent individual /// characters in the given range. pub fn character_slices_in_range(&'a self, range: &Range<ByteIndex>) -> CharacterSliceIterator<'a> { let index = match self.index_of_first_glyph_run_containing(range.begin()) { None => self.glyphs.len(), Some(index) => index, }; let mut glyph_run_iter = self.glyphs[index..].iter(); let first_glyph_run = glyph_run_iter.next(); CharacterSliceIterator { text: &self.text, glyph_run: first_glyph_run, glyph_run_iter: glyph_run_iter, range: *range, } } }
random_line_split
text_run.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 app_units::Au; use font::{Font, FontHandleMethods, FontMetrics, ShapingFlags}; use font::{RunMetrics, ShapingOptions}; use platform::font_template::FontTemplateData; use range::Range; use std::cell::Cell; use std::cmp::{Ordering, max}; use std::slice::Iter; use std::sync::Arc; use style::str::char_is_whitespace; use text::glyph::{ByteIndex, GlyphStore}; use unicode_bidi as bidi; use webrender_api; use xi_unicode::LineBreakIterator; thread_local! { static INDEX_OF_FIRST_GLYPH_RUN_CACHE: Cell<Option<(*const TextRun, ByteIndex, usize)>> = Cell::new(None) } /// A single "paragraph" of text in one font size and style. #[derive(Clone, Deserialize, Serialize)] pub struct TextRun { /// The UTF-8 string represented by this text run. pub text: Arc<String>, pub font_template: Arc<FontTemplateData>, pub actual_pt_size: Au, pub font_metrics: FontMetrics, pub font_key: webrender_api::FontInstanceKey, /// The glyph runs that make up this text run. pub glyphs: Arc<Vec<GlyphRun>>, pub bidi_level: bidi::Level, pub extra_word_spacing: Au, } impl Drop for TextRun { fn drop(&mut self) { // Invalidate the glyph run cache if it was our text run that got freed. INDEX_OF_FIRST_GLYPH_RUN_CACHE.with(|index_of_first_glyph_run_cache| { if let Some((text_run_ptr, _, _)) = index_of_first_glyph_run_cache.get() { if text_run_ptr == (self as *const TextRun) { index_of_first_glyph_run_cache.set(None); } } }) } } /// A single series of glyphs within a text run. #[derive(Clone, Deserialize, Serialize)] pub struct GlyphRun { /// The glyphs. pub glyph_store: Arc<GlyphStore>, /// The byte range of characters in the containing run. pub range: Range<ByteIndex>, } pub struct NaturalWordSliceIterator<'a> { glyphs: &'a [GlyphRun], index: usize, range: Range<ByteIndex>, reverse: bool, } impl GlyphRun { fn compare(&self, key: &ByteIndex) -> Ordering { if *key < self.range.begin() { Ordering::Greater } else if *key >= self.range.end() { Ordering::Less } else { Ordering::Equal } } } /// A "slice" of a text run is a series of contiguous glyphs that all belong to the same glyph /// store. Line breaking strategies yield these. pub struct TextRunSlice<'a> { /// The glyph store that the glyphs in this slice belong to. pub glyphs: &'a GlyphStore, /// The byte index that this slice begins at, relative to the start of the *text run*. pub offset: ByteIndex, /// The range that these glyphs encompass, relative to the start of the *glyph store*. pub range: Range<ByteIndex>, } impl<'a> TextRunSlice<'a> { /// Returns the range that these glyphs encompass, relative to the start of the *text run*. #[inline] pub fn text_run_range(&self) -> Range<ByteIndex> { let mut range = self.range; range.shift_by(self.offset); range } } impl<'a> Iterator for NaturalWordSliceIterator<'a> { type Item = TextRunSlice<'a>; // inline(always) due to the inefficient rt failures messing up inline heuristics, I think. #[inline(always)] fn
(&mut self) -> Option<TextRunSlice<'a>> { let slice_glyphs; if self.reverse { if self.index == 0 { return None; } self.index -= 1; slice_glyphs = &self.glyphs[self.index]; } else { if self.index >= self.glyphs.len() { return None; } slice_glyphs = &self.glyphs[self.index]; self.index += 1; } let mut byte_range = self.range.intersect(&slice_glyphs.range); let slice_range_begin = slice_glyphs.range.begin(); byte_range.shift_by(-slice_range_begin); if!byte_range.is_empty() { Some(TextRunSlice { glyphs: &*slice_glyphs.glyph_store, offset: slice_range_begin, range: byte_range, }) } else { None } } } pub struct CharacterSliceIterator<'a> { text: &'a str, glyph_run: Option<&'a GlyphRun>, glyph_run_iter: Iter<'a, GlyphRun>, range: Range<ByteIndex>, } impl<'a> Iterator for CharacterSliceIterator<'a> { type Item = TextRunSlice<'a>; // inline(always) due to the inefficient rt failures messing up inline heuristics, I think. #[inline(always)] fn next(&mut self) -> Option<TextRunSlice<'a>> { let glyph_run = self.glyph_run?; debug_assert!(!self.range.is_empty()); let byte_start = self.range.begin(); let byte_len = match self.text[byte_start.to_usize()..].chars().next() { Some(ch) => ByteIndex(ch.len_utf8() as isize), None => unreachable!() // XXX refactor? }; self.range.adjust_by(byte_len, -byte_len); if self.range.is_empty() { // We're done. self.glyph_run = None } else if self.range.intersect(&glyph_run.range).is_empty() { // Move on to the next glyph run. self.glyph_run = self.glyph_run_iter.next(); } let index_within_glyph_run = byte_start - glyph_run.range.begin(); Some(TextRunSlice { glyphs: &*glyph_run.glyph_store, offset: glyph_run.range.begin(), range: Range::new(index_within_glyph_run, byte_len), }) } } impl<'a> TextRun { pub fn new(font: &mut Font, text: String, options: &ShapingOptions, bidi_level: bidi::Level) -> TextRun { let glyphs = TextRun::break_and_shape(font, &text, options); TextRun { text: Arc::new(text), font_metrics: font.metrics.clone(), font_template: font.handle.template(), font_key: font.font_key, actual_pt_size: font.actual_pt_size, glyphs: Arc::new(glyphs), bidi_level: bidi_level, extra_word_spacing: Au(0), } } pub fn break_and_shape(font: &mut Font, text: &str, options: &ShapingOptions) -> Vec<GlyphRun> { let mut glyphs = vec!(); let mut slice = 0..0; for (idx, _is_hard_break) in LineBreakIterator::new(text) { // Extend the slice to the next UAX#14 line break opportunity. slice.end = idx; let word = &text[slice.clone()]; // Split off any trailing whitespace into a separate glyph run. let mut whitespace = slice.end..slice.end; if let Some((i, _)) = word.char_indices().rev() .take_while(|&(_, c)| char_is_whitespace(c)).last() { whitespace.start = slice.start + i; slice.end = whitespace.start; } else if idx!= text.len() && options.flags.contains(ShapingFlags::KEEP_ALL_FLAG) { // If there's no whitespace and word-break is set to // keep-all, try increasing the slice. continue; } if slice.len() > 0 { glyphs.push(GlyphRun { glyph_store: font.shape_text(&text[slice.clone()], options), range: Range::new(ByteIndex(slice.start as isize), ByteIndex(slice.len() as isize)), }); } if whitespace.len() > 0 { let mut options = options.clone(); options.flags.insert(ShapingFlags::IS_WHITESPACE_SHAPING_FLAG); glyphs.push(GlyphRun { glyph_store: font.shape_text(&text[whitespace.clone()], &options), range: Range::new(ByteIndex(whitespace.start as isize), ByteIndex(whitespace.len() as isize)), }); } slice.start = whitespace.end; } glyphs } pub fn ascent(&self) -> Au { self.font_metrics.ascent } pub fn descent(&self) -> Au { self.font_metrics.descent } pub fn advance_for_range(&self, range: &Range<ByteIndex>) -> Au { if range.is_empty() { return Au(0) } // TODO(Issue #199): alter advance direction for RTL // TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text self.natural_word_slices_in_range(range) .fold(Au(0), |advance, slice| { advance + slice.glyphs.advance_for_byte_range(&slice.range, self.extra_word_spacing) }) } pub fn metrics_for_range(&self, range: &Range<ByteIndex>) -> RunMetrics { RunMetrics::new(self.advance_for_range(range), self.font_metrics.ascent, self.font_metrics.descent) } pub fn metrics_for_slice(&self, glyphs: &GlyphStore, slice_range: &Range<ByteIndex>) -> RunMetrics { RunMetrics::new(glyphs.advance_for_byte_range(slice_range, self.extra_word_spacing), self.font_metrics.ascent, self.font_metrics.descent) } pub fn min_width_for_range(&self, range: &Range<ByteIndex>) -> Au { debug!("iterating outer range {:?}", range); self.natural_word_slices_in_range(range).fold(Au(0), |max_piece_width, slice| { debug!("iterated on {:?}[{:?}]", slice.offset, slice.range); max(max_piece_width, self.advance_for_range(&slice.range)) }) } pub fn minimum_splittable_inline_size(&self, range: &Range<ByteIndex>) -> Au { match self.natural_word_slices_in_range(range).next() { None => Au(0), Some(slice) => self.advance_for_range(&slice.range), } } /// Returns the index of the first glyph run containing the given character index. fn index_of_first_glyph_run_containing(&self, index: ByteIndex) -> Option<usize> { let self_ptr = self as *const TextRun; INDEX_OF_FIRST_GLYPH_RUN_CACHE.with(|index_of_first_glyph_run_cache| { if let Some((last_text_run, last_index, last_result)) = index_of_first_glyph_run_cache.get() { if last_text_run == self_ptr && last_index == index { return Some(last_result) } } if let Ok(result) = (&**self.glyphs).binary_search_by(|current| current.compare(&index)) { index_of_first_glyph_run_cache.set(Some((self_ptr, index, result))); Some(result) } else { None } }) } /// Returns the index in the range of the first glyph advancing over given advance pub fn range_index_of_advance(&self, range: &Range<ByteIndex>, advance: Au) -> usize { // TODO(Issue #199): alter advance direction for RTL // TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text let mut remaining = advance; self.natural_word_slices_in_range(range) .map(|slice| { let (slice_index, slice_advance) = slice.glyphs.range_index_of_advance(&slice.range, remaining, self.extra_word_spacing); remaining -= slice_advance; slice_index }) .sum() } /// Returns an iterator that will iterate over all slices of glyphs that represent natural /// words in the given range. pub fn natural_word_slices_in_range(&'a self, range: &Range<ByteIndex>) -> NaturalWordSliceIterator<'a> { let index = match self.index_of_first_glyph_run_containing(range.begin()) { None => self.glyphs.len(), Some(index) => index, }; NaturalWordSliceIterator { glyphs: &self.glyphs[..], index: index, range: *range, reverse: false, } } /// Returns an iterator that over natural word slices in visual order (left to right or /// right to left, depending on the bidirectional embedding level). pub fn natural_word_slices_in_visual_order(&'a self, range: &Range<ByteIndex>) -> NaturalWordSliceIterator<'a> { // Iterate in reverse order if bidi level is RTL. let reverse = self.bidi_level.is_rtl(); let index = if reverse { match self.index_of_first_glyph_run_containing(range.end() - ByteIndex(1)) { Some(i) => i + 1, // In reverse mode, index points one past the next element. None => 0 } } else { match self.index_of_first_glyph_run_containing(range.begin()) { Some(i) => i, None => self.glyphs.len() } }; NaturalWordSliceIterator { glyphs: &self.glyphs[..], index: index, range: *range, reverse: reverse, } } /// Returns an iterator that will iterate over all slices of glyphs that represent individual /// characters in the given range. pub fn character_slices_in_range(&'a self, range: &Range<ByteIndex>) -> CharacterSliceIterator<'a> { let index = match self.index_of_first_glyph_run_containing(range.begin()) { None => self.glyphs.len(), Some(index) => index, }; let mut glyph_run_iter = self.glyphs[index..].iter(); let first_glyph_run = glyph_run_iter.next(); CharacterSliceIterator { text: &self.text, glyph_run: first_glyph_run, glyph_run_iter: glyph_run_iter, range: *range, } } }
next
identifier_name
main.rs
extern crate may; extern crate num_cpus; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate may_minihttp; use std::io; use may_minihttp::{HttpServer, HttpService, Request, Response}; #[derive(Serialize)] struct Message<'a> { message: &'a str, } struct Techempower; impl HttpService for Techempower { fn call(&self, req: Request) -> io::Result<Response> { let mut resp = Response::new(); // Bare-bones router match req.path() { "/json" => { resp.header("Content-Type", "application/json"); *resp.body_mut() = serde_json::to_vec(&Message { message: "Hello, World!" }).unwrap(); } "/plaintext" => { resp.header("Content-Type", "text/plain") .body("Hello, World!"); } _ => { resp.status_code(404, "Not Found"); } } Ok(resp) } } fn
() { may::config().set_io_workers(num_cpus::get()); let server = HttpServer(Techempower).start("0.0.0.0:8080").unwrap(); server.join().unwrap(); }
main
identifier_name
main.rs
extern crate may; extern crate num_cpus; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate may_minihttp; use std::io; use may_minihttp::{HttpServer, HttpService, Request, Response}; #[derive(Serialize)] struct Message<'a> { message: &'a str, } struct Techempower;
impl HttpService for Techempower { fn call(&self, req: Request) -> io::Result<Response> { let mut resp = Response::new(); // Bare-bones router match req.path() { "/json" => { resp.header("Content-Type", "application/json"); *resp.body_mut() = serde_json::to_vec(&Message { message: "Hello, World!" }).unwrap(); } "/plaintext" => { resp.header("Content-Type", "text/plain") .body("Hello, World!"); } _ => { resp.status_code(404, "Not Found"); } } Ok(resp) } } fn main() { may::config().set_io_workers(num_cpus::get()); let server = HttpServer(Techempower).start("0.0.0.0:8080").unwrap(); server.join().unwrap(); }
random_line_split
testPriority.rs
extern mod extra; use std::rt::io::*; use std::rt::io::net::ip::SocketAddr; use std::io::println; use std::cell::Cell; use std::{os, str, io, run, uint}; use extra::arc; use std::comm::*; use extra::priority_queue::PriorityQueue; use std::rt::io::net::ip::*; use std::hashmap::HashMap; struct sched_msg { ip: IpAddr, filesize: Option<uint>, //filesize added to store file size } fn main()
println(req_vec.pop().filesize.to_str()); println(req_vec.pop().filesize.to_str()); println(req_vec.pop().filesize.to_str()); } impl Ord for sched_msg { fn lt(&self, other: &sched_msg) -> bool { let selfIP: IpAddr = self.ip; let otherIP: IpAddr = other.ip; let selfSize : Option<uint> = self.filesize; let mut sSize: uint = 0; match selfSize{ Some(i) => { sSize=i;}, None => {return true;} } let otherSize : Option<uint> = other.filesize; let mut oSize: uint = 0; match otherSize{ Some(k) => { oSize=k;}, None => {return true;} } let mut sIP : bool = false; let mut oIP : bool = false; match selfIP { Ipv4Addr(a, b, c, d) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ sIP = true; } }, Ipv6Addr(a, b, c, d, e, f, g, h) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ sIP = true; } } } match otherIP { Ipv4Addr(a, b, c, d) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ oIP = true; } }, Ipv6Addr(a, b, c, d, e, f, g, h) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ oIP = true; } } } if(sIP && oIP){ if(sSize < oSize){ return false; }else { return true; } }else if(sIP){ return false; }else if (oIP){ return true; }else if(sSize < oSize){ return false; }else { return true; } } }
{ let mut opt1 : Option<uint> = Some(10u); let mut opt2 : Option<uint> = Some(3u); let mut opt3 : Option<uint> = Some(20u); let mut local: IpAddr = std::rt::io::net::ip::Ipv4Addr(128, 143, -1, -1); let mut local2: IpAddr = std::rt::io::net::ip::Ipv4Addr(137, 54, -1, -1); let mut other: IpAddr = std::rt::io::net::ip::Ipv4Addr(-1, -1, -1, -1); let msg: sched_msg = sched_msg{ip: local, filesize : opt1 }; let msg2: sched_msg = sched_msg{ ip: other, filesize: opt2}; let msg3: sched_msg = sched_msg{ip: local2, filesize: opt3}; let mut req_vec : PriorityQueue<sched_msg> = PriorityQueue::new(); req_vec.push(msg); req_vec.push(msg2); req_vec.push(msg3);
identifier_body
testPriority.rs
extern mod extra; use std::rt::io::*; use std::rt::io::net::ip::SocketAddr; use std::io::println; use std::cell::Cell; use std::{os, str, io, run, uint}; use extra::arc; use std::comm::*; use extra::priority_queue::PriorityQueue; use std::rt::io::net::ip::*; use std::hashmap::HashMap; struct sched_msg { ip: IpAddr, filesize: Option<uint>, //filesize added to store file size } fn main() { let mut opt1 : Option<uint> = Some(10u); let mut opt2 : Option<uint> = Some(3u); let mut opt3 : Option<uint> = Some(20u); let mut local: IpAddr = std::rt::io::net::ip::Ipv4Addr(128, 143, -1, -1); let mut local2: IpAddr = std::rt::io::net::ip::Ipv4Addr(137, 54, -1, -1); let mut other: IpAddr = std::rt::io::net::ip::Ipv4Addr(-1, -1, -1, -1); let msg: sched_msg = sched_msg{ip: local, filesize : opt1 }; let msg2: sched_msg = sched_msg{ ip: other, filesize: opt2}; let msg3: sched_msg = sched_msg{ip: local2, filesize: opt3}; let mut req_vec : PriorityQueue<sched_msg> = PriorityQueue::new(); req_vec.push(msg); req_vec.push(msg2); req_vec.push(msg3); println(req_vec.pop().filesize.to_str()); println(req_vec.pop().filesize.to_str()); println(req_vec.pop().filesize.to_str()); } impl Ord for sched_msg { fn lt(&self, other: &sched_msg) -> bool { let selfIP: IpAddr = self.ip; let otherIP: IpAddr = other.ip; let selfSize : Option<uint> = self.filesize;
match selfSize{ Some(i) => { sSize=i;}, None => {return true;} } let otherSize : Option<uint> = other.filesize; let mut oSize: uint = 0; match otherSize{ Some(k) => { oSize=k;}, None => {return true;} } let mut sIP : bool = false; let mut oIP : bool = false; match selfIP { Ipv4Addr(a, b, c, d) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ sIP = true; } }, Ipv6Addr(a, b, c, d, e, f, g, h) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ sIP = true; } } } match otherIP { Ipv4Addr(a, b, c, d) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ oIP = true; } }, Ipv6Addr(a, b, c, d, e, f, g, h) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ oIP = true; } } } if(sIP && oIP){ if(sSize < oSize){ return false; }else { return true; } }else if(sIP){ return false; }else if (oIP){ return true; }else if(sSize < oSize){ return false; }else { return true; } } }
let mut sSize: uint = 0;
random_line_split
testPriority.rs
extern mod extra; use std::rt::io::*; use std::rt::io::net::ip::SocketAddr; use std::io::println; use std::cell::Cell; use std::{os, str, io, run, uint}; use extra::arc; use std::comm::*; use extra::priority_queue::PriorityQueue; use std::rt::io::net::ip::*; use std::hashmap::HashMap; struct sched_msg { ip: IpAddr, filesize: Option<uint>, //filesize added to store file size } fn main() { let mut opt1 : Option<uint> = Some(10u); let mut opt2 : Option<uint> = Some(3u); let mut opt3 : Option<uint> = Some(20u); let mut local: IpAddr = std::rt::io::net::ip::Ipv4Addr(128, 143, -1, -1); let mut local2: IpAddr = std::rt::io::net::ip::Ipv4Addr(137, 54, -1, -1); let mut other: IpAddr = std::rt::io::net::ip::Ipv4Addr(-1, -1, -1, -1); let msg: sched_msg = sched_msg{ip: local, filesize : opt1 }; let msg2: sched_msg = sched_msg{ ip: other, filesize: opt2}; let msg3: sched_msg = sched_msg{ip: local2, filesize: opt3}; let mut req_vec : PriorityQueue<sched_msg> = PriorityQueue::new(); req_vec.push(msg); req_vec.push(msg2); req_vec.push(msg3); println(req_vec.pop().filesize.to_str()); println(req_vec.pop().filesize.to_str()); println(req_vec.pop().filesize.to_str()); } impl Ord for sched_msg { fn lt(&self, other: &sched_msg) -> bool { let selfIP: IpAddr = self.ip; let otherIP: IpAddr = other.ip; let selfSize : Option<uint> = self.filesize; let mut sSize: uint = 0; match selfSize{ Some(i) => { sSize=i;}, None => {return true;} } let otherSize : Option<uint> = other.filesize; let mut oSize: uint = 0; match otherSize{ Some(k) =>
, None => {return true;} } let mut sIP : bool = false; let mut oIP : bool = false; match selfIP { Ipv4Addr(a, b, c, d) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ sIP = true; } }, Ipv6Addr(a, b, c, d, e, f, g, h) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ sIP = true; } } } match otherIP { Ipv4Addr(a, b, c, d) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ oIP = true; } }, Ipv6Addr(a, b, c, d, e, f, g, h) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ oIP = true; } } } if(sIP && oIP){ if(sSize < oSize){ return false; }else { return true; } }else if(sIP){ return false; }else if (oIP){ return true; }else if(sSize < oSize){ return false; }else { return true; } } }
{ oSize=k;}
conditional_block
testPriority.rs
extern mod extra; use std::rt::io::*; use std::rt::io::net::ip::SocketAddr; use std::io::println; use std::cell::Cell; use std::{os, str, io, run, uint}; use extra::arc; use std::comm::*; use extra::priority_queue::PriorityQueue; use std::rt::io::net::ip::*; use std::hashmap::HashMap; struct
{ ip: IpAddr, filesize: Option<uint>, //filesize added to store file size } fn main() { let mut opt1 : Option<uint> = Some(10u); let mut opt2 : Option<uint> = Some(3u); let mut opt3 : Option<uint> = Some(20u); let mut local: IpAddr = std::rt::io::net::ip::Ipv4Addr(128, 143, -1, -1); let mut local2: IpAddr = std::rt::io::net::ip::Ipv4Addr(137, 54, -1, -1); let mut other: IpAddr = std::rt::io::net::ip::Ipv4Addr(-1, -1, -1, -1); let msg: sched_msg = sched_msg{ip: local, filesize : opt1 }; let msg2: sched_msg = sched_msg{ ip: other, filesize: opt2}; let msg3: sched_msg = sched_msg{ip: local2, filesize: opt3}; let mut req_vec : PriorityQueue<sched_msg> = PriorityQueue::new(); req_vec.push(msg); req_vec.push(msg2); req_vec.push(msg3); println(req_vec.pop().filesize.to_str()); println(req_vec.pop().filesize.to_str()); println(req_vec.pop().filesize.to_str()); } impl Ord for sched_msg { fn lt(&self, other: &sched_msg) -> bool { let selfIP: IpAddr = self.ip; let otherIP: IpAddr = other.ip; let selfSize : Option<uint> = self.filesize; let mut sSize: uint = 0; match selfSize{ Some(i) => { sSize=i;}, None => {return true;} } let otherSize : Option<uint> = other.filesize; let mut oSize: uint = 0; match otherSize{ Some(k) => { oSize=k;}, None => {return true;} } let mut sIP : bool = false; let mut oIP : bool = false; match selfIP { Ipv4Addr(a, b, c, d) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ sIP = true; } }, Ipv6Addr(a, b, c, d, e, f, g, h) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ sIP = true; } } } match otherIP { Ipv4Addr(a, b, c, d) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ oIP = true; } }, Ipv6Addr(a, b, c, d, e, f, g, h) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ oIP = true; } } } if(sIP && oIP){ if(sSize < oSize){ return false; }else { return true; } }else if(sIP){ return false; }else if (oIP){ return true; }else if(sSize < oSize){ return false; }else { return true; } } }
sched_msg
identifier_name
diagnostic.rs
s) | FileLine(s) => s } } fn is_full_span(&self) -> bool { match self { &FullSpan(..) => true, &FileLine(..) => false, } } } #[derive(Clone, Copy)] pub enum ColorConfig { Auto, Always, Never } pub trait Emitter { fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level); fn custom_emit(&mut self, cm: &codemap::CodeMap, sp: RenderSpan, msg: &str, lvl: Level); } /// This structure is used to signify that a task has panicked with a fatal error /// from the diagnostics. You can use this with the `Any` trait to figure out /// how a rustc task died (if so desired). #[derive(Copy)] pub struct FatalError; /// Signifies that the compiler died with an explicit call to `.bug` /// or `.span_bug` rather than a failed assertion, etc. #[derive(Copy)] pub struct ExplicitBug; /// A span-handler is like a handler but also /// accepts span information for source-location /// reporting. pub struct SpanHandler { pub handler: Handler, pub cm: codemap::CodeMap, } impl SpanHandler { pub fn span_fatal(&self, sp: Span, msg: &str) ->! { self.handler.emit(Some((&self.cm, sp)), msg, Fatal); panic!(FatalError); } pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) ->! { self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Fatal); panic!(FatalError); } pub fn span_err(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Error); self.handler.bump_err_count(); } pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) { self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Error); self.handler.bump_err_count(); } pub fn span_warn(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Warning); } pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) { self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Warning); } pub fn span_note(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Note); } pub fn span_end_note(&self, sp: Span, msg: &str) { self.handler.custom_emit(&self.cm, FullSpan(sp), msg, Note); } pub fn span_help(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Help); } pub fn fileline_note(&self, sp: Span, msg: &str) { self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note); } pub fn fileline_help(&self, sp: Span, msg: &str) { self.handler.custom_emit(&self.cm, FileLine(sp), msg, Help); } pub fn span_bug(&self, sp: Span, msg: &str) ->! { self.handler.emit(Some((&self.cm, sp)), msg, Bug); panic!(ExplicitBug); } pub fn span_unimpl(&self, sp: Span, msg: &str) ->! { self.span_bug(sp, &format!("unimplemented {}", msg)[]); } pub fn handler<'a>(&'a self) -> &'a Handler { &self.handler } } /// A handler deals with errors; certain errors /// (fatal, bug, unimpl) may cause immediate exit, /// others log errors for later reporting. pub struct Handler { err_count: Cell<usize>, emit: RefCell<Box<Emitter + Send>>, } impl Handler { pub fn fatal(&self, msg: &str) ->! { self.emit.borrow_mut().emit(None, msg, None, Fatal); panic!(FatalError); } pub fn err(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Error); self.bump_err_count(); } pub fn bump_err_count(&self) { self.err_count.set(self.err_count.get() + 1us); } pub fn err_count(&self) -> usize { self.err_count.get() } pub fn has_errors(&self) -> bool { self.err_count.get() > 0us } pub fn abort_if_errors(&self) { let s; match self.err_count.get() { 0us => return, 1us => s = "aborting due to previous error".to_string(), _ => { s = format!("aborting due to {} previous errors", self.err_count.get()); } } self.fatal(&s[]); } pub fn warn(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Warning); } pub fn note(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Note); } pub fn help(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Help); } pub fn bug(&self, msg: &str) ->! { self.emit.borrow_mut().emit(None, msg, None, Bug); panic!(ExplicitBug); } pub fn unimpl(&self, msg: &str) ->! { self.bug(&format!("unimplemented {}", msg)[]); } pub fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level) { self.emit.borrow_mut().emit(cmsp, msg, None, lvl); } pub fn emit_with_code(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, code: &str, lvl: Level) { self.emit.borrow_mut().emit(cmsp, msg, Some(code), lvl); } pub fn custom_emit(&self, cm: &codemap::CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl); } } pub fn mk_span_handler(handler: Handler, cm: codemap::CodeMap) -> SpanHandler { SpanHandler { handler: handler, cm: cm, } } pub fn default_handler(color_config: ColorConfig, registry: Option<diagnostics::registry::Registry>) -> Handler { mk_handler(box EmitterWriter::stderr(color_config, registry)) } pub fn mk_handler(e: Box<Emitter + Send>) -> Handler { Handler { err_count: Cell::new(0), emit: RefCell::new(e), } } #[derive(Copy, PartialEq, Clone, Show)] pub enum Level { Bug, Fatal, Error, Warning, Note, Help, } impl fmt::Display for Level { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::fmt::Display; match *self { Bug => "error: internal compiler error".fmt(f), Fatal | Error => "error".fmt(f), Warning => "warning".fmt(f), Note => "note".fmt(f), Help => "help".fmt(f), } } } impl Level { fn color(self) -> term::color::Color { match self { Bug | Fatal | Error => term::color::BRIGHT_RED, Warning => term::color::BRIGHT_YELLOW, Note => term::color::BRIGHT_GREEN, Help => term::color::BRIGHT_CYAN, } } } fn print_maybe_styled(w: &mut EmitterWriter, msg: &str, color: term::attr::Attr) -> io::IoResult<()> { match w.dst { Terminal(ref mut t) => { try!(t.attr(color)); // If `msg` ends in a newline, we need to reset the color before // the newline. We're making the assumption that we end up writing // to a `LineBufferedWriter`, which means that emitting the reset // after the newline ends up buffering the reset until we print // another line or exit. Buffering the reset is a problem if we're // sharing the terminal with any other programs (e.g. other rustc // instances via `make -jN`). // // Note that if `msg` contains any internal newlines, this will // result in the `LineBufferedWriter` flushing twice instead of // once, which still leaves the opportunity for interleaved output // to be miscolored. We assume this is rare enough that we don't // have to worry about it. if msg.ends_with("\n") { try!(t.write_str(&msg[..msg.len()-1])); try!(t.reset()); try!(t.write_str("\n")); } else { try!(t.write_str(msg)); try!(t.reset()); } Ok(()) } Raw(ref mut w) => { w.write_str(msg) } } } fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level, msg: &str, code: Option<&str>) -> io::IoResult<()> { if!topic.is_empty() { try!(write!(&mut dst.dst, "{} ", topic)); } try!(print_maybe_styled(dst, &format!("{}: ", lvl.to_string())[], term::attr::ForegroundColor(lvl.color()))); try!(print_maybe_styled(dst, &format!("{}", msg)[], term::attr::Bold)); match code { Some(code) => { let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA); try!(print_maybe_styled(dst, &format!(" [{}]", code.clone())[], style)); } None => () } try!(dst.dst.write_char('\n')); Ok(()) } pub struct EmitterWriter { dst: Destination, registry: Option<diagnostics::registry::Registry> } enum Destination { Terminal(Box<term::Terminal<WriterWrapper> + Send>), Raw(Box<Writer + Send>), } impl EmitterWriter { pub fn stderr(color_config: ColorConfig, registry: Option<diagnostics::registry::Registry>) -> EmitterWriter { let stderr = io::stderr(); let use_color = match color_config { Always => true, Never => false, Auto => stderr.get_ref().isatty() }; if use_color { let dst = match term::stderr() { Some(t) => Terminal(t), None => Raw(box stderr), }; EmitterWriter { dst: dst, registry: registry } } else { EmitterWriter { dst: Raw(box stderr), registry: registry } } } pub fn new(dst: Box<Writer + Send>, registry: Option<diagnostics::registry::Registry>) -> EmitterWriter { EmitterWriter { dst: Raw(dst), registry: registry } } } impl Writer for Destination { fn write(&mut self, bytes: &[u8]) -> io::IoResult<()> { match *self { Terminal(ref mut t) => t.write(bytes), Raw(ref mut w) => w.write(bytes), } } } impl Emitter for EmitterWriter { fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level) { let error = match cmsp { Some((cm, COMMAND_LINE_SP)) => emit(self, cm, FileLine(COMMAND_LINE_SP), msg, code, lvl, false), Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl, false), None => print_diagnostic(self, "", lvl, msg, code), }; match error { Ok(()) => {} Err(e) => panic!("failed to print diagnostics: {:?}", e), } } fn custom_emit(&mut self, cm: &codemap::CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { match emit(self, cm, sp, msg, None, lvl, true) { Ok(()) => {} Err(e) => panic!("failed to print diagnostics: {:?}", e), } } } fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan, msg: &str, code: Option<&str>, lvl: Level, custom: bool) -> io::IoResult<()> { let sp = rsp.span(); // We cannot check equality directly with COMMAND_LINE_SP // since PartialEq is manually implemented to ignore the ExpnId let ss = if sp.expn_id == COMMAND_LINE_EXPN { "<command line option>".to_string() } else { cm.span_to_string(sp) }; if custom { // we want to tell compiletest/runtest to look at the last line of the // span (since `custom_highlight_lines` displays an arrow to the end of // the span) let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id}; let ses = cm.span_to_string(span_end); try!(print_diagnostic(dst, &ses[], lvl, msg, code)); if rsp.is_full_span() { try!(custom_highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp))); } } else { try!(print_diagnostic(dst, &ss[], lvl, msg, code)); if rsp.is_full_span() { try!(highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp))); } } if sp!= COMMAND_LINE_SP { try!(print_macro_backtrace(dst, cm, sp)); } match code { Some(code) => match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) { Some(_) => { try!(print_diagnostic(dst, &ss[], Help, &format!("pass `--explain {}` to see a detailed \ explanation", code)[], None)); } None => () }, None => (), } Ok(()) } fn highlight_lines(err: &mut EmitterWriter, cm: &codemap::CodeMap, sp: Span, lvl: Level, lines: codemap::FileLines) -> io::IoResult<()> { let fm = &*lines.file; let mut elided = false; let mut display_lines = &lines.lines[]; if display_lines.len() > MAX_LINES { display_lines = &display_lines[0us..MAX_LINES]; elided = true; } // Print the offending lines for &line_number in display_lines.iter() { if let Some(line) = fm.get_line(line_number) { try!(write!(&mut err.dst, "{}:{} {}\n", fm.name, line_number + 1, line)); } } if elided { let last_line = display_lines[display_lines.len() - 1us]; let s = format!("{}:{} ", fm.name, last_line + 1us); try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len())); } // FIXME (#3260) // If there's one line at fault we can easily point to the problem if lines.lines.len() == 1us { let lo = cm.lookup_char_pos(sp.lo); let mut digits = 0us; let mut num = (lines.lines[0] + 1us) / 10us; // how many digits must be indent past? while num > 0us { num /= 10us; digits += 1us; } // indent past |name:## | and the 0-offset column location let left = fm.name.len() + digits + lo.col.to_usize() + 3us; let mut s = String::new(); // Skip is the number of characters we need to skip because they are // part of the 'filename:line'part of the previous line. let skip = fm.name.len() + digits + 3us; for _ in range(0, skip) { s.push(' '); } if let Some(orig) = fm.get_line(lines.lines[0]) { for pos in range(0us, left - skip) { let cur_char = orig.as_bytes()[pos] as char; // Whenever a tab occurs on the previous line, we insert one on // the error-point-squiggly-line as well (instead of a space). // That way the squiggly line will usually appear in the correct // position. match cur_char {
'\t' => s.push('\t'), _ => s.push(' '), }; } } try!(write!(&mut err.dst, "{}", s)); let mut s = String::from_str("^"); let hi = cm.lookup_char_pos(sp.hi); if hi.col!= lo.col { // the ^ already takes up one space let num_squigglies = hi.col.to_usize() - lo.col.to_usize() - 1us; for _ in range(0, num_squigglies) { s.push('~'); } } try!(print_maybe_styled(err, &format!("{}\n", s)[], term::attr::ForegroundColor(lvl.color()))); } Ok(()) } /// Here are the differences between this and the normal `highlight_lines`: /// `custom_highlight_lines` will always put arrow on the last byte of the /// span (instead of the first byte). Also, when the span is too long (more /// than 6 lines), `custom_highlight_lines` will print the first line, then /// dot dot dot, then last line, whereas `highlight_lines` prints the first /// six lines. fn custom_highlight_lines(w: &mut EmitterWriter, cm: &codemap::CodeMap, sp: Span, lvl: Level, lines: codemap::FileLines) -> io::IoResult<()> { let fm = &*lines.file; let lines = &lines.lines[]; if lines.len() > MAX_LINES { if let Some(line) = fm.get_line(lines[0]) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, lines[0] + 1, line)); } try!(write!(&mut w.dst, "...\n")); let last_line_number = lines[lines.len() - 1]; if let Some(last_line) = fm.get_line(last_line_number) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, last_line_number + 1, last_line)); } } else { for &line_number in lines.iter() { if let Some(line) = fm.get_line(line_number) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
random_line_split
diagnostic.rs
) | FileLine(s) => s } } fn is_full_span(&self) -> bool { match self { &FullSpan(..) => true, &FileLine(..) => false, } } } #[derive(Clone, Copy)] pub enum ColorConfig { Auto, Always, Never } pub trait Emitter { fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level); fn custom_emit(&mut self, cm: &codemap::CodeMap, sp: RenderSpan, msg: &str, lvl: Level); } /// This structure is used to signify that a task has panicked with a fatal error /// from the diagnostics. You can use this with the `Any` trait to figure out /// how a rustc task died (if so desired). #[derive(Copy)] pub struct FatalError; /// Signifies that the compiler died with an explicit call to `.bug` /// or `.span_bug` rather than a failed assertion, etc. #[derive(Copy)] pub struct ExplicitBug; /// A span-handler is like a handler but also /// accepts span information for source-location /// reporting. pub struct SpanHandler { pub handler: Handler, pub cm: codemap::CodeMap, } impl SpanHandler { pub fn span_fatal(&self, sp: Span, msg: &str) ->! { self.handler.emit(Some((&self.cm, sp)), msg, Fatal); panic!(FatalError); } pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) ->! { self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Fatal); panic!(FatalError); } pub fn span_err(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Error); self.handler.bump_err_count(); } pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) { self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Error); self.handler.bump_err_count(); } pub fn span_warn(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Warning); } pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) { self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Warning); } pub fn span_note(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Note); } pub fn span_end_note(&self, sp: Span, msg: &str) { self.handler.custom_emit(&self.cm, FullSpan(sp), msg, Note); } pub fn span_help(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Help); } pub fn fileline_note(&self, sp: Span, msg: &str) { self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note); } pub fn fileline_help(&self, sp: Span, msg: &str) { self.handler.custom_emit(&self.cm, FileLine(sp), msg, Help); } pub fn span_bug(&self, sp: Span, msg: &str) ->! { self.handler.emit(Some((&self.cm, sp)), msg, Bug); panic!(ExplicitBug); } pub fn span_unimpl(&self, sp: Span, msg: &str) ->! { self.span_bug(sp, &format!("unimplemented {}", msg)[]); } pub fn handler<'a>(&'a self) -> &'a Handler { &self.handler } } /// A handler deals with errors; certain errors /// (fatal, bug, unimpl) may cause immediate exit, /// others log errors for later reporting. pub struct Handler { err_count: Cell<usize>, emit: RefCell<Box<Emitter + Send>>, } impl Handler { pub fn fatal(&self, msg: &str) ->! { self.emit.borrow_mut().emit(None, msg, None, Fatal); panic!(FatalError); } pub fn err(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Error); self.bump_err_count(); } pub fn bump_err_count(&self) { self.err_count.set(self.err_count.get() + 1us); } pub fn err_count(&self) -> usize { self.err_count.get() } pub fn has_errors(&self) -> bool { self.err_count.get() > 0us } pub fn abort_if_errors(&self) { let s; match self.err_count.get() { 0us => return, 1us => s = "aborting due to previous error".to_string(), _ => { s = format!("aborting due to {} previous errors", self.err_count.get()); } } self.fatal(&s[]); } pub fn warn(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Warning); } pub fn note(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Note); } pub fn help(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Help); } pub fn bug(&self, msg: &str) ->! { self.emit.borrow_mut().emit(None, msg, None, Bug); panic!(ExplicitBug); } pub fn unimpl(&self, msg: &str) ->! { self.bug(&format!("unimplemented {}", msg)[]); } pub fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level) { self.emit.borrow_mut().emit(cmsp, msg, None, lvl); } pub fn emit_with_code(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, code: &str, lvl: Level) { self.emit.borrow_mut().emit(cmsp, msg, Some(code), lvl); } pub fn custom_emit(&self, cm: &codemap::CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl); } } pub fn mk_span_handler(handler: Handler, cm: codemap::CodeMap) -> SpanHandler { SpanHandler { handler: handler, cm: cm, } } pub fn default_handler(color_config: ColorConfig, registry: Option<diagnostics::registry::Registry>) -> Handler { mk_handler(box EmitterWriter::stderr(color_config, registry)) } pub fn mk_handler(e: Box<Emitter + Send>) -> Handler { Handler { err_count: Cell::new(0), emit: RefCell::new(e), } } #[derive(Copy, PartialEq, Clone, Show)] pub enum Level { Bug, Fatal, Error, Warning, Note, Help, } impl fmt::Display for Level { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::fmt::Display; match *self { Bug => "error: internal compiler error".fmt(f), Fatal | Error => "error".fmt(f), Warning => "warning".fmt(f), Note => "note".fmt(f), Help => "help".fmt(f), } } } impl Level { fn color(self) -> term::color::Color { match self { Bug | Fatal | Error => term::color::BRIGHT_RED, Warning => term::color::BRIGHT_YELLOW, Note => term::color::BRIGHT_GREEN, Help => term::color::BRIGHT_CYAN, } } } fn print_maybe_styled(w: &mut EmitterWriter, msg: &str, color: term::attr::Attr) -> io::IoResult<()> { match w.dst { Terminal(ref mut t) => { try!(t.attr(color)); // If `msg` ends in a newline, we need to reset the color before // the newline. We're making the assumption that we end up writing // to a `LineBufferedWriter`, which means that emitting the reset // after the newline ends up buffering the reset until we print // another line or exit. Buffering the reset is a problem if we're // sharing the terminal with any other programs (e.g. other rustc // instances via `make -jN`). // // Note that if `msg` contains any internal newlines, this will // result in the `LineBufferedWriter` flushing twice instead of // once, which still leaves the opportunity for interleaved output // to be miscolored. We assume this is rare enough that we don't // have to worry about it. if msg.ends_with("\n") { try!(t.write_str(&msg[..msg.len()-1])); try!(t.reset()); try!(t.write_str("\n")); } else { try!(t.write_str(msg)); try!(t.reset()); } Ok(()) } Raw(ref mut w) => { w.write_str(msg) } } } fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level, msg: &str, code: Option<&str>) -> io::IoResult<()> { if!topic.is_empty() { try!(write!(&mut dst.dst, "{} ", topic)); } try!(print_maybe_styled(dst, &format!("{}: ", lvl.to_string())[], term::attr::ForegroundColor(lvl.color()))); try!(print_maybe_styled(dst, &format!("{}", msg)[], term::attr::Bold)); match code { Some(code) => { let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA); try!(print_maybe_styled(dst, &format!(" [{}]", code.clone())[], style)); } None => () } try!(dst.dst.write_char('\n')); Ok(()) } pub struct EmitterWriter { dst: Destination, registry: Option<diagnostics::registry::Registry> } enum Destination { Terminal(Box<term::Terminal<WriterWrapper> + Send>), Raw(Box<Writer + Send>), } impl EmitterWriter { pub fn stderr(color_config: ColorConfig, registry: Option<diagnostics::registry::Registry>) -> EmitterWriter { let stderr = io::stderr(); let use_color = match color_config { Always => true, Never => false, Auto => stderr.get_ref().isatty() }; if use_color { let dst = match term::stderr() { Some(t) => Terminal(t), None => Raw(box stderr), }; EmitterWriter { dst: dst, registry: registry } } else { EmitterWriter { dst: Raw(box stderr), registry: registry } } } pub fn new(dst: Box<Writer + Send>, registry: Option<diagnostics::registry::Registry>) -> EmitterWriter { EmitterWriter { dst: Raw(dst), registry: registry } } } impl Writer for Destination { fn write(&mut self, bytes: &[u8]) -> io::IoResult<()> { match *self { Terminal(ref mut t) => t.write(bytes), Raw(ref mut w) => w.write(bytes), } } } impl Emitter for EmitterWriter { fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level) { let error = match cmsp { Some((cm, COMMAND_LINE_SP)) => emit(self, cm, FileLine(COMMAND_LINE_SP), msg, code, lvl, false), Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl, false), None => print_diagnostic(self, "", lvl, msg, code), }; match error { Ok(()) => {} Err(e) => panic!("failed to print diagnostics: {:?}", e), } } fn custom_emit(&mut self, cm: &codemap::CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { match emit(self, cm, sp, msg, None, lvl, true) { Ok(()) => {} Err(e) => panic!("failed to print diagnostics: {:?}", e), } } } fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan, msg: &str, code: Option<&str>, lvl: Level, custom: bool) -> io::IoResult<()> { let sp = rsp.span(); // We cannot check equality directly with COMMAND_LINE_SP // since PartialEq is manually implemented to ignore the ExpnId let ss = if sp.expn_id == COMMAND_LINE_EXPN { "<command line option>".to_string() } else { cm.span_to_string(sp) }; if custom { // we want to tell compiletest/runtest to look at the last line of the // span (since `custom_highlight_lines` displays an arrow to the end of // the span) let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id}; let ses = cm.span_to_string(span_end); try!(print_diagnostic(dst, &ses[], lvl, msg, code)); if rsp.is_full_span() { try!(custom_highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp))); } } else { try!(print_diagnostic(dst, &ss[], lvl, msg, code)); if rsp.is_full_span() { try!(highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp))); } } if sp!= COMMAND_LINE_SP { try!(print_macro_backtrace(dst, cm, sp)); } match code { Some(code) => match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) { Some(_) => { try!(print_diagnostic(dst, &ss[], Help, &format!("pass `--explain {}` to see a detailed \ explanation", code)[], None)); } None => () }, None => (), } Ok(()) } fn highlight_lines(err: &mut EmitterWriter, cm: &codemap::CodeMap, sp: Span, lvl: Level, lines: codemap::FileLines) -> io::IoResult<()> { let fm = &*lines.file; let mut elided = false; let mut display_lines = &lines.lines[]; if display_lines.len() > MAX_LINES { display_lines = &display_lines[0us..MAX_LINES]; elided = true; } // Print the offending lines for &line_number in display_lines.iter() { if let Some(line) = fm.get_line(line_number) { try!(write!(&mut err.dst, "{}:{} {}\n", fm.name, line_number + 1, line)); } } if elided { let last_line = display_lines[display_lines.len() - 1us]; let s = format!("{}:{} ", fm.name, last_line + 1us); try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len())); } // FIXME (#3260) // If there's one line at fault we can easily point to the problem if lines.lines.len() == 1us { let lo = cm.lookup_char_pos(sp.lo); let mut digits = 0us; let mut num = (lines.lines[0] + 1us) / 10us; // how many digits must be indent past? while num > 0us { num /= 10us; digits += 1us; } // indent past |name:## | and the 0-offset column location let left = fm.name.len() + digits + lo.col.to_usize() + 3us; let mut s = String::new(); // Skip is the number of characters we need to skip because they are // part of the 'filename:line'part of the previous line. let skip = fm.name.len() + digits + 3us; for _ in range(0, skip) { s.push(' '); } if let Some(orig) = fm.get_line(lines.lines[0]) { for pos in range(0us, left - skip) { let cur_char = orig.as_bytes()[pos] as char; // Whenever a tab occurs on the previous line, we insert one on // the error-point-squiggly-line as well (instead of a space). // That way the squiggly line will usually appear in the correct // position. match cur_char { '\t' => s.push('\t'), _ => s.push(' '), }; } } try!(write!(&mut err.dst, "{}", s)); let mut s = String::from_str("^"); let hi = cm.lookup_char_pos(sp.hi); if hi.col!= lo.col { // the ^ already takes up one space let num_squigglies = hi.col.to_usize() - lo.col.to_usize() - 1us; for _ in range(0, num_squigglies) { s.push('~'); } } try!(print_maybe_styled(err, &format!("{}\n", s)[], term::attr::ForegroundColor(lvl.color()))); } Ok(()) } /// Here are the differences between this and the normal `highlight_lines`: /// `custom_highlight_lines` will always put arrow on the last byte of the /// span (instead of the first byte). Also, when the span is too long (more /// than 6 lines), `custom_highlight_lines` will print the first line, then /// dot dot dot, then last line, whereas `highlight_lines` prints the first /// six lines. fn custom_highlight_lines(w: &mut EmitterWriter, cm: &codemap::CodeMap, sp: Span, lvl: Level, lines: codemap::FileLines) -> io::IoResult<()> { let fm = &*lines.file; let lines = &lines.lines[]; if lines.len() > MAX_LINES
else { for &line_number in lines.iter() { if let Some(line) = fm.get_line(line_number) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
{ if let Some(line) = fm.get_line(lines[0]) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, lines[0] + 1, line)); } try!(write!(&mut w.dst, "...\n")); let last_line_number = lines[lines.len() - 1]; if let Some(last_line) = fm.get_line(last_line_number) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, last_line_number + 1, last_line)); } }
conditional_block
diagnostic.rs
) | FileLine(s) => s } } fn is_full_span(&self) -> bool { match self { &FullSpan(..) => true, &FileLine(..) => false, } } } #[derive(Clone, Copy)] pub enum ColorConfig { Auto, Always, Never } pub trait Emitter { fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level); fn custom_emit(&mut self, cm: &codemap::CodeMap, sp: RenderSpan, msg: &str, lvl: Level); } /// This structure is used to signify that a task has panicked with a fatal error /// from the diagnostics. You can use this with the `Any` trait to figure out /// how a rustc task died (if so desired). #[derive(Copy)] pub struct FatalError; /// Signifies that the compiler died with an explicit call to `.bug` /// or `.span_bug` rather than a failed assertion, etc. #[derive(Copy)] pub struct ExplicitBug; /// A span-handler is like a handler but also /// accepts span information for source-location /// reporting. pub struct SpanHandler { pub handler: Handler, pub cm: codemap::CodeMap, } impl SpanHandler { pub fn span_fatal(&self, sp: Span, msg: &str) ->! { self.handler.emit(Some((&self.cm, sp)), msg, Fatal); panic!(FatalError); } pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) ->! { self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Fatal); panic!(FatalError); } pub fn span_err(&self, sp: Span, msg: &str)
pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) { self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Error); self.handler.bump_err_count(); } pub fn span_warn(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Warning); } pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) { self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Warning); } pub fn span_note(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Note); } pub fn span_end_note(&self, sp: Span, msg: &str) { self.handler.custom_emit(&self.cm, FullSpan(sp), msg, Note); } pub fn span_help(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Help); } pub fn fileline_note(&self, sp: Span, msg: &str) { self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note); } pub fn fileline_help(&self, sp: Span, msg: &str) { self.handler.custom_emit(&self.cm, FileLine(sp), msg, Help); } pub fn span_bug(&self, sp: Span, msg: &str) ->! { self.handler.emit(Some((&self.cm, sp)), msg, Bug); panic!(ExplicitBug); } pub fn span_unimpl(&self, sp: Span, msg: &str) ->! { self.span_bug(sp, &format!("unimplemented {}", msg)[]); } pub fn handler<'a>(&'a self) -> &'a Handler { &self.handler } } /// A handler deals with errors; certain errors /// (fatal, bug, unimpl) may cause immediate exit, /// others log errors for later reporting. pub struct Handler { err_count: Cell<usize>, emit: RefCell<Box<Emitter + Send>>, } impl Handler { pub fn fatal(&self, msg: &str) ->! { self.emit.borrow_mut().emit(None, msg, None, Fatal); panic!(FatalError); } pub fn err(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Error); self.bump_err_count(); } pub fn bump_err_count(&self) { self.err_count.set(self.err_count.get() + 1us); } pub fn err_count(&self) -> usize { self.err_count.get() } pub fn has_errors(&self) -> bool { self.err_count.get() > 0us } pub fn abort_if_errors(&self) { let s; match self.err_count.get() { 0us => return, 1us => s = "aborting due to previous error".to_string(), _ => { s = format!("aborting due to {} previous errors", self.err_count.get()); } } self.fatal(&s[]); } pub fn warn(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Warning); } pub fn note(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Note); } pub fn help(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Help); } pub fn bug(&self, msg: &str) ->! { self.emit.borrow_mut().emit(None, msg, None, Bug); panic!(ExplicitBug); } pub fn unimpl(&self, msg: &str) ->! { self.bug(&format!("unimplemented {}", msg)[]); } pub fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level) { self.emit.borrow_mut().emit(cmsp, msg, None, lvl); } pub fn emit_with_code(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, code: &str, lvl: Level) { self.emit.borrow_mut().emit(cmsp, msg, Some(code), lvl); } pub fn custom_emit(&self, cm: &codemap::CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl); } } pub fn mk_span_handler(handler: Handler, cm: codemap::CodeMap) -> SpanHandler { SpanHandler { handler: handler, cm: cm, } } pub fn default_handler(color_config: ColorConfig, registry: Option<diagnostics::registry::Registry>) -> Handler { mk_handler(box EmitterWriter::stderr(color_config, registry)) } pub fn mk_handler(e: Box<Emitter + Send>) -> Handler { Handler { err_count: Cell::new(0), emit: RefCell::new(e), } } #[derive(Copy, PartialEq, Clone, Show)] pub enum Level { Bug, Fatal, Error, Warning, Note, Help, } impl fmt::Display for Level { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::fmt::Display; match *self { Bug => "error: internal compiler error".fmt(f), Fatal | Error => "error".fmt(f), Warning => "warning".fmt(f), Note => "note".fmt(f), Help => "help".fmt(f), } } } impl Level { fn color(self) -> term::color::Color { match self { Bug | Fatal | Error => term::color::BRIGHT_RED, Warning => term::color::BRIGHT_YELLOW, Note => term::color::BRIGHT_GREEN, Help => term::color::BRIGHT_CYAN, } } } fn print_maybe_styled(w: &mut EmitterWriter, msg: &str, color: term::attr::Attr) -> io::IoResult<()> { match w.dst { Terminal(ref mut t) => { try!(t.attr(color)); // If `msg` ends in a newline, we need to reset the color before // the newline. We're making the assumption that we end up writing // to a `LineBufferedWriter`, which means that emitting the reset // after the newline ends up buffering the reset until we print // another line or exit. Buffering the reset is a problem if we're // sharing the terminal with any other programs (e.g. other rustc // instances via `make -jN`). // // Note that if `msg` contains any internal newlines, this will // result in the `LineBufferedWriter` flushing twice instead of // once, which still leaves the opportunity for interleaved output // to be miscolored. We assume this is rare enough that we don't // have to worry about it. if msg.ends_with("\n") { try!(t.write_str(&msg[..msg.len()-1])); try!(t.reset()); try!(t.write_str("\n")); } else { try!(t.write_str(msg)); try!(t.reset()); } Ok(()) } Raw(ref mut w) => { w.write_str(msg) } } } fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level, msg: &str, code: Option<&str>) -> io::IoResult<()> { if!topic.is_empty() { try!(write!(&mut dst.dst, "{} ", topic)); } try!(print_maybe_styled(dst, &format!("{}: ", lvl.to_string())[], term::attr::ForegroundColor(lvl.color()))); try!(print_maybe_styled(dst, &format!("{}", msg)[], term::attr::Bold)); match code { Some(code) => { let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA); try!(print_maybe_styled(dst, &format!(" [{}]", code.clone())[], style)); } None => () } try!(dst.dst.write_char('\n')); Ok(()) } pub struct EmitterWriter { dst: Destination, registry: Option<diagnostics::registry::Registry> } enum Destination { Terminal(Box<term::Terminal<WriterWrapper> + Send>), Raw(Box<Writer + Send>), } impl EmitterWriter { pub fn stderr(color_config: ColorConfig, registry: Option<diagnostics::registry::Registry>) -> EmitterWriter { let stderr = io::stderr(); let use_color = match color_config { Always => true, Never => false, Auto => stderr.get_ref().isatty() }; if use_color { let dst = match term::stderr() { Some(t) => Terminal(t), None => Raw(box stderr), }; EmitterWriter { dst: dst, registry: registry } } else { EmitterWriter { dst: Raw(box stderr), registry: registry } } } pub fn new(dst: Box<Writer + Send>, registry: Option<diagnostics::registry::Registry>) -> EmitterWriter { EmitterWriter { dst: Raw(dst), registry: registry } } } impl Writer for Destination { fn write(&mut self, bytes: &[u8]) -> io::IoResult<()> { match *self { Terminal(ref mut t) => t.write(bytes), Raw(ref mut w) => w.write(bytes), } } } impl Emitter for EmitterWriter { fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level) { let error = match cmsp { Some((cm, COMMAND_LINE_SP)) => emit(self, cm, FileLine(COMMAND_LINE_SP), msg, code, lvl, false), Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl, false), None => print_diagnostic(self, "", lvl, msg, code), }; match error { Ok(()) => {} Err(e) => panic!("failed to print diagnostics: {:?}", e), } } fn custom_emit(&mut self, cm: &codemap::CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { match emit(self, cm, sp, msg, None, lvl, true) { Ok(()) => {} Err(e) => panic!("failed to print diagnostics: {:?}", e), } } } fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan, msg: &str, code: Option<&str>, lvl: Level, custom: bool) -> io::IoResult<()> { let sp = rsp.span(); // We cannot check equality directly with COMMAND_LINE_SP // since PartialEq is manually implemented to ignore the ExpnId let ss = if sp.expn_id == COMMAND_LINE_EXPN { "<command line option>".to_string() } else { cm.span_to_string(sp) }; if custom { // we want to tell compiletest/runtest to look at the last line of the // span (since `custom_highlight_lines` displays an arrow to the end of // the span) let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id}; let ses = cm.span_to_string(span_end); try!(print_diagnostic(dst, &ses[], lvl, msg, code)); if rsp.is_full_span() { try!(custom_highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp))); } } else { try!(print_diagnostic(dst, &ss[], lvl, msg, code)); if rsp.is_full_span() { try!(highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp))); } } if sp!= COMMAND_LINE_SP { try!(print_macro_backtrace(dst, cm, sp)); } match code { Some(code) => match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) { Some(_) => { try!(print_diagnostic(dst, &ss[], Help, &format!("pass `--explain {}` to see a detailed \ explanation", code)[], None)); } None => () }, None => (), } Ok(()) } fn highlight_lines(err: &mut EmitterWriter, cm: &codemap::CodeMap, sp: Span, lvl: Level, lines: codemap::FileLines) -> io::IoResult<()> { let fm = &*lines.file; let mut elided = false; let mut display_lines = &lines.lines[]; if display_lines.len() > MAX_LINES { display_lines = &display_lines[0us..MAX_LINES]; elided = true; } // Print the offending lines for &line_number in display_lines.iter() { if let Some(line) = fm.get_line(line_number) { try!(write!(&mut err.dst, "{}:{} {}\n", fm.name, line_number + 1, line)); } } if elided { let last_line = display_lines[display_lines.len() - 1us]; let s = format!("{}:{} ", fm.name, last_line + 1us); try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len())); } // FIXME (#3260) // If there's one line at fault we can easily point to the problem if lines.lines.len() == 1us { let lo = cm.lookup_char_pos(sp.lo); let mut digits = 0us; let mut num = (lines.lines[0] + 1us) / 10us; // how many digits must be indent past? while num > 0us { num /= 10us; digits += 1us; } // indent past |name:## | and the 0-offset column location let left = fm.name.len() + digits + lo.col.to_usize() + 3us; let mut s = String::new(); // Skip is the number of characters we need to skip because they are // part of the 'filename:line'part of the previous line. let skip = fm.name.len() + digits + 3us; for _ in range(0, skip) { s.push(' '); } if let Some(orig) = fm.get_line(lines.lines[0]) { for pos in range(0us, left - skip) { let cur_char = orig.as_bytes()[pos] as char; // Whenever a tab occurs on the previous line, we insert one on // the error-point-squiggly-line as well (instead of a space). // That way the squiggly line will usually appear in the correct // position. match cur_char { '\t' => s.push('\t'), _ => s.push(' '), }; } } try!(write!(&mut err.dst, "{}", s)); let mut s = String::from_str("^"); let hi = cm.lookup_char_pos(sp.hi); if hi.col!= lo.col { // the ^ already takes up one space let num_squigglies = hi.col.to_usize() - lo.col.to_usize() - 1us; for _ in range(0, num_squigglies) { s.push('~'); } } try!(print_maybe_styled(err, &format!("{}\n", s)[], term::attr::ForegroundColor(lvl.color()))); } Ok(()) } /// Here are the differences between this and the normal `highlight_lines`: /// `custom_highlight_lines` will always put arrow on the last byte of the /// span (instead of the first byte). Also, when the span is too long (more /// than 6 lines), `custom_highlight_lines` will print the first line, then /// dot dot dot, then last line, whereas `highlight_lines` prints the first /// six lines. fn custom_highlight_lines(w: &mut EmitterWriter, cm: &codemap::CodeMap, sp: Span, lvl: Level, lines: codemap::FileLines) -> io::IoResult<()> { let fm = &*lines.file; let lines = &lines.lines[]; if lines.len() > MAX_LINES { if let Some(line) = fm.get_line(lines[0]) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, lines[0] + 1, line)); } try!(write!(&mut w.dst, "...\n")); let last_line_number = lines[lines.len() - 1]; if let Some(last_line) = fm.get_line(last_line_number) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, last_line_number + 1, last_line)); } } else { for &line_number in lines.iter() { if let Some(line) = fm.get_line(line_number) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
{ self.handler.emit(Some((&self.cm, sp)), msg, Error); self.handler.bump_err_count(); }
identifier_body
diagnostic.rs
) | FileLine(s) => s } } fn is_full_span(&self) -> bool { match self { &FullSpan(..) => true, &FileLine(..) => false, } } } #[derive(Clone, Copy)] pub enum ColorConfig { Auto, Always, Never } pub trait Emitter { fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level); fn custom_emit(&mut self, cm: &codemap::CodeMap, sp: RenderSpan, msg: &str, lvl: Level); } /// This structure is used to signify that a task has panicked with a fatal error /// from the diagnostics. You can use this with the `Any` trait to figure out /// how a rustc task died (if so desired). #[derive(Copy)] pub struct FatalError; /// Signifies that the compiler died with an explicit call to `.bug` /// or `.span_bug` rather than a failed assertion, etc. #[derive(Copy)] pub struct ExplicitBug; /// A span-handler is like a handler but also /// accepts span information for source-location /// reporting. pub struct SpanHandler { pub handler: Handler, pub cm: codemap::CodeMap, } impl SpanHandler { pub fn span_fatal(&self, sp: Span, msg: &str) ->! { self.handler.emit(Some((&self.cm, sp)), msg, Fatal); panic!(FatalError); } pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) ->! { self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Fatal); panic!(FatalError); } pub fn span_err(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Error); self.handler.bump_err_count(); } pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) { self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Error); self.handler.bump_err_count(); } pub fn span_warn(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Warning); } pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) { self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Warning); } pub fn span_note(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Note); } pub fn span_end_note(&self, sp: Span, msg: &str) { self.handler.custom_emit(&self.cm, FullSpan(sp), msg, Note); } pub fn span_help(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Help); } pub fn fileline_note(&self, sp: Span, msg: &str) { self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note); } pub fn fileline_help(&self, sp: Span, msg: &str) { self.handler.custom_emit(&self.cm, FileLine(sp), msg, Help); } pub fn span_bug(&self, sp: Span, msg: &str) ->! { self.handler.emit(Some((&self.cm, sp)), msg, Bug); panic!(ExplicitBug); } pub fn span_unimpl(&self, sp: Span, msg: &str) ->! { self.span_bug(sp, &format!("unimplemented {}", msg)[]); } pub fn handler<'a>(&'a self) -> &'a Handler { &self.handler } } /// A handler deals with errors; certain errors /// (fatal, bug, unimpl) may cause immediate exit, /// others log errors for later reporting. pub struct Handler { err_count: Cell<usize>, emit: RefCell<Box<Emitter + Send>>, } impl Handler { pub fn fatal(&self, msg: &str) ->! { self.emit.borrow_mut().emit(None, msg, None, Fatal); panic!(FatalError); } pub fn err(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Error); self.bump_err_count(); } pub fn bump_err_count(&self) { self.err_count.set(self.err_count.get() + 1us); } pub fn err_count(&self) -> usize { self.err_count.get() } pub fn has_errors(&self) -> bool { self.err_count.get() > 0us } pub fn abort_if_errors(&self) { let s; match self.err_count.get() { 0us => return, 1us => s = "aborting due to previous error".to_string(), _ => { s = format!("aborting due to {} previous errors", self.err_count.get()); } } self.fatal(&s[]); } pub fn warn(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Warning); } pub fn note(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Note); } pub fn help(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Help); } pub fn bug(&self, msg: &str) ->! { self.emit.borrow_mut().emit(None, msg, None, Bug); panic!(ExplicitBug); } pub fn unimpl(&self, msg: &str) ->! { self.bug(&format!("unimplemented {}", msg)[]); } pub fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level) { self.emit.borrow_mut().emit(cmsp, msg, None, lvl); } pub fn emit_with_code(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, code: &str, lvl: Level) { self.emit.borrow_mut().emit(cmsp, msg, Some(code), lvl); } pub fn custom_emit(&self, cm: &codemap::CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl); } } pub fn mk_span_handler(handler: Handler, cm: codemap::CodeMap) -> SpanHandler { SpanHandler { handler: handler, cm: cm, } } pub fn default_handler(color_config: ColorConfig, registry: Option<diagnostics::registry::Registry>) -> Handler { mk_handler(box EmitterWriter::stderr(color_config, registry)) } pub fn mk_handler(e: Box<Emitter + Send>) -> Handler { Handler { err_count: Cell::new(0), emit: RefCell::new(e), } } #[derive(Copy, PartialEq, Clone, Show)] pub enum Level { Bug, Fatal, Error, Warning, Note, Help, } impl fmt::Display for Level { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::fmt::Display; match *self { Bug => "error: internal compiler error".fmt(f), Fatal | Error => "error".fmt(f), Warning => "warning".fmt(f), Note => "note".fmt(f), Help => "help".fmt(f), } } } impl Level { fn color(self) -> term::color::Color { match self { Bug | Fatal | Error => term::color::BRIGHT_RED, Warning => term::color::BRIGHT_YELLOW, Note => term::color::BRIGHT_GREEN, Help => term::color::BRIGHT_CYAN, } } } fn print_maybe_styled(w: &mut EmitterWriter, msg: &str, color: term::attr::Attr) -> io::IoResult<()> { match w.dst { Terminal(ref mut t) => { try!(t.attr(color)); // If `msg` ends in a newline, we need to reset the color before // the newline. We're making the assumption that we end up writing // to a `LineBufferedWriter`, which means that emitting the reset // after the newline ends up buffering the reset until we print // another line or exit. Buffering the reset is a problem if we're // sharing the terminal with any other programs (e.g. other rustc // instances via `make -jN`). // // Note that if `msg` contains any internal newlines, this will // result in the `LineBufferedWriter` flushing twice instead of // once, which still leaves the opportunity for interleaved output // to be miscolored. We assume this is rare enough that we don't // have to worry about it. if msg.ends_with("\n") { try!(t.write_str(&msg[..msg.len()-1])); try!(t.reset()); try!(t.write_str("\n")); } else { try!(t.write_str(msg)); try!(t.reset()); } Ok(()) } Raw(ref mut w) => { w.write_str(msg) } } } fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level, msg: &str, code: Option<&str>) -> io::IoResult<()> { if!topic.is_empty() { try!(write!(&mut dst.dst, "{} ", topic)); } try!(print_maybe_styled(dst, &format!("{}: ", lvl.to_string())[], term::attr::ForegroundColor(lvl.color()))); try!(print_maybe_styled(dst, &format!("{}", msg)[], term::attr::Bold)); match code { Some(code) => { let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA); try!(print_maybe_styled(dst, &format!(" [{}]", code.clone())[], style)); } None => () } try!(dst.dst.write_char('\n')); Ok(()) } pub struct EmitterWriter { dst: Destination, registry: Option<diagnostics::registry::Registry> } enum Destination { Terminal(Box<term::Terminal<WriterWrapper> + Send>), Raw(Box<Writer + Send>), } impl EmitterWriter { pub fn stderr(color_config: ColorConfig, registry: Option<diagnostics::registry::Registry>) -> EmitterWriter { let stderr = io::stderr(); let use_color = match color_config { Always => true, Never => false, Auto => stderr.get_ref().isatty() }; if use_color { let dst = match term::stderr() { Some(t) => Terminal(t), None => Raw(box stderr), }; EmitterWriter { dst: dst, registry: registry } } else { EmitterWriter { dst: Raw(box stderr), registry: registry } } } pub fn new(dst: Box<Writer + Send>, registry: Option<diagnostics::registry::Registry>) -> EmitterWriter { EmitterWriter { dst: Raw(dst), registry: registry } } } impl Writer for Destination { fn write(&mut self, bytes: &[u8]) -> io::IoResult<()> { match *self { Terminal(ref mut t) => t.write(bytes), Raw(ref mut w) => w.write(bytes), } } } impl Emitter for EmitterWriter { fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level) { let error = match cmsp { Some((cm, COMMAND_LINE_SP)) => emit(self, cm, FileLine(COMMAND_LINE_SP), msg, code, lvl, false), Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl, false), None => print_diagnostic(self, "", lvl, msg, code), }; match error { Ok(()) => {} Err(e) => panic!("failed to print diagnostics: {:?}", e), } } fn custom_emit(&mut self, cm: &codemap::CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { match emit(self, cm, sp, msg, None, lvl, true) { Ok(()) => {} Err(e) => panic!("failed to print diagnostics: {:?}", e), } } } fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan, msg: &str, code: Option<&str>, lvl: Level, custom: bool) -> io::IoResult<()> { let sp = rsp.span(); // We cannot check equality directly with COMMAND_LINE_SP // since PartialEq is manually implemented to ignore the ExpnId let ss = if sp.expn_id == COMMAND_LINE_EXPN { "<command line option>".to_string() } else { cm.span_to_string(sp) }; if custom { // we want to tell compiletest/runtest to look at the last line of the // span (since `custom_highlight_lines` displays an arrow to the end of // the span) let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id}; let ses = cm.span_to_string(span_end); try!(print_diagnostic(dst, &ses[], lvl, msg, code)); if rsp.is_full_span() { try!(custom_highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp))); } } else { try!(print_diagnostic(dst, &ss[], lvl, msg, code)); if rsp.is_full_span() { try!(highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp))); } } if sp!= COMMAND_LINE_SP { try!(print_macro_backtrace(dst, cm, sp)); } match code { Some(code) => match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) { Some(_) => { try!(print_diagnostic(dst, &ss[], Help, &format!("pass `--explain {}` to see a detailed \ explanation", code)[], None)); } None => () }, None => (), } Ok(()) } fn highlight_lines(err: &mut EmitterWriter, cm: &codemap::CodeMap, sp: Span, lvl: Level, lines: codemap::FileLines) -> io::IoResult<()> { let fm = &*lines.file; let mut elided = false; let mut display_lines = &lines.lines[]; if display_lines.len() > MAX_LINES { display_lines = &display_lines[0us..MAX_LINES]; elided = true; } // Print the offending lines for &line_number in display_lines.iter() { if let Some(line) = fm.get_line(line_number) { try!(write!(&mut err.dst, "{}:{} {}\n", fm.name, line_number + 1, line)); } } if elided { let last_line = display_lines[display_lines.len() - 1us]; let s = format!("{}:{} ", fm.name, last_line + 1us); try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len())); } // FIXME (#3260) // If there's one line at fault we can easily point to the problem if lines.lines.len() == 1us { let lo = cm.lookup_char_pos(sp.lo); let mut digits = 0us; let mut num = (lines.lines[0] + 1us) / 10us; // how many digits must be indent past? while num > 0us { num /= 10us; digits += 1us; } // indent past |name:## | and the 0-offset column location let left = fm.name.len() + digits + lo.col.to_usize() + 3us; let mut s = String::new(); // Skip is the number of characters we need to skip because they are // part of the 'filename:line'part of the previous line. let skip = fm.name.len() + digits + 3us; for _ in range(0, skip) { s.push(' '); } if let Some(orig) = fm.get_line(lines.lines[0]) { for pos in range(0us, left - skip) { let cur_char = orig.as_bytes()[pos] as char; // Whenever a tab occurs on the previous line, we insert one on // the error-point-squiggly-line as well (instead of a space). // That way the squiggly line will usually appear in the correct // position. match cur_char { '\t' => s.push('\t'), _ => s.push(' '), }; } } try!(write!(&mut err.dst, "{}", s)); let mut s = String::from_str("^"); let hi = cm.lookup_char_pos(sp.hi); if hi.col!= lo.col { // the ^ already takes up one space let num_squigglies = hi.col.to_usize() - lo.col.to_usize() - 1us; for _ in range(0, num_squigglies) { s.push('~'); } } try!(print_maybe_styled(err, &format!("{}\n", s)[], term::attr::ForegroundColor(lvl.color()))); } Ok(()) } /// Here are the differences between this and the normal `highlight_lines`: /// `custom_highlight_lines` will always put arrow on the last byte of the /// span (instead of the first byte). Also, when the span is too long (more /// than 6 lines), `custom_highlight_lines` will print the first line, then /// dot dot dot, then last line, whereas `highlight_lines` prints the first /// six lines. fn custom_highlight_lines(w: &mut EmitterWriter, cm: &codemap::CodeMap, sp: Span, lvl: Level, lines: codemap::FileLines) -> io::IoResult<()> { let fm = &*lines.file; let lines = &lines.lines[]; if lines.len() > MAX_LINES { if let Some(line) = fm.get_line(lines[0]) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, lines[0] + 1, line)); } try!(write!(&mut w.dst, "...\n")); let last_line_number = lines[lines.len() - 1]; if let Some(last_line) = fm.get_line(last_line_number) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, last_line_number + 1, last_line)); } } else { for &line_number in lines.iter() { if let Some(line) = fm.get_line(line_number) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
fmt
identifier_name
issue-7013.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. use std::rc::Rc; use std::cell::RefCell; trait Foo { fn set(&mut self, v: Rc<RefCell<A>>); } struct B { v: Option<Rc<RefCell<A>>> } impl Foo for B { fn set(&mut self, v: Rc<RefCell<A>>) { self.v = Some(v); } } struct A { v: ~Foo:Send, } fn
() { let a = A {v: ~B{v: None} as ~Foo:Send}; //~^ ERROR cannot pack type `~B`, which does not fulfill `Send` let v = Rc::new(RefCell::new(a)); let w = v.clone(); let b = &*v; let mut b = b.borrow_mut(); b.v.set(w.clone()); }
main
identifier_name
issue-7013.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. use std::rc::Rc; use std::cell::RefCell; trait Foo { fn set(&mut self, v: Rc<RefCell<A>>); } struct B { v: Option<Rc<RefCell<A>>> }
} } struct A { v: ~Foo:Send, } fn main() { let a = A {v: ~B{v: None} as ~Foo:Send}; //~^ ERROR cannot pack type `~B`, which does not fulfill `Send` let v = Rc::new(RefCell::new(a)); let w = v.clone(); let b = &*v; let mut b = b.borrow_mut(); b.v.set(w.clone()); }
impl Foo for B { fn set(&mut self, v: Rc<RefCell<A>>) { self.v = Some(v);
random_line_split
mind.rs
.intersection(file) .pincount(); if blue_servants_in_line > 1 { valuation += 0.5 * f32::from(blue_servants_in_line - 1); } } // servants should aspire to something more in life someday let orange_subascendants = world.orange_servants .intersection(high_seventh) .pincount(); valuation += 1.8 * f32::from(orange_subascendants); let high_colonelcy = Pinfield(HIGH_COLONELCY); let orange_subsubascendants = world.orange_servants .intersection(high_colonelcy) .pincount(); valuation += 0.6 * f32::from(orange_subsubascendants); let blue_subascendants = world.blue_servants .intersection(low_seventh) .pincount(); valuation -= 1.8 * f32::from(blue_subascendants); let low_colonelcy = Pinfield(LOW_COLONELCY); let blue_subsubascendants = world.blue_servants .intersection(low_colonelcy) .pincount(); valuation -= 0.6 * f32::from(blue_subsubascendants); // secret service eligbility has option value if world.orange_west_service_eligibility() || world.orange_east_service_eligibility() { valuation += 0.1 } if world.blue_west_service_eligibility() || world.blue_east_service_eligibility() { valuation -= 0.1 } valuation } fn mvv_lva_heuristic(commit: &Commit) -> f32 { // https://chessprogramming.wikispaces.com/MVV-LVA match commit.hospitalization { Some(patient) => { (figurine_valuation(patient) - figurine_valuation(commit.patch.star)) } None => 0.0, } } fn order_movements_intuitively( experience: &fnv::FnvHashMap<Patch, u32>, commits: &mut Vec<Commit>) -> Vec<Commit> { let mut sorted: Vec<(Commit, Option<&u32>, f32)> = Vec::with_capacity(commits.len()); for c in commits { sorted.push((*c, experience.get(&c.patch), mvv_lva_heuristic(&c))); } sorted.sort_unstable_by(|a, b| { match b.1.cmp(&a.1) { Ordering::Equal => b.2.partial_cmp(&a.2).unwrap_or(Ordering::Equal), other => other, } }); sorted.iter().map(|c| { c.0 }).collect() } pub type Variation = Vec<Patch>; #[allow(ptr_arg)] pub fn pagan_variation_format(variation: &Variation) -> String { variation.iter() .map(|p| p.abbreviated_pagan_movement_rune()) .collect::<Vec<_>>() .join(" ") } pub trait Memory: Clone + Send { fn recombine(&mut self, other: Self); fn flash(patch: Patch) -> Self; fn blank() -> Self; fn readable(&self) -> String; } impl Memory for Patch { fn recombine(&mut self, other: Self) { self.star = other.star; self.whence = other.whence; self.whither = other.whither; } fn flash(patch: Patch) -> Self { patch } fn blank() -> Self { // deliberately illegal hyperspace warp from the Figurehead; possibly useful for debugging. // a "blank" commit isn't really a thing. Patch { star: Agent::new(Team::Orange, JobDescription::Figurehead), whence: Locale::new(0, 0), whither: Locale::new(7, 7), } } fn readable(&self) -> String { self.abbreviated_pagan_movement_rune() } } impl Memory for Variation { fn recombine(&mut self, other: Self) { self.extend(other); } fn flash(patch: Patch) -> Self { vec![patch] } fn blank() -> Self { vec![] } fn readable(&self) -> String { pagan_variation_format(&self) } } #[derive(Clone)] pub struct Lodestar<T: Memory> { pub score: f32, pub memory: T, } impl<T: Memory> Lodestar<T> { fn new(score: f32, memory: T) -> Self { Self { score, memory, } } } impl<T: Memory> fmt::Debug for Lodestar<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Lodestar {{ score: {}, memory: {} }}", self.score, self.memory.readable()) } } #[derive(Eq,PartialEq,Hash)] pub struct SpaceTime { world_state: WorldState, instant: i8, } impl SpaceTime { fn new(world_state: WorldState, instant: i8) -> Self { Self { world_state, instant } } } #[allow(too_many_arguments)] pub fn α_β_negamax_search<T: Memory>( world: WorldState, depth: i8, mut α: f32, β: f32, memory_bank: Arc<parking_lot::Mutex<LruCache<SpaceTime, Lodestar<T>, BuildHasherDefault<XxHash>>>>, intuition_bank: Arc<parking_lot::Mutex<fnv::FnvHashMap<Patch, u32>>>, quiet: Option<u8>) -> Lodestar<T> { let mut premonitions = world.reckless_lookahead(); let mut optimum = NEG_INFINITY; let mut optimand = T::blank(); if depth <= 0 || premonitions.is_empty() { let potential_score = orientation(world.initiative) * score(world); match quiet { None => { return Lodestar::new(potential_score, T::blank()); }, Some(extension) => { if depth.abs() >= extension as i8 { return Lodestar::new(potential_score, T::blank()); } premonitions = premonitions.into_iter() .filter(|c| c.hospitalization.is_some()) .collect::<Vec<_>>(); if premonitions.is_empty() { return Lodestar::new(potential_score, T::blank()) } else { optimum = potential_score; } } } }; // Note: if sorting by heuristic were sufficiently expensive, it would, on balance, be better // to do so only at the higher levels of the tree. From some minor empiric testing, though, // sorting only at depth >= 1 has no performance impact, and at depth >=2 has a negative // performance impact. So that's not the way to go. { let experience = intuition_bank.lock(); premonitions = order_movements_intuitively(&experience, &mut premonitions) } for premonition in premonitions { let mut value = NEG_INFINITY; // can't hurt to be pessimistic let mut memory: T = T::flash(premonition.patch); let cached: bool; let space_time = SpaceTime::new(premonition.tree, depth); { let mut open_vault = memory_bank.lock(); let remembered_lodestar_maybe = open_vault.get_mut(&space_time); match remembered_lodestar_maybe { Some(remembered_lodestar) => { cached = true; value = remembered_lodestar.score; memory.recombine(remembered_lodestar.memory.clone()); } None => { cached = false; } }; } if!cached { let mut lodestar = α_β_negamax_search( premonition.tree, depth - 1, -β, -α, memory_bank.clone(), intuition_bank.clone(), quiet ); lodestar.score *= -1.; // nega- value = lodestar.score; memory.recombine(lodestar.memory.clone()); memory_bank.lock().insert( space_time, lodestar, ); } if value > optimum { optimum = value; optimand = memory; } if value > α { α = value; } if α >= β { if depth > 0 { // not a quietness extension let mut open_vault = intuition_bank.lock(); let intuition = open_vault.entry(premonition.patch) .or_insert(0); *intuition += 2u32.pow(depth as u32); } break; // cutoff! } } Lodestar::new(optimum, optimand) } pub fn déjà_vu_table_size_bound<T: Memory>(gib: f32) -> usize { let bound = usize::from(Bytes::gibi(gib)) / (mem::size_of::<SpaceTime>() + mem::size_of::<Lodestar<T>>()); bound } pub fn potentially_timebound_kickoff<T:'static + Memory>( world: &WorldState, depth: u8, extension_maybe: Option<u8>, nihilistically: bool, deadline_maybe: Option<time::Timespec>, intuition_bank: Arc<parking_lot::Mutex<fnv::FnvHashMap<Patch, u32>>>, déjà_vu_bound: f32) -> Option<Vec<(Commit, f32, T)>> { let déjà_vu_table: LruCache<SpaceTime, Lodestar<T>, BuildHasherDefault<XxHash>> = LruCache::with_hash_state(déjà_vu_table_size_bound::<T>(déjà_vu_bound), Default::default()); let memory_bank = Arc::new(parking_lot::Mutex::new(déjà_vu_table)); let mut premonitions = if nihilistically { world.reckless_lookahead() } else { world.lookahead() }; { let experience = intuition_bank.lock(); premonitions = order_movements_intuitively(&experience, &mut premonitions) } let mut forecasts = Vec::with_capacity(40); let mut time_radios: Vec<(Commit, mpsc::Receiver<Lodestar<T>>)> = Vec::new(); for &premonition in &premonitions { let travel_memory_bank = memory_bank.clone(); let travel_intuition_bank = intuition_bank.clone(); let (tx, rx) = mpsc::channel(); let explorer_radio = tx.clone(); time_radios.push((premonition, rx)); thread::spawn(move || { let search_hit: Lodestar<T> = α_β_negamax_search( premonition.tree, (depth - 1) as i8, NEG_INFINITY, INFINITY, travel_memory_bank, travel_intuition_bank, extension_maybe ); explorer_radio.send(search_hit).ok(); }); } while!time_radios.is_empty() { // polling for results if let Some(deadline) = deadline_maybe { if time::get_time() > deadline { return None; } } // iterate over indices so that we can use swap_remove during the loop for i in (0..time_radios.len()).rev() { let premonition = time_radios[i].0; if let Ok(search_hit) = time_radios[i].1.try_recv() { let value = -search_hit.score; let mut full_variation = T::flash(premonition.patch); full_variation.recombine(search_hit.memory); forecasts.push((premonition, value, full_variation)); time_radios.swap_remove(i); } } thread::sleep(Duration::from_millis(2)); debug!("waiting for {} of {} first-movement search threads", time_radios.len(), premonitions.len()) } forecasts.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(Ordering::Equal)); Some(forecasts) } pub fn kickoff<T:'static + Memory>(world: &WorldState, depth: u8, extension: Option<u8>, nihilistically: bool, déjà_vu_bound: f32) -> Vec<(Commit, f32, T)> { let experience_table: fnv::FnvHashMap<Patch, u32> = fnv::FnvHashMap::default(); let intuition_bank = Arc::new(parking_lot::Mutex::new(experience_table)); potentially_timebound_kickoff::<T>(world, depth, extension, nihilistically, None, intuition_bank, déjà_vu_bound).unwrap() } pub fn iterative_deepening_kickoff<T:'static + Memory>(world: &WorldState, timeout: time::Duration, nihilistically: bool, déjà_vu_bound: f32) -> (Vec<(Commit, f32, T)>, u8) { let deadline = time::get_time() + timeout; let mut depth = 1; let experience_table = fnv::FnvHashMap::default(); let intuition_bank = Arc::new(parking_lot::Mutex::new(experience_table)); let mut forecasts = potentially_timebound_kickoff( world, depth, None, nihilistically, None, intuition_bank.clone(), déjà_vu_bound).unwrap(); while let Some(prophecy) = potentially_timebound_kickoff::<T>( world, depth, None, nihilistically, Some(deadline), intuition_bank.clone(), déjà_vu_bound) { forecasts = prophecy; depth += 1; } (forecasts, depth-1) } #[allow(needless_pass_by_value)] // `depth_sequence` pub fn fixed_depth_sequence_kickoff<T:'static + Memory>(world: &WorldState, depth_sequence: Vec<u8>, nihilistically: bool, déjà_vu_bound: f32) -> Vec<(Commit, f32, T)> { let mut depths = depth_sequence.iter(); let experience_table = fnv::FnvHashMap::default(); let intuition_bank = Arc::new(parking_lot::Mutex::new(experience_table)); let mut forecasts = potentially_timebound_kickoff::<T>( world, *depths.next().expect("`depth_sequence` should be nonempty"), None, nihilistically, None, intuition_bank.clone(), déjà_vu_bound ).unwrap(); for &depth in depths { forecasts = potentially_timebound_kickoff::<T>( world, depth, None, nihilistically, None, intuition_bank.clone(), déjà_vu_bound).unwrap(); } forecasts } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use time; use super::{REWARD_FOR_INITIATIVE, kickoff, score, SpaceTime, Variation}; use space::Locale; use life::{WorldState, Patch}; use fnv; use twox_hash::XxHash; use std::hash::Hash; use std::collections::hash_map; use identity::{Agent, JobDescription, Team}; const MOCK_DÉJÀ_VU_BOUND: f32 = 2.0; impl WorldState { fn no_castling_at_all(&mut self) { self.clear_orange_east_service_eligibility(); self.clear_orange_west_service_eligibility(); self.clear_blue_east_service_eligibility(); self.clear_blue_west_service_eligibility(); } } #[bench] fn benchmark_hashing_spacetime_fnv(b: &mut Bencher) { let w = WorldState::new(); let st = SpaceTime::new(w, 3); let mut hasher = fnv::FnvHasher::default(); b.iter(|| { for _ in 0..1000 { st.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_spacetime_xx(b: &mut Bencher) { let w = WorldState::new(); let mut hasher = XxHash::default(); let st = SpaceTime::new(w, 3); b.iter(|| { for _ in 0..1000 { st.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_spacetime_sip(b: &mut Bencher) { let w = WorldState::new(); let mut hasher = hash_map::DefaultHasher::new(); let st = SpaceTime::new(w, 3); b.iter(|| { for _ in 0..1000 { st.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_patch_fnv(b: &mut Bencher) { let mut hasher = fnv::FnvHasher::default(); let p = Patch { star: Agent { team: Team::Orange, job_description: JobDescription::Figurehead, }, whence: Locale::new(1, 2), whither: Locale::new(3, 4) }; b.iter(|| { for _ in 0..1000 { p.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_patch_xx(b: &mut Bencher) { let mut hasher = XxHash::default(); let p = Patch { star: Agent { team: Team::Orange, job_description: JobDescription::Figurehead, }, whence: Locale::new(1, 2), whither: Locale::new(3, 4) }; b.iter(|| { for _ in 0..1000 { p.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_patch_sip(b: &mut Bencher) { let mut hasher = hash_map::DefaultHasher::new(); let p = Patch { star: Agent { team: Team::Orange, job_description: JobDescription::Figurehead, }, whence: Locale::new(1, 2), whither: Locale::new(3, 4) }; b.iter(|| { for _ in 0..1000 { p.hash(&mut hasher); } }); } #[bench] fn benchmark_scoring(b: &mut Bencher) { b.iter(|| score(WorldState::new())); } #[bench] fn benchmark_kickoff_depth_1(b: &mut Bencher) { let ws = WorldState::new(); b.iter(|| kickoff::<Patch>(&ws, 1, None, true, MOCK_DÉJÀ_VU_BOUND)); } #[bench] fn benchmark_kickoff_depth_2_arbys(b: &mut Bencher
) { let ws = WorldState
identifier_name
mind.rs
.pincount(); valuation -= 1.8 * f32::from(blue_subascendants); let low_colonelcy = Pinfield(LOW_COLONELCY); let blue_subsubascendants = world.blue_servants .intersection(low_colonelcy) .pincount(); valuation -= 0.6 * f32::from(blue_subsubascendants); // secret service eligbility has option value if world.orange_west_service_eligibility() || world.orange_east_service_eligibility() { valuation += 0.1 } if world.blue_west_service_eligibility() || world.blue_east_service_eligibility() { valuation -= 0.1 } valuation } fn mvv_lva_heuristic(commit: &Commit) -> f32 { // https://chessprogramming.wikispaces.com/MVV-LVA match commit.hospitalization { Some(patient) => { (figurine_valuation(patient) - figurine_valuation(commit.patch.star)) } None => 0.0, } } fn order_movements_intuitively( experience: &fnv::FnvHashMap<Patch, u32>, commits: &mut Vec<Commit>) -> Vec<Commit> { let mut sorted: Vec<(Commit, Option<&u32>, f32)> = Vec::with_capacity(commits.len()); for c in commits { sorted.push((*c, experience.get(&c.patch), mvv_lva_heuristic(&c))); } sorted.sort_unstable_by(|a, b| { match b.1.cmp(&a.1) { Ordering::Equal => b.2.partial_cmp(&a.2).unwrap_or(Ordering::Equal), other => other, } }); sorted.iter().map(|c| { c.0 }).collect() } pub type Variation = Vec<Patch>; #[allow(ptr_arg)] pub fn pagan_variation_format(variation: &Variation) -> String { variation.iter() .map(|p| p.abbreviated_pagan_movement_rune()) .collect::<Vec<_>>() .join(" ") } pub trait Memory: Clone + Send { fn recombine(&mut self, other: Self); fn flash(patch: Patch) -> Self; fn blank() -> Self; fn readable(&self) -> String; } impl Memory for Patch { fn recombine(&mut self, other: Self) { self.star = other.star; self.whence = other.whence; self.whither = other.whither; } fn flash(patch: Patch) -> Self { patch } fn blank() -> Self { // deliberately illegal hyperspace warp from the Figurehead; possibly useful for debugging. // a "blank" commit isn't really a thing. Patch { star: Agent::new(Team::Orange, JobDescription::Figurehead), whence: Locale::new(0, 0), whither: Locale::new(7, 7), } } fn readable(&self) -> String { self.abbreviated_pagan_movement_rune() } } impl Memory for Variation { fn recombine(&mut self, other: Self) { self.extend(other); } fn flash(patch: Patch) -> Self { vec![patch] } fn blank() -> Self { vec![] } fn readable(&self) -> String { pagan_variation_format(&self) } } #[derive(Clone)] pub struct Lodestar<T: Memory> { pub score: f32, pub memory: T, } impl<T: Memory> Lodestar<T> { fn new(score: f32, memory: T) -> Self { Self { score, memory, } } } impl<T: Memory> fmt::Debug for Lodestar<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Lodestar {{ score: {}, memory: {} }}", self.score, self.memory.readable()) } } #[derive(Eq,PartialEq,Hash)] pub struct SpaceTime { world_state: WorldState, instant: i8, } impl SpaceTime { fn new(world_state: WorldState, instant: i8) -> Self { Self { world_state, instant } } } #[allow(too_many_arguments)] pub fn α_β_negamax_search<T: Memory>( world: WorldState, depth: i8, mut α: f32, β: f32, memory_bank: Arc<parking_lot::Mutex<LruCache<SpaceTime, Lodestar<T>, BuildHasherDefault<XxHash>>>>, intuition_bank: Arc<parking_lot::Mutex<fnv::FnvHashMap<Patch, u32>>>, quiet: Option<u8>) -> Lodestar<T> { let mut premonitions = world.reckless_lookahead(); let mut optimum = NEG_INFINITY; let mut optimand = T::blank(); if depth <= 0 || premonitions.is_empty() { let potential_score = orientation(world.initiative) * score(world); match quiet { None => { return Lodestar::new(potential_score, T::blank()); }, Some(extension) => { if depth.abs() >= extension as i8 { return Lodestar::new(potential_score, T::blank()); } premonitions = premonitions.into_iter() .filter(|c| c.hospitalization.is_some()) .collect::<Vec<_>>(); if premonitions.is_empty() { return Lodestar::new(potential_score, T::blank()) } else { optimum = potential_score; } } } }; // Note: if sorting by heuristic were sufficiently expensive, it would, on balance, be better // to do so only at the higher levels of the tree. From some minor empiric testing, though, // sorting only at depth >= 1 has no performance impact, and at depth >=2 has a negative // performance impact. So that's not the way to go. { let experience = intuition_bank.lock(); premonitions = order_movements_intuitively(&experience, &mut premonitions) } for premonition in premonitions { let mut value = NEG_INFINITY; // can't hurt to be pessimistic let mut memory: T = T::flash(premonition.patch); let cached: bool; let space_time = SpaceTime::new(premonition.tree, depth); { let mut open_vault = memory_bank.lock(); let remembered_lodestar_maybe = open_vault.get_mut(&space_time); match remembered_lodestar_maybe { Some(remembered_lodestar) => { cached = true; value = remembered_lodestar.score; memory.recombine(remembered_lodestar.memory.clone()); } None => { cached = false; } }; } if!cached { let mut lodestar = α_β_negamax_search( premonition.tree, depth - 1, -β, -α, memory_bank.clone(), intuition_bank.clone(), quiet ); lodestar.score *= -1.; // nega- value = lodestar.score; memory.recombine(lodestar.memory.clone()); memory_bank.lock().insert( space_time, lodestar, ); } if value > optimum { optimum = value; optimand = memory; } if value > α { α = value; } if α >= β { if depth > 0 { // not a quietness extension let mut open_vault = intuition_bank.lock(); let intuition = open_vault.entry(premonition.patch) .or_insert(0); *intuition += 2u32.pow(depth as u32); } break; // cutoff! } } Lodestar::new(optimum, optimand) } pub fn déjà_vu_table_size_bound<T: Memory>(gib: f32) -> usize { let bound = usize::from(Bytes::gibi(gib)) / (mem::size_of::<SpaceTime>() + mem::size_of::<Lodestar<T>>()); bound } pub fn potentially_timebound_kickoff<T:'static + Memory>( world: &WorldState, depth: u8, extension_maybe: Option<u8>, nihilistically: bool, deadline_maybe: Option<time::Timespec>, intuition_bank: Arc<parking_lot::Mutex<fnv::FnvHashMap<Patch, u32>>>, déjà_vu_bound: f32) -> Option<Vec<(Commit, f32, T)>> { let déjà_vu_table: LruCache<SpaceTime, Lodestar<T>, BuildHasherDefault<XxHash>> = LruCache::with_hash_state(déjà_vu_table_size_bound::<T>(déjà_vu_bound), Default::default()); let memory_bank = Arc::new(parking_lot::Mutex::new(déjà_vu_table)); let mut premonitions = if nihilistically { world.reckless_lookahead() } else { world.lookahead() }; { let experience = intuition_bank.lock(); premonitions = order_movements_intuitively(&experience, &mut premonitions) } let mut forecasts = Vec::with_capacity(40); let mut time_radios: Vec<(Commit, mpsc::Receiver<Lodestar<T>>)> = Vec::new(); for &premonition in &premonitions { let travel_memory_bank = memory_bank.clone(); let travel_intuition_bank = intuition_bank.clone(); let (tx, rx) = mpsc::channel(); let explorer_radio = tx.clone(); time_radios.push((premonition, rx)); thread::spawn(move || { let search_hit: Lodestar<T> = α_β_negamax_search( premonition.tree, (depth - 1) as i8, NEG_INFINITY, INFINITY, travel_memory_bank, travel_intuition_bank, extension_maybe ); explorer_radio.send(search_hit).ok(); }); } while!time_radios.is_empty() { // polling for results if let Some(deadline) = deadline_maybe { if time::get_time() > deadline { return None; } } // iterate over indices so that we can use swap_remove during the loop for i in (0..time_radios.len()).rev() { let premonition = time_radios[i].0; if let Ok(search_hit) = time_radios[i].1.try_recv() { let value = -search_hit.score; let mut full_variation = T::flash(premonition.patch); full_variation.recombine(search_hit.memory); forecasts.push((premonition, value, full_variation)); time_radios.swap_remove(i); } } thread::sleep(Duration::from_millis(2)); debug!("waiting for {} of {} first-movement search threads", time_radios.len(), premonitions.len()) } forecasts.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(Ordering::Equal)); Some(forecasts) } pub fn kickoff<T:'static + Memory>(world: &WorldState, depth: u8, extension: Option<u8>, nihilistically: bool, déjà_vu_bound: f32) -> Vec<(Commit, f32, T)> { let experience_table: fnv::FnvHashMap<Patch, u32> = fnv::FnvHashMap::default(); let intuition_bank = Arc::new(parking_lot::Mutex::new(experience_table)); potentially_timebound_kickoff::<T>(world, depth, extension, nihilistically, None, intuition_bank, déjà_vu_bound).unwrap() } pub fn iterative_deepening_kickoff<T:'static + Memory>(world: &WorldState, timeout: time::Duration, nihilistically: bool, déjà_vu_bound: f32) -> (Vec<(Commit, f32, T)>, u8) { let deadline = time::get_time() + timeout; let mut depth = 1; let experience_table = fnv::FnvHashMap::default(); let intuition_bank = Arc::new(parking_lot::Mutex::new(experience_table)); let mut forecasts = potentially_timebound_kickoff( world, depth, None, nihilistically, None, intuition_bank.clone(), déjà_vu_bound).unwrap(); while let Some(prophecy) = potentially_timebound_kickoff::<T>( world, depth, None, nihilistically, Some(deadline), intuition_bank.clone(), déjà_vu_bound) { forecasts = prophecy; depth += 1; } (forecasts, depth-1) } #[allow(needless_pass_by_value)] // `depth_sequence` pub fn fixed_depth_sequence_kickoff<T:'static + Memory>(world: &WorldState, depth_sequence: Vec<u8>, nihilistically: bool, déjà_vu_bound: f32) -> Vec<(Commit, f32, T)> { let mut depths = depth_sequence.iter(); let experience_table = fnv::FnvHashMap::default(); let intuition_bank = Arc::new(parking_lot::Mutex::new(experience_table)); let mut forecasts = potentially_timebound_kickoff::<T>( world, *depths.next().expect("`depth_sequence` should be nonempty"), None, nihilistically, None, intuition_bank.clone(), déjà_vu_bound ).unwrap(); for &depth in depths { forecasts = potentially_timebound_kickoff::<T>( world, depth, None, nihilistically, None, intuition_bank.clone(), déjà_vu_bound).unwrap(); } forecasts } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use time; use super::{REWARD_FOR_INITIATIVE, kickoff, score, SpaceTime, Variation}; use space::Locale; use life::{WorldState, Patch}; use fnv; use twox_hash::XxHash; use std::hash::Hash; use std::collections::hash_map; use identity::{Agent, JobDescription, Team}; const MOCK_DÉJÀ_VU_BOUND: f32 = 2.0; impl WorldState { fn no_castling_at_all(&mut self) { self.clear_orange_east_service_eligibility(); self.clear_orange_west_service_eligibility(); self.clear_blue_east_service_eligibility(); self.clear_blue_west_service_eligibility(); } } #[bench] fn benchmark_hashing_spacetime_fnv(b: &mut Bencher) { let w = WorldState::new(); let st = SpaceTime::new(w, 3); let mut hasher = fnv::FnvHasher::default(); b.iter(|| { for _ in 0..1000 { st.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_spacetime_xx(b: &mut Bencher) { let w = WorldState::new(); let mut hasher = XxHash::default(); let st = SpaceTime::new(w, 3); b.iter(|| { for _ in 0..1000 { st.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_spacetime_sip(b: &mut Bencher) { let w = WorldState::new(); let mut hasher = hash_map::DefaultHasher::new(); let st = SpaceTime::new(w, 3); b.iter(|| { for _ in 0..1000 { st.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_patch_fnv(b: &mut Bencher) { let mut hasher = fnv::FnvHasher::default(); let p = Patch { star: Agent { team: Team::Orange, job_description: JobDescription::Figurehead, }, whence: Locale::new(1, 2), whither: Locale::new(3, 4) }; b.iter(|| { for _ in 0..1000 { p.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_patch_xx(b: &mut Bencher) { let mut hasher = XxHash::default(); let p = Patch { star: Agent { team: Team::Orange, job_description: JobDescription::Figurehead, }, whence: Locale::new(1, 2), whither: Locale::new(3, 4) }; b.iter(|| { for _ in 0..1000 { p.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_patch_sip(b: &mut Bencher) { let mut hasher = hash_map::DefaultHasher::new(); let p = Patch { star: Agent { team: Team::Orange, job_description: JobDescription::Figurehead, }, whence: Locale::new(1, 2), whither: Locale::new(3, 4) }; b.iter(|| { for _ in 0..1000 { p.hash(&mut hasher); } }); } #[bench] fn benchmark_scoring(b: &mut Bencher) { b.iter(|| score(WorldState::new())); } #[bench] fn benchmark_kickoff_depth_1(b: &mut Bencher) { let ws = WorldState::new(); b.iter(|| kickoff::<Patch>(&ws, 1, None, true, MOCK_DÉJÀ_VU_BOUND)); } #[bench] fn benchmark_kickoff_depth_2_arbys(b: &mut Bencher) { let ws = WorldState::new(); b.iter(|| kickoff::<Patch>(&ws, 2, None, true, MOCK_DÉJÀ_VU_BOUND)); } #[bench] fn benchmark_kickoff_depth_2_carefully(b: &mut Bencher) { let ws = WorldState::new(); b.iter(|| kickoff::<Patch>(&ws, 2, None, false, MOCK_DÉJÀ_VU_BOUND)); } #[bench] fn benchmark_kickoff_depth_3(b: &mut Bencher) { let ws = WorldState::new(); b.iter(|| kickoff::<Patch>(&ws, 3, None, true, MOCK_DÉJÀ_VU_BOUND)); } #[test] #[ignore] // more research is needed fn concerning_short_circuiting_upon_finding_critical_endangerment() { let ws = WorldState::reconstruct("7K/r7/1r6/8/8/8/8/7k b -"); let start = time::get_time(); kickoff::<Variation>(&ws, 30, None, true, MOCK_DÉJÀ_VU_BOUND); let duration = time::get_time() - start; assert!(duration.num_seconds() < 20); } #[test] #[allow(float_cmp)] fn concerning_fairness_of_the_initial_position() { // It's okay to assume this is really 0.0. Floats may be imprecise,
// but they do have well-defined behavior.
random_line_split
mind.rs
, and a smarter engine might choose more // dynamically, but half-a-point is OK, I think. // Wikipedia has examples where a doubled servant is worth anywhere // from.3 to.75 points. if orange_servants_in_line > 1 { valuation -= 0.5 * f32::from(orange_servants_in_line - 1); } let blue_servants_in_line = world.blue_servants .intersection(file) .pincount(); if blue_servants_in_line > 1 { valuation += 0.5 * f32::from(blue_servants_in_line - 1); } } // servants should aspire to something more in life someday let orange_subascendants = world.orange_servants .intersection(high_seventh) .pincount(); valuation += 1.8 * f32::from(orange_subascendants); let high_colonelcy = Pinfield(HIGH_COLONELCY); let orange_subsubascendants = world.orange_servants .intersection(high_colonelcy) .pincount(); valuation += 0.6 * f32::from(orange_subsubascendants); let blue_subascendants = world.blue_servants .intersection(low_seventh) .pincount(); valuation -= 1.8 * f32::from(blue_subascendants); let low_colonelcy = Pinfield(LOW_COLONELCY); let blue_subsubascendants = world.blue_servants .intersection(low_colonelcy) .pincount(); valuation -= 0.6 * f32::from(blue_subsubascendants); // secret service eligbility has option value if world.orange_west_service_eligibility() || world.orange_east_service_eligibility() { valuation += 0.1 } if world.blue_west_service_eligibility() || world.blue_east_service_eligibility() { valuation -= 0.1 } valuation } fn mvv_lva_heuristic(commit: &Commit) -> f32 { // https://chessprogramming.wikispaces.com/MVV-LVA match commit.hospitalization { Some(patient) => { (figurine_valuation(patient) - figurine_valuation(commit.patch.star)) } None => 0.0, } } fn order_movements_intuitively( experience: &fnv::FnvHashMap<Patch, u32>, commits: &mut Vec<Commit>) -> Vec<Commit> { let mut sorted: Vec<(Commit, Option<&u32>, f32)> = Vec::with_capacity(commits.len()); for c in commits { sorted.push((*c, experience.get(&c.patch), mvv_lva_heuristic(&c))); } sorted.sort_unstable_by(|a, b| { match b.1.cmp(&a.1) { Ordering::Equal => b.2.partial_cmp(&a.2).unwrap_or(Ordering::Equal), other => other, } }); sorted.iter().map(|c| { c.0 }).collect() } pub type Variation = Vec<Patch>; #[allow(ptr_arg)] pub fn pagan_variation_format(variation: &Variation) -> String { variation.iter() .map(|p| p.abbreviated_pagan_movement_rune()) .collect::<Vec<_>>() .join(" ") } pub trait Memory: Clone + Send { fn recombine(&mut self, other: Self); fn flash(patch: Patch) -> Self; fn blank() -> Self; fn readable(&self) -> String; } impl Memory for Patch { fn recombine(&mut self, other: Self) { self.star = other.star; self.whence = other.whence; self.whither = other.whither; } fn flash(patch: Patch) -> Self { patch } fn blank() -> Self { // deliberately illegal hyperspace warp from the Figurehead; possibly useful for debugging. // a "blank" commit isn't really a thing. Patch { star: Agent::new(Team::Orange, JobDescription::Figurehead), whence: Locale::new(0, 0), whither: Locale::new(7, 7), } } fn readable(&self) -> String { self.abbreviated_pagan_movement_rune() } } impl Memory for Variation { fn recombine(&mut self, other: Self) { self.extend(other); } fn flash(patch: Patch) -> Self { vec![patch] } fn blank() -> Self { vec![] } fn readable(&self) -> String { pagan_variation_format(&self) } } #[derive(Clone)] pub struct Lodestar<T: Memory> { pub score: f32, pub memory: T, } impl<T: Memory> Lodestar<T> { fn new(score: f32, memory: T) -> Self { Self { score, memory, } } } impl<T: Memory> fmt::Debug for Lodestar<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Lodestar {{ score: {}, memory: {} }}", self.score, self.memory.readable()) } } #[derive(Eq,PartialEq,Hash)] pub struct SpaceTime { world_state: WorldState, instant: i8, } impl SpaceTime { fn new(world_state: WorldState, instant: i8) -> Self { Self { world_state, instant } } } #[allow(too_many_arguments)] pub fn α_β_negamax_search<T: Memory>( world: WorldState, depth: i8, mut α: f32, β: f32, memory_bank: Arc<parking_lot::Mutex<LruCache<SpaceTime, Lodestar<T>, BuildHasherDefault<XxHash>>>>, intuition_bank: Arc<parking_lot::Mutex<fnv::FnvHashMap<Patch, u32>>>, quiet: Option<u8>) -> Lodestar<T> {
} } } }; // Note: if sorting by heuristic were sufficiently expensive, it would, on balance, be better // to do so only at the higher levels of the tree. From some minor empiric testing, though, // sorting only at depth >= 1 has no performance impact, and at depth >=2 has a negative // performance impact. So that's not the way to go. { let experience = intuition_bank.lock(); premonitions = order_movements_intuitively(&experience, &mut premonitions) } for premonition in premonitions { let mut value = NEG_INFINITY; // can't hurt to be pessimistic let mut memory: T = T::flash(premonition.patch); let cached: bool; let space_time = SpaceTime::new(premonition.tree, depth); { let mut open_vault = memory_bank.lock(); let remembered_lodestar_maybe = open_vault.get_mut(&space_time); match remembered_lodestar_maybe { Some(remembered_lodestar) => { cached = true; value = remembered_lodestar.score; memory.recombine(remembered_lodestar.memory.clone()); } None => { cached = false; } }; } if!cached { let mut lodestar = α_β_negamax_search( premonition.tree, depth - 1, -β, -α, memory_bank.clone(), intuition_bank.clone(), quiet ); lodestar.score *= -1.; // nega- value = lodestar.score; memory.recombine(lodestar.memory.clone()); memory_bank.lock().insert( space_time, lodestar, ); } if value > optimum { optimum = value; optimand = memory; } if value > α { α = value; } if α >= β { if depth > 0 { // not a quietness extension let mut open_vault = intuition_bank.lock(); let intuition = open_vault.entry(premonition.patch) .or_insert(0); *intuition += 2u32.pow(depth as u32); } break; // cutoff! } } Lodestar::new(optimum, optimand) } pub fn déj à_vu_table_size_bound<T: Memory>(gib: f32) -> usize { let bound = usize::from(Bytes::gibi(gib)) / (mem::size_of::<SpaceTime>() + mem::size_of::<Lodestar<T>>()); bound } pub fn potentially_timebound_kickoff<T:'static + Memory>( world: &WorldState, depth: u8, extension_maybe: Option<u8>, nihilistically: bool, deadline_maybe: Option<time::Timespec>, intuition_bank: Arc<parking_lot::Mutex<fnv::FnvHashMap<Patch, u32>>>, déjà_vu_bound: f32) -> Option<Vec<(Commit, f32, T)>> { let déjà_vu_table: LruCache<SpaceTime, Lodestar<T>, BuildHasherDefault<XxHash>> = LruCache::with_hash_state(déjà_vu_table_size_bound::<T>(déjà_vu_bound), Default::default()); let memory_bank = Arc::new(parking_lot::Mutex::new(déjà_vu_table)); let mut premonitions = if nihilistically { world.reckless_lookahead() } else { world.lookahead() }; { let experience = intuition_bank.lock(); premonitions = order_movements_intuitively(&experience, &mut premonitions) } let mut forecasts = Vec::with_capacity(40); let mut time_radios: Vec<(Commit, mpsc::Receiver<Lodestar<T>>)> = Vec::new(); for &premonition in &premonitions { let travel_memory_bank = memory_bank.clone(); let travel_intuition_bank = intuition_bank.clone(); let (tx, rx) = mpsc::channel(); let explorer_radio = tx.clone(); time_radios.push((premonition, rx)); thread::spawn(move || { let search_hit: Lodestar<T> = α_β_negamax_search( premonition.tree, (depth - 1) as i8, NEG_INFINITY, INFINITY, travel_memory_bank, travel_intuition_bank, extension_maybe ); explorer_radio.send(search_hit).ok(); }); } while!time_radios.is_empty() { // polling for results if let Some(deadline) = deadline_maybe { if time::get_time() > deadline { return None; } } // iterate over indices so that we can use swap_remove during the loop for i in (0..time_radios.len()).rev() { let premonition = time_radios[i].0; if let Ok(search_hit) = time_radios[i].1.try_recv() { let value = -search_hit.score; let mut full_variation = T::flash(premonition.patch); full_variation.recombine(search_hit.memory); forecasts.push((premonition, value, full_variation)); time_radios.swap_remove(i); } } thread::sleep(Duration::from_millis(2)); debug!("waiting for {} of {} first-movement search threads", time_radios.len(), premonitions.len()) } forecasts.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(Ordering::Equal)); Some(forecasts) } pub fn kickoff<T:'static + Memory>(world: &WorldState, depth: u8, extension: Option<u8>, nihilistically: bool, déjà_vu_bound: f32) -> Vec<(Commit, f32, T)> { let experience_table: fnv::FnvHashMap<Patch, u32> = fnv::FnvHashMap::default(); let intuition_bank = Arc::new(parking_lot::Mutex::new(experience_table)); potentially_timebound_kickoff::<T>(world, depth, extension, nihilistically, None, intuition_bank, déjà_vu_bound).unwrap() } pub fn iterative_deepening_kickoff<T:'static + Memory>(world: &WorldState, timeout: time::Duration, nihilistically: bool, déjà_vu_bound: f32) -> (Vec<(Commit, f32, T)>, u8) { let deadline = time::get_time() + timeout; let mut depth = 1; let experience_table = fnv::FnvHashMap::default(); let intuition_bank = Arc::new(parking_lot::Mutex::new(experience_table)); let mut forecasts = potentially_timebound_kickoff( world, depth, None, nihilistically, None, intuition_bank.clone(), déjà_vu_bound).unwrap(); while let Some(prophecy) = potentially_timebound_kickoff::<T>( world, depth, None, nihilistically, Some(deadline), intuition_bank.clone(), déjà_vu_bound) { forecasts = prophecy; depth += 1; } (forecasts, depth-1) } #[allow(needless_pass_by_value)] // `depth_sequence` pub fn fixed_depth_sequence_kickoff<T:'static + Memory>(world: &WorldState, depth_sequence: Vec<u8>, nihilistically: bool, déjà_vu_bound: f32) -> Vec<(Commit, f32, T)> { let mut depths = depth_sequence.iter(); let experience_table = fnv::FnvHashMap::default(); let intuition_bank = Arc::new(parking_lot::Mutex::new(experience_table)); let mut forecasts = potentially_timebound_kickoff::<T>( world, *depths.next().expect("`depth_sequence` should be nonempty"), None, nihilistically, None, intuition_bank.clone(), déjà_vu_bound ).unwrap(); for &depth in depths { forecasts = potentially_timebound_kickoff::<T>( world, depth, None, nihilistically, None, intuition_bank.clone(), déjà_vu_bound).unwrap(); } forecasts } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use time; use super::{REWARD_FOR_INITIATIVE, kickoff, score, SpaceTime, Variation}; use space::Locale; use life::{WorldState, Patch}; use fnv; use twox_hash::XxHash; use std::hash::Hash; use std::collections::hash_map; use identity::{Agent, JobDescription, Team}; const MOCK_DÉJÀ_VU_BOUND: f32 = 2.0; impl WorldState { fn no_castling_at_all(&mut self) { self.clear_orange_east_service_eligibility(); self.clear_orange_west_service_eligibility(); self.clear_blue_east_service_eligibility(); self.clear_blue_west_service_eligibility(); } } #[bench] fn benchmark_hashing_spacetime_fnv(b: &mut Bencher) { let w = WorldState::new(); let st = SpaceTime::new(w, 3); let mut hasher = fnv::FnvHasher::default(); b.iter(|| { for _ in 0..1000 { st.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_spacetime_xx(b: &mut Bencher) { let w = WorldState::new(); let mut hasher = XxHash::default(); let st = SpaceTime::new(w, 3); b.iter(|| { for _ in 0..1000 { st.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_spacetime_sip(b: &mut Bencher) { let w = WorldState::new(); let mut hasher = hash_map::DefaultHasher::new(); let st = SpaceTime::new(w, 3); b.iter(|| { for _ in 0..1000 { st.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_patch_fnv(b: &mut Bencher) { let mut hasher = fnv::FnvHasher::default(); let p = Patch { star: Agent { team: Team::Orange, job_description: JobDescription::Figurehead, }, whence: Locale::new(1, 2), whither: Locale::new(3, 4) }; b.iter(|| { for _ in 0..1000 { p.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_patch_xx(b: &mut Bencher) { let mut hasher = XxHash::default(); let p = Patch { star: Agent { team: Team::Orange, job_description: JobDescription::Figurehead, }, whence: Locale::new(1, 2), whither: Locale::new(3, 4) }; b.iter(|| { for _ in 0..1000 { p.hash(&mut hasher); } }); } #[bench] fn benchmark_hashing_patch_sip(b: &mut Bencher) { let mut hasher = hash_map::DefaultHasher::new(); let p = Patch { star: Agent { team: Team::Orange, job_description: JobDescription::Figurehead, }, whence: Locale::new(1, 2), whither: Locale::new(3, 4) }; b.iter(|| { for _ in 0..1000 { p.hash(&mut hasher); }
let mut premonitions = world.reckless_lookahead(); let mut optimum = NEG_INFINITY; let mut optimand = T::blank(); if depth <= 0 || premonitions.is_empty() { let potential_score = orientation(world.initiative) * score(world); match quiet { None => { return Lodestar::new(potential_score, T::blank()); }, Some(extension) => { if depth.abs() >= extension as i8 { return Lodestar::new(potential_score, T::blank()); } premonitions = premonitions.into_iter() .filter(|c| c.hospitalization.is_some()) .collect::<Vec<_>>(); if premonitions.is_empty() { return Lodestar::new(potential_score, T::blank()) } else { optimum = potential_score;
identifier_body
statistics.rs
use std::cmp; use crate::sketch_schemes::KmerCount; pub fn cardinality(sketch: &[KmerCount]) -> Result<u64, &'static str> { // Other (possibly more accurate) possibilities: // "hyper log-log" estimate from lowest value? // multiset distribution applied to total count number? // "AKMV" approach: http://people.mpi-inf.mpg.de/~rgemulla/publications/beyer07distinct.pdf // fast and simple k-minimum value estimate // https://research.neustar.biz/2012/07/09/sketch-of-the-day-k-minimum-values/ if sketch.is_empty() { return Ok(0u64); } Ok(((sketch.len() - 1) as f32 / (sketch.last().unwrap().hash as f32 / usize::max_value() as f32)) as u64) } /// Generates a Vec of numbers of kmers for each coverage level /// /// For example, a size 1000 sketch of the same genome repeated 5 times (e.g. 5x coverage) should /// produce a "histogram" like [0, 0, 0, 0, 1000] (assuming no repetative kmers in the genome) /// pub fn hist(sketch: &[KmerCount]) -> Vec<u64> { let mut counts = vec![0u64; 65536]; let mut max_count: u64 = 0; for kmer in sketch { max_count = cmp::max(max_count, u64::from(kmer.count)); counts[kmer.count as usize - 1] += 1; } counts.truncate(max_count as usize); counts } #[test] fn test_hist()
extra_count: 0, label: None, }, ]; let hist_data = hist(&sketch); assert_eq!(hist_data.len(), 1); assert_eq!(hist_data[0], 3); let sketch = vec![ KmerCount { hash: 1, kmer: vec![], count: 4, extra_count: 0, label: None, }, KmerCount { hash: 2, kmer: vec![], count: 2, extra_count: 0, label: None, }, KmerCount { hash: 3, kmer: vec![], count: 4, extra_count: 0, label: None, }, KmerCount { hash: 4, kmer: vec![], count: 3, extra_count: 0, label: None, }, ]; let hist_data = hist(&sketch); assert_eq!(hist_data.len(), 4); assert_eq!(hist_data[0], 0); assert_eq!(hist_data[1], 1); assert_eq!(hist_data[2], 1); assert_eq!(hist_data[3], 2); }
{ let sketch = vec![ KmerCount { hash: 1, kmer: vec![], count: 1, extra_count: 0, label: None, }, KmerCount { hash: 2, kmer: vec![], count: 1, extra_count: 0, label: None, }, KmerCount { hash: 3, kmer: vec![], count: 1,
identifier_body
statistics.rs
use std::cmp; use crate::sketch_schemes::KmerCount; pub fn cardinality(sketch: &[KmerCount]) -> Result<u64, &'static str> { // Other (possibly more accurate) possibilities: // "hyper log-log" estimate from lowest value? // multiset distribution applied to total count number? // "AKMV" approach: http://people.mpi-inf.mpg.de/~rgemulla/publications/beyer07distinct.pdf // fast and simple k-minimum value estimate // https://research.neustar.biz/2012/07/09/sketch-of-the-day-k-minimum-values/ if sketch.is_empty() { return Ok(0u64); } Ok(((sketch.len() - 1) as f32 / (sketch.last().unwrap().hash as f32 / usize::max_value() as f32)) as u64) } /// Generates a Vec of numbers of kmers for each coverage level /// /// For example, a size 1000 sketch of the same genome repeated 5 times (e.g. 5x coverage) should /// produce a "histogram" like [0, 0, 0, 0, 1000] (assuming no repetative kmers in the genome) /// pub fn hist(sketch: &[KmerCount]) -> Vec<u64> { let mut counts = vec![0u64; 65536]; let mut max_count: u64 = 0; for kmer in sketch { max_count = cmp::max(max_count, u64::from(kmer.count)); counts[kmer.count as usize - 1] += 1; } counts.truncate(max_count as usize); counts } #[test] fn test_hist() { let sketch = vec![ KmerCount { hash: 1, kmer: vec![], count: 1, extra_count: 0, label: None, }, KmerCount { hash: 2, kmer: vec![], count: 1,
extra_count: 0, label: None, }, KmerCount { hash: 3, kmer: vec![], count: 1, extra_count: 0, label: None, }, ]; let hist_data = hist(&sketch); assert_eq!(hist_data.len(), 1); assert_eq!(hist_data[0], 3); let sketch = vec![ KmerCount { hash: 1, kmer: vec![], count: 4, extra_count: 0, label: None, }, KmerCount { hash: 2, kmer: vec![], count: 2, extra_count: 0, label: None, }, KmerCount { hash: 3, kmer: vec![], count: 4, extra_count: 0, label: None, }, KmerCount { hash: 4, kmer: vec![], count: 3, extra_count: 0, label: None, }, ]; let hist_data = hist(&sketch); assert_eq!(hist_data.len(), 4); assert_eq!(hist_data[0], 0); assert_eq!(hist_data[1], 1); assert_eq!(hist_data[2], 1); assert_eq!(hist_data[3], 2); }
random_line_split
statistics.rs
use std::cmp; use crate::sketch_schemes::KmerCount; pub fn cardinality(sketch: &[KmerCount]) -> Result<u64, &'static str> { // Other (possibly more accurate) possibilities: // "hyper log-log" estimate from lowest value? // multiset distribution applied to total count number? // "AKMV" approach: http://people.mpi-inf.mpg.de/~rgemulla/publications/beyer07distinct.pdf // fast and simple k-minimum value estimate // https://research.neustar.biz/2012/07/09/sketch-of-the-day-k-minimum-values/ if sketch.is_empty() { return Ok(0u64); } Ok(((sketch.len() - 1) as f32 / (sketch.last().unwrap().hash as f32 / usize::max_value() as f32)) as u64) } /// Generates a Vec of numbers of kmers for each coverage level /// /// For example, a size 1000 sketch of the same genome repeated 5 times (e.g. 5x coverage) should /// produce a "histogram" like [0, 0, 0, 0, 1000] (assuming no repetative kmers in the genome) /// pub fn
(sketch: &[KmerCount]) -> Vec<u64> { let mut counts = vec![0u64; 65536]; let mut max_count: u64 = 0; for kmer in sketch { max_count = cmp::max(max_count, u64::from(kmer.count)); counts[kmer.count as usize - 1] += 1; } counts.truncate(max_count as usize); counts } #[test] fn test_hist() { let sketch = vec![ KmerCount { hash: 1, kmer: vec![], count: 1, extra_count: 0, label: None, }, KmerCount { hash: 2, kmer: vec![], count: 1, extra_count: 0, label: None, }, KmerCount { hash: 3, kmer: vec![], count: 1, extra_count: 0, label: None, }, ]; let hist_data = hist(&sketch); assert_eq!(hist_data.len(), 1); assert_eq!(hist_data[0], 3); let sketch = vec![ KmerCount { hash: 1, kmer: vec![], count: 4, extra_count: 0, label: None, }, KmerCount { hash: 2, kmer: vec![], count: 2, extra_count: 0, label: None, }, KmerCount { hash: 3, kmer: vec![], count: 4, extra_count: 0, label: None, }, KmerCount { hash: 4, kmer: vec![], count: 3, extra_count: 0, label: None, }, ]; let hist_data = hist(&sketch); assert_eq!(hist_data.len(), 4); assert_eq!(hist_data[0], 0); assert_eq!(hist_data[1], 1); assert_eq!(hist_data[2], 1); assert_eq!(hist_data[3], 2); }
hist
identifier_name
statistics.rs
use std::cmp; use crate::sketch_schemes::KmerCount; pub fn cardinality(sketch: &[KmerCount]) -> Result<u64, &'static str> { // Other (possibly more accurate) possibilities: // "hyper log-log" estimate from lowest value? // multiset distribution applied to total count number? // "AKMV" approach: http://people.mpi-inf.mpg.de/~rgemulla/publications/beyer07distinct.pdf // fast and simple k-minimum value estimate // https://research.neustar.biz/2012/07/09/sketch-of-the-day-k-minimum-values/ if sketch.is_empty()
Ok(((sketch.len() - 1) as f32 / (sketch.last().unwrap().hash as f32 / usize::max_value() as f32)) as u64) } /// Generates a Vec of numbers of kmers for each coverage level /// /// For example, a size 1000 sketch of the same genome repeated 5 times (e.g. 5x coverage) should /// produce a "histogram" like [0, 0, 0, 0, 1000] (assuming no repetative kmers in the genome) /// pub fn hist(sketch: &[KmerCount]) -> Vec<u64> { let mut counts = vec![0u64; 65536]; let mut max_count: u64 = 0; for kmer in sketch { max_count = cmp::max(max_count, u64::from(kmer.count)); counts[kmer.count as usize - 1] += 1; } counts.truncate(max_count as usize); counts } #[test] fn test_hist() { let sketch = vec![ KmerCount { hash: 1, kmer: vec![], count: 1, extra_count: 0, label: None, }, KmerCount { hash: 2, kmer: vec![], count: 1, extra_count: 0, label: None, }, KmerCount { hash: 3, kmer: vec![], count: 1, extra_count: 0, label: None, }, ]; let hist_data = hist(&sketch); assert_eq!(hist_data.len(), 1); assert_eq!(hist_data[0], 3); let sketch = vec![ KmerCount { hash: 1, kmer: vec![], count: 4, extra_count: 0, label: None, }, KmerCount { hash: 2, kmer: vec![], count: 2, extra_count: 0, label: None, }, KmerCount { hash: 3, kmer: vec![], count: 4, extra_count: 0, label: None, }, KmerCount { hash: 4, kmer: vec![], count: 3, extra_count: 0, label: None, }, ]; let hist_data = hist(&sketch); assert_eq!(hist_data.len(), 4); assert_eq!(hist_data[0], 0); assert_eq!(hist_data[1], 1); assert_eq!(hist_data[2], 1); assert_eq!(hist_data[3], 2); }
{ return Ok(0u64); }
conditional_block
main.rs
#[macro_use] extern crate clap; #[macro_use] extern crate log; extern crate env_logger; extern crate chrono; extern crate responder; use std::env::{self, VarError}; use std::io::{self, Write}; use std::net::SocketAddr; use std::path::Path; use std::process; use clap::{App, Arg, Format}; use log::{LogRecord, LogLevel, LogLevelFilter}; use env_logger::LogBuilder; use chrono::offset::local::Local as LocalTime; use responder::Context; use responder::server; use responder::context::DEFAULT_ADDR; const DEFAULT_CONFIG: &'static str = "responder.yaml"; fn main() { match setup_logger() { Ok(_) => {}, Err(e) => { write!(io::stderr(), "{} {}\n", Format::Error("error:"), e) .expect("Unknown error"); process::exit(1); } }; let matches = App::new("Responder") .version(crate_version!()) .author("Livio Ribeiro <[email protected]>") .about("Web server generator used to serve static responses") .arg(Arg::with_name("config") .short("c") .long("config") .value_name("FILE") .help("Config file used to generate the server") .default_value(DEFAULT_CONFIG) .display_order(1)) .arg(Arg::with_name("bind") .short("b") .long("bind") .value_name("ADDRESS") .help("Address to bind server to") .validator(address_validator) .default_value(DEFAULT_ADDR) .display_order(2)) .arg(Arg::with_name("reload") .short("r") .long("reload") .help("Reload configuration file on every request") .display_order(3)) .get_matches(); let address = if matches.occurrences_of("bind") > 0 { matches.value_of("bind") } else { None }; let config = matches.value_of("config").map(|c| Path::new(c)).unwrap(); let reload = matches.is_present("reload"); match run_server(address, config, reload) { Ok(_) => {} Err(e) => { write!(io::stderr(), "{} {}\n", Format::Error("error:"), e) .expect("Unknown error"); process::exit(1); } } } fn setup_logger() -> Result<(), String> { let format = |record: &LogRecord| { let now = LocalTime::now().time().format("%H:%M:%S"); let rec_level = format!("{}", record.level()); let level = match record.level() { LogLevel::Error => Format::Error(rec_level), LogLevel::Warn => Format::Warning(rec_level), LogLevel::Info => Format::Good(rec_level), LogLevel::Debug | LogLevel::Trace => Format::None(rec_level), }; format!("[{}] {} {}", now, level, record.args()) }; let mut builder = LogBuilder::new(); builder.format(format).filter(Some("responder"), LogLevelFilter::Info); match env::var("RUST_LOG") { Ok(rust_log) => { builder.parse(&rust_log); }, Err(VarError::NotPresent) => {} Err(e) => return Err(format!("RUST_LOG {}", e)), } builder.init().map_err(|e| format!("{}", e)) } fn
(arg: String) -> Result<(), String> { arg.parse::<SocketAddr>() .map(|_| ()) .map_err(|_| String::from("invalid adrress")) } fn run_server(address: Option<&str>, config_file: &Path, reload: bool) -> Result<(), String> { let context = try!(Context::from_config_file(config_file, reload)); let address = address.or(Some(context.address())) .unwrap_or(DEFAULT_ADDR) .to_owned(); info!("Starting http server at http://{}/", &address); try!(server::run(context, &address)); Ok(()) }
address_validator
identifier_name
main.rs
#[macro_use] extern crate clap; #[macro_use] extern crate log; extern crate env_logger; extern crate chrono; extern crate responder; use std::env::{self, VarError}; use std::io::{self, Write}; use std::net::SocketAddr; use std::path::Path; use std::process; use clap::{App, Arg, Format}; use log::{LogRecord, LogLevel, LogLevelFilter}; use env_logger::LogBuilder; use chrono::offset::local::Local as LocalTime; use responder::Context; use responder::server; use responder::context::DEFAULT_ADDR; const DEFAULT_CONFIG: &'static str = "responder.yaml"; fn main() { match setup_logger() { Ok(_) => {}, Err(e) => { write!(io::stderr(), "{} {}\n", Format::Error("error:"), e) .expect("Unknown error"); process::exit(1); } }; let matches = App::new("Responder") .version(crate_version!()) .author("Livio Ribeiro <[email protected]>") .about("Web server generator used to serve static responses") .arg(Arg::with_name("config") .short("c") .long("config") .value_name("FILE") .help("Config file used to generate the server") .default_value(DEFAULT_CONFIG) .display_order(1)) .arg(Arg::with_name("bind") .short("b") .long("bind") .value_name("ADDRESS") .help("Address to bind server to") .validator(address_validator) .default_value(DEFAULT_ADDR) .display_order(2)) .arg(Arg::with_name("reload") .short("r") .long("reload") .help("Reload configuration file on every request") .display_order(3)) .get_matches(); let address = if matches.occurrences_of("bind") > 0
else { None }; let config = matches.value_of("config").map(|c| Path::new(c)).unwrap(); let reload = matches.is_present("reload"); match run_server(address, config, reload) { Ok(_) => {} Err(e) => { write!(io::stderr(), "{} {}\n", Format::Error("error:"), e) .expect("Unknown error"); process::exit(1); } } } fn setup_logger() -> Result<(), String> { let format = |record: &LogRecord| { let now = LocalTime::now().time().format("%H:%M:%S"); let rec_level = format!("{}", record.level()); let level = match record.level() { LogLevel::Error => Format::Error(rec_level), LogLevel::Warn => Format::Warning(rec_level), LogLevel::Info => Format::Good(rec_level), LogLevel::Debug | LogLevel::Trace => Format::None(rec_level), }; format!("[{}] {} {}", now, level, record.args()) }; let mut builder = LogBuilder::new(); builder.format(format).filter(Some("responder"), LogLevelFilter::Info); match env::var("RUST_LOG") { Ok(rust_log) => { builder.parse(&rust_log); }, Err(VarError::NotPresent) => {} Err(e) => return Err(format!("RUST_LOG {}", e)), } builder.init().map_err(|e| format!("{}", e)) } fn address_validator(arg: String) -> Result<(), String> { arg.parse::<SocketAddr>() .map(|_| ()) .map_err(|_| String::from("invalid adrress")) } fn run_server(address: Option<&str>, config_file: &Path, reload: bool) -> Result<(), String> { let context = try!(Context::from_config_file(config_file, reload)); let address = address.or(Some(context.address())) .unwrap_or(DEFAULT_ADDR) .to_owned(); info!("Starting http server at http://{}/", &address); try!(server::run(context, &address)); Ok(()) }
{ matches.value_of("bind") }
conditional_block
main.rs
#[macro_use] extern crate clap; #[macro_use] extern crate log; extern crate env_logger; extern crate chrono; extern crate responder; use std::env::{self, VarError}; use std::io::{self, Write}; use std::net::SocketAddr; use std::path::Path; use std::process; use clap::{App, Arg, Format}; use log::{LogRecord, LogLevel, LogLevelFilter}; use env_logger::LogBuilder; use chrono::offset::local::Local as LocalTime; use responder::Context; use responder::server; use responder::context::DEFAULT_ADDR; const DEFAULT_CONFIG: &'static str = "responder.yaml"; fn main() { match setup_logger() { Ok(_) => {}, Err(e) => { write!(io::stderr(), "{} {}\n", Format::Error("error:"), e) .expect("Unknown error"); process::exit(1); } }; let matches = App::new("Responder") .version(crate_version!()) .author("Livio Ribeiro <[email protected]>") .about("Web server generator used to serve static responses") .arg(Arg::with_name("config") .short("c") .long("config") .value_name("FILE") .help("Config file used to generate the server") .default_value(DEFAULT_CONFIG) .display_order(1)) .arg(Arg::with_name("bind") .short("b") .long("bind") .value_name("ADDRESS") .help("Address to bind server to") .validator(address_validator) .default_value(DEFAULT_ADDR) .display_order(2)) .arg(Arg::with_name("reload") .short("r") .long("reload") .help("Reload configuration file on every request") .display_order(3)) .get_matches(); let address = if matches.occurrences_of("bind") > 0 { matches.value_of("bind") } else { None }; let config = matches.value_of("config").map(|c| Path::new(c)).unwrap(); let reload = matches.is_present("reload"); match run_server(address, config, reload) { Ok(_) => {} Err(e) => { write!(io::stderr(), "{} {}\n", Format::Error("error:"), e) .expect("Unknown error"); process::exit(1); } } } fn setup_logger() -> Result<(), String> { let format = |record: &LogRecord| { let now = LocalTime::now().time().format("%H:%M:%S"); let rec_level = format!("{}", record.level()); let level = match record.level() { LogLevel::Error => Format::Error(rec_level), LogLevel::Warn => Format::Warning(rec_level), LogLevel::Info => Format::Good(rec_level), LogLevel::Debug | LogLevel::Trace => Format::None(rec_level), }; format!("[{}] {} {}", now, level, record.args()) }; let mut builder = LogBuilder::new(); builder.format(format).filter(Some("responder"), LogLevelFilter::Info); match env::var("RUST_LOG") { Ok(rust_log) => { builder.parse(&rust_log); }, Err(VarError::NotPresent) => {} Err(e) => return Err(format!("RUST_LOG {}", e)), } builder.init().map_err(|e| format!("{}", e)) } fn address_validator(arg: String) -> Result<(), String>
fn run_server(address: Option<&str>, config_file: &Path, reload: bool) -> Result<(), String> { let context = try!(Context::from_config_file(config_file, reload)); let address = address.or(Some(context.address())) .unwrap_or(DEFAULT_ADDR) .to_owned(); info!("Starting http server at http://{}/", &address); try!(server::run(context, &address)); Ok(()) }
{ arg.parse::<SocketAddr>() .map(|_| ()) .map_err(|_| String::from("invalid adrress")) }
identifier_body
main.rs
#[macro_use] extern crate clap; #[macro_use] extern crate log; extern crate env_logger; extern crate chrono; extern crate responder; use std::env::{self, VarError}; use std::io::{self, Write}; use std::net::SocketAddr; use std::path::Path; use std::process; use clap::{App, Arg, Format}; use log::{LogRecord, LogLevel, LogLevelFilter}; use env_logger::LogBuilder; use chrono::offset::local::Local as LocalTime; use responder::Context; use responder::server; use responder::context::DEFAULT_ADDR; const DEFAULT_CONFIG: &'static str = "responder.yaml"; fn main() { match setup_logger() { Ok(_) => {}, Err(e) => { write!(io::stderr(), "{} {}\n", Format::Error("error:"), e) .expect("Unknown error"); process::exit(1); } }; let matches = App::new("Responder") .version(crate_version!()) .author("Livio Ribeiro <[email protected]>") .about("Web server generator used to serve static responses") .arg(Arg::with_name("config") .short("c") .long("config") .value_name("FILE") .help("Config file used to generate the server") .default_value(DEFAULT_CONFIG) .display_order(1)) .arg(Arg::with_name("bind") .short("b") .long("bind") .value_name("ADDRESS") .help("Address to bind server to") .validator(address_validator) .default_value(DEFAULT_ADDR) .display_order(2)) .arg(Arg::with_name("reload") .short("r") .long("reload") .help("Reload configuration file on every request") .display_order(3)) .get_matches(); let address = if matches.occurrences_of("bind") > 0 { matches.value_of("bind") } else { None }; let config = matches.value_of("config").map(|c| Path::new(c)).unwrap(); let reload = matches.is_present("reload"); match run_server(address, config, reload) { Ok(_) => {} Err(e) => { write!(io::stderr(), "{} {}\n", Format::Error("error:"), e) .expect("Unknown error"); process::exit(1); } } } fn setup_logger() -> Result<(), String> { let format = |record: &LogRecord| { let now = LocalTime::now().time().format("%H:%M:%S"); let rec_level = format!("{}", record.level()); let level = match record.level() { LogLevel::Error => Format::Error(rec_level), LogLevel::Warn => Format::Warning(rec_level), LogLevel::Info => Format::Good(rec_level), LogLevel::Debug | LogLevel::Trace => Format::None(rec_level), }; format!("[{}] {} {}", now, level, record.args()) }; let mut builder = LogBuilder::new(); builder.format(format).filter(Some("responder"), LogLevelFilter::Info); match env::var("RUST_LOG") { Ok(rust_log) => { builder.parse(&rust_log); }, Err(VarError::NotPresent) => {} Err(e) => return Err(format!("RUST_LOG {}", e)), } builder.init().map_err(|e| format!("{}", e)) } fn address_validator(arg: String) -> Result<(), String> { arg.parse::<SocketAddr>() .map(|_| ()) .map_err(|_| String::from("invalid adrress"))
-> Result<(), String> { let context = try!(Context::from_config_file(config_file, reload)); let address = address.or(Some(context.address())) .unwrap_or(DEFAULT_ADDR) .to_owned(); info!("Starting http server at http://{}/", &address); try!(server::run(context, &address)); Ok(()) }
} fn run_server(address: Option<&str>, config_file: &Path, reload: bool)
random_line_split
variance-types.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. #![allow(dead_code)] #![feature(rustc_attrs)] use std::cell::Cell; // Check that a type parameter which is only used in a trait bound is // not considered bivariant. #[rustc_variance] struct InvariantMut<'a,A:'a,B:'a> { //~ ERROR [-, o, o] t: &'a mut (A,B) } #[rustc_variance] struct InvariantCell<A> { //~ ERROR [o] t: Cell<A> } #[rustc_variance] struct
<A> { //~ ERROR [o] t: InvariantCell<A> } #[rustc_variance] struct Covariant<A> { //~ ERROR [+] t: A, u: fn() -> A } #[rustc_variance] struct Contravariant<A> { //~ ERROR [-] t: fn(A) } #[rustc_variance] enum Enum<A,B,C> { //~ ERROR [+, -, o] Foo(Covariant<A>), Bar(Contravariant<B>), Zed(Covariant<C>,Contravariant<C>) } pub fn main() { }
InvariantIndirect
identifier_name
variance-types.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. #![allow(dead_code)] #![feature(rustc_attrs)] use std::cell::Cell; // Check that a type parameter which is only used in a trait bound is // not considered bivariant. #[rustc_variance] struct InvariantMut<'a,A:'a,B:'a> { //~ ERROR [-, o, o] t: &'a mut (A,B) } #[rustc_variance] struct InvariantCell<A> { //~ ERROR [o] t: Cell<A> } #[rustc_variance] struct InvariantIndirect<A> { //~ ERROR [o] t: InvariantCell<A> } #[rustc_variance] struct Covariant<A> { //~ ERROR [+] t: A, u: fn() -> A } #[rustc_variance] struct Contravariant<A> { //~ ERROR [-] t: fn(A) } #[rustc_variance] enum Enum<A,B,C> { //~ ERROR [+, -, o] Foo(Covariant<A>), Bar(Contravariant<B>), Zed(Covariant<C>,Contravariant<C>) } pub fn main() { }
//
random_line_split
popstateevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::PopStateEventBinding; use dom::bindings::codegen::Bindings::PopStateEventBinding::PopStateEventMethods; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::{MutHeapJSVal, Root}; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::Event; use dom::window::Window; use js::jsapi::{HandleValue, JSContext}; use js::jsval::JSVal; use servo_atoms::Atom; // https://html.spec.whatwg.org/multipage/#the-popstateevent-interface #[dom_struct] pub struct
{ event: Event, #[ignore_heap_size_of = "Defined in rust-mozjs"] state: MutHeapJSVal, } impl PopStateEvent { fn new_inherited() -> PopStateEvent { PopStateEvent { event: Event::new_inherited(), state: MutHeapJSVal::new(), } } pub fn new_uninitialized(window: &Window) -> Root<PopStateEvent> { reflect_dom_object(box PopStateEvent::new_inherited(), window, PopStateEventBinding::Wrap) } pub fn new(window: &Window, type_: Atom, bubbles: bool, cancelable: bool, state: HandleValue) -> Root<PopStateEvent> { let ev = PopStateEvent::new_uninitialized(window); ev.state.set(state.get()); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } #[allow(unsafe_code)] pub fn Constructor(window: &Window, type_: DOMString, init: &PopStateEventBinding::PopStateEventInit) -> Fallible<Root<PopStateEvent>> { Ok(PopStateEvent::new(window, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, unsafe { HandleValue::from_marked_location(&init.state) })) } } impl PopStateEventMethods for PopStateEvent { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-popstateevent-state unsafe fn State(&self, _cx: *mut JSContext) -> JSVal { self.state.get() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
PopStateEvent
identifier_name
popstateevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::PopStateEventBinding; use dom::bindings::codegen::Bindings::PopStateEventBinding::PopStateEventMethods; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::{MutHeapJSVal, Root}; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::Event; use dom::window::Window; use js::jsapi::{HandleValue, JSContext}; use js::jsval::JSVal; use servo_atoms::Atom; // https://html.spec.whatwg.org/multipage/#the-popstateevent-interface #[dom_struct] pub struct PopStateEvent { event: Event, #[ignore_heap_size_of = "Defined in rust-mozjs"] state: MutHeapJSVal, } impl PopStateEvent { fn new_inherited() -> PopStateEvent { PopStateEvent { event: Event::new_inherited(), state: MutHeapJSVal::new(), } } pub fn new_uninitialized(window: &Window) -> Root<PopStateEvent> { reflect_dom_object(box PopStateEvent::new_inherited(), window, PopStateEventBinding::Wrap) } pub fn new(window: &Window, type_: Atom, bubbles: bool, cancelable: bool, state: HandleValue) -> Root<PopStateEvent> { let ev = PopStateEvent::new_uninitialized(window); ev.state.set(state.get()); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } #[allow(unsafe_code)] pub fn Constructor(window: &Window, type_: DOMString, init: &PopStateEventBinding::PopStateEventInit) -> Fallible<Root<PopStateEvent>>
} impl PopStateEventMethods for PopStateEvent { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-popstateevent-state unsafe fn State(&self, _cx: *mut JSContext) -> JSVal { self.state.get() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
{ Ok(PopStateEvent::new(window, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, unsafe { HandleValue::from_marked_location(&init.state) })) }
identifier_body
popstateevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::PopStateEventBinding; use dom::bindings::codegen::Bindings::PopStateEventBinding::PopStateEventMethods; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::{MutHeapJSVal, Root}; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::Event; use dom::window::Window; use js::jsapi::{HandleValue, JSContext}; use js::jsval::JSVal; use servo_atoms::Atom; // https://html.spec.whatwg.org/multipage/#the-popstateevent-interface #[dom_struct] pub struct PopStateEvent { event: Event, #[ignore_heap_size_of = "Defined in rust-mozjs"] state: MutHeapJSVal, } impl PopStateEvent { fn new_inherited() -> PopStateEvent { PopStateEvent { event: Event::new_inherited(),
pub fn new_uninitialized(window: &Window) -> Root<PopStateEvent> { reflect_dom_object(box PopStateEvent::new_inherited(), window, PopStateEventBinding::Wrap) } pub fn new(window: &Window, type_: Atom, bubbles: bool, cancelable: bool, state: HandleValue) -> Root<PopStateEvent> { let ev = PopStateEvent::new_uninitialized(window); ev.state.set(state.get()); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } #[allow(unsafe_code)] pub fn Constructor(window: &Window, type_: DOMString, init: &PopStateEventBinding::PopStateEventInit) -> Fallible<Root<PopStateEvent>> { Ok(PopStateEvent::new(window, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, unsafe { HandleValue::from_marked_location(&init.state) })) } } impl PopStateEventMethods for PopStateEvent { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-popstateevent-state unsafe fn State(&self, _cx: *mut JSContext) -> JSVal { self.state.get() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
state: MutHeapJSVal::new(), } }
random_line_split
issue-2631-a.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. #![feature(managed_boxes)] #![crate_id="req"] #![crate_type = "lib"] extern crate collections; use std::cell::RefCell; use collections::HashMap; pub type header_map = HashMap<StrBuf, @RefCell<Vec<@StrBuf>>>; // the unused ty param is necessary so this gets monomorphized pub fn
<T>(req: &header_map) { let _x = (**((**req.get(&"METHOD".to_strbuf())).clone()).borrow() .clone() .get(0)).clone(); }
request
identifier_name
issue-2631-a.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. #![feature(managed_boxes)] #![crate_id="req"] #![crate_type = "lib"] extern crate collections; use std::cell::RefCell; use collections::HashMap; pub type header_map = HashMap<StrBuf, @RefCell<Vec<@StrBuf>>>; // the unused ty param is necessary so this gets monomorphized pub fn request<T>(req: &header_map) {
.clone() .get(0)).clone(); }
let _x = (**((**req.get(&"METHOD".to_strbuf())).clone()).borrow()
random_line_split
issue-2631-a.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. #![feature(managed_boxes)] #![crate_id="req"] #![crate_type = "lib"] extern crate collections; use std::cell::RefCell; use collections::HashMap; pub type header_map = HashMap<StrBuf, @RefCell<Vec<@StrBuf>>>; // the unused ty param is necessary so this gets monomorphized pub fn request<T>(req: &header_map)
{ let _x = (**((**req.get(&"METHOD".to_strbuf())).clone()).borrow() .clone() .get(0)).clone(); }
identifier_body
dir_reg.rs
use std::io::{self, Read, Write}; use std::fmt; use instruction::parameter::{Direct, Register, RegisterError, InvalidRegister}; use instruction::parameter::{ParamType, ParamTypeOf}; use instruction::parameter::InvalidParamType; use instruction::mem_size::MemSize; use instruction::write_to::WriteTo; use instruction::get_value::GetValue; use machine::Machine; use process::Context; #[derive(Debug)] pub enum Error { Io(io::Error), InvalidParamType(InvalidParamType), InvalidRegister(InvalidRegister) } impl From<io::Error> for Error { fn from(error: io::Error) -> Self { Error::Io(error) } } impl From<InvalidRegister> for Error { fn from(error: InvalidRegister) -> Self { Error::InvalidRegister(error) } } impl From<RegisterError> for Error { fn from(error: RegisterError) -> Self { match error { RegisterError::Io(e) => Error::Io(e), RegisterError::InvalidRegister(invalid_reg) => Error::InvalidRegister(invalid_reg), } } } #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub enum DirReg { Direct(Direct), Register(Register), } impl DirReg { pub fn read_from<R: Read>(param_type: ParamType, reader: &mut R) -> Result<Self, Error> { match param_type { ParamType::Direct => Ok(DirReg::Direct(Direct::read_from(reader)?)), ParamType::Register => Ok(DirReg::Register(Register::read_from(reader)?)), _ => Err(Error::InvalidParamType(InvalidParamType(param_type))), } } } impl GetValue for DirReg { fn get_value(&self, vm: &Machine, context: &Context) -> i32 { match *self { DirReg::Direct(direct) => direct.get_value(vm, context), DirReg::Register(register) => register.get_value(vm, context), } } } impl MemSize for DirReg { fn mem_size(&self) -> usize { match *self { DirReg::Direct(direct) => direct.mem_size(), DirReg::Register(register) => register.mem_size(), } } }
DirReg::Register(_) => ParamType::Register, } } } impl WriteTo for DirReg { fn write_to<W: Write>(&self, writer: &mut W) -> io::Result<()> { match *self { DirReg::Direct(direct) => direct.write_to(writer), DirReg::Register(register) => register.write_to(writer), } } } impl fmt::Debug for DirReg { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { DirReg::Direct(direct) => write!(f, "{:?}", direct), DirReg::Register(register) => write!(f, "{:?}", register), } } } impl fmt::Display for DirReg { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { DirReg::Direct(dir) => dir.fmt(f), DirReg::Register(reg) => reg.fmt(f), } } }
impl ParamTypeOf for DirReg { fn param_type(&self) -> ParamType { match *self { DirReg::Direct(_) => ParamType::Direct,
random_line_split
dir_reg.rs
use std::io::{self, Read, Write}; use std::fmt; use instruction::parameter::{Direct, Register, RegisterError, InvalidRegister}; use instruction::parameter::{ParamType, ParamTypeOf}; use instruction::parameter::InvalidParamType; use instruction::mem_size::MemSize; use instruction::write_to::WriteTo; use instruction::get_value::GetValue; use machine::Machine; use process::Context; #[derive(Debug)] pub enum Error { Io(io::Error), InvalidParamType(InvalidParamType), InvalidRegister(InvalidRegister) } impl From<io::Error> for Error { fn from(error: io::Error) -> Self { Error::Io(error) } } impl From<InvalidRegister> for Error { fn from(error: InvalidRegister) -> Self { Error::InvalidRegister(error) } } impl From<RegisterError> for Error { fn from(error: RegisterError) -> Self { match error { RegisterError::Io(e) => Error::Io(e), RegisterError::InvalidRegister(invalid_reg) => Error::InvalidRegister(invalid_reg), } } } #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub enum DirReg { Direct(Direct), Register(Register), } impl DirReg { pub fn read_from<R: Read>(param_type: ParamType, reader: &mut R) -> Result<Self, Error> { match param_type { ParamType::Direct => Ok(DirReg::Direct(Direct::read_from(reader)?)), ParamType::Register => Ok(DirReg::Register(Register::read_from(reader)?)), _ => Err(Error::InvalidParamType(InvalidParamType(param_type))), } } } impl GetValue for DirReg { fn get_value(&self, vm: &Machine, context: &Context) -> i32 { match *self { DirReg::Direct(direct) => direct.get_value(vm, context), DirReg::Register(register) => register.get_value(vm, context), } } } impl MemSize for DirReg { fn mem_size(&self) -> usize { match *self { DirReg::Direct(direct) => direct.mem_size(), DirReg::Register(register) => register.mem_size(), } } } impl ParamTypeOf for DirReg { fn
(&self) -> ParamType { match *self { DirReg::Direct(_) => ParamType::Direct, DirReg::Register(_) => ParamType::Register, } } } impl WriteTo for DirReg { fn write_to<W: Write>(&self, writer: &mut W) -> io::Result<()> { match *self { DirReg::Direct(direct) => direct.write_to(writer), DirReg::Register(register) => register.write_to(writer), } } } impl fmt::Debug for DirReg { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { DirReg::Direct(direct) => write!(f, "{:?}", direct), DirReg::Register(register) => write!(f, "{:?}", register), } } } impl fmt::Display for DirReg { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { DirReg::Direct(dir) => dir.fmt(f), DirReg::Register(reg) => reg.fmt(f), } } }
param_type
identifier_name
mod.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt;
// Modules -------------------------------------------------------------------- pub mod alias; pub mod ban; //pub mod debug; pub mod effect; pub mod greeting; pub mod message; pub mod recording; pub mod server; pub mod uploader; pub mod timed; pub mod twitch; // Re-Exports ----------------------------------------------------------------- pub use self::alias as AliasActions; pub use self::ban as BanActions; //pub use self::debug as DebugActions; pub use self::effect as EffectActions; pub use self::greeting as GreetingActions; pub use self::message as MessageActions; pub use self::recording as RecordingActions; pub use self::server as ServerActions; pub use self::uploader as UploaderActions; pub use self::timed as TimedActions; pub use self::twitch as TwitchActions; // General Action Abstraction ------------------------------------------------- pub type ActionGroup = Vec<Box<ActionHandler>>; pub type ActionOption = Option<Box<ActionHandler>>; pub trait ActionHandler: fmt::Display + Send { fn ready(&self) -> bool { true } fn run(&mut self, &mut Bot, &BotConfig, &mut EventQueue) -> ActionGroup; }
// Internal Dependencies ------------------------------------------------------ use ::core::EventQueue; use ::bot::{Bot, BotConfig};
random_line_split
mod.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt; // Internal Dependencies ------------------------------------------------------ use ::core::EventQueue; use ::bot::{Bot, BotConfig}; // Modules -------------------------------------------------------------------- pub mod alias; pub mod ban; //pub mod debug; pub mod effect; pub mod greeting; pub mod message; pub mod recording; pub mod server; pub mod uploader; pub mod timed; pub mod twitch; // Re-Exports ----------------------------------------------------------------- pub use self::alias as AliasActions; pub use self::ban as BanActions; //pub use self::debug as DebugActions; pub use self::effect as EffectActions; pub use self::greeting as GreetingActions; pub use self::message as MessageActions; pub use self::recording as RecordingActions; pub use self::server as ServerActions; pub use self::uploader as UploaderActions; pub use self::timed as TimedActions; pub use self::twitch as TwitchActions; // General Action Abstraction ------------------------------------------------- pub type ActionGroup = Vec<Box<ActionHandler>>; pub type ActionOption = Option<Box<ActionHandler>>; pub trait ActionHandler: fmt::Display + Send { fn
(&self) -> bool { true } fn run(&mut self, &mut Bot, &BotConfig, &mut EventQueue) -> ActionGroup; }
ready
identifier_name
mod.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt; // Internal Dependencies ------------------------------------------------------ use ::core::EventQueue; use ::bot::{Bot, BotConfig}; // Modules -------------------------------------------------------------------- pub mod alias; pub mod ban; //pub mod debug; pub mod effect; pub mod greeting; pub mod message; pub mod recording; pub mod server; pub mod uploader; pub mod timed; pub mod twitch; // Re-Exports ----------------------------------------------------------------- pub use self::alias as AliasActions; pub use self::ban as BanActions; //pub use self::debug as DebugActions; pub use self::effect as EffectActions; pub use self::greeting as GreetingActions; pub use self::message as MessageActions; pub use self::recording as RecordingActions; pub use self::server as ServerActions; pub use self::uploader as UploaderActions; pub use self::timed as TimedActions; pub use self::twitch as TwitchActions; // General Action Abstraction ------------------------------------------------- pub type ActionGroup = Vec<Box<ActionHandler>>; pub type ActionOption = Option<Box<ActionHandler>>; pub trait ActionHandler: fmt::Display + Send { fn ready(&self) -> bool
fn run(&mut self, &mut Bot, &BotConfig, &mut EventQueue) -> ActionGroup; }
{ true }
identifier_body
borrowingmutsource0.rs
#[allow(dead_code)] #[derive(Clone, Copy)] struct Book { // `&'static str` est une référence d'une chaîne de caractères allouée // dans un bloc mémoire qui ne peut être accédé qu'en lecture. author: &'static str, title: &'static str, year: u32, } // Cette fonction prend une référence d'une instance // de la structure `Book` en paramètre. fn borrow_book(book: &Book) { println!("I immutably borrowed {} - {} edition", book.title, book.year); } // Cette fonction prend une référence mutable d'une instance de la // structure `Book` en paramètre, et initialise sa date de publication // à 2014. fn new_edition(book: &mut Book) { book.year = 2014; println!("I mutably borrowed {} - {} edition", book.title, book.year); } fn main() { // On créé une instance immuable de la // structure `Book` nommée `immutabook`. let immutabook = Book { // Les chaînes littérales sont typées `&'static str`. author: "Douglas Hofstadter", title: "Gödel, Escher, Bach", year: 1979, }; // On créé une copie mutable de `immutabook` nommée // `mutabook`.
let mut mutabook = immutabook; // Emprunte un objet en lecture seule. borrow_book(&immutabook); // Emprunte un objet en lecture seule. borrow_book(&mutabook); // Récupère une référence mutable d'un objet mutable. new_edition(&mut mutabook); // Erreur! Vous ne pouvez pas récupérer une référence // mutable d'un objet immuable. // new_edition(&mut immutabook); // FIXME ^ Décommentez cette ligne. }
random_line_split
borrowingmutsource0.rs
#[allow(dead_code)] #[derive(Clone, Copy)] struct Book { // `&'static str` est une référence d'une chaîne de caractères allouée // dans un bloc mémoire qui ne peut être accédé qu'en lecture. author: &'static str, title: &'static str, year: u32, } // Cette fonction prend une référence d'une instance // de la structure `Book` en paramètre. fn borrow_book(
) { println!("I immutably borrowed {} - {} edition", book.title, book.year); } // Cette fonction prend une référence mutable d'une instance de la // structure `Book` en paramètre, et initialise sa date de publication // à 2014. fn new_edition(book: &mut Book) { book.year = 2014; println!("I mutably borrowed {} - {} edition", book.title, book.year); } fn main() { // On créé une instance immuable de la // structure `Book` nommée `immutabook`. let immutabook = Book { // Les chaînes littérales sont typées `&'static str`. author: "Douglas Hofstadter", title: "Gödel, Escher, Bach", year: 1979, }; // On créé une copie mutable de `immutabook` nommée // `mutabook`. let mut mutabook = immutabook; // Emprunte un objet en lecture seule. borrow_book(&immutabook); // Emprunte un objet en lecture seule. borrow_book(&mutabook); // Récupère une référence mutable d'un objet mutable. new_edition(&mut mutabook); // Erreur! Vous ne pouvez pas récupérer une référence // mutable d'un objet immuable. // new_edition(&mut immutabook); // FIXME ^ Décommentez cette ligne. }
book: &Book
identifier_name
functions4.rs
// Make me compile! Scroll down for hints :) // This store is having a sale where if the price is an even number, you get // 10 (money unit) off, but if it's an odd number, it's 3 (money unit) less. fn main()
fn sale_price(price: i32) -> i32 { if is_even(price) { price - 10 } else { price - 3 } } fn is_even(num: i32) -> bool { num % 2 == 0 } // The error message points to line 10 and says it expects a type after the // `->`. This is where the function's return type should be-- take a look at // the `is_even` function for an example!
{ let original_price: i32 = 51; println!("Your sale price is {}", sale_price(original_price)); }
identifier_body
functions4.rs
// Make me compile! Scroll down for hints :) // This store is having a sale where if the price is an even number, you get // 10 (money unit) off, but if it's an odd number, it's 3 (money unit) less. fn main() { let original_price: i32 = 51; println!("Your sale price is {}", sale_price(original_price)); } fn sale_price(price: i32) -> i32 { if is_even(price)
else { price - 3 } } fn is_even(num: i32) -> bool { num % 2 == 0 } // The error message points to line 10 and says it expects a type after the // `->`. This is where the function's return type should be-- take a look at // the `is_even` function for an example!
{ price - 10 }
conditional_block
functions4.rs
// Make me compile! Scroll down for hints :) // This store is having a sale where if the price is an even number, you get // 10 (money unit) off, but if it's an odd number, it's 3 (money unit) less. fn main() { let original_price: i32 = 51; println!("Your sale price is {}", sale_price(original_price)); } fn sale_price(price: i32) -> i32 { if is_even(price) { price - 10 } else { price - 3 } } fn is_even(num: i32) -> bool { num % 2 == 0 }
// The error message points to line 10 and says it expects a type after the // `->`. This is where the function's return type should be-- take a look at // the `is_even` function for an example!
random_line_split
functions4.rs
// Make me compile! Scroll down for hints :) // This store is having a sale where if the price is an even number, you get // 10 (money unit) off, but if it's an odd number, it's 3 (money unit) less. fn
() { let original_price: i32 = 51; println!("Your sale price is {}", sale_price(original_price)); } fn sale_price(price: i32) -> i32 { if is_even(price) { price - 10 } else { price - 3 } } fn is_even(num: i32) -> bool { num % 2 == 0 } // The error message points to line 10 and says it expects a type after the // `->`. This is where the function's return type should be-- take a look at // the `is_even` function for an example!
main
identifier_name
mime.rs
use std::io::{Write, BufRead, BufReader}; use std::fs::File; use std::collections::HashMap; use std::borrow::Cow; macro_rules! or_continue { ($e: expr) => (if let Some(v) = $e { v } else { continue; }) } pub fn gen()
let top: Cow<_> = match or_continue!(mime_type.next()) { "*" => "MaybeKnown::Known(::mime::TopLevel::Star)".into(), "text" => "MaybeKnown::Known(::mime::TopLevel::Text)".into(), "image" => "MaybeKnown::Known(::mime::TopLevel::Image)".into(), "audio" => "MaybeKnown::Known(::mime::TopLevel::Audio)".into(), "video" => "MaybeKnown::Known(::mime::TopLevel::Image)".into(), "application" => "MaybeKnown::Known(::mime::TopLevel::Application)".into(), "multipart" => "MaybeKnown::Known(::mime::TopLevel::Multipart)".into(), "message" => "MaybeKnown::Known(::mime::TopLevel::Message)".into(), "model" => "MaybeKnown::Known(::mime::TopLevel::Model)".into(), top => format!("MaybeKnown::Unknown(\"{}\")", top).into() }; let sub: Cow<_> = match or_continue!(mime_type.next()) { "*" => "MaybeKnown::Known(::mime::SubLevel::Star)".into(), "plain" => "MaybeKnown::Known(::mime::SubLevel::Plain)".into(), "html" => "MaybeKnown::Known(::mime::SubLevel::Html)".into(), "xml" => "MaybeKnown::Known(::mime::SubLevel::Xml)".into(), "javascript" => "MaybeKnown::Known(::mime::SubLevel::Javascript)".into(), "css" => "MaybeKnown::Known(::mime::SubLevel::Css)".into(), "json" => "MaybeKnown::Known(::mime::SubLevel::Json)".into(), "www-form-url-encoded" => "MaybeKnown::Known(::mime::SubLevel::WwwFormUrlEncoded)".into(), "form-data" => "MaybeKnown::Known(::mime::SubLevel::FormData)".into(), "png" => "MaybeKnown::Known(::mime::SubLevel::Png)".into(), "gif" => "MaybeKnown::Known(::mime::SubLevel::Gif)".into(), "bmp" => "MaybeKnown::Known(::mime::SubLevel::Bmp)".into(), "jpeg" => "MaybeKnown::Known(::mime::SubLevel::Jpeg)".into(), sub => format!("MaybeKnown::Unknown(\"{}\")", sub).into() }; for ext in or_continue!(parts.next()).split(' ') { types.insert(String::from(ext), format!("({}, {})", top, sub)); } } write!(&mut output, "static MIME: ::phf::Map<&'static str, (MaybeKnown<TopLevel>, MaybeKnown<SubLevel>)> = ").unwrap(); let mut mimes = ::phf_codegen::Map::new(); for (ext, ty) in &types { mimes.entry(&ext[..], ty); } mimes.build(&mut output).unwrap(); write!(&mut output, ";\n").unwrap(); }
{ let input = File::open("build/apache/mime.types").unwrap_or_else(|e| { panic!("could not open 'build/apache/mime.types': {}", e); }); let out_path = format!("{}/mime.rs", env!("OUT_DIR")); let mut output = File::create(&out_path).unwrap_or_else(|e| { panic!("could not create '{}': {}", out_path, e); }); let mut types = HashMap::new(); for line in BufReader::new(input).lines().filter_map(Result::ok) { if let Some('#') = line.chars().next() { continue; } let mut parts = line.split('\t').filter(|v| v.len() > 0); let mut mime_type = or_continue!(parts.next()).split('/');
identifier_body
mime.rs
use std::io::{Write, BufRead, BufReader}; use std::fs::File; use std::collections::HashMap; use std::borrow::Cow; macro_rules! or_continue { ($e: expr) => (if let Some(v) = $e { v } else { continue; }) } pub fn
() { let input = File::open("build/apache/mime.types").unwrap_or_else(|e| { panic!("could not open 'build/apache/mime.types': {}", e); }); let out_path = format!("{}/mime.rs", env!("OUT_DIR")); let mut output = File::create(&out_path).unwrap_or_else(|e| { panic!("could not create '{}': {}", out_path, e); }); let mut types = HashMap::new(); for line in BufReader::new(input).lines().filter_map(Result::ok) { if let Some('#') = line.chars().next() { continue; } let mut parts = line.split('\t').filter(|v| v.len() > 0); let mut mime_type = or_continue!(parts.next()).split('/'); let top: Cow<_> = match or_continue!(mime_type.next()) { "*" => "MaybeKnown::Known(::mime::TopLevel::Star)".into(), "text" => "MaybeKnown::Known(::mime::TopLevel::Text)".into(), "image" => "MaybeKnown::Known(::mime::TopLevel::Image)".into(), "audio" => "MaybeKnown::Known(::mime::TopLevel::Audio)".into(), "video" => "MaybeKnown::Known(::mime::TopLevel::Image)".into(), "application" => "MaybeKnown::Known(::mime::TopLevel::Application)".into(), "multipart" => "MaybeKnown::Known(::mime::TopLevel::Multipart)".into(), "message" => "MaybeKnown::Known(::mime::TopLevel::Message)".into(), "model" => "MaybeKnown::Known(::mime::TopLevel::Model)".into(), top => format!("MaybeKnown::Unknown(\"{}\")", top).into() }; let sub: Cow<_> = match or_continue!(mime_type.next()) { "*" => "MaybeKnown::Known(::mime::SubLevel::Star)".into(), "plain" => "MaybeKnown::Known(::mime::SubLevel::Plain)".into(), "html" => "MaybeKnown::Known(::mime::SubLevel::Html)".into(), "xml" => "MaybeKnown::Known(::mime::SubLevel::Xml)".into(), "javascript" => "MaybeKnown::Known(::mime::SubLevel::Javascript)".into(), "css" => "MaybeKnown::Known(::mime::SubLevel::Css)".into(), "json" => "MaybeKnown::Known(::mime::SubLevel::Json)".into(), "www-form-url-encoded" => "MaybeKnown::Known(::mime::SubLevel::WwwFormUrlEncoded)".into(), "form-data" => "MaybeKnown::Known(::mime::SubLevel::FormData)".into(), "png" => "MaybeKnown::Known(::mime::SubLevel::Png)".into(), "gif" => "MaybeKnown::Known(::mime::SubLevel::Gif)".into(), "bmp" => "MaybeKnown::Known(::mime::SubLevel::Bmp)".into(), "jpeg" => "MaybeKnown::Known(::mime::SubLevel::Jpeg)".into(), sub => format!("MaybeKnown::Unknown(\"{}\")", sub).into() }; for ext in or_continue!(parts.next()).split(' ') { types.insert(String::from(ext), format!("({}, {})", top, sub)); } } write!(&mut output, "static MIME: ::phf::Map<&'static str, (MaybeKnown<TopLevel>, MaybeKnown<SubLevel>)> = ").unwrap(); let mut mimes = ::phf_codegen::Map::new(); for (ext, ty) in &types { mimes.entry(&ext[..], ty); } mimes.build(&mut output).unwrap(); write!(&mut output, ";\n").unwrap(); }
gen
identifier_name
mime.rs
use std::io::{Write, BufRead, BufReader}; use std::fs::File; use std::collections::HashMap; use std::borrow::Cow; macro_rules! or_continue { ($e: expr) => (if let Some(v) = $e { v } else { continue; }) } pub fn gen() { let input = File::open("build/apache/mime.types").unwrap_or_else(|e| { panic!("could not open 'build/apache/mime.types': {}", e); });
panic!("could not create '{}': {}", out_path, e); }); let mut types = HashMap::new(); for line in BufReader::new(input).lines().filter_map(Result::ok) { if let Some('#') = line.chars().next() { continue; } let mut parts = line.split('\t').filter(|v| v.len() > 0); let mut mime_type = or_continue!(parts.next()).split('/'); let top: Cow<_> = match or_continue!(mime_type.next()) { "*" => "MaybeKnown::Known(::mime::TopLevel::Star)".into(), "text" => "MaybeKnown::Known(::mime::TopLevel::Text)".into(), "image" => "MaybeKnown::Known(::mime::TopLevel::Image)".into(), "audio" => "MaybeKnown::Known(::mime::TopLevel::Audio)".into(), "video" => "MaybeKnown::Known(::mime::TopLevel::Image)".into(), "application" => "MaybeKnown::Known(::mime::TopLevel::Application)".into(), "multipart" => "MaybeKnown::Known(::mime::TopLevel::Multipart)".into(), "message" => "MaybeKnown::Known(::mime::TopLevel::Message)".into(), "model" => "MaybeKnown::Known(::mime::TopLevel::Model)".into(), top => format!("MaybeKnown::Unknown(\"{}\")", top).into() }; let sub: Cow<_> = match or_continue!(mime_type.next()) { "*" => "MaybeKnown::Known(::mime::SubLevel::Star)".into(), "plain" => "MaybeKnown::Known(::mime::SubLevel::Plain)".into(), "html" => "MaybeKnown::Known(::mime::SubLevel::Html)".into(), "xml" => "MaybeKnown::Known(::mime::SubLevel::Xml)".into(), "javascript" => "MaybeKnown::Known(::mime::SubLevel::Javascript)".into(), "css" => "MaybeKnown::Known(::mime::SubLevel::Css)".into(), "json" => "MaybeKnown::Known(::mime::SubLevel::Json)".into(), "www-form-url-encoded" => "MaybeKnown::Known(::mime::SubLevel::WwwFormUrlEncoded)".into(), "form-data" => "MaybeKnown::Known(::mime::SubLevel::FormData)".into(), "png" => "MaybeKnown::Known(::mime::SubLevel::Png)".into(), "gif" => "MaybeKnown::Known(::mime::SubLevel::Gif)".into(), "bmp" => "MaybeKnown::Known(::mime::SubLevel::Bmp)".into(), "jpeg" => "MaybeKnown::Known(::mime::SubLevel::Jpeg)".into(), sub => format!("MaybeKnown::Unknown(\"{}\")", sub).into() }; for ext in or_continue!(parts.next()).split(' ') { types.insert(String::from(ext), format!("({}, {})", top, sub)); } } write!(&mut output, "static MIME: ::phf::Map<&'static str, (MaybeKnown<TopLevel>, MaybeKnown<SubLevel>)> = ").unwrap(); let mut mimes = ::phf_codegen::Map::new(); for (ext, ty) in &types { mimes.entry(&ext[..], ty); } mimes.build(&mut output).unwrap(); write!(&mut output, ";\n").unwrap(); }
let out_path = format!("{}/mime.rs", env!("OUT_DIR")); let mut output = File::create(&out_path).unwrap_or_else(|e| {
random_line_split
cleanup.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // Code to handle cleanup after a failed operation. use crate::stratis::{ErrorEnum, StratisError, StratisResult}; use crate::engine::structures::Table; use crate::engine::strat_engine::pool::StratPool; /// Teardown pools. pub fn teardown_pools(pools: Table<StratPool>) -> StratisResult<()> { let mut untorndown_pools = Vec::new(); for (_, uuid, mut pool) in pools { pool.teardown() .unwrap_or_else(|_| untorndown_pools.push(uuid)); } if untorndown_pools.is_empty()
else { let err_msg = format!( "Failed to teardown already set up pools: {:?}", untorndown_pools ); Err(StratisError::Engine(ErrorEnum::Error, err_msg)) } }
{ Ok(()) }
conditional_block
cleanup.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // Code to handle cleanup after a failed operation. use crate::stratis::{ErrorEnum, StratisError, StratisResult}; use crate::engine::structures::Table; use crate::engine::strat_engine::pool::StratPool; /// Teardown pools. pub fn
(pools: Table<StratPool>) -> StratisResult<()> { let mut untorndown_pools = Vec::new(); for (_, uuid, mut pool) in pools { pool.teardown() .unwrap_or_else(|_| untorndown_pools.push(uuid)); } if untorndown_pools.is_empty() { Ok(()) } else { let err_msg = format!( "Failed to teardown already set up pools: {:?}", untorndown_pools ); Err(StratisError::Engine(ErrorEnum::Error, err_msg)) } }
teardown_pools
identifier_name
cleanup.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // Code to handle cleanup after a failed operation. use crate::stratis::{ErrorEnum, StratisError, StratisResult}; use crate::engine::structures::Table; use crate::engine::strat_engine::pool::StratPool; /// Teardown pools. pub fn teardown_pools(pools: Table<StratPool>) -> StratisResult<()> { let mut untorndown_pools = Vec::new(); for (_, uuid, mut pool) in pools { pool.teardown() .unwrap_or_else(|_| untorndown_pools.push(uuid)); } if untorndown_pools.is_empty() { Ok(()) } else { let err_msg = format!( "Failed to teardown already set up pools: {:?}", untorndown_pools
); Err(StratisError::Engine(ErrorEnum::Error, err_msg)) } }
random_line_split
cleanup.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // Code to handle cleanup after a failed operation. use crate::stratis::{ErrorEnum, StratisError, StratisResult}; use crate::engine::structures::Table; use crate::engine::strat_engine::pool::StratPool; /// Teardown pools. pub fn teardown_pools(pools: Table<StratPool>) -> StratisResult<()>
{ let mut untorndown_pools = Vec::new(); for (_, uuid, mut pool) in pools { pool.teardown() .unwrap_or_else(|_| untorndown_pools.push(uuid)); } if untorndown_pools.is_empty() { Ok(()) } else { let err_msg = format!( "Failed to teardown already set up pools: {:?}", untorndown_pools ); Err(StratisError::Engine(ErrorEnum::Error, err_msg)) } }
identifier_body
spi_master.rs
//! Traits and parameters for SPI master communication. use core::option::Option; /// Values for the ordering of bits #[derive(Copy, Clone)] pub enum DataOrder {MSBFirst, LSBFirst} /// Values for the clock polarity (idle state or CPOL) #[derive(Copy, Clone)] pub enum ClockPolarity {IdleHigh, IdleLow} /// Which clock edge values are sampled on #[derive(Copy, Clone)] pub enum
{SampleLeading, SampleTrailing} pub trait SpiCallback { /// Called when a read/write operation finishes fn read_write_done(&'static self); } /// The `SpiMaster` trait for interacting with SPI slave /// devices at a byte or buffer level. /// /// Using SpiMaster normally involves three steps: /// /// 1. Configure the SPI bus for a peripheral /// 1a. Call set_chip_select to select which peripheral and /// turn on SPI /// 1b. Call set operations as needed to configure bus /// 2. Invoke read, write, read_write on SpiMaster /// 3a. Call clear_chip_select to turn off bus, or /// 3b. Call set_chip_select to choose another peripheral, /// go to step 1b or 2. /// /// This interface assumes that the SPI configuration for /// a particular peripheral persists across chip select. For /// example, with this set of calls: /// /// set_chip_select(1); /// set_phase(SampleLeading); /// set_chip_select(2); /// set_phase(SampleTrailing); /// set_chip_select(1); /// write_byte(0); // Uses SampleLeading /// /// If additional chip selects are needed, they can be performed /// with GPIO and manual re-initialization of settings. /// /// set_chip_select(0); /// set_phase(SampleLeading); /// pin_a.set(); /// write_byte(0xaa); // Uses SampleLeading /// pin_a.clear(); /// set_phase(SampleTrailing); /// pin_b.set(); /// write_byte(0xaa); // Uses SampleTrailing /// pub trait SpiMaster { fn init(&mut self, client: &'static SpiCallback); fn is_busy(&self) -> bool; /// Perform an asynchronous read/write operation, whose /// completion is signaled by invoking SpiCallback on /// the initialzied client. write_buffer must be Some, /// read_buffer may be None. If read_buffer is Some, the /// length of the operation is the minimum of the size of /// the two buffers. fn read_write_bytes(&self, mut write_buffer: Option<&'static mut [u8]>, mut read_buffer: Option<&'static mut [u8]>, len: usize) -> bool; fn write_byte(&self, val: u8); fn read_byte(&self) -> u8; fn read_write_byte(&self, val: u8) -> u8; /// Returns whether this chip select is valid and was /// applied, 0 is always valid. fn set_chip_select(&self, cs: u8) -> bool; fn clear_chip_select(&self); /// Returns the actual rate set fn set_rate(&self, rate: u32) -> u32; fn set_clock(&self, polarity: ClockPolarity); fn set_phase(&self, phase: ClockPhase); }
ClockPhase
identifier_name
spi_master.rs
//! Traits and parameters for SPI master communication. use core::option::Option; /// Values for the ordering of bits #[derive(Copy, Clone)] pub enum DataOrder {MSBFirst, LSBFirst} /// Values for the clock polarity (idle state or CPOL) #[derive(Copy, Clone)] pub enum ClockPolarity {IdleHigh, IdleLow} /// Which clock edge values are sampled on #[derive(Copy, Clone)] pub enum ClockPhase {SampleLeading, SampleTrailing} pub trait SpiCallback { /// Called when a read/write operation finishes fn read_write_done(&'static self); } /// The `SpiMaster` trait for interacting with SPI slave /// devices at a byte or buffer level. /// /// Using SpiMaster normally involves three steps: /// /// 1. Configure the SPI bus for a peripheral /// 1a. Call set_chip_select to select which peripheral and /// turn on SPI /// 1b. Call set operations as needed to configure bus /// 2. Invoke read, write, read_write on SpiMaster /// 3a. Call clear_chip_select to turn off bus, or /// 3b. Call set_chip_select to choose another peripheral, /// go to step 1b or 2. /// /// This interface assumes that the SPI configuration for /// a particular peripheral persists across chip select. For /// example, with this set of calls: /// /// set_chip_select(1); /// set_phase(SampleLeading); /// set_chip_select(2); /// set_phase(SampleTrailing); /// set_chip_select(1); /// write_byte(0); // Uses SampleLeading /// /// If additional chip selects are needed, they can be performed /// with GPIO and manual re-initialization of settings. /// /// set_chip_select(0); /// set_phase(SampleLeading); /// pin_a.set(); /// write_byte(0xaa); // Uses SampleLeading /// pin_a.clear(); /// set_phase(SampleTrailing); /// pin_b.set(); /// write_byte(0xaa); // Uses SampleTrailing /// pub trait SpiMaster { fn init(&mut self, client: &'static SpiCallback); fn is_busy(&self) -> bool; /// Perform an asynchronous read/write operation, whose /// completion is signaled by invoking SpiCallback on /// the initialzied client. write_buffer must be Some, /// read_buffer may be None. If read_buffer is Some, the /// length of the operation is the minimum of the size of /// the two buffers. fn read_write_bytes(&self, mut write_buffer: Option<&'static mut [u8]>, mut read_buffer: Option<&'static mut [u8]>, len: usize) -> bool; fn write_byte(&self, val: u8); fn read_byte(&self) -> u8; fn read_write_byte(&self, val: u8) -> u8;
/// Returns whether this chip select is valid and was /// applied, 0 is always valid. fn set_chip_select(&self, cs: u8) -> bool; fn clear_chip_select(&self); /// Returns the actual rate set fn set_rate(&self, rate: u32) -> u32; fn set_clock(&self, polarity: ClockPolarity); fn set_phase(&self, phase: ClockPhase); }
random_line_split
main.rs
extern crate term_size; extern crate getch; extern crate doh; use getch::Getch; use std::process::exit; use std::io::{Write, stdout, stderr}; fn main() { let ec = handler_main(); exit(ec); } fn handler_main() -> i32 { if let Err((msg, errc)) = real_main() { let _ = writeln!(stderr(), "{}", msg); errc } else
} fn real_main() -> Result<(), (String, i32)> { let opts = doh::Options::parse(); let termsize = try!(term_size::dimensions().ok_or_else(|| ("Unknown terminal dimensions.".to_string(), 1))); let _cursor = doh::util::RaiiGuard::new(|| print!("{}", doh::ops::term::show_cursor(false)), || print!("{}", doh::ops::term::show_cursor(true))); let input = Getch::new(); let mut ctx = doh::ops::ListContext::new(opts.remote_dir.clone()); while try!(ctx.one_loop(&mut stdout(), &input, termsize).map_err(|e| (format!("Listing failure: {}", e), 3))) { println!(); } Ok(()) }
{ 0 }
conditional_block
main.rs
extern crate term_size; extern crate getch; extern crate doh; use getch::Getch; use std::process::exit; use std::io::{Write, stdout, stderr}; fn main()
fn handler_main() -> i32 { if let Err((msg, errc)) = real_main() { let _ = writeln!(stderr(), "{}", msg); errc } else { 0 } } fn real_main() -> Result<(), (String, i32)> { let opts = doh::Options::parse(); let termsize = try!(term_size::dimensions().ok_or_else(|| ("Unknown terminal dimensions.".to_string(), 1))); let _cursor = doh::util::RaiiGuard::new(|| print!("{}", doh::ops::term::show_cursor(false)), || print!("{}", doh::ops::term::show_cursor(true))); let input = Getch::new(); let mut ctx = doh::ops::ListContext::new(opts.remote_dir.clone()); while try!(ctx.one_loop(&mut stdout(), &input, termsize).map_err(|e| (format!("Listing failure: {}", e), 3))) { println!(); } Ok(()) }
{ let ec = handler_main(); exit(ec); }
identifier_body
main.rs
extern crate term_size; extern crate getch; extern crate doh; use getch::Getch; use std::process::exit; use std::io::{Write, stdout, stderr}; fn main() { let ec = handler_main(); exit(ec);
if let Err((msg, errc)) = real_main() { let _ = writeln!(stderr(), "{}", msg); errc } else { 0 } } fn real_main() -> Result<(), (String, i32)> { let opts = doh::Options::parse(); let termsize = try!(term_size::dimensions().ok_or_else(|| ("Unknown terminal dimensions.".to_string(), 1))); let _cursor = doh::util::RaiiGuard::new(|| print!("{}", doh::ops::term::show_cursor(false)), || print!("{}", doh::ops::term::show_cursor(true))); let input = Getch::new(); let mut ctx = doh::ops::ListContext::new(opts.remote_dir.clone()); while try!(ctx.one_loop(&mut stdout(), &input, termsize).map_err(|e| (format!("Listing failure: {}", e), 3))) { println!(); } Ok(()) }
} fn handler_main() -> i32 {
random_line_split
main.rs
extern crate term_size; extern crate getch; extern crate doh; use getch::Getch; use std::process::exit; use std::io::{Write, stdout, stderr}; fn main() { let ec = handler_main(); exit(ec); } fn
() -> i32 { if let Err((msg, errc)) = real_main() { let _ = writeln!(stderr(), "{}", msg); errc } else { 0 } } fn real_main() -> Result<(), (String, i32)> { let opts = doh::Options::parse(); let termsize = try!(term_size::dimensions().ok_or_else(|| ("Unknown terminal dimensions.".to_string(), 1))); let _cursor = doh::util::RaiiGuard::new(|| print!("{}", doh::ops::term::show_cursor(false)), || print!("{}", doh::ops::term::show_cursor(true))); let input = Getch::new(); let mut ctx = doh::ops::ListContext::new(opts.remote_dir.clone()); while try!(ctx.one_loop(&mut stdout(), &input, termsize).map_err(|e| (format!("Listing failure: {}", e), 3))) { println!(); } Ok(()) }
handler_main
identifier_name
rfc2045.rs
//! Module for dealing with RFC2045 style headers. use super::rfc5322::Rfc5322Parser; use std::collections::HashMap; /// Parser over RFC 2045 style headers. /// /// Things of the style `value; param1=foo; param2="bar"` pub struct Rfc2045Parser<'s> { parser: Rfc5322Parser<'s>, } impl<'s> Rfc2045Parser<'s> { /// Create a new parser over `s` pub fn new(s: &str) -> Rfc2045Parser { Rfc2045Parser { parser: Rfc5322Parser::new(s) } } fn consume_token(&mut self) -> Option<String> { let token = self.parser.consume_while(|c| { match c { // Not any tspecials '(' | ')' | '<' | '>' | '@' | ',' | ';' | ':' | '\\' | '\"' | '/' | '[' | ']' | '?' | '=' => false, '!'...'~' => true, _ => false, } }); if token.len() > 0 { Some(token) } else { None } } /// Consume up to all of the input into the value and a hashmap /// over parameters to values. pub fn consume_all(&mut self) -> (String, HashMap<String, String>) { let value = self.parser.consume_while(|c| { c!= ';' }); // Find the parameters let mut params = HashMap::new(); while!self.parser.eof() { // Eat the ; and any whitespace assert_eq!(self.parser.consume_char(), Some(';')); self.parser.consume_linear_whitespace(); let attribute = self.consume_token(); assert_eq!(self.parser.consume_char(), Some('=')); // Value can be token or quoted-string let value = if self.parser.peek() == '"' { self.parser.consume_quoted_string() } else { self.consume_token() }; match (attribute, value) { (Some(attrib), Some(val)) => { params.insert(attrib, val); }, _ => {} } } (value, params) } } #[cfg(test)] mod tests { use super::*; use std::collections::HashMap; struct ParserTestCase<'s> { input: &'s str, output: (&'s str, Vec<(&'s str, &'s str)>), name: &'s str, } #[test] pub fn
() { let tests = vec![ ParserTestCase { input: "foo/bar", output: ("foo/bar", vec![]), name: "Basic value", }, ParserTestCase { input: "foo/bar; foo=bar", output: ("foo/bar", vec![ ("foo", "bar"), ]), name: "Basic value with parameter", }, ParserTestCase { input: "foo/bar; foo=\"bar\"", output: ("foo/bar", vec![ ("foo", "bar"), ]), name: "Basic value with quoted parameter", }, ParserTestCase { input: "foo/bar; foo=\"bar\"; baz=qux", output: ("foo/bar", vec![ ("foo", "bar"), ("baz", "qux"), ]), name: "Multiple values", }, ]; for test in tests.into_iter() { let (expected_value, expected_param_list) = test.output; let mut expected_params = HashMap::new(); for &(param_name, param_value) in expected_param_list.iter() { expected_params.insert(param_name.to_string(), param_value.to_string()); } let mut parser = Rfc2045Parser::new(test.input); let (value, parameters) = parser.consume_all(); assert!(value == expected_value.to_string(), test.name); assert!(parameters == expected_params, test.name); } } }
test_foo
identifier_name
rfc2045.rs
//! Module for dealing with RFC2045 style headers. use super::rfc5322::Rfc5322Parser; use std::collections::HashMap; /// Parser over RFC 2045 style headers. /// /// Things of the style `value; param1=foo; param2="bar"` pub struct Rfc2045Parser<'s> { parser: Rfc5322Parser<'s>, } impl<'s> Rfc2045Parser<'s> { /// Create a new parser over `s` pub fn new(s: &str) -> Rfc2045Parser { Rfc2045Parser { parser: Rfc5322Parser::new(s) } } fn consume_token(&mut self) -> Option<String> { let token = self.parser.consume_while(|c| { match c { // Not any tspecials '(' | ')' | '<' | '>' | '@' | ',' | ';' | ':' | '\\' | '\"' | '/' | '[' | ']' | '?' | '=' => false, '!'...'~' => true, _ => false, } }); if token.len() > 0 { Some(token) } else { None } } /// Consume up to all of the input into the value and a hashmap /// over parameters to values. pub fn consume_all(&mut self) -> (String, HashMap<String, String>) { let value = self.parser.consume_while(|c| { c!= ';' }); // Find the parameters let mut params = HashMap::new(); while!self.parser.eof() { // Eat the ; and any whitespace assert_eq!(self.parser.consume_char(), Some(';')); self.parser.consume_linear_whitespace(); let attribute = self.consume_token(); assert_eq!(self.parser.consume_char(), Some('=')); // Value can be token or quoted-string let value = if self.parser.peek() == '"' { self.parser.consume_quoted_string() } else {
(Some(attrib), Some(val)) => { params.insert(attrib, val); }, _ => {} } } (value, params) } } #[cfg(test)] mod tests { use super::*; use std::collections::HashMap; struct ParserTestCase<'s> { input: &'s str, output: (&'s str, Vec<(&'s str, &'s str)>), name: &'s str, } #[test] pub fn test_foo() { let tests = vec![ ParserTestCase { input: "foo/bar", output: ("foo/bar", vec![]), name: "Basic value", }, ParserTestCase { input: "foo/bar; foo=bar", output: ("foo/bar", vec![ ("foo", "bar"), ]), name: "Basic value with parameter", }, ParserTestCase { input: "foo/bar; foo=\"bar\"", output: ("foo/bar", vec![ ("foo", "bar"), ]), name: "Basic value with quoted parameter", }, ParserTestCase { input: "foo/bar; foo=\"bar\"; baz=qux", output: ("foo/bar", vec![ ("foo", "bar"), ("baz", "qux"), ]), name: "Multiple values", }, ]; for test in tests.into_iter() { let (expected_value, expected_param_list) = test.output; let mut expected_params = HashMap::new(); for &(param_name, param_value) in expected_param_list.iter() { expected_params.insert(param_name.to_string(), param_value.to_string()); } let mut parser = Rfc2045Parser::new(test.input); let (value, parameters) = parser.consume_all(); assert!(value == expected_value.to_string(), test.name); assert!(parameters == expected_params, test.name); } } }
self.consume_token() }; match (attribute, value) {
random_line_split
rfc2045.rs
//! Module for dealing with RFC2045 style headers. use super::rfc5322::Rfc5322Parser; use std::collections::HashMap; /// Parser over RFC 2045 style headers. /// /// Things of the style `value; param1=foo; param2="bar"` pub struct Rfc2045Parser<'s> { parser: Rfc5322Parser<'s>, } impl<'s> Rfc2045Parser<'s> { /// Create a new parser over `s` pub fn new(s: &str) -> Rfc2045Parser { Rfc2045Parser { parser: Rfc5322Parser::new(s) } } fn consume_token(&mut self) -> Option<String> { let token = self.parser.consume_while(|c| { match c { // Not any tspecials '(' | ')' | '<' | '>' | '@' | ',' | ';' | ':' | '\\' | '\"' | '/' | '[' | ']' | '?' | '=' => false, '!'...'~' => true, _ => false, } }); if token.len() > 0 { Some(token) } else { None } } /// Consume up to all of the input into the value and a hashmap /// over parameters to values. pub fn consume_all(&mut self) -> (String, HashMap<String, String>) { let value = self.parser.consume_while(|c| { c!= ';' }); // Find the parameters let mut params = HashMap::new(); while!self.parser.eof() { // Eat the ; and any whitespace assert_eq!(self.parser.consume_char(), Some(';')); self.parser.consume_linear_whitespace(); let attribute = self.consume_token(); assert_eq!(self.parser.consume_char(), Some('=')); // Value can be token or quoted-string let value = if self.parser.peek() == '"' { self.parser.consume_quoted_string() } else { self.consume_token() }; match (attribute, value) { (Some(attrib), Some(val)) =>
, _ => {} } } (value, params) } } #[cfg(test)] mod tests { use super::*; use std::collections::HashMap; struct ParserTestCase<'s> { input: &'s str, output: (&'s str, Vec<(&'s str, &'s str)>), name: &'s str, } #[test] pub fn test_foo() { let tests = vec![ ParserTestCase { input: "foo/bar", output: ("foo/bar", vec![]), name: "Basic value", }, ParserTestCase { input: "foo/bar; foo=bar", output: ("foo/bar", vec![ ("foo", "bar"), ]), name: "Basic value with parameter", }, ParserTestCase { input: "foo/bar; foo=\"bar\"", output: ("foo/bar", vec![ ("foo", "bar"), ]), name: "Basic value with quoted parameter", }, ParserTestCase { input: "foo/bar; foo=\"bar\"; baz=qux", output: ("foo/bar", vec![ ("foo", "bar"), ("baz", "qux"), ]), name: "Multiple values", }, ]; for test in tests.into_iter() { let (expected_value, expected_param_list) = test.output; let mut expected_params = HashMap::new(); for &(param_name, param_value) in expected_param_list.iter() { expected_params.insert(param_name.to_string(), param_value.to_string()); } let mut parser = Rfc2045Parser::new(test.input); let (value, parameters) = parser.consume_all(); assert!(value == expected_value.to_string(), test.name); assert!(parameters == expected_params, test.name); } } }
{ params.insert(attrib, val); }
conditional_block
server.rs
//! A low-level interface to send and receive server-client protocol messages use std; use std::sync::{Arc, Mutex}; use std::sync::mpsc::{Sender, Receiver, TryRecvError}; use std::sync::atomic::{Ordering, AtomicUsize}; use bincode; use common::protocol; use common::socket::{SendSocket, ReceiveSocket}; #[allow(missing_docs)] #[derive(Clone)] pub struct SSender {
impl SSender { #[allow(missing_docs)] pub fn new(sender: Sender<Box<[u8]>>) -> SSender { SSender { sender: sender, bytes_sent: Arc::new(AtomicUsize::new(0)), } } #[allow(missing_docs)] pub fn tell(&self, msg: &protocol::ClientToServer) { let msg = bincode::serialize(msg, bincode::Infinite).unwrap(); // We aren't reading this until long after the write, so we use `Relaxed` self.bytes_sent.fetch_add(msg.len() as usize, Ordering::Relaxed); self.sender.send(msg.into_boxed_slice()).unwrap(); } } #[allow(missing_docs)] #[derive(Clone)] pub struct SReceiver (Arc<Mutex<Receiver<Box<[u8]>>>>); impl SReceiver { #[allow(missing_docs)] pub fn try(&self) -> Option<protocol::ServerToClient> { match self.0.lock().unwrap().try_recv() { Ok(msg) => Some(bincode::deserialize(&Vec::from(msg)).unwrap()), Err(TryRecvError::Empty) => None, e => { e.unwrap(); unreachable!(); }, } } #[allow(missing_docs)] pub fn wait(&self) -> protocol::ServerToClient { let msg = self.0.lock().unwrap().recv().unwrap(); bincode::deserialize(msg.as_ref()).unwrap() } } #[allow(missing_docs)] #[derive(Clone)] pub struct T { pub talk : SSender, pub listen : SReceiver, } #[allow(missing_docs)] pub fn new( server_url: &str, listen_url: &str, ) -> T { let (send_send, send_recv) = std::sync::mpsc::channel(); let (recv_send, recv_recv) = std::sync::mpsc::channel(); let _recv_thread ={ let listen_url = listen_url.to_owned(); let recv_send = recv_send.clone(); std::thread::spawn(move || { let mut listen_socket = ReceiveSocket::new( listen_url.clone().as_ref(), Some(std::time::Duration::from_secs(30)), ); loop { match listen_socket.read() { None => break, Some(msg) => { recv_send.send(msg.into_boxed_slice()).unwrap() }, } } }) }; let _send_thread = { let server_url = server_url.to_owned(); std::thread::spawn(move || { let mut talk_socket = SendSocket::new( server_url.as_ref(), Some(std::time::Duration::from_secs(30)), ); loop { match send_recv.recv() { Err(_) => break, Ok(msg) => { let msg = Vec::from(msg); talk_socket.write(msg.as_ref()).unwrap(); }, } } }) }; T { talk: SSender::new(send_send), listen: SReceiver(Arc::new(Mutex::new(recv_recv))), } }
// A boxed slice is used to reduce the sent size pub sender: Sender<Box<[u8]>>, // Please replace with AtomicU64 when it becomes stable pub bytes_sent: Arc<AtomicUsize>, }
random_line_split
server.rs
//! A low-level interface to send and receive server-client protocol messages use std; use std::sync::{Arc, Mutex}; use std::sync::mpsc::{Sender, Receiver, TryRecvError}; use std::sync::atomic::{Ordering, AtomicUsize}; use bincode; use common::protocol; use common::socket::{SendSocket, ReceiveSocket}; #[allow(missing_docs)] #[derive(Clone)] pub struct SSender { // A boxed slice is used to reduce the sent size pub sender: Sender<Box<[u8]>>, // Please replace with AtomicU64 when it becomes stable pub bytes_sent: Arc<AtomicUsize>, } impl SSender { #[allow(missing_docs)] pub fn new(sender: Sender<Box<[u8]>>) -> SSender { SSender { sender: sender, bytes_sent: Arc::new(AtomicUsize::new(0)), } } #[allow(missing_docs)] pub fn tell(&self, msg: &protocol::ClientToServer) { let msg = bincode::serialize(msg, bincode::Infinite).unwrap(); // We aren't reading this until long after the write, so we use `Relaxed` self.bytes_sent.fetch_add(msg.len() as usize, Ordering::Relaxed); self.sender.send(msg.into_boxed_slice()).unwrap(); } } #[allow(missing_docs)] #[derive(Clone)] pub struct SReceiver (Arc<Mutex<Receiver<Box<[u8]>>>>); impl SReceiver { #[allow(missing_docs)] pub fn try(&self) -> Option<protocol::ServerToClient> { match self.0.lock().unwrap().try_recv() { Ok(msg) => Some(bincode::deserialize(&Vec::from(msg)).unwrap()), Err(TryRecvError::Empty) => None, e => { e.unwrap(); unreachable!(); }, } } #[allow(missing_docs)] pub fn wait(&self) -> protocol::ServerToClient { let msg = self.0.lock().unwrap().recv().unwrap(); bincode::deserialize(msg.as_ref()).unwrap() } } #[allow(missing_docs)] #[derive(Clone)] pub struct
{ pub talk : SSender, pub listen : SReceiver, } #[allow(missing_docs)] pub fn new( server_url: &str, listen_url: &str, ) -> T { let (send_send, send_recv) = std::sync::mpsc::channel(); let (recv_send, recv_recv) = std::sync::mpsc::channel(); let _recv_thread ={ let listen_url = listen_url.to_owned(); let recv_send = recv_send.clone(); std::thread::spawn(move || { let mut listen_socket = ReceiveSocket::new( listen_url.clone().as_ref(), Some(std::time::Duration::from_secs(30)), ); loop { match listen_socket.read() { None => break, Some(msg) => { recv_send.send(msg.into_boxed_slice()).unwrap() }, } } }) }; let _send_thread = { let server_url = server_url.to_owned(); std::thread::spawn(move || { let mut talk_socket = SendSocket::new( server_url.as_ref(), Some(std::time::Duration::from_secs(30)), ); loop { match send_recv.recv() { Err(_) => break, Ok(msg) => { let msg = Vec::from(msg); talk_socket.write(msg.as_ref()).unwrap(); }, } } }) }; T { talk: SSender::new(send_send), listen: SReceiver(Arc::new(Mutex::new(recv_recv))), } }
T
identifier_name
server.rs
//! A low-level interface to send and receive server-client protocol messages use std; use std::sync::{Arc, Mutex}; use std::sync::mpsc::{Sender, Receiver, TryRecvError}; use std::sync::atomic::{Ordering, AtomicUsize}; use bincode; use common::protocol; use common::socket::{SendSocket, ReceiveSocket}; #[allow(missing_docs)] #[derive(Clone)] pub struct SSender { // A boxed slice is used to reduce the sent size pub sender: Sender<Box<[u8]>>, // Please replace with AtomicU64 when it becomes stable pub bytes_sent: Arc<AtomicUsize>, } impl SSender { #[allow(missing_docs)] pub fn new(sender: Sender<Box<[u8]>>) -> SSender { SSender { sender: sender, bytes_sent: Arc::new(AtomicUsize::new(0)), } } #[allow(missing_docs)] pub fn tell(&self, msg: &protocol::ClientToServer) { let msg = bincode::serialize(msg, bincode::Infinite).unwrap(); // We aren't reading this until long after the write, so we use `Relaxed` self.bytes_sent.fetch_add(msg.len() as usize, Ordering::Relaxed); self.sender.send(msg.into_boxed_slice()).unwrap(); } } #[allow(missing_docs)] #[derive(Clone)] pub struct SReceiver (Arc<Mutex<Receiver<Box<[u8]>>>>); impl SReceiver { #[allow(missing_docs)] pub fn try(&self) -> Option<protocol::ServerToClient>
#[allow(missing_docs)] pub fn wait(&self) -> protocol::ServerToClient { let msg = self.0.lock().unwrap().recv().unwrap(); bincode::deserialize(msg.as_ref()).unwrap() } } #[allow(missing_docs)] #[derive(Clone)] pub struct T { pub talk : SSender, pub listen : SReceiver, } #[allow(missing_docs)] pub fn new( server_url: &str, listen_url: &str, ) -> T { let (send_send, send_recv) = std::sync::mpsc::channel(); let (recv_send, recv_recv) = std::sync::mpsc::channel(); let _recv_thread ={ let listen_url = listen_url.to_owned(); let recv_send = recv_send.clone(); std::thread::spawn(move || { let mut listen_socket = ReceiveSocket::new( listen_url.clone().as_ref(), Some(std::time::Duration::from_secs(30)), ); loop { match listen_socket.read() { None => break, Some(msg) => { recv_send.send(msg.into_boxed_slice()).unwrap() }, } } }) }; let _send_thread = { let server_url = server_url.to_owned(); std::thread::spawn(move || { let mut talk_socket = SendSocket::new( server_url.as_ref(), Some(std::time::Duration::from_secs(30)), ); loop { match send_recv.recv() { Err(_) => break, Ok(msg) => { let msg = Vec::from(msg); talk_socket.write(msg.as_ref()).unwrap(); }, } } }) }; T { talk: SSender::new(send_send), listen: SReceiver(Arc::new(Mutex::new(recv_recv))), } }
{ match self.0.lock().unwrap().try_recv() { Ok(msg) => Some(bincode::deserialize(&Vec::from(msg)).unwrap()), Err(TryRecvError::Empty) => None, e => { e.unwrap(); unreachable!(); }, } }
identifier_body
definition.rs
use iron::mime::Mime; use iron::prelude::*; use iron::status; use serde_json::to_string; use super::EngineProvider; use crate::engine::{Buffer, Context, CursorPosition, Definition}; /// Given a location, return where the identifier is defined /// /// Possible responses include /// /// - `200 OK` the request was successful and a JSON object is returned. /// - `204 No Content` the request was successful, but no match was found. /// - `400 Bad Request` the request payload was malformed /// - `500 Internal Server Error` some unexpected error occurred pub fn find(req: &mut Request) -> IronResult<Response> { // Parse the request. If the request doesn't parse properly, the request is invalid, and a 400 // BadRequest is returned. let fdr = match req.get::<::bodyparser::Struct<FindDefinitionRequest>>() { Ok(Some(s)) => { trace!("definition::find parsed FindDefinitionRequest"); s } Ok(None) => { trace!("definition::find failed parsing FindDefinitionRequest"); return Ok(Response::with(status::BadRequest)); } Err(err) => { trace!("definition::find received error while parsing FindDefinitionRequest"); return Err(IronError::new(err, status::InternalServerError)); } }; let mutex = req.get::<::persistent::Write<EngineProvider>>().unwrap(); let engine = mutex.lock().unwrap_or_else(|e| e.into_inner()); match engine.find_definition(&fdr.context()) { // 200 OK; found the definition Ok(Some(definition)) => { trace!("definition::find got a match"); let res = FindDefinitionResponse::from(definition); let content_type = "application/json".parse::<Mime>().unwrap(); Ok(Response::with(( content_type, status::Ok, to_string(&res).unwrap(), ))) } // 204 No Content; Everything went ok, but the definition was not found. Ok(None) => { trace!("definition::find did not find a match"); Ok(Response::with(status::NoContent)) } // 500 Internal Server Error; Error occurred while searching for the definition Err(err) => { trace!("definition::find encountered an error"); Err(IronError::new(err, status::InternalServerError)) } } } impl From<Definition> for FindDefinitionResponse { fn from(def: Definition) -> FindDefinitionResponse { FindDefinitionResponse { file_path: def.file_path, column: def.position.col, line: def.position.line, text: def.text, context: def.text_context, kind: def.dtype, docs: def.docs, } } } #[derive(Debug, Deserialize, Clone)] struct FindDefinitionRequest { pub buffers: Vec<Buffer>, pub file_path: String, pub column: usize, pub line: usize, } impl FindDefinitionRequest { pub fn context(self) -> Context { let cursor = CursorPosition { line: self.line, col: self.column, }; Context::new(self.buffers, cursor, self.file_path) } } #[test] fn find_definition_request_from_json() { let s = stringify!({ "file_path": "src.rs", "buffers": [{ "file_path": "src.rs", "contents": "fn foo() {}\nfn bar() {}\nfn main() {\nfoo();\n}" }], "line": 4, "column": 3 }); let req: FindDefinitionRequest = serde_json::from_str(s).unwrap(); assert_eq!(req.file_path, "src.rs"); assert_eq!(req.line, 4); assert_eq!(req.column, 3);
struct FindDefinitionResponse { pub file_path: String, pub column: usize, pub line: usize, pub text: String, pub context: String, pub kind: String, pub docs: String, }
} #[derive(Debug, Deserialize, Serialize)]
random_line_split
definition.rs
use iron::mime::Mime; use iron::prelude::*; use iron::status; use serde_json::to_string; use super::EngineProvider; use crate::engine::{Buffer, Context, CursorPosition, Definition}; /// Given a location, return where the identifier is defined /// /// Possible responses include /// /// - `200 OK` the request was successful and a JSON object is returned. /// - `204 No Content` the request was successful, but no match was found. /// - `400 Bad Request` the request payload was malformed /// - `500 Internal Server Error` some unexpected error occurred pub fn find(req: &mut Request) -> IronResult<Response> { // Parse the request. If the request doesn't parse properly, the request is invalid, and a 400 // BadRequest is returned. let fdr = match req.get::<::bodyparser::Struct<FindDefinitionRequest>>() { Ok(Some(s)) => { trace!("definition::find parsed FindDefinitionRequest"); s } Ok(None) => { trace!("definition::find failed parsing FindDefinitionRequest"); return Ok(Response::with(status::BadRequest)); } Err(err) => { trace!("definition::find received error while parsing FindDefinitionRequest"); return Err(IronError::new(err, status::InternalServerError)); } }; let mutex = req.get::<::persistent::Write<EngineProvider>>().unwrap(); let engine = mutex.lock().unwrap_or_else(|e| e.into_inner()); match engine.find_definition(&fdr.context()) { // 200 OK; found the definition Ok(Some(definition)) => { trace!("definition::find got a match"); let res = FindDefinitionResponse::from(definition); let content_type = "application/json".parse::<Mime>().unwrap(); Ok(Response::with(( content_type, status::Ok, to_string(&res).unwrap(), ))) } // 204 No Content; Everything went ok, but the definition was not found. Ok(None) => { trace!("definition::find did not find a match"); Ok(Response::with(status::NoContent)) } // 500 Internal Server Error; Error occurred while searching for the definition Err(err) => { trace!("definition::find encountered an error"); Err(IronError::new(err, status::InternalServerError)) } } } impl From<Definition> for FindDefinitionResponse { fn from(def: Definition) -> FindDefinitionResponse { FindDefinitionResponse { file_path: def.file_path, column: def.position.col, line: def.position.line, text: def.text, context: def.text_context, kind: def.dtype, docs: def.docs, } } } #[derive(Debug, Deserialize, Clone)] struct FindDefinitionRequest { pub buffers: Vec<Buffer>, pub file_path: String, pub column: usize, pub line: usize, } impl FindDefinitionRequest { pub fn context(self) -> Context { let cursor = CursorPosition { line: self.line, col: self.column, }; Context::new(self.buffers, cursor, self.file_path) } } #[test] fn
() { let s = stringify!({ "file_path": "src.rs", "buffers": [{ "file_path": "src.rs", "contents": "fn foo() {}\nfn bar() {}\nfn main() {\nfoo();\n}" }], "line": 4, "column": 3 }); let req: FindDefinitionRequest = serde_json::from_str(s).unwrap(); assert_eq!(req.file_path, "src.rs"); assert_eq!(req.line, 4); assert_eq!(req.column, 3); } #[derive(Debug, Deserialize, Serialize)] struct FindDefinitionResponse { pub file_path: String, pub column: usize, pub line: usize, pub text: String, pub context: String, pub kind: String, pub docs: String, }
find_definition_request_from_json
identifier_name
definition.rs
use iron::mime::Mime; use iron::prelude::*; use iron::status; use serde_json::to_string; use super::EngineProvider; use crate::engine::{Buffer, Context, CursorPosition, Definition}; /// Given a location, return where the identifier is defined /// /// Possible responses include /// /// - `200 OK` the request was successful and a JSON object is returned. /// - `204 No Content` the request was successful, but no match was found. /// - `400 Bad Request` the request payload was malformed /// - `500 Internal Server Error` some unexpected error occurred pub fn find(req: &mut Request) -> IronResult<Response>
match engine.find_definition(&fdr.context()) { // 200 OK; found the definition Ok(Some(definition)) => { trace!("definition::find got a match"); let res = FindDefinitionResponse::from(definition); let content_type = "application/json".parse::<Mime>().unwrap(); Ok(Response::with(( content_type, status::Ok, to_string(&res).unwrap(), ))) } // 204 No Content; Everything went ok, but the definition was not found. Ok(None) => { trace!("definition::find did not find a match"); Ok(Response::with(status::NoContent)) } // 500 Internal Server Error; Error occurred while searching for the definition Err(err) => { trace!("definition::find encountered an error"); Err(IronError::new(err, status::InternalServerError)) } } } impl From<Definition> for FindDefinitionResponse { fn from(def: Definition) -> FindDefinitionResponse { FindDefinitionResponse { file_path: def.file_path, column: def.position.col, line: def.position.line, text: def.text, context: def.text_context, kind: def.dtype, docs: def.docs, } } } #[derive(Debug, Deserialize, Clone)] struct FindDefinitionRequest { pub buffers: Vec<Buffer>, pub file_path: String, pub column: usize, pub line: usize, } impl FindDefinitionRequest { pub fn context(self) -> Context { let cursor = CursorPosition { line: self.line, col: self.column, }; Context::new(self.buffers, cursor, self.file_path) } } #[test] fn find_definition_request_from_json() { let s = stringify!({ "file_path": "src.rs", "buffers": [{ "file_path": "src.rs", "contents": "fn foo() {}\nfn bar() {}\nfn main() {\nfoo();\n}" }], "line": 4, "column": 3 }); let req: FindDefinitionRequest = serde_json::from_str(s).unwrap(); assert_eq!(req.file_path, "src.rs"); assert_eq!(req.line, 4); assert_eq!(req.column, 3); } #[derive(Debug, Deserialize, Serialize)] struct FindDefinitionResponse { pub file_path: String, pub column: usize, pub line: usize, pub text: String, pub context: String, pub kind: String, pub docs: String, }
{ // Parse the request. If the request doesn't parse properly, the request is invalid, and a 400 // BadRequest is returned. let fdr = match req.get::<::bodyparser::Struct<FindDefinitionRequest>>() { Ok(Some(s)) => { trace!("definition::find parsed FindDefinitionRequest"); s } Ok(None) => { trace!("definition::find failed parsing FindDefinitionRequest"); return Ok(Response::with(status::BadRequest)); } Err(err) => { trace!("definition::find received error while parsing FindDefinitionRequest"); return Err(IronError::new(err, status::InternalServerError)); } }; let mutex = req.get::<::persistent::Write<EngineProvider>>().unwrap(); let engine = mutex.lock().unwrap_or_else(|e| e.into_inner());
identifier_body
util.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fs::{self, File}; use std::io::Write; use std::path::{Path, PathBuf}; use std::str::FromStr; use hcore::package::{PackageIdent, PackageInstall}; use error::Result; use super::BUSYBOX_IDENT; const BIN_PATH: &'static str = "/bin"; /// Returns the `bin` path used for symlinking programs. pub fn bin_path() -> &'static Path { Path::new(BIN_PATH) } /// Returns the Package Identifier for a Busybox package. pub fn
() -> Result<PackageIdent> { Ok(PackageIdent::from_str(BUSYBOX_IDENT)?) } /// Returns the path to a package prefix for the provided Package Identifier in a root file system. /// /// # Errors /// /// * If a package cannot be loaded from in the root file system pub fn pkg_path_for<P: AsRef<Path>>(ident: &PackageIdent, rootfs: P) -> Result<PathBuf> { let pkg_install = PackageInstall::load(ident, Some(rootfs.as_ref()))?; Ok( Path::new("/").join( pkg_install .installed_path() .strip_prefix(rootfs.as_ref()) .expect("installed path contains rootfs path"), ), ) } /// Writes a truncated/new file at the provided path with the provided content. /// /// # Errors /// /// * If an `IO` error occurs while creating, tuncating, writing, or closing the file pub fn write_file<T>(file: T, content: &str) -> Result<()> where T: AsRef<Path>, { fs::create_dir_all(file.as_ref().parent().expect("Parent directory exists"))?; let mut f = File::create(file)?; f.write_all(content.as_bytes())?; Ok(()) }
busybox_ident
identifier_name
util.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fs::{self, File}; use std::io::Write; use std::path::{Path, PathBuf}; use std::str::FromStr; use hcore::package::{PackageIdent, PackageInstall}; use error::Result; use super::BUSYBOX_IDENT; const BIN_PATH: &'static str = "/bin"; /// Returns the `bin` path used for symlinking programs. pub fn bin_path() -> &'static Path { Path::new(BIN_PATH) } /// Returns the Package Identifier for a Busybox package. pub fn busybox_ident() -> Result<PackageIdent>
/// Returns the path to a package prefix for the provided Package Identifier in a root file system. /// /// # Errors /// /// * If a package cannot be loaded from in the root file system pub fn pkg_path_for<P: AsRef<Path>>(ident: &PackageIdent, rootfs: P) -> Result<PathBuf> { let pkg_install = PackageInstall::load(ident, Some(rootfs.as_ref()))?; Ok( Path::new("/").join( pkg_install .installed_path() .strip_prefix(rootfs.as_ref()) .expect("installed path contains rootfs path"), ), ) } /// Writes a truncated/new file at the provided path with the provided content. /// /// # Errors /// /// * If an `IO` error occurs while creating, tuncating, writing, or closing the file pub fn write_file<T>(file: T, content: &str) -> Result<()> where T: AsRef<Path>, { fs::create_dir_all(file.as_ref().parent().expect("Parent directory exists"))?; let mut f = File::create(file)?; f.write_all(content.as_bytes())?; Ok(()) }
{ Ok(PackageIdent::from_str(BUSYBOX_IDENT)?) }
identifier_body
util.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fs::{self, File}; use std::io::Write; use std::path::{Path, PathBuf}; use std::str::FromStr; use hcore::package::{PackageIdent, PackageInstall}; use error::Result; use super::BUSYBOX_IDENT; const BIN_PATH: &'static str = "/bin"; /// Returns the `bin` path used for symlinking programs. pub fn bin_path() -> &'static Path { Path::new(BIN_PATH) } /// Returns the Package Identifier for a Busybox package. pub fn busybox_ident() -> Result<PackageIdent> { Ok(PackageIdent::from_str(BUSYBOX_IDENT)?) } /// Returns the path to a package prefix for the provided Package Identifier in a root file system. /// /// # Errors /// /// * If a package cannot be loaded from in the root file system pub fn pkg_path_for<P: AsRef<Path>>(ident: &PackageIdent, rootfs: P) -> Result<PathBuf> {
Path::new("/").join( pkg_install .installed_path() .strip_prefix(rootfs.as_ref()) .expect("installed path contains rootfs path"), ), ) } /// Writes a truncated/new file at the provided path with the provided content. /// /// # Errors /// /// * If an `IO` error occurs while creating, tuncating, writing, or closing the file pub fn write_file<T>(file: T, content: &str) -> Result<()> where T: AsRef<Path>, { fs::create_dir_all(file.as_ref().parent().expect("Parent directory exists"))?; let mut f = File::create(file)?; f.write_all(content.as_bytes())?; Ok(()) }
let pkg_install = PackageInstall::load(ident, Some(rootfs.as_ref()))?; Ok(
random_line_split
proteins.rs
extern crate protein_translation as proteins; #[test] fn test_methionine() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("ATG"), Ok("methionine")); } #[test] fn test_cysteine_tgt() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("TGT"), Ok("cysteine")); } #[test] fn test_cysteine_tgy() { // "compressed" name for TGT and TGC let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("TGT"), info.name_for("TGY")); assert_eq!(info.name_for("TGC"), info.name_for("TGY")); } #[test] fn test_stop() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("TAA"), Ok("stop codon")); } #[test] fn test_valine() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("GTN"), Ok("valine")); } #[test] fn test_isoleucine() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("ATH"), Ok("isoleucine")); } #[test] fn test_arginine_name() { // In arginine CGA can be "compresed" both as CGN and as MGR let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("CGA"), Ok("arginine")); assert_eq!(info.name_for("CGN"), Ok("arginine")); assert_eq!(info.name_for("MGR"), Ok("arginine")); } #[test] fn empty_is_invalid() { let info = proteins::parse(make_pairs()); assert!(info.name_for("").is_err()); } #[test] fn x_is_not_shorthand_so_is_invalid() { let info = proteins::parse(make_pairs()); assert!(info.name_for("VWX").is_err()); } #[test] fn too_short_is_invalid() { let info = proteins::parse(make_pairs()); assert!(info.name_for("AT").is_err()); } #[test] fn too_long_is_invalid() { let info = proteins::parse(make_pairs()); assert!(info.name_for("ATTA").is_err()); } // The input data constructor. Returns a list of codon, name pairs. fn
() -> Vec<(&'static str, &'static str)> { let grouped = vec![ ("isoleucine", vec!["ATT", "ATC", "ATA"]), ("leucine", vec!["CTT", "CTC", "CTA", "CTG", "TTA", "TTG"]), ("valine", vec!["GTT", "GTC", "GTA", "GTG"]), ("phenylalanine", vec!["TTT", "TTC"]), ("methionine", vec!["ATG"]), ("cysteine", vec!["TGT", "TGC"]), ("alanine", vec!["GCT", "GCC", "GCA", "GCG"]), ("glycine", vec!["GGT", "GGC", "GGA", "GGG"]), ("proline", vec!["CCT", "CCC", "CCA", "CCG"]), ("threonine", vec!["ACT", "ACC", "ACA", "ACG"]), ("serine", vec!["TCT", "TCC", "TCA", "TCG", "AGT", "AGC"]), ("tyrosine", vec!["TAT", "TAC"]), ("tryptophan", vec!["TGG"]), ("glutamine", vec!["CAA", "CAG"]), ("asparagine", vec!["AAT", "AAC"]), ("histidine", vec!["CAT", "CAC"]), ("glutamic acid", vec!["GAA", "GAG"]), ("aspartic acid", vec!["GAT", "GAC"]), ("lysine", vec!["AAA", "AAG"]), ("arginine", vec!["CGT", "CGC", "CGA", "CGG", "AGA", "AGG"]), ("stop codon", vec!["TAA", "TAG", "TGA"])]; let mut pairs = Vec::<(&'static str, &'static str)>::new(); for (name, codons) in grouped.into_iter() { for codon in codons { pairs.push((codon, name)); } }; pairs.sort_by(|&(_, a), &(_, b)| a.cmp(b)); return pairs }
make_pairs
identifier_name
proteins.rs
extern crate protein_translation as proteins; #[test] fn test_methionine() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("ATG"), Ok("methionine")); } #[test] fn test_cysteine_tgt() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("TGT"), Ok("cysteine")); } #[test] fn test_cysteine_tgy() { // "compressed" name for TGT and TGC let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("TGT"), info.name_for("TGY")); assert_eq!(info.name_for("TGC"), info.name_for("TGY")); } #[test] fn test_stop() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("TAA"), Ok("stop codon")); } #[test] fn test_valine() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("GTN"), Ok("valine")); } #[test] fn test_isoleucine() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("ATH"), Ok("isoleucine")); } #[test] fn test_arginine_name() { // In arginine CGA can be "compresed" both as CGN and as MGR let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("CGA"), Ok("arginine")); assert_eq!(info.name_for("CGN"), Ok("arginine")); assert_eq!(info.name_for("MGR"), Ok("arginine")); } #[test] fn empty_is_invalid() { let info = proteins::parse(make_pairs());
assert!(info.name_for("").is_err()); } #[test] fn x_is_not_shorthand_so_is_invalid() { let info = proteins::parse(make_pairs()); assert!(info.name_for("VWX").is_err()); } #[test] fn too_short_is_invalid() { let info = proteins::parse(make_pairs()); assert!(info.name_for("AT").is_err()); } #[test] fn too_long_is_invalid() { let info = proteins::parse(make_pairs()); assert!(info.name_for("ATTA").is_err()); } // The input data constructor. Returns a list of codon, name pairs. fn make_pairs() -> Vec<(&'static str, &'static str)> { let grouped = vec![ ("isoleucine", vec!["ATT", "ATC", "ATA"]), ("leucine", vec!["CTT", "CTC", "CTA", "CTG", "TTA", "TTG"]), ("valine", vec!["GTT", "GTC", "GTA", "GTG"]), ("phenylalanine", vec!["TTT", "TTC"]), ("methionine", vec!["ATG"]), ("cysteine", vec!["TGT", "TGC"]), ("alanine", vec!["GCT", "GCC", "GCA", "GCG"]), ("glycine", vec!["GGT", "GGC", "GGA", "GGG"]), ("proline", vec!["CCT", "CCC", "CCA", "CCG"]), ("threonine", vec!["ACT", "ACC", "ACA", "ACG"]), ("serine", vec!["TCT", "TCC", "TCA", "TCG", "AGT", "AGC"]), ("tyrosine", vec!["TAT", "TAC"]), ("tryptophan", vec!["TGG"]), ("glutamine", vec!["CAA", "CAG"]), ("asparagine", vec!["AAT", "AAC"]), ("histidine", vec!["CAT", "CAC"]), ("glutamic acid", vec!["GAA", "GAG"]), ("aspartic acid", vec!["GAT", "GAC"]), ("lysine", vec!["AAA", "AAG"]), ("arginine", vec!["CGT", "CGC", "CGA", "CGG", "AGA", "AGG"]), ("stop codon", vec!["TAA", "TAG", "TGA"])]; let mut pairs = Vec::<(&'static str, &'static str)>::new(); for (name, codons) in grouped.into_iter() { for codon in codons { pairs.push((codon, name)); } }; pairs.sort_by(|&(_, a), &(_, b)| a.cmp(b)); return pairs }
random_line_split
proteins.rs
extern crate protein_translation as proteins; #[test] fn test_methionine() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("ATG"), Ok("methionine")); } #[test] fn test_cysteine_tgt() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("TGT"), Ok("cysteine")); } #[test] fn test_cysteine_tgy()
#[test] fn test_stop() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("TAA"), Ok("stop codon")); } #[test] fn test_valine() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("GTN"), Ok("valine")); } #[test] fn test_isoleucine() { let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("ATH"), Ok("isoleucine")); } #[test] fn test_arginine_name() { // In arginine CGA can be "compresed" both as CGN and as MGR let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("CGA"), Ok("arginine")); assert_eq!(info.name_for("CGN"), Ok("arginine")); assert_eq!(info.name_for("MGR"), Ok("arginine")); } #[test] fn empty_is_invalid() { let info = proteins::parse(make_pairs()); assert!(info.name_for("").is_err()); } #[test] fn x_is_not_shorthand_so_is_invalid() { let info = proteins::parse(make_pairs()); assert!(info.name_for("VWX").is_err()); } #[test] fn too_short_is_invalid() { let info = proteins::parse(make_pairs()); assert!(info.name_for("AT").is_err()); } #[test] fn too_long_is_invalid() { let info = proteins::parse(make_pairs()); assert!(info.name_for("ATTA").is_err()); } // The input data constructor. Returns a list of codon, name pairs. fn make_pairs() -> Vec<(&'static str, &'static str)> { let grouped = vec![ ("isoleucine", vec!["ATT", "ATC", "ATA"]), ("leucine", vec!["CTT", "CTC", "CTA", "CTG", "TTA", "TTG"]), ("valine", vec!["GTT", "GTC", "GTA", "GTG"]), ("phenylalanine", vec!["TTT", "TTC"]), ("methionine", vec!["ATG"]), ("cysteine", vec!["TGT", "TGC"]), ("alanine", vec!["GCT", "GCC", "GCA", "GCG"]), ("glycine", vec!["GGT", "GGC", "GGA", "GGG"]), ("proline", vec!["CCT", "CCC", "CCA", "CCG"]), ("threonine", vec!["ACT", "ACC", "ACA", "ACG"]), ("serine", vec!["TCT", "TCC", "TCA", "TCG", "AGT", "AGC"]), ("tyrosine", vec!["TAT", "TAC"]), ("tryptophan", vec!["TGG"]), ("glutamine", vec!["CAA", "CAG"]), ("asparagine", vec!["AAT", "AAC"]), ("histidine", vec!["CAT", "CAC"]), ("glutamic acid", vec!["GAA", "GAG"]), ("aspartic acid", vec!["GAT", "GAC"]), ("lysine", vec!["AAA", "AAG"]), ("arginine", vec!["CGT", "CGC", "CGA", "CGG", "AGA", "AGG"]), ("stop codon", vec!["TAA", "TAG", "TGA"])]; let mut pairs = Vec::<(&'static str, &'static str)>::new(); for (name, codons) in grouped.into_iter() { for codon in codons { pairs.push((codon, name)); } }; pairs.sort_by(|&(_, a), &(_, b)| a.cmp(b)); return pairs }
{ // "compressed" name for TGT and TGC let info = proteins::parse(make_pairs()); assert_eq!(info.name_for("TGT"), info.name_for("TGY")); assert_eq!(info.name_for("TGC"), info.name_for("TGY")); }
identifier_body
iced_error.rs
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors use alloc::borrow::Cow; use alloc::string::String; use core::fmt; #[cfg(feature = "std")] use std::error::Error; /// iced error #[derive(Debug, Clone)] pub struct IcedError { error: Cow<'static, str>, } impl IcedError { #[allow(dead_code)] pub(crate) fn new(error: &'static str) -> Self { Self { error: error.into() } } #[allow(dead_code)] pub(crate) fn with_string(error: String) -> Self { Self { error: error.into() } } }
#[allow(clippy::missing_inline_in_public_items)] fn description(&self) -> &str { &self.error } } impl fmt::Display for IcedError { #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", &self.error) } }
#[cfg(feature = "std")] impl Error for IcedError { // Required since MSRV < 1.42.0
random_line_split
iced_error.rs
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors use alloc::borrow::Cow; use alloc::string::String; use core::fmt; #[cfg(feature = "std")] use std::error::Error; /// iced error #[derive(Debug, Clone)] pub struct IcedError { error: Cow<'static, str>, } impl IcedError { #[allow(dead_code)] pub(crate) fn new(error: &'static str) -> Self { Self { error: error.into() } } #[allow(dead_code)] pub(crate) fn with_string(error: String) -> Self { Self { error: error.into() } } } #[cfg(feature = "std")] impl Error for IcedError { // Required since MSRV < 1.42.0 #[allow(clippy::missing_inline_in_public_items)] fn
(&self) -> &str { &self.error } } impl fmt::Display for IcedError { #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", &self.error) } }
description
identifier_name
iced_error.rs
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors use alloc::borrow::Cow; use alloc::string::String; use core::fmt; #[cfg(feature = "std")] use std::error::Error; /// iced error #[derive(Debug, Clone)] pub struct IcedError { error: Cow<'static, str>, } impl IcedError { #[allow(dead_code)] pub(crate) fn new(error: &'static str) -> Self { Self { error: error.into() } } #[allow(dead_code)] pub(crate) fn with_string(error: String) -> Self { Self { error: error.into() } } } #[cfg(feature = "std")] impl Error for IcedError { // Required since MSRV < 1.42.0 #[allow(clippy::missing_inline_in_public_items)] fn description(&self) -> &str { &self.error } } impl fmt::Display for IcedError { #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
}
{ write!(f, "{}", &self.error) }
identifier_body
ko.rs
/************************************************************************ * * * Copyright 2014 Urban Hafner, Thomas Poinsot * * Copyright 2015 Urban Hafner, Igor Polyakov * * * * This file is part of Iomrascálaí. * * * * Iomrascálaí 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. * * * * Iomrascálaí 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 Iomrascálaí. If not, see <http://www.gnu.org/licenses/>. * * * ************************************************************************/ #![cfg(test)] use board::Black; use board::IllegalMove; use board::Play; use board::White; use game::Game; use ruleset::AnySizeTrompTaylor; use sgf::Parser; use std::path::Path; #[test] fn replayin
let mut g = Game::new(19, 6.5, AnySizeTrompTaylor); g = g.play(Play(Black, 4, 4)).unwrap(); g = g.play(Play(White, 5, 4)).unwrap(); g = g.play(Play(Black, 3, 3)).unwrap(); g = g.play(Play(White, 4, 3)).unwrap(); g = g.play(Play(Black, 3, 5)).unwrap(); g = g.play(Play(White, 4, 5)).unwrap(); g = g.play(Play(Black, 2, 4)).unwrap(); g = g.play(Play(White, 3, 4)).unwrap(); let ko = g.play(Play(Black, 4, 4)); match ko { Err(e) => assert_eq!(e, IllegalMove::Ko), Ok(_) => panic!("expected Err") } } #[test] fn positional_super_ko_should_be_illegal() { let parser = Parser::from_path(Path::new("fixtures/sgf/positional-superko.sgf")).unwrap(); let game = parser.game().unwrap(); let super_ko = game.play(Play(White, 2, 9)); match super_ko { Err(e) => assert_eq!(e, IllegalMove::SuperKo), Ok(_) => panic!("expected Err") } } #[test] fn not_a_super_ko() { let parser = Parser::from_path(Path::new("fixtures/sgf/not-superko.sgf")).unwrap(); let game = parser.game().unwrap(); let no_super_ko = game.play(Play(Black, 1, 1)); match no_super_ko { Err(e) => panic!("No err expected, got {}", e), Ok(_) => {} } } #[test] fn not_a_super_ko2() { let parser = Parser::from_path(Path::new("fixtures/sgf/not-superko2.sgf")).unwrap(); let game = parser.game().unwrap(); let no_super_ko = game.play(Play(Black, 13, 12)); match no_super_ko { Err(e) => panic!("No err expected, got {}", e), Ok(_) => {} } }
g_directly_on_a_ko_point_should_be_illegal() {
identifier_name
ko.rs
/************************************************************************ * * * Copyright 2014 Urban Hafner, Thomas Poinsot * * Copyright 2015 Urban Hafner, Igor Polyakov * * * * This file is part of Iomrascálaí. * * * * Iomrascálaí 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. * * * * Iomrascálaí 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 Iomrascálaí. If not, see <http://www.gnu.org/licenses/>. * * * ************************************************************************/ #![cfg(test)] use board::Black; use board::IllegalMove; use board::Play; use board::White; use game::Game; use ruleset::AnySizeTrompTaylor; use sgf::Parser; use std::path::Path; #[test] fn replaying_directly_on_a_ko_point_should_be_illegal() { le
] fn positional_super_ko_should_be_illegal() { let parser = Parser::from_path(Path::new("fixtures/sgf/positional-superko.sgf")).unwrap(); let game = parser.game().unwrap(); let super_ko = game.play(Play(White, 2, 9)); match super_ko { Err(e) => assert_eq!(e, IllegalMove::SuperKo), Ok(_) => panic!("expected Err") } } #[test] fn not_a_super_ko() { let parser = Parser::from_path(Path::new("fixtures/sgf/not-superko.sgf")).unwrap(); let game = parser.game().unwrap(); let no_super_ko = game.play(Play(Black, 1, 1)); match no_super_ko { Err(e) => panic!("No err expected, got {}", e), Ok(_) => {} } } #[test] fn not_a_super_ko2() { let parser = Parser::from_path(Path::new("fixtures/sgf/not-superko2.sgf")).unwrap(); let game = parser.game().unwrap(); let no_super_ko = game.play(Play(Black, 13, 12)); match no_super_ko { Err(e) => panic!("No err expected, got {}", e), Ok(_) => {} } }
t mut g = Game::new(19, 6.5, AnySizeTrompTaylor); g = g.play(Play(Black, 4, 4)).unwrap(); g = g.play(Play(White, 5, 4)).unwrap(); g = g.play(Play(Black, 3, 3)).unwrap(); g = g.play(Play(White, 4, 3)).unwrap(); g = g.play(Play(Black, 3, 5)).unwrap(); g = g.play(Play(White, 4, 5)).unwrap(); g = g.play(Play(Black, 2, 4)).unwrap(); g = g.play(Play(White, 3, 4)).unwrap(); let ko = g.play(Play(Black, 4, 4)); match ko { Err(e) => assert_eq!(e, IllegalMove::Ko), Ok(_) => panic!("expected Err") } } #[test
identifier_body
ko.rs
/************************************************************************ * * * Copyright 2014 Urban Hafner, Thomas Poinsot * * Copyright 2015 Urban Hafner, Igor Polyakov * * * * This file is part of Iomrascálaí. * * * * Iomrascálaí 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. * * * * Iomrascálaí 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 Iomrascálaí. If not, see <http://www.gnu.org/licenses/>. * * * ************************************************************************/ #![cfg(test)] use board::Black; use board::IllegalMove; use board::Play; use board::White; use game::Game; use ruleset::AnySizeTrompTaylor; use sgf::Parser; use std::path::Path; #[test] fn replaying_directly_on_a_ko_point_should_be_illegal() { let mut g = Game::new(19, 6.5, AnySizeTrompTaylor);
g = g.play(Play(White, 5, 4)).unwrap(); g = g.play(Play(Black, 3, 3)).unwrap(); g = g.play(Play(White, 4, 3)).unwrap(); g = g.play(Play(Black, 3, 5)).unwrap(); g = g.play(Play(White, 4, 5)).unwrap(); g = g.play(Play(Black, 2, 4)).unwrap(); g = g.play(Play(White, 3, 4)).unwrap(); let ko = g.play(Play(Black, 4, 4)); match ko { Err(e) => assert_eq!(e, IllegalMove::Ko), Ok(_) => panic!("expected Err") } } #[test] fn positional_super_ko_should_be_illegal() { let parser = Parser::from_path(Path::new("fixtures/sgf/positional-superko.sgf")).unwrap(); let game = parser.game().unwrap(); let super_ko = game.play(Play(White, 2, 9)); match super_ko { Err(e) => assert_eq!(e, IllegalMove::SuperKo), Ok(_) => panic!("expected Err") } } #[test] fn not_a_super_ko() { let parser = Parser::from_path(Path::new("fixtures/sgf/not-superko.sgf")).unwrap(); let game = parser.game().unwrap(); let no_super_ko = game.play(Play(Black, 1, 1)); match no_super_ko { Err(e) => panic!("No err expected, got {}", e), Ok(_) => {} } } #[test] fn not_a_super_ko2() { let parser = Parser::from_path(Path::new("fixtures/sgf/not-superko2.sgf")).unwrap(); let game = parser.game().unwrap(); let no_super_ko = game.play(Play(Black, 13, 12)); match no_super_ko { Err(e) => panic!("No err expected, got {}", e), Ok(_) => {} } }
g = g.play(Play(Black, 4, 4)).unwrap();
random_line_split
htmloptionelement.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::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataCast, ElementCast, HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLOptionElementDerived}; use dom::bindings::codegen::InheritTypes::{HTMLScriptElementDerived}; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::characterdata::CharacterData; use dom::document::Document; use dom::element::{AttributeHandlers, Element, ElementHelpers, HTMLOptionElementTypeId}; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::{DOMString, split_html_space_chars}; use string_cache::Atom; #[dom_struct] pub struct HTMLOptionElement { htmlelement: HTMLElement } impl HTMLOptionElementDerived for EventTarget { fn is_htmloptionelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLOptionElementTypeId)) } } impl HTMLOptionElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptionElement { HTMLOptionElement { htmlelement: HTMLElement::new_inherited(HTMLOptionElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLOptionElement> { let element = HTMLOptionElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLOptionElementBinding::Wrap) } } fn collect_text(node: &JSRef<Node>, value: &mut DOMString) { let elem: JSRef<Element> = ElementCast::to_ref(*node).unwrap(); let svg_script = *elem.namespace() == ns!(SVG) && elem.local_name().as_slice() == "script"; let html_script = node.is_htmlscriptelement(); if svg_script || html_script { return; } else { for child in node.children() { if child.is_text() { let characterdata: JSRef<CharacterData> = CharacterDataCast::to_ref(child).unwrap(); value.push_str(characterdata.Data().as_slice()); } else { collect_text(&child, value); } } } } impl<'a> HTMLOptionElementMethods for JSRef<'a, HTMLOptionElement> { // http://www.whatwg.org/html/#dom-option-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-option-disabled fn SetDisabled(self, disabled: bool) { let elem: JSRef<Element> = ElementCast::from_ref(self); elem.set_bool_attribute(&atom!("disabled"), disabled) } // http://www.whatwg.org/html/#dom-option-text fn Text(self) -> DOMString { let node: JSRef<Node> = NodeCast::from_ref(self); let mut content = String::new(); collect_text(&node, &mut content); let v: Vec<&str> = split_html_space_chars(content.as_slice()).collect(); v.connect(" ") } // http://www.whatwg.org/html/#dom-option-text fn SetText(self, value: DOMString) { let node: JSRef<Node> = NodeCast::from_ref(self); node.SetTextContent(Some(value)) } // https://html.spec.whatwg.org/multipage/forms.html#attr-option-value fn Value(self) -> DOMString { let element: JSRef<Element> = ElementCast::from_ref(self); let attr = &atom!("value"); if element.has_attribute(attr) { element.get_string_attribute(attr) } else { self.Text() } } // https://html.spec.whatwg.org/multipage/forms.html#attr-option-value make_setter!(SetValue, "value") // https://html.spec.whatwg.org/multipage/forms.html#attr-option-label fn Label(self) -> DOMString { let element: JSRef<Element> = ElementCast::from_ref(self); let attr = &atom!("label"); if element.has_attribute(attr) { element.get_string_attribute(attr) } else { self.Text() } } // https://html.spec.whatwg.org/multipage/forms.html#attr-option-label make_setter!(SetLabel, "label") } impl<'a> VirtualMethods for JSRef<'a, HTMLOptionElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods>
fn after_set_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); } _ => () } } fn before_remove_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.before_remove_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_parent_disabled_state_for_option(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.bind_to_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_parent_disabled_state_for_option(); } fn unbind_from_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.unbind_from_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.parent_node().is_some() { node.check_parent_disabled_state_for_option(); } else { node.check_disabled_attribute(); } } } impl Reflectable for HTMLOptionElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
{ let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) }
identifier_body
htmloptionelement.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::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataCast, ElementCast, HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLOptionElementDerived}; use dom::bindings::codegen::InheritTypes::{HTMLScriptElementDerived}; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::characterdata::CharacterData; use dom::document::Document; use dom::element::{AttributeHandlers, Element, ElementHelpers, HTMLOptionElementTypeId}; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::{DOMString, split_html_space_chars}; use string_cache::Atom; #[dom_struct] pub struct HTMLOptionElement { htmlelement: HTMLElement } impl HTMLOptionElementDerived for EventTarget { fn is_htmloptionelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLOptionElementTypeId)) } } impl HTMLOptionElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptionElement { HTMLOptionElement { htmlelement: HTMLElement::new_inherited(HTMLOptionElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLOptionElement> { let element = HTMLOptionElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLOptionElementBinding::Wrap) } } fn
(node: &JSRef<Node>, value: &mut DOMString) { let elem: JSRef<Element> = ElementCast::to_ref(*node).unwrap(); let svg_script = *elem.namespace() == ns!(SVG) && elem.local_name().as_slice() == "script"; let html_script = node.is_htmlscriptelement(); if svg_script || html_script { return; } else { for child in node.children() { if child.is_text() { let characterdata: JSRef<CharacterData> = CharacterDataCast::to_ref(child).unwrap(); value.push_str(characterdata.Data().as_slice()); } else { collect_text(&child, value); } } } } impl<'a> HTMLOptionElementMethods for JSRef<'a, HTMLOptionElement> { // http://www.whatwg.org/html/#dom-option-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-option-disabled fn SetDisabled(self, disabled: bool) { let elem: JSRef<Element> = ElementCast::from_ref(self); elem.set_bool_attribute(&atom!("disabled"), disabled) } // http://www.whatwg.org/html/#dom-option-text fn Text(self) -> DOMString { let node: JSRef<Node> = NodeCast::from_ref(self); let mut content = String::new(); collect_text(&node, &mut content); let v: Vec<&str> = split_html_space_chars(content.as_slice()).collect(); v.connect(" ") } // http://www.whatwg.org/html/#dom-option-text fn SetText(self, value: DOMString) { let node: JSRef<Node> = NodeCast::from_ref(self); node.SetTextContent(Some(value)) } // https://html.spec.whatwg.org/multipage/forms.html#attr-option-value fn Value(self) -> DOMString { let element: JSRef<Element> = ElementCast::from_ref(self); let attr = &atom!("value"); if element.has_attribute(attr) { element.get_string_attribute(attr) } else { self.Text() } } // https://html.spec.whatwg.org/multipage/forms.html#attr-option-value make_setter!(SetValue, "value") // https://html.spec.whatwg.org/multipage/forms.html#attr-option-label fn Label(self) -> DOMString { let element: JSRef<Element> = ElementCast::from_ref(self); let attr = &atom!("label"); if element.has_attribute(attr) { element.get_string_attribute(attr) } else { self.Text() } } // https://html.spec.whatwg.org/multipage/forms.html#attr-option-label make_setter!(SetLabel, "label") } impl<'a> VirtualMethods for JSRef<'a, HTMLOptionElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); } _ => () } } fn before_remove_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.before_remove_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_parent_disabled_state_for_option(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.bind_to_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_parent_disabled_state_for_option(); } fn unbind_from_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.unbind_from_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.parent_node().is_some() { node.check_parent_disabled_state_for_option(); } else { node.check_disabled_attribute(); } } } impl Reflectable for HTMLOptionElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
collect_text
identifier_name
htmloptionelement.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::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataCast, ElementCast, HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLOptionElementDerived}; use dom::bindings::codegen::InheritTypes::{HTMLScriptElementDerived}; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::characterdata::CharacterData; use dom::document::Document; use dom::element::{AttributeHandlers, Element, ElementHelpers, HTMLOptionElementTypeId}; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::{DOMString, split_html_space_chars}; use string_cache::Atom; #[dom_struct] pub struct HTMLOptionElement { htmlelement: HTMLElement } impl HTMLOptionElementDerived for EventTarget { fn is_htmloptionelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLOptionElementTypeId)) } } impl HTMLOptionElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptionElement { HTMLOptionElement { htmlelement: HTMLElement::new_inherited(HTMLOptionElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLOptionElement> { let element = HTMLOptionElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLOptionElementBinding::Wrap) } }
let svg_script = *elem.namespace() == ns!(SVG) && elem.local_name().as_slice() == "script"; let html_script = node.is_htmlscriptelement(); if svg_script || html_script { return; } else { for child in node.children() { if child.is_text() { let characterdata: JSRef<CharacterData> = CharacterDataCast::to_ref(child).unwrap(); value.push_str(characterdata.Data().as_slice()); } else { collect_text(&child, value); } } } } impl<'a> HTMLOptionElementMethods for JSRef<'a, HTMLOptionElement> { // http://www.whatwg.org/html/#dom-option-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-option-disabled fn SetDisabled(self, disabled: bool) { let elem: JSRef<Element> = ElementCast::from_ref(self); elem.set_bool_attribute(&atom!("disabled"), disabled) } // http://www.whatwg.org/html/#dom-option-text fn Text(self) -> DOMString { let node: JSRef<Node> = NodeCast::from_ref(self); let mut content = String::new(); collect_text(&node, &mut content); let v: Vec<&str> = split_html_space_chars(content.as_slice()).collect(); v.connect(" ") } // http://www.whatwg.org/html/#dom-option-text fn SetText(self, value: DOMString) { let node: JSRef<Node> = NodeCast::from_ref(self); node.SetTextContent(Some(value)) } // https://html.spec.whatwg.org/multipage/forms.html#attr-option-value fn Value(self) -> DOMString { let element: JSRef<Element> = ElementCast::from_ref(self); let attr = &atom!("value"); if element.has_attribute(attr) { element.get_string_attribute(attr) } else { self.Text() } } // https://html.spec.whatwg.org/multipage/forms.html#attr-option-value make_setter!(SetValue, "value") // https://html.spec.whatwg.org/multipage/forms.html#attr-option-label fn Label(self) -> DOMString { let element: JSRef<Element> = ElementCast::from_ref(self); let attr = &atom!("label"); if element.has_attribute(attr) { element.get_string_attribute(attr) } else { self.Text() } } // https://html.spec.whatwg.org/multipage/forms.html#attr-option-label make_setter!(SetLabel, "label") } impl<'a> VirtualMethods for JSRef<'a, HTMLOptionElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); } _ => () } } fn before_remove_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.before_remove_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_parent_disabled_state_for_option(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.bind_to_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_parent_disabled_state_for_option(); } fn unbind_from_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.unbind_from_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.parent_node().is_some() { node.check_parent_disabled_state_for_option(); } else { node.check_disabled_attribute(); } } } impl Reflectable for HTMLOptionElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
fn collect_text(node: &JSRef<Node>, value: &mut DOMString) { let elem: JSRef<Element> = ElementCast::to_ref(*node).unwrap();
random_line_split
ops.rs
//! Image operations for textures. /// Flips the image vertically. pub fn flip_vertical(memory: &[u8], size: [u32; 2], channels: u8) -> Vec<u8> { let (width, height, channels) = (size[0] as usize, size[1] as usize, channels as usize); let mut res = vec![0; width * height]; let stride = width * channels; for y in 0..height { for x in 0..width { for c in 0..channels { res[(c + x * channels + (height - 1 - y) * stride) as usize] = memory[(c + x * channels + y * stride) as usize]; } } } res } /// Converts from alpha to rgba8. pub fn
(memory: &[u8], size: [u32; 2]) -> Vec<u8> { let (width, height) = (size[0] as usize, size[1] as usize); let capacity = width * height * 4; let stride = width; let mut res = Vec::with_capacity(capacity); for y in 0..height { for x in 0..width { res.push(255); res.push(255); res.push(255); res.push(memory[x + y * stride]); } } res }
alpha_to_rgba8
identifier_name
ops.rs
//! Image operations for textures. /// Flips the image vertically. pub fn flip_vertical(memory: &[u8], size: [u32; 2], channels: u8) -> Vec<u8> { let (width, height, channels) = (size[0] as usize, size[1] as usize, channels as usize); let mut res = vec![0; width * height]; let stride = width * channels; for y in 0..height { for x in 0..width { for c in 0..channels { res[(c + x * channels + (height - 1 - y) * stride) as usize] = memory[(c + x * channels + y * stride) as usize]; } } } res } /// Converts from alpha to rgba8.
pub fn alpha_to_rgba8(memory: &[u8], size: [u32; 2]) -> Vec<u8> { let (width, height) = (size[0] as usize, size[1] as usize); let capacity = width * height * 4; let stride = width; let mut res = Vec::with_capacity(capacity); for y in 0..height { for x in 0..width { res.push(255); res.push(255); res.push(255); res.push(memory[x + y * stride]); } } res }
random_line_split
ops.rs
//! Image operations for textures. /// Flips the image vertically. pub fn flip_vertical(memory: &[u8], size: [u32; 2], channels: u8) -> Vec<u8> { let (width, height, channels) = (size[0] as usize, size[1] as usize, channels as usize); let mut res = vec![0; width * height]; let stride = width * channels; for y in 0..height { for x in 0..width { for c in 0..channels { res[(c + x * channels + (height - 1 - y) * stride) as usize] = memory[(c + x * channels + y * stride) as usize]; } } } res } /// Converts from alpha to rgba8. pub fn alpha_to_rgba8(memory: &[u8], size: [u32; 2]) -> Vec<u8>
{ let (width, height) = (size[0] as usize, size[1] as usize); let capacity = width * height * 4; let stride = width; let mut res = Vec::with_capacity(capacity); for y in 0..height { for x in 0..width { res.push(255); res.push(255); res.push(255); res.push(memory[x + y * stride]); } } res }
identifier_body
lib.rs
#[macro_use] extern crate matches; #[macro_use] extern crate log; /// Simple Rpc Module. /// See the submodules for information on how to set up a server and a client. pub mod rpc; /// Common code between structs. // TODO: This probably should not all be public pub mod common; /// /// Raft Server /// pub mod server; /// /// Raft Client libraries /// pub mod client; extern crate capnp; extern crate rand; // DO NOT MOVE THIS OR RENAME THIS // TODO: This is a giant hack, but appears to be the "correct" way to do this // See: https://github.com/dwrensha/capnpc-rust/issues/5 // Need to allow dead code since the capnp compiler outputs a ton of code #[allow(dead_code)] mod rpc_capnp { include!(concat!(env!("OUT_DIR"), "/rpc_capnp.rs")); } #[allow(dead_code)] mod raft_capnp {
include!(concat!(env!("OUT_DIR"), "/raft_capnp.rs")); }
random_line_split
main.rs
/* Commented to avoid compile errors an failed build badges on TravisCI, extern crate orbclient; extern crate orbclient_window_shortcuts; use orbclient::{Window, Renderer, EventOption, Color}; use orbclient_window_shortcuts::shortcut::{Comparator, GenericShortcutId, Shortcut, CommonId, Shortcuts}; fn window() -> orbclient::Window { let (width, height) = orbclient::get_display_size().unwrap(); let mut window = Window::new_flags(0, 0, width / 2, height / 2, "Shortcuts Example", &[orbclient::WindowFlag::Resizable]).unwrap(); println!("This example does only support the Quit shortcut: CRTL+Q"); window.sync(); window } enum MyId { Increase, Decrease } */ fn main()
supported.push(Shortcut{id: GenericShortcutId::Id(MyId::Decrease), keys: decrease_k}); //Error: Type inferred from line above //supported.push(Shortcut{id: GenericShortcutId::Id(CommonId::Quit), keys: quit_k}); scs.enable(supported); 'events: loop { for event in window.events() { match event.to_option() { EventOption::Quit(qe) => break 'events, EventOption::Key(ke) => { match scs.update(ke) { Some(scid) => { match scid { &CommonId::Quit => {println!("{:?} returned.", scid); break 'events }, &CommonId::Open => {println!("{:?} not implemented.", scid)}, _ => {println!("{:?} unknown shortcut.", scid)} }; }, None => {println!("No match")}, }; }, //orbclient_window_shortcuts implementation _ => break }; } } */ }
{ /* let mut window = window(); let scs = Shortcuts::new(); //Quit Shortcut with ShortcutId from CommonId let mut quit_k: Vec<u8> = Vec::new(); quit_k.push(orbclient::event::K_CTRL); quit_k.push(orbclient::event::K_Q); quit_k.sort(); let mut decrease_k = Vec::new(); decrease_k.push(orbclient::event::K_CTRL); decrease_k.push(orbclient::event::K_MINUS); decrease_k.sort(); let supported = Vec::new();
identifier_body
main.rs
/* Commented to avoid compile errors an failed build badges on TravisCI, extern crate orbclient; extern crate orbclient_window_shortcuts; use orbclient::{Window, Renderer, EventOption, Color}; use orbclient_window_shortcuts::shortcut::{Comparator, GenericShortcutId, Shortcut, CommonId, Shortcuts}; fn window() -> orbclient::Window { let (width, height) = orbclient::get_display_size().unwrap(); let mut window = Window::new_flags(0, 0, width / 2, height / 2, "Shortcuts Example", &[orbclient::WindowFlag::Resizable]).unwrap(); println!("This example does only support the Quit shortcut: CRTL+Q"); window.sync(); window } enum MyId { Increase, Decrease } */ fn
() { /* let mut window = window(); let scs = Shortcuts::new(); //Quit Shortcut with ShortcutId from CommonId let mut quit_k: Vec<u8> = Vec::new(); quit_k.push(orbclient::event::K_CTRL); quit_k.push(orbclient::event::K_Q); quit_k.sort(); let mut decrease_k = Vec::new(); decrease_k.push(orbclient::event::K_CTRL); decrease_k.push(orbclient::event::K_MINUS); decrease_k.sort(); let supported = Vec::new(); supported.push(Shortcut{id: GenericShortcutId::Id(MyId::Decrease), keys: decrease_k}); //Error: Type inferred from line above //supported.push(Shortcut{id: GenericShortcutId::Id(CommonId::Quit), keys: quit_k}); scs.enable(supported); 'events: loop { for event in window.events() { match event.to_option() { EventOption::Quit(qe) => break 'events, EventOption::Key(ke) => { match scs.update(ke) { Some(scid) => { match scid { &CommonId::Quit => {println!("{:?} returned.", scid); break 'events }, &CommonId::Open => {println!("{:?} not implemented.", scid)}, _ => {println!("{:?} unknown shortcut.", scid)} }; }, None => {println!("No match")}, }; }, //orbclient_window_shortcuts implementation _ => break }; } } */ }
main
identifier_name
main.rs
/* Commented to avoid compile errors an failed build badges on TravisCI,
use orbclient_window_shortcuts::shortcut::{Comparator, GenericShortcutId, Shortcut, CommonId, Shortcuts}; fn window() -> orbclient::Window { let (width, height) = orbclient::get_display_size().unwrap(); let mut window = Window::new_flags(0, 0, width / 2, height / 2, "Shortcuts Example", &[orbclient::WindowFlag::Resizable]).unwrap(); println!("This example does only support the Quit shortcut: CRTL+Q"); window.sync(); window } enum MyId { Increase, Decrease } */ fn main() { /* let mut window = window(); let scs = Shortcuts::new(); //Quit Shortcut with ShortcutId from CommonId let mut quit_k: Vec<u8> = Vec::new(); quit_k.push(orbclient::event::K_CTRL); quit_k.push(orbclient::event::K_Q); quit_k.sort(); let mut decrease_k = Vec::new(); decrease_k.push(orbclient::event::K_CTRL); decrease_k.push(orbclient::event::K_MINUS); decrease_k.sort(); let supported = Vec::new(); supported.push(Shortcut{id: GenericShortcutId::Id(MyId::Decrease), keys: decrease_k}); //Error: Type inferred from line above //supported.push(Shortcut{id: GenericShortcutId::Id(CommonId::Quit), keys: quit_k}); scs.enable(supported); 'events: loop { for event in window.events() { match event.to_option() { EventOption::Quit(qe) => break 'events, EventOption::Key(ke) => { match scs.update(ke) { Some(scid) => { match scid { &CommonId::Quit => {println!("{:?} returned.", scid); break 'events }, &CommonId::Open => {println!("{:?} not implemented.", scid)}, _ => {println!("{:?} unknown shortcut.", scid)} }; }, None => {println!("No match")}, }; }, //orbclient_window_shortcuts implementation _ => break }; } } */ }
extern crate orbclient; extern crate orbclient_window_shortcuts; use orbclient::{Window, Renderer, EventOption, Color};
random_line_split
string_utils.rs
//! Various utilities for string operations. /// Join items of a collection with separator. pub trait JoinWithSeparator<S> { /// Result type of the operation type Output; /// Join items of `self` with `separator`. fn join(self, separator: S) -> Self::Output; } impl<S, S2, X> JoinWithSeparator<S2> for X where S: AsRef<str>, S2: AsRef<str>, X: Iterator<Item = S> { type Output = String; fn join(self, separator: S2) -> String { self.fold("".to_string(), |a, b| { let m = if a.is_empty() { a } else { a + separator.as_ref() }; m + b.as_ref() }) } } /// Iterator over words in a camel-case /// or snake-case string. pub struct WordIterator<'a> { string: &'a str, index: usize, } impl<'a> WordIterator<'a> { /// Create iterator over `string`. pub fn new(string: &str) -> WordIterator { WordIterator { string: string, index: 0, } } } fn char_at(str: &str, index: usize) -> char { if index >= str.len() { panic!("char_at: index out of bounds"); } str[index..index + 1].chars().next().unwrap() } impl<'a> Iterator for WordIterator<'a> { type Item = &'a str; fn next(&mut self) -> Option<&'a str> { while self.index < self.string.len() && &self.string[self.index..self.index + 1] == "_" { self.index += 1; } if self.index >= self.string.len() { return None; } let mut i = self.index + 1; let current_word_is_number = i < self.string.len() && char_at(self.string, i).is_digit(10); while i < self.string.len() { let current = char_at(self.string, i); if current == '_' || current.is_uppercase() { break; } if!current_word_is_number && current.is_digit(10) { break; } i += 1; } let result = &self.string[self.index..i]; self.index = i; Some(result) } } /// Convert to string with different cases pub trait CaseOperations { /// Convert to class-case string ("WordWordWord") fn to_class_case(self) -> String; /// Convert to snake-case string ("word_word_word") fn to_snake_case(self) -> String; /// Convert to upper-case string ("WORD_WORD_WORD") fn to_upper_case_words(self) -> String; } fn
<S: AsRef<str>, T: Iterator<Item = S>>(it: T) -> String { it.map(|x| if char_at(x.as_ref(), 0).is_digit(10) { x.as_ref().to_uppercase() } else { format!("{}{}", x.as_ref()[0..1].to_uppercase(), x.as_ref()[1..].to_lowercase()) }) .join("") } fn ends_with_digit<S: AsRef<str>>(s: S) -> bool { let str = s.as_ref(); if str.len() > 0 { str[str.len() - 1..str.len()] .chars() .next() .unwrap() .is_digit(10) } else { false } } fn iterator_to_snake_case<S: AsRef<str>, T: Iterator<Item = S>>(it: T) -> String { let mut parts: Vec<_> = it.map(|x| x.as_ref().to_lowercase()).collect(); replace_all_sub_vecs(&mut parts, vec!["na", "n"]); replace_all_sub_vecs(&mut parts, vec!["open", "g", "l"]); replace_all_sub_vecs(&mut parts, vec!["i", "o"]); replace_all_sub_vecs(&mut parts, vec!["2", "d"]); replace_all_sub_vecs(&mut parts, vec!["3", "d"]); replace_all_sub_vecs(&mut parts, vec!["4", "d"]); let mut str = String::new(); for (i, part) in parts.into_iter().enumerate() { if part.is_empty() { continue; } if i > 0 &&!(part.chars().all(|c| c.is_digit(10)) &&!ends_with_digit(&str)) { str.push('_'); } str.push_str(&part); } str } fn iterator_to_upper_case_words<S: AsRef<str>, T: Iterator<Item = S>>(it: T) -> String { it.map(|x| x.as_ref().to_uppercase()).join("_") } #[cfg_attr(feature="clippy", allow(needless_range_loop))] fn replace_all_sub_vecs(parts: &mut Vec<String>, needle: Vec<&str>) { let mut any_found = true; while any_found { any_found = false; if parts.len() + 1 >= needle.len() { // TODO: maybe rewrite this for i in 0..parts.len() + 1 - needle.len() { if &parts[i..i + needle.len()] == &needle[..] { for _ in 0..needle.len() - 1 { parts.remove(i + 1); } parts[i] = needle.join(""); any_found = true; break; } } } } } impl<'a> CaseOperations for &'a str { fn to_class_case(self) -> String { iterator_to_class_case(WordIterator::new(self)) } fn to_snake_case(self) -> String { iterator_to_snake_case(WordIterator::new(self)) } fn to_upper_case_words(self) -> String { iterator_to_upper_case_words(WordIterator::new(self)) } } impl<'a> CaseOperations for Vec<&'a str> { fn to_class_case(self) -> String { iterator_to_class_case(self.into_iter()) } fn to_snake_case(self) -> String { iterator_to_snake_case(self.into_iter()) } fn to_upper_case_words(self) -> String { iterator_to_upper_case_words(self.into_iter()) } }
iterator_to_class_case
identifier_name
string_utils.rs
//! Various utilities for string operations. /// Join items of a collection with separator. pub trait JoinWithSeparator<S> { /// Result type of the operation type Output; /// Join items of `self` with `separator`. fn join(self, separator: S) -> Self::Output; } impl<S, S2, X> JoinWithSeparator<S2> for X where S: AsRef<str>, S2: AsRef<str>, X: Iterator<Item = S> { type Output = String; fn join(self, separator: S2) -> String { self.fold("".to_string(), |a, b| { let m = if a.is_empty() { a } else { a + separator.as_ref() }; m + b.as_ref() }) } } /// Iterator over words in a camel-case /// or snake-case string. pub struct WordIterator<'a> { string: &'a str, index: usize, } impl<'a> WordIterator<'a> { /// Create iterator over `string`. pub fn new(string: &str) -> WordIterator { WordIterator { string: string, index: 0, } } } fn char_at(str: &str, index: usize) -> char { if index >= str.len() { panic!("char_at: index out of bounds"); } str[index..index + 1].chars().next().unwrap() } impl<'a> Iterator for WordIterator<'a> { type Item = &'a str; fn next(&mut self) -> Option<&'a str> { while self.index < self.string.len() && &self.string[self.index..self.index + 1] == "_" { self.index += 1; } if self.index >= self.string.len() { return None; } let mut i = self.index + 1; let current_word_is_number = i < self.string.len() && char_at(self.string, i).is_digit(10); while i < self.string.len() { let current = char_at(self.string, i); if current == '_' || current.is_uppercase() { break; } if!current_word_is_number && current.is_digit(10) { break; } i += 1; } let result = &self.string[self.index..i]; self.index = i; Some(result) } } /// Convert to string with different cases pub trait CaseOperations { /// Convert to class-case string ("WordWordWord") fn to_class_case(self) -> String; /// Convert to snake-case string ("word_word_word") fn to_snake_case(self) -> String; /// Convert to upper-case string ("WORD_WORD_WORD") fn to_upper_case_words(self) -> String; } fn iterator_to_class_case<S: AsRef<str>, T: Iterator<Item = S>>(it: T) -> String { it.map(|x| if char_at(x.as_ref(), 0).is_digit(10) { x.as_ref().to_uppercase() } else { format!("{}{}", x.as_ref()[0..1].to_uppercase(), x.as_ref()[1..].to_lowercase()) }) .join("") } fn ends_with_digit<S: AsRef<str>>(s: S) -> bool { let str = s.as_ref(); if str.len() > 0 { str[str.len() - 1..str.len()] .chars() .next() .unwrap() .is_digit(10) } else { false } } fn iterator_to_snake_case<S: AsRef<str>, T: Iterator<Item = S>>(it: T) -> String { let mut parts: Vec<_> = it.map(|x| x.as_ref().to_lowercase()).collect(); replace_all_sub_vecs(&mut parts, vec!["na", "n"]); replace_all_sub_vecs(&mut parts, vec!["open", "g", "l"]); replace_all_sub_vecs(&mut parts, vec!["i", "o"]); replace_all_sub_vecs(&mut parts, vec!["2", "d"]); replace_all_sub_vecs(&mut parts, vec!["3", "d"]); replace_all_sub_vecs(&mut parts, vec!["4", "d"]); let mut str = String::new(); for (i, part) in parts.into_iter().enumerate() { if part.is_empty() { continue; } if i > 0 &&!(part.chars().all(|c| c.is_digit(10)) &&!ends_with_digit(&str))
str.push_str(&part); } str } fn iterator_to_upper_case_words<S: AsRef<str>, T: Iterator<Item = S>>(it: T) -> String { it.map(|x| x.as_ref().to_uppercase()).join("_") } #[cfg_attr(feature="clippy", allow(needless_range_loop))] fn replace_all_sub_vecs(parts: &mut Vec<String>, needle: Vec<&str>) { let mut any_found = true; while any_found { any_found = false; if parts.len() + 1 >= needle.len() { // TODO: maybe rewrite this for i in 0..parts.len() + 1 - needle.len() { if &parts[i..i + needle.len()] == &needle[..] { for _ in 0..needle.len() - 1 { parts.remove(i + 1); } parts[i] = needle.join(""); any_found = true; break; } } } } } impl<'a> CaseOperations for &'a str { fn to_class_case(self) -> String { iterator_to_class_case(WordIterator::new(self)) } fn to_snake_case(self) -> String { iterator_to_snake_case(WordIterator::new(self)) } fn to_upper_case_words(self) -> String { iterator_to_upper_case_words(WordIterator::new(self)) } } impl<'a> CaseOperations for Vec<&'a str> { fn to_class_case(self) -> String { iterator_to_class_case(self.into_iter()) } fn to_snake_case(self) -> String { iterator_to_snake_case(self.into_iter()) } fn to_upper_case_words(self) -> String { iterator_to_upper_case_words(self.into_iter()) } }
{ str.push('_'); }
conditional_block
string_utils.rs
//! Various utilities for string operations. /// Join items of a collection with separator. pub trait JoinWithSeparator<S> { /// Result type of the operation type Output; /// Join items of `self` with `separator`. fn join(self, separator: S) -> Self::Output; } impl<S, S2, X> JoinWithSeparator<S2> for X where S: AsRef<str>, S2: AsRef<str>, X: Iterator<Item = S> { type Output = String; fn join(self, separator: S2) -> String { self.fold("".to_string(), |a, b| { let m = if a.is_empty() { a } else { a + separator.as_ref() }; m + b.as_ref() }) } } /// Iterator over words in a camel-case /// or snake-case string. pub struct WordIterator<'a> { string: &'a str, index: usize, } impl<'a> WordIterator<'a> { /// Create iterator over `string`. pub fn new(string: &str) -> WordIterator { WordIterator { string: string, index: 0, } } } fn char_at(str: &str, index: usize) -> char { if index >= str.len() { panic!("char_at: index out of bounds"); } str[index..index + 1].chars().next().unwrap() } impl<'a> Iterator for WordIterator<'a> { type Item = &'a str; fn next(&mut self) -> Option<&'a str> { while self.index < self.string.len() && &self.string[self.index..self.index + 1] == "_" { self.index += 1; } if self.index >= self.string.len() { return None; } let mut i = self.index + 1; let current_word_is_number = i < self.string.len() && char_at(self.string, i).is_digit(10); while i < self.string.len() { let current = char_at(self.string, i); if current == '_' || current.is_uppercase() { break; } if!current_word_is_number && current.is_digit(10) { break; } i += 1; } let result = &self.string[self.index..i]; self.index = i; Some(result) } } /// Convert to string with different cases pub trait CaseOperations { /// Convert to class-case string ("WordWordWord") fn to_class_case(self) -> String; /// Convert to snake-case string ("word_word_word") fn to_snake_case(self) -> String; /// Convert to upper-case string ("WORD_WORD_WORD") fn to_upper_case_words(self) -> String; } fn iterator_to_class_case<S: AsRef<str>, T: Iterator<Item = S>>(it: T) -> String { it.map(|x| if char_at(x.as_ref(), 0).is_digit(10) { x.as_ref().to_uppercase() } else { format!("{}{}", x.as_ref()[0..1].to_uppercase(), x.as_ref()[1..].to_lowercase()) }) .join("") } fn ends_with_digit<S: AsRef<str>>(s: S) -> bool { let str = s.as_ref(); if str.len() > 0 { str[str.len() - 1..str.len()] .chars() .next() .unwrap() .is_digit(10) } else { false } } fn iterator_to_snake_case<S: AsRef<str>, T: Iterator<Item = S>>(it: T) -> String { let mut parts: Vec<_> = it.map(|x| x.as_ref().to_lowercase()).collect(); replace_all_sub_vecs(&mut parts, vec!["na", "n"]); replace_all_sub_vecs(&mut parts, vec!["open", "g", "l"]); replace_all_sub_vecs(&mut parts, vec!["i", "o"]); replace_all_sub_vecs(&mut parts, vec!["2", "d"]); replace_all_sub_vecs(&mut parts, vec!["3", "d"]); replace_all_sub_vecs(&mut parts, vec!["4", "d"]); let mut str = String::new(); for (i, part) in parts.into_iter().enumerate() { if part.is_empty() { continue; } if i > 0 &&!(part.chars().all(|c| c.is_digit(10)) &&!ends_with_digit(&str)) { str.push('_'); } str.push_str(&part); } str } fn iterator_to_upper_case_words<S: AsRef<str>, T: Iterator<Item = S>>(it: T) -> String
#[cfg_attr(feature="clippy", allow(needless_range_loop))] fn replace_all_sub_vecs(parts: &mut Vec<String>, needle: Vec<&str>) { let mut any_found = true; while any_found { any_found = false; if parts.len() + 1 >= needle.len() { // TODO: maybe rewrite this for i in 0..parts.len() + 1 - needle.len() { if &parts[i..i + needle.len()] == &needle[..] { for _ in 0..needle.len() - 1 { parts.remove(i + 1); } parts[i] = needle.join(""); any_found = true; break; } } } } } impl<'a> CaseOperations for &'a str { fn to_class_case(self) -> String { iterator_to_class_case(WordIterator::new(self)) } fn to_snake_case(self) -> String { iterator_to_snake_case(WordIterator::new(self)) } fn to_upper_case_words(self) -> String { iterator_to_upper_case_words(WordIterator::new(self)) } } impl<'a> CaseOperations for Vec<&'a str> { fn to_class_case(self) -> String { iterator_to_class_case(self.into_iter()) } fn to_snake_case(self) -> String { iterator_to_snake_case(self.into_iter()) } fn to_upper_case_words(self) -> String { iterator_to_upper_case_words(self.into_iter()) } }
{ it.map(|x| x.as_ref().to_uppercase()).join("_") }
identifier_body