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
task-spawn-barefn.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. // error-pattern:Ensure that the child thread runs by panicking // ignore-emscripten Needs threads. use std::thread; fn main() { // the purpose of this test is to make sure that thread::spawn() // works when provided with a bare function: let r = thread::spawn(startfn).join(); if r.is_err() { panic!() } } fn startfn()
{ assert!("Ensure that the child thread runs by panicking".is_empty()); }
identifier_body
task-spawn-barefn.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. // error-pattern:Ensure that the child thread runs by panicking // ignore-emscripten Needs threads. use std::thread; fn main() { // the purpose of this test is to make sure that thread::spawn() // works when provided with a bare function: let r = thread::spawn(startfn).join(); if r.is_err()
} fn startfn() { assert!("Ensure that the child thread runs by panicking".is_empty()); }
{ panic!() }
conditional_block
methods.rs
// aux-build:option_helpers.rs #![warn(clippy::all, clippy::pedantic)] #![allow( clippy::blacklisted_name, clippy::default_trait_access, clippy::missing_docs_in_private_items, clippy::missing_safety_doc, clippy::non_ascii_literal, clippy::new_without_default, clippy::needless_pass_by_value, clippy::needless_lifetimes, clippy::print_stdout, clippy::must_use_candidate, clippy::use_self, clippy::useless_format, clippy::wrong_self_convention, clippy::unused_self, unused )] #[macro_use] extern crate option_helpers; use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::HashSet; use std::collections::VecDeque; use std::iter::FromIterator; use std::ops::Mul; use std::rc::{self, Rc}; use std::sync::{self, Arc}; use option_helpers::{IteratorFalsePositives, IteratorMethodFalsePositives}; struct Lt<'a> { foo: &'a u32, } impl<'a> Lt<'a> { // The lifetime is different, but that’s irrelevant; see issue #734. #[allow(clippy::needless_lifetimes)] pub fn new<'b>(s: &'b str) -> Lt<'b> { unimplemented!() } } struct Lt2<'a> { foo: &'a u32, } impl<'a> Lt2<'a> { // The lifetime is different, but that’s irrelevant; see issue #734. pub fn new(s: &str) -> Lt2 { unimplemented!() } } struct Lt3<'a> { foo: &'a u32, } impl<'a> Lt3<'a> { // The lifetime is different, but that’s irrelevant; see issue #734. pub fn new() -> Lt3<'static> { unimplemented!() } } #[derive(Clone, Copy)] struct U; impl U { fn new() -> Self { U } // Ok because `U` is `Copy`. fn to_something(self) -> u32 { 0 } } struct V<T> { _dummy: T, } impl<T> V<T> { fn new() -> Option<V<T>> { None } } struct AsyncNew; impl AsyncNew { async fn new() -> Option<Self> { None } } struct BadNew;
impl BadNew { fn new() -> i32 { 0 } } struct T; impl Mul<T> for T { type Output = T; // No error, obviously. fn mul(self, other: T) -> T { self } } /// Checks implementation of `FILTER_NEXT` lint. #[rustfmt::skip] fn filter_next() { let v = vec![3, 2, 1, 0, -1, -2, -3]; // Multi-line case. let _ = v.iter().filter(|&x| { *x < 0 } ).next(); // Check that we don't lint if the caller is not an `Iterator`. let foo = IteratorFalsePositives { foo: 0 }; let _ = foo.filter().next(); let foo = IteratorMethodFalsePositives {}; let _ = foo.filter(42).next(); } fn main() { filter_next(); }
random_line_split
methods.rs
// aux-build:option_helpers.rs #![warn(clippy::all, clippy::pedantic)] #![allow( clippy::blacklisted_name, clippy::default_trait_access, clippy::missing_docs_in_private_items, clippy::missing_safety_doc, clippy::non_ascii_literal, clippy::new_without_default, clippy::needless_pass_by_value, clippy::needless_lifetimes, clippy::print_stdout, clippy::must_use_candidate, clippy::use_self, clippy::useless_format, clippy::wrong_self_convention, clippy::unused_self, unused )] #[macro_use] extern crate option_helpers; use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::HashSet; use std::collections::VecDeque; use std::iter::FromIterator; use std::ops::Mul; use std::rc::{self, Rc}; use std::sync::{self, Arc}; use option_helpers::{IteratorFalsePositives, IteratorMethodFalsePositives}; struct Lt<'a> { foo: &'a u32, } impl<'a> Lt<'a> { // The lifetime is different, but that’s irrelevant; see issue #734. #[allow(clippy::needless_lifetimes)] pub fn new<'b>(s: &'b str) -> Lt<'b> { unimplemented!() } } struct Lt2<'a> { foo: &'a u32, } impl<'a> Lt2<'a> { // The lifetime is different, but that’s irrelevant; see issue #734. pub fn new(s: &str) -> Lt2 { unimplemented!() } } struct Lt3<'a> { foo: &'a u32, } impl<'a> Lt3<'a> { // The lifetime is different, but that’s irrelevant; see issue #734. pub fn new() -> Lt3<'static> { unimplemented!() } } #[derive(Clone, Copy)] struct U; impl U { fn new() -> Self { U } // Ok because `U` is `Copy`. fn to_something(self) -> u32 { 0 } } struct V<T> { _dummy: T, } impl<T> V<T> { fn new() -> Option<V<T>> { None } } struct AsyncNew; impl AsyncNew { async fn new() -> Option<Self> { None } } struct BadNew
l BadNew { fn new() -> i32 { 0 } } struct T; impl Mul<T> for T { type Output = T; // No error, obviously. fn mul(self, other: T) -> T { self } } /// Checks implementation of `FILTER_NEXT` lint. #[rustfmt::skip] fn filter_next() { let v = vec![3, 2, 1, 0, -1, -2, -3]; // Multi-line case. let _ = v.iter().filter(|&x| { *x < 0 } ).next(); // Check that we don't lint if the caller is not an `Iterator`. let foo = IteratorFalsePositives { foo: 0 }; let _ = foo.filter().next(); let foo = IteratorMethodFalsePositives {}; let _ = foo.filter(42).next(); } fn main() { filter_next(); }
; imp
identifier_name
font_template.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 core_graphics::data_provider::CGDataProvider; use core_graphics::font::CGFont; use core_text; use core_text::font::CTFont; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::de::{Error, Visitor}; use servo_atoms::Atom; use servo_url::ServoUrl; use std::borrow::ToOwned; use std::collections::HashMap; use std::fmt; use std::fs::File; use std::io::{Read, Error as IoError}; use std::ops::Deref; use std::sync::Mutex; use webrender_traits::NativeFontHandle; /// Platform specific font representation for mac. /// The identifier is a PostScript font name. The /// CTFont object is cached here for use by the /// paint functions that create CGFont references. #[derive(Deserialize, Serialize, Debug)] pub struct FontTemplateData { /// The `CTFont` object, if present. This is cached here so that we don't have to keep creating /// `CTFont` instances over and over. It can always be recreated from the `identifier` and/or /// `font_data` fields. /// /// When sending a `FontTemplateData` instance across processes, this will be cleared out on /// the other side, because `CTFont` instances cannot be sent across processes. This is /// harmless, however, because it can always be recreated. ctfont: CachedCTFont, pub identifier: Atom, pub font_data: Option<Vec<u8>> } unsafe impl Send for FontTemplateData {} unsafe impl Sync for FontTemplateData {} impl FontTemplateData { pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> Result<FontTemplateData, IoError> { Ok(FontTemplateData { ctfont: CachedCTFont(Mutex::new(HashMap::new())), identifier: identifier.to_owned(), font_data: font_data }) } /// Retrieves the Core Text font instance, instantiating it if necessary. pub fn ctfont(&self, pt_size: f64) -> Option<CTFont> { let mut ctfonts = self.ctfont.lock().unwrap(); let pt_size_key = Au::from_f64_px(pt_size); if!ctfonts.contains_key(&pt_size_key) { // If you pass a zero font size to one of the Core Text APIs, it'll replace it with // 12.0. We don't want that! (Issue #10492.) let clamped_pt_size = pt_size.max(0.01); let ctfont = match self.font_data { Some(ref bytes) => { let fontprov = CGDataProvider::from_buffer(bytes); let cgfont_result = CGFont::from_data_provider(fontprov); match cgfont_result { Ok(cgfont) => { Some(core_text::font::new_from_CGFont(&cgfont, clamped_pt_size)) } Err(_) => None } } None => core_text::font::new_from_name(&*self.identifier, clamped_pt_size).ok(), }; if let Some(ctfont) = ctfont { ctfonts.insert(pt_size_key, ctfont); } } ctfonts.get(&pt_size_key).map(|ctfont| (*ctfont).clone()) } /// Returns a clone of the data in this font. This may be a hugely expensive /// operation (depending on the platform) which performs synchronous disk I/O /// and should never be done lightly. pub fn bytes(&self) -> Vec<u8> { if let Some(font_data) = self.bytes_if_in_memory() { return font_data; } let path = ServoUrl::parse(&*self.ctfont(0.0) .expect("No Core Text font available!") .url() .expect("No URL for Core Text font!") .get_string() .to_string()).expect("Couldn't parse Core Text font URL!") .as_url().to_file_path() .expect("Core Text font didn't name a path!"); let mut bytes = Vec::new(); File::open(path).expect("Couldn't open font file!").read_to_end(&mut bytes).unwrap(); bytes } /// Returns a clone of the bytes in this font if they are in memory. This function never /// performs disk I/O. pub fn bytes_if_in_memory(&self) -> Option<Vec<u8>> { self.font_data.clone() } /// Returns the native font that underlies this font template, if applicable. pub fn native_font(&self) -> Option<NativeFontHandle> { self.ctfont(0.0).map(|ctfont| NativeFontHandle(ctfont.copy_to_CGFont())) } } #[derive(Debug)] pub struct CachedCTFont(Mutex<HashMap<Au, CTFont>>); impl Deref for CachedCTFont { type Target = Mutex<HashMap<Au, CTFont>>; fn deref(&self) -> &Mutex<HashMap<Au, CTFont>> { &self.0 } } impl Serialize for CachedCTFont { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer
} impl<'de> Deserialize<'de> for CachedCTFont { fn deserialize<D>(deserializer: D) -> Result<CachedCTFont, D::Error> where D: Deserializer<'de> { struct NoneOptionVisitor; impl<'de> Visitor<'de> for NoneOptionVisitor { type Value = CachedCTFont; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "none") } #[inline] fn visit_none<E>(self) -> Result<CachedCTFont, E> where E: Error { Ok(CachedCTFont(Mutex::new(HashMap::new()))) } } deserializer.deserialize_option(NoneOptionVisitor) } }
{ serializer.serialize_none() }
identifier_body
font_template.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 core_graphics::data_provider::CGDataProvider; use core_graphics::font::CGFont; use core_text; use core_text::font::CTFont; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::de::{Error, Visitor}; use servo_atoms::Atom; use servo_url::ServoUrl; use std::borrow::ToOwned; use std::collections::HashMap; use std::fmt; use std::fs::File; use std::io::{Read, Error as IoError}; use std::ops::Deref; use std::sync::Mutex; use webrender_traits::NativeFontHandle; /// Platform specific font representation for mac. /// The identifier is a PostScript font name. The /// CTFont object is cached here for use by the /// paint functions that create CGFont references. #[derive(Deserialize, Serialize, Debug)] pub struct FontTemplateData { /// The `CTFont` object, if present. This is cached here so that we don't have to keep creating /// `CTFont` instances over and over. It can always be recreated from the `identifier` and/or /// `font_data` fields. /// /// When sending a `FontTemplateData` instance across processes, this will be cleared out on /// the other side, because `CTFont` instances cannot be sent across processes. This is /// harmless, however, because it can always be recreated. ctfont: CachedCTFont, pub identifier: Atom, pub font_data: Option<Vec<u8>> } unsafe impl Send for FontTemplateData {} unsafe impl Sync for FontTemplateData {} impl FontTemplateData { pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> Result<FontTemplateData, IoError> { Ok(FontTemplateData { ctfont: CachedCTFont(Mutex::new(HashMap::new())), identifier: identifier.to_owned(), font_data: font_data }) } /// Retrieves the Core Text font instance, instantiating it if necessary. pub fn ctfont(&self, pt_size: f64) -> Option<CTFont> { let mut ctfonts = self.ctfont.lock().unwrap(); let pt_size_key = Au::from_f64_px(pt_size); if!ctfonts.contains_key(&pt_size_key) { // If you pass a zero font size to one of the Core Text APIs, it'll replace it with // 12.0. We don't want that! (Issue #10492.) let clamped_pt_size = pt_size.max(0.01); let ctfont = match self.font_data { Some(ref bytes) => { let fontprov = CGDataProvider::from_buffer(bytes); let cgfont_result = CGFont::from_data_provider(fontprov); match cgfont_result { Ok(cgfont) => { Some(core_text::font::new_from_CGFont(&cgfont, clamped_pt_size)) } Err(_) => None } } None => core_text::font::new_from_name(&*self.identifier, clamped_pt_size).ok(), }; if let Some(ctfont) = ctfont { ctfonts.insert(pt_size_key, ctfont); } } ctfonts.get(&pt_size_key).map(|ctfont| (*ctfont).clone()) } /// Returns a clone of the data in this font. This may be a hugely expensive /// operation (depending on the platform) which performs synchronous disk I/O /// and should never be done lightly. pub fn bytes(&self) -> Vec<u8> { if let Some(font_data) = self.bytes_if_in_memory() { return font_data; } let path = ServoUrl::parse(&*self.ctfont(0.0) .expect("No Core Text font available!") .url() .expect("No URL for Core Text font!") .get_string() .to_string()).expect("Couldn't parse Core Text font URL!") .as_url().to_file_path() .expect("Core Text font didn't name a path!"); let mut bytes = Vec::new(); File::open(path).expect("Couldn't open font file!").read_to_end(&mut bytes).unwrap(); bytes } /// Returns a clone of the bytes in this font if they are in memory. This function never /// performs disk I/O. pub fn bytes_if_in_memory(&self) -> Option<Vec<u8>> { self.font_data.clone() } /// Returns the native font that underlies this font template, if applicable. pub fn native_font(&self) -> Option<NativeFontHandle> { self.ctfont(0.0).map(|ctfont| NativeFontHandle(ctfont.copy_to_CGFont())) } } #[derive(Debug)] pub struct CachedCTFont(Mutex<HashMap<Au, CTFont>>); impl Deref for CachedCTFont { type Target = Mutex<HashMap<Au, CTFont>>; fn deref(&self) -> &Mutex<HashMap<Au, CTFont>> { &self.0 } } impl Serialize for CachedCTFont { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { serializer.serialize_none() } } impl<'de> Deserialize<'de> for CachedCTFont { fn deserialize<D>(deserializer: D) -> Result<CachedCTFont, D::Error> where D: Deserializer<'de> { struct NoneOptionVisitor; impl<'de> Visitor<'de> for NoneOptionVisitor { type Value = CachedCTFont; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "none") } #[inline] fn visit_none<E>(self) -> Result<CachedCTFont, E> where E: Error { Ok(CachedCTFont(Mutex::new(HashMap::new())))
} }
} } deserializer.deserialize_option(NoneOptionVisitor)
random_line_split
font_template.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 core_graphics::data_provider::CGDataProvider; use core_graphics::font::CGFont; use core_text; use core_text::font::CTFont; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::de::{Error, Visitor}; use servo_atoms::Atom; use servo_url::ServoUrl; use std::borrow::ToOwned; use std::collections::HashMap; use std::fmt; use std::fs::File; use std::io::{Read, Error as IoError}; use std::ops::Deref; use std::sync::Mutex; use webrender_traits::NativeFontHandle; /// Platform specific font representation for mac. /// The identifier is a PostScript font name. The /// CTFont object is cached here for use by the /// paint functions that create CGFont references. #[derive(Deserialize, Serialize, Debug)] pub struct FontTemplateData { /// The `CTFont` object, if present. This is cached here so that we don't have to keep creating /// `CTFont` instances over and over. It can always be recreated from the `identifier` and/or /// `font_data` fields. /// /// When sending a `FontTemplateData` instance across processes, this will be cleared out on /// the other side, because `CTFont` instances cannot be sent across processes. This is /// harmless, however, because it can always be recreated. ctfont: CachedCTFont, pub identifier: Atom, pub font_data: Option<Vec<u8>> } unsafe impl Send for FontTemplateData {} unsafe impl Sync for FontTemplateData {} impl FontTemplateData { pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> Result<FontTemplateData, IoError> { Ok(FontTemplateData { ctfont: CachedCTFont(Mutex::new(HashMap::new())), identifier: identifier.to_owned(), font_data: font_data }) } /// Retrieves the Core Text font instance, instantiating it if necessary. pub fn ctfont(&self, pt_size: f64) -> Option<CTFont> { let mut ctfonts = self.ctfont.lock().unwrap(); let pt_size_key = Au::from_f64_px(pt_size); if!ctfonts.contains_key(&pt_size_key) { // If you pass a zero font size to one of the Core Text APIs, it'll replace it with // 12.0. We don't want that! (Issue #10492.) let clamped_pt_size = pt_size.max(0.01); let ctfont = match self.font_data { Some(ref bytes) => { let fontprov = CGDataProvider::from_buffer(bytes); let cgfont_result = CGFont::from_data_provider(fontprov); match cgfont_result { Ok(cgfont) => { Some(core_text::font::new_from_CGFont(&cgfont, clamped_pt_size)) } Err(_) => None } } None => core_text::font::new_from_name(&*self.identifier, clamped_pt_size).ok(), }; if let Some(ctfont) = ctfont { ctfonts.insert(pt_size_key, ctfont); } } ctfonts.get(&pt_size_key).map(|ctfont| (*ctfont).clone()) } /// Returns a clone of the data in this font. This may be a hugely expensive /// operation (depending on the platform) which performs synchronous disk I/O /// and should never be done lightly. pub fn bytes(&self) -> Vec<u8> { if let Some(font_data) = self.bytes_if_in_memory() { return font_data; } let path = ServoUrl::parse(&*self.ctfont(0.0) .expect("No Core Text font available!") .url() .expect("No URL for Core Text font!") .get_string() .to_string()).expect("Couldn't parse Core Text font URL!") .as_url().to_file_path() .expect("Core Text font didn't name a path!"); let mut bytes = Vec::new(); File::open(path).expect("Couldn't open font file!").read_to_end(&mut bytes).unwrap(); bytes } /// Returns a clone of the bytes in this font if they are in memory. This function never /// performs disk I/O. pub fn bytes_if_in_memory(&self) -> Option<Vec<u8>> { self.font_data.clone() } /// Returns the native font that underlies this font template, if applicable. pub fn native_font(&self) -> Option<NativeFontHandle> { self.ctfont(0.0).map(|ctfont| NativeFontHandle(ctfont.copy_to_CGFont())) } } #[derive(Debug)] pub struct CachedCTFont(Mutex<HashMap<Au, CTFont>>); impl Deref for CachedCTFont { type Target = Mutex<HashMap<Au, CTFont>>; fn deref(&self) -> &Mutex<HashMap<Au, CTFont>> { &self.0 } } impl Serialize for CachedCTFont { fn
<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { serializer.serialize_none() } } impl<'de> Deserialize<'de> for CachedCTFont { fn deserialize<D>(deserializer: D) -> Result<CachedCTFont, D::Error> where D: Deserializer<'de> { struct NoneOptionVisitor; impl<'de> Visitor<'de> for NoneOptionVisitor { type Value = CachedCTFont; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "none") } #[inline] fn visit_none<E>(self) -> Result<CachedCTFont, E> where E: Error { Ok(CachedCTFont(Mutex::new(HashMap::new()))) } } deserializer.deserialize_option(NoneOptionVisitor) } }
serialize
identifier_name
main.rs
#![deny(warnings)] #![deny(unused_import_braces, unused_qualifications)] #[macro_use] extern crate log; extern crate clap; extern crate env_logger; extern crate breeze_core; extern crate breeze_backends; extern crate breeze_backend; mod input; use input::attach_default_input; use breeze_core::rom::Rom; use breeze_core::snes::Emulator; use breeze_core::save::SaveStateFormat; use breeze_core::record::{RecordingFormat, create_recorder, create_replayer}; use breeze_backend::Renderer; use clap::ArgMatches; use std::env; use std::error::Error; use std::fs::File; use std::io::{BufReader, Read}; use std::process; fn
(args: &ArgMatches) -> Result<(), Box<Error>> { if args.value_of("record").is_some() && args.value_of("replay").is_some() { return Err("`record` and `replay` may not be specified together!".into()); } let renderer_name = args.value_of("renderer").unwrap_or(&breeze_backends::DEFAULT_RENDERER); let renderer_fn = match breeze_backends::RENDERER_MAP.get(renderer_name) { None => { let mut message = format!("unknown renderer: {}\n", renderer_name); message.push_str(&format!("{} renderers known:\n", breeze_backends::RENDERER_MAP.len())); for (name, opt_fn) in breeze_backends::RENDERER_MAP.iter() { message.push_str(&format!("\t{}\t{}\n", name, match *opt_fn { Some(_) => "available", None => "not compiled in", })); } return Err(message.into()); } Some(&None) => { let mut message = format!("renderer '{}' not compiled in", renderer_name); message.push_str(&format!("(compile with `cargo build --features {}` to enable)", renderer_name)); // NOTE: Make sure that renderer name always matches feature name! return Err("exiting".into()); } Some(&Some(renderer_fn)) => { renderer_fn } }; let audio_name = args.value_of("audio").unwrap_or(&breeze_backends::DEFAULT_AUDIO); let audio_fn = match breeze_backends::AUDIO_MAP.get(audio_name) { None => { let mut message = format!("unknown audio sink: {}\n", audio_name); message.push_str(&format!("{} audio sinks known:\n", breeze_backends::AUDIO_MAP.len())); for (name, opt_fn) in breeze_backends::AUDIO_MAP.iter() { message.push_str(&format!("\t{}\t{}\n", name, match *opt_fn { Some(_) => "available", None => "not compiled in", })); } return Err(message.into()); } Some(&None) => { let mut message = format!("audio backend '{0}' not compiled in\n", audio_name); message.push_str(&format!("(compile with `cargo build --features {0}` to enable)", audio_name)); // NOTE: Make sure that audio sink name always matches feature name! return Err(message.into()); } Some(&Some(audio_fn)) => { audio_fn } }; // Load the ROM into memory let filename = args.value_of("rom").unwrap(); let mut file = try!(File::open(&filename)); let mut buf = Vec::new(); try!(file.read_to_end(&mut buf)); let rom = try!(Rom::from_bytes(&buf)); // Create the backend parts info!("using {} renderer", renderer_name); let mut renderer = try!(renderer_fn()); if let Some(title) = rom.get_title() { renderer.set_rom_title(title); } info!("using {} audio sink", audio_name); let audio = try!(audio_fn()); // Put everything together in the emulator let mut emu = Emulator::new(rom, renderer, audio); attach_default_input(&mut emu.peripherals_mut().input, renderer_name); if let Some(record_file) = args.value_of("record") { let writer = Box::new(File::create(record_file).unwrap()); let recorder = create_recorder(RecordingFormat::default(), writer, &emu.snes).unwrap(); emu.peripherals_mut().input.start_recording(recorder); } if let Some(replay_file) = args.value_of("replay") { let reader = Box::new(BufReader::new(File::open(replay_file).unwrap())); let replayer = create_replayer(RecordingFormat::default(), reader, &emu.snes).unwrap(); emu.peripherals_mut().input.start_replay(replayer); } if let Some(filename) = args.value_of("savestate") { let file = File::open(filename).unwrap(); let mut bufrd = BufReader::new(file); emu.snes.restore_save_state(SaveStateFormat::default(), &mut bufrd).unwrap() } if cfg!(debug_assertions) && args.is_present("oneframe") { debug!("PPU H={}, V={}", emu.peripherals().ppu.h_counter(), emu.peripherals().ppu.v_counter()); try!(emu.snes.render_frame(|_framebuf| Ok(vec![]))); info!("frame rendered. pausing emulation."); // Keep rendering, but don't run emulation // Copy out the frame buffer because the damn borrow checker doesn't like it otherwise let framebuf = emu.peripherals().ppu.framebuf.clone(); loop { let actions = try!(emu.renderer.render(&*framebuf)); for a in actions { if emu.handle_action(a) { break } } } } else { // Run normally try!(emu.run()); } Ok(()) } fn main() { if env::var_os("RUST_LOG").is_none() { env::set_var("RUST_LOG", "breeze=INFO"); } env_logger::init().unwrap(); let mut app = clap::App::new("breeze") .version(env!("CARGO_PKG_VERSION")) .about("SNES emulator") .arg(clap::Arg::with_name("rom") .required(true) .value_name("ROM_PATH") .takes_value(true) .help("The ROM file to execute")) .arg(clap::Arg::with_name("renderer") .short("R") .long("renderer") .takes_value(true) .help("The renderer to use")) .arg(clap::Arg::with_name("audio") .short("A") .long("audio") .takes_value(true) .help("The audio backend to use")) .arg(clap::Arg::with_name("savestate") .long("savestate") .takes_value(true) .help("The save state file to load")) .arg(clap::Arg::with_name("record") .long("record") .takes_value(true) .help("Record input to a text file")) .arg(clap::Arg::with_name("replay") .long("replay") .takes_value(true) .help("Replay a recording from a text file")); // Add debugging options if cfg!(debug_assertions) { app = app.arg(clap::Arg::with_name("oneframe") .long("oneframe") .help("Render a single frame, then pause")); } let args = app.get_matches(); match process_args(&args) { Ok(()) => {}, Err(e) => { // FIXME: Glium swallows useful information when using {} instead of {:?} // I should fix this upstream when I have time. debug!("error: {:?}", e); println!("error: {}", e); process::exit(1); } } }
process_args
identifier_name
main.rs
#![deny(warnings)] #![deny(unused_import_braces, unused_qualifications)] #[macro_use] extern crate log; extern crate clap; extern crate env_logger; extern crate breeze_core; extern crate breeze_backends; extern crate breeze_backend; mod input; use input::attach_default_input; use breeze_core::rom::Rom; use breeze_core::snes::Emulator; use breeze_core::save::SaveStateFormat; use breeze_core::record::{RecordingFormat, create_recorder, create_replayer}; use breeze_backend::Renderer; use clap::ArgMatches; use std::env; use std::error::Error; use std::fs::File; use std::io::{BufReader, Read}; use std::process; fn process_args(args: &ArgMatches) -> Result<(), Box<Error>> { if args.value_of("record").is_some() && args.value_of("replay").is_some() { return Err("`record` and `replay` may not be specified together!".into()); } let renderer_name = args.value_of("renderer").unwrap_or(&breeze_backends::DEFAULT_RENDERER); let renderer_fn = match breeze_backends::RENDERER_MAP.get(renderer_name) { None => { let mut message = format!("unknown renderer: {}\n", renderer_name); message.push_str(&format!("{} renderers known:\n", breeze_backends::RENDERER_MAP.len())); for (name, opt_fn) in breeze_backends::RENDERER_MAP.iter() { message.push_str(&format!("\t{}\t{}\n", name, match *opt_fn { Some(_) => "available", None => "not compiled in", })); } return Err(message.into()); } Some(&None) => { let mut message = format!("renderer '{}' not compiled in", renderer_name); message.push_str(&format!("(compile with `cargo build --features {}` to enable)", renderer_name)); // NOTE: Make sure that renderer name always matches feature name! return Err("exiting".into()); } Some(&Some(renderer_fn)) => { renderer_fn } }; let audio_name = args.value_of("audio").unwrap_or(&breeze_backends::DEFAULT_AUDIO); let audio_fn = match breeze_backends::AUDIO_MAP.get(audio_name) { None => { let mut message = format!("unknown audio sink: {}\n", audio_name); message.push_str(&format!("{} audio sinks known:\n", breeze_backends::AUDIO_MAP.len())); for (name, opt_fn) in breeze_backends::AUDIO_MAP.iter() { message.push_str(&format!("\t{}\t{}\n", name, match *opt_fn { Some(_) => "available", None => "not compiled in", })); } return Err(message.into()); } Some(&None) => { let mut message = format!("audio backend '{0}' not compiled in\n", audio_name); message.push_str(&format!("(compile with `cargo build --features {0}` to enable)", audio_name)); // NOTE: Make sure that audio sink name always matches feature name! return Err(message.into()); } Some(&Some(audio_fn)) => { audio_fn } }; // Load the ROM into memory let filename = args.value_of("rom").unwrap(); let mut file = try!(File::open(&filename)); let mut buf = Vec::new(); try!(file.read_to_end(&mut buf)); let rom = try!(Rom::from_bytes(&buf)); // Create the backend parts info!("using {} renderer", renderer_name); let mut renderer = try!(renderer_fn()); if let Some(title) = rom.get_title() { renderer.set_rom_title(title); } info!("using {} audio sink", audio_name); let audio = try!(audio_fn()); // Put everything together in the emulator let mut emu = Emulator::new(rom, renderer, audio); attach_default_input(&mut emu.peripherals_mut().input, renderer_name); if let Some(record_file) = args.value_of("record") { let writer = Box::new(File::create(record_file).unwrap()); let recorder = create_recorder(RecordingFormat::default(), writer, &emu.snes).unwrap(); emu.peripherals_mut().input.start_recording(recorder); } if let Some(replay_file) = args.value_of("replay") { let reader = Box::new(BufReader::new(File::open(replay_file).unwrap())); let replayer = create_replayer(RecordingFormat::default(), reader, &emu.snes).unwrap(); emu.peripherals_mut().input.start_replay(replayer); } if let Some(filename) = args.value_of("savestate") { let file = File::open(filename).unwrap(); let mut bufrd = BufReader::new(file); emu.snes.restore_save_state(SaveStateFormat::default(), &mut bufrd).unwrap() } if cfg!(debug_assertions) && args.is_present("oneframe") { debug!("PPU H={}, V={}", emu.peripherals().ppu.h_counter(), emu.peripherals().ppu.v_counter()); try!(emu.snes.render_frame(|_framebuf| Ok(vec![]))); info!("frame rendered. pausing emulation."); // Keep rendering, but don't run emulation // Copy out the frame buffer because the damn borrow checker doesn't like it otherwise let framebuf = emu.peripherals().ppu.framebuf.clone(); loop { let actions = try!(emu.renderer.render(&*framebuf)); for a in actions { if emu.handle_action(a) { break } } } } else { // Run normally try!(emu.run()); } Ok(()) } fn main() { if env::var_os("RUST_LOG").is_none() { env::set_var("RUST_LOG", "breeze=INFO"); } env_logger::init().unwrap(); let mut app = clap::App::new("breeze") .version(env!("CARGO_PKG_VERSION")) .about("SNES emulator") .arg(clap::Arg::with_name("rom") .required(true) .value_name("ROM_PATH") .takes_value(true) .help("The ROM file to execute")) .arg(clap::Arg::with_name("renderer") .short("R") .long("renderer") .takes_value(true) .help("The renderer to use")) .arg(clap::Arg::with_name("audio") .short("A") .long("audio") .takes_value(true) .help("The audio backend to use")) .arg(clap::Arg::with_name("savestate") .long("savestate") .takes_value(true) .help("The save state file to load"))
.long("replay") .takes_value(true) .help("Replay a recording from a text file")); // Add debugging options if cfg!(debug_assertions) { app = app.arg(clap::Arg::with_name("oneframe") .long("oneframe") .help("Render a single frame, then pause")); } let args = app.get_matches(); match process_args(&args) { Ok(()) => {}, Err(e) => { // FIXME: Glium swallows useful information when using {} instead of {:?} // I should fix this upstream when I have time. debug!("error: {:?}", e); println!("error: {}", e); process::exit(1); } } }
.arg(clap::Arg::with_name("record") .long("record") .takes_value(true) .help("Record input to a text file")) .arg(clap::Arg::with_name("replay")
random_line_split
main.rs
#![deny(warnings)] #![deny(unused_import_braces, unused_qualifications)] #[macro_use] extern crate log; extern crate clap; extern crate env_logger; extern crate breeze_core; extern crate breeze_backends; extern crate breeze_backend; mod input; use input::attach_default_input; use breeze_core::rom::Rom; use breeze_core::snes::Emulator; use breeze_core::save::SaveStateFormat; use breeze_core::record::{RecordingFormat, create_recorder, create_replayer}; use breeze_backend::Renderer; use clap::ArgMatches; use std::env; use std::error::Error; use std::fs::File; use std::io::{BufReader, Read}; use std::process; fn process_args(args: &ArgMatches) -> Result<(), Box<Error>> { if args.value_of("record").is_some() && args.value_of("replay").is_some() { return Err("`record` and `replay` may not be specified together!".into()); } let renderer_name = args.value_of("renderer").unwrap_or(&breeze_backends::DEFAULT_RENDERER); let renderer_fn = match breeze_backends::RENDERER_MAP.get(renderer_name) { None => { let mut message = format!("unknown renderer: {}\n", renderer_name); message.push_str(&format!("{} renderers known:\n", breeze_backends::RENDERER_MAP.len())); for (name, opt_fn) in breeze_backends::RENDERER_MAP.iter() { message.push_str(&format!("\t{}\t{}\n", name, match *opt_fn { Some(_) => "available", None => "not compiled in", })); } return Err(message.into()); } Some(&None) => { let mut message = format!("renderer '{}' not compiled in", renderer_name); message.push_str(&format!("(compile with `cargo build --features {}` to enable)", renderer_name)); // NOTE: Make sure that renderer name always matches feature name! return Err("exiting".into()); } Some(&Some(renderer_fn)) => { renderer_fn } }; let audio_name = args.value_of("audio").unwrap_or(&breeze_backends::DEFAULT_AUDIO); let audio_fn = match breeze_backends::AUDIO_MAP.get(audio_name) { None => { let mut message = format!("unknown audio sink: {}\n", audio_name); message.push_str(&format!("{} audio sinks known:\n", breeze_backends::AUDIO_MAP.len())); for (name, opt_fn) in breeze_backends::AUDIO_MAP.iter() { message.push_str(&format!("\t{}\t{}\n", name, match *opt_fn { Some(_) => "available", None => "not compiled in", })); } return Err(message.into()); } Some(&None) => { let mut message = format!("audio backend '{0}' not compiled in\n", audio_name); message.push_str(&format!("(compile with `cargo build --features {0}` to enable)", audio_name)); // NOTE: Make sure that audio sink name always matches feature name! return Err(message.into()); } Some(&Some(audio_fn)) => { audio_fn } }; // Load the ROM into memory let filename = args.value_of("rom").unwrap(); let mut file = try!(File::open(&filename)); let mut buf = Vec::new(); try!(file.read_to_end(&mut buf)); let rom = try!(Rom::from_bytes(&buf)); // Create the backend parts info!("using {} renderer", renderer_name); let mut renderer = try!(renderer_fn()); if let Some(title) = rom.get_title() { renderer.set_rom_title(title); } info!("using {} audio sink", audio_name); let audio = try!(audio_fn()); // Put everything together in the emulator let mut emu = Emulator::new(rom, renderer, audio); attach_default_input(&mut emu.peripherals_mut().input, renderer_name); if let Some(record_file) = args.value_of("record") { let writer = Box::new(File::create(record_file).unwrap()); let recorder = create_recorder(RecordingFormat::default(), writer, &emu.snes).unwrap(); emu.peripherals_mut().input.start_recording(recorder); } if let Some(replay_file) = args.value_of("replay") { let reader = Box::new(BufReader::new(File::open(replay_file).unwrap())); let replayer = create_replayer(RecordingFormat::default(), reader, &emu.snes).unwrap(); emu.peripherals_mut().input.start_replay(replayer); } if let Some(filename) = args.value_of("savestate") { let file = File::open(filename).unwrap(); let mut bufrd = BufReader::new(file); emu.snes.restore_save_state(SaveStateFormat::default(), &mut bufrd).unwrap() } if cfg!(debug_assertions) && args.is_present("oneframe") { debug!("PPU H={}, V={}", emu.peripherals().ppu.h_counter(), emu.peripherals().ppu.v_counter()); try!(emu.snes.render_frame(|_framebuf| Ok(vec![]))); info!("frame rendered. pausing emulation."); // Keep rendering, but don't run emulation // Copy out the frame buffer because the damn borrow checker doesn't like it otherwise let framebuf = emu.peripherals().ppu.framebuf.clone(); loop { let actions = try!(emu.renderer.render(&*framebuf)); for a in actions { if emu.handle_action(a) { break } } } } else { // Run normally try!(emu.run()); } Ok(()) } fn main()
.short("A") .long("audio") .takes_value(true) .help("The audio backend to use")) .arg(clap::Arg::with_name("savestate") .long("savestate") .takes_value(true) .help("The save state file to load")) .arg(clap::Arg::with_name("record") .long("record") .takes_value(true) .help("Record input to a text file")) .arg(clap::Arg::with_name("replay") .long("replay") .takes_value(true) .help("Replay a recording from a text file")); // Add debugging options if cfg!(debug_assertions) { app = app.arg(clap::Arg::with_name("oneframe") .long("oneframe") .help("Render a single frame, then pause")); } let args = app.get_matches(); match process_args(&args) { Ok(()) => {}, Err(e) => { // FIXME: Glium swallows useful information when using {} instead of {:?} // I should fix this upstream when I have time. debug!("error: {:?}", e); println!("error: {}", e); process::exit(1); } } }
{ if env::var_os("RUST_LOG").is_none() { env::set_var("RUST_LOG", "breeze=INFO"); } env_logger::init().unwrap(); let mut app = clap::App::new("breeze") .version(env!("CARGO_PKG_VERSION")) .about("SNES emulator") .arg(clap::Arg::with_name("rom") .required(true) .value_name("ROM_PATH") .takes_value(true) .help("The ROM file to execute")) .arg(clap::Arg::with_name("renderer") .short("R") .long("renderer") .takes_value(true) .help("The renderer to use")) .arg(clap::Arg::with_name("audio")
identifier_body
proof.rs
use crate::services::ledger::merkletree::tree::{Tree, TreeLeafData}; use indy_utils::crypto::hash::Hash; use indy_api_types::errors::prelude::*; /// An inclusion proof represent the fact that a `value` is a member /// of a `MerkleTree` with root hash `root_hash`. #[derive(Clone, Debug)] pub struct Proof { /// The hash of the root of the original `MerkleTree` pub root_hash: Vec<u8>, /// The first `Lemma` of the `Proof` pub lemma: Lemma, /// The value concerned by this `Proof` pub value: TreeLeafData } impl Proof { /// Constructs a new `Proof` pub fn new(root_hash: Vec<u8>, lemma: Lemma, value: TreeLeafData) -> Self { Proof { root_hash, lemma, value } } /// Checks whether this inclusion proof is well-formed, /// and whether its root hash matches the given `root_hash`. pub fn validate(&self, root_hash: &[u8]) -> IndyResult<bool> { if self.root_hash!= root_hash || self.lemma.node_hash!= root_hash { return Ok(false) } Ok(self.validate_lemma(&self.lemma)?) } fn validate_lemma(&self, lemma: &Lemma) -> IndyResult<bool> { match lemma.sub_lemma { None => Ok(lemma.sibling_hash.is_none()), Some(ref sub) => match lemma.sibling_hash { None => Ok(false), Some(Positioned::Left(ref hash)) => { let combined = Hash::hash_nodes(hash, &sub.node_hash)?; let hashes_match = combined.to_vec().as_slice() == lemma.node_hash.as_slice(); Ok(hashes_match && self.validate_lemma(sub)?) } Some(Positioned::Right(ref hash)) => { let combined = Hash::hash_nodes(&sub.node_hash, hash)?; let hashes_match = combined.to_vec().as_slice() == lemma.node_hash.as_slice(); Ok(hashes_match && self.validate_lemma(sub)?) } } } } } /// A `Lemma` holds the hash of a node, the hash of its sibling node, /// and a sub lemma, whose `node_hash`, when combined with this `sibling_hash` /// must be equal to this `node_hash`. #[derive(Clone, Debug, PartialEq)] pub struct Lemma { pub node_hash: Vec<u8>, pub sibling_hash: Option<Positioned<Vec<u8>>>, pub sub_lemma: Option<Box<Lemma>> } impl Lemma { /// Attempts to generate a proof that the a value with hash `needle` is a member of the given `tree`. pub fn new(tree: &Tree, needle: &[u8]) -> Option<Lemma>
fn new_leaf_proof(hash: &[u8], needle: &[u8]) -> Option<Lemma> { if *hash == *needle { Some(Lemma { node_hash: hash.into(), sibling_hash: None, sub_lemma: None }) } else { None } } fn new_tree_proof(hash: &[u8], needle: &[u8], left: &Tree, right: &Tree) -> Option<Lemma> { Lemma::new(left, needle) .map(|lemma| { let right_hash = right.hash().clone(); let sub_lemma = Some(Positioned::Right(right_hash)); (lemma, sub_lemma) }) .or_else(|| { let sub_lemma = Lemma::new(right, needle); sub_lemma.map(|lemma| { let left_hash = left.hash().clone(); let sub_lemma = Some(Positioned::Left(left_hash)); (lemma, sub_lemma) }) }) .map(|(sub_lemma, sibling_hash)| { Lemma { node_hash: hash.into(), sibling_hash, sub_lemma: Some(Box::new(sub_lemma)) } }) } } /// Tags a value so that we know from which branch of a `Tree` (if any) it was found. #[derive(Clone, Debug, PartialEq)] pub enum Positioned<T> { /// The value was found in the left branch Left(T), /// The value was found in the right branch Right(T) }
{ match *tree { Tree::Empty {.. } => None, Tree::Leaf { ref hash, .. } => Lemma::new_leaf_proof(hash, needle), Tree::Node { ref hash, ref left, ref right } => Lemma::new_tree_proof(hash, needle, left, right) } }
identifier_body
proof.rs
use crate::services::ledger::merkletree::tree::{Tree, TreeLeafData}; use indy_utils::crypto::hash::Hash; use indy_api_types::errors::prelude::*; /// An inclusion proof represent the fact that a `value` is a member /// of a `MerkleTree` with root hash `root_hash`. #[derive(Clone, Debug)] pub struct Proof { /// The hash of the root of the original `MerkleTree` pub root_hash: Vec<u8>, /// The first `Lemma` of the `Proof` pub lemma: Lemma, /// The value concerned by this `Proof` pub value: TreeLeafData } impl Proof { /// Constructs a new `Proof` pub fn
(root_hash: Vec<u8>, lemma: Lemma, value: TreeLeafData) -> Self { Proof { root_hash, lemma, value } } /// Checks whether this inclusion proof is well-formed, /// and whether its root hash matches the given `root_hash`. pub fn validate(&self, root_hash: &[u8]) -> IndyResult<bool> { if self.root_hash!= root_hash || self.lemma.node_hash!= root_hash { return Ok(false) } Ok(self.validate_lemma(&self.lemma)?) } fn validate_lemma(&self, lemma: &Lemma) -> IndyResult<bool> { match lemma.sub_lemma { None => Ok(lemma.sibling_hash.is_none()), Some(ref sub) => match lemma.sibling_hash { None => Ok(false), Some(Positioned::Left(ref hash)) => { let combined = Hash::hash_nodes(hash, &sub.node_hash)?; let hashes_match = combined.to_vec().as_slice() == lemma.node_hash.as_slice(); Ok(hashes_match && self.validate_lemma(sub)?) } Some(Positioned::Right(ref hash)) => { let combined = Hash::hash_nodes(&sub.node_hash, hash)?; let hashes_match = combined.to_vec().as_slice() == lemma.node_hash.as_slice(); Ok(hashes_match && self.validate_lemma(sub)?) } } } } } /// A `Lemma` holds the hash of a node, the hash of its sibling node, /// and a sub lemma, whose `node_hash`, when combined with this `sibling_hash` /// must be equal to this `node_hash`. #[derive(Clone, Debug, PartialEq)] pub struct Lemma { pub node_hash: Vec<u8>, pub sibling_hash: Option<Positioned<Vec<u8>>>, pub sub_lemma: Option<Box<Lemma>> } impl Lemma { /// Attempts to generate a proof that the a value with hash `needle` is a member of the given `tree`. pub fn new(tree: &Tree, needle: &[u8]) -> Option<Lemma> { match *tree { Tree::Empty {.. } => None, Tree::Leaf { ref hash,.. } => Lemma::new_leaf_proof(hash, needle), Tree::Node { ref hash, ref left, ref right } => Lemma::new_tree_proof(hash, needle, left, right) } } fn new_leaf_proof(hash: &[u8], needle: &[u8]) -> Option<Lemma> { if *hash == *needle { Some(Lemma { node_hash: hash.into(), sibling_hash: None, sub_lemma: None }) } else { None } } fn new_tree_proof(hash: &[u8], needle: &[u8], left: &Tree, right: &Tree) -> Option<Lemma> { Lemma::new(left, needle) .map(|lemma| { let right_hash = right.hash().clone(); let sub_lemma = Some(Positioned::Right(right_hash)); (lemma, sub_lemma) }) .or_else(|| { let sub_lemma = Lemma::new(right, needle); sub_lemma.map(|lemma| { let left_hash = left.hash().clone(); let sub_lemma = Some(Positioned::Left(left_hash)); (lemma, sub_lemma) }) }) .map(|(sub_lemma, sibling_hash)| { Lemma { node_hash: hash.into(), sibling_hash, sub_lemma: Some(Box::new(sub_lemma)) } }) } } /// Tags a value so that we know from which branch of a `Tree` (if any) it was found. #[derive(Clone, Debug, PartialEq)] pub enum Positioned<T> { /// The value was found in the left branch Left(T), /// The value was found in the right branch Right(T) }
new
identifier_name
proof.rs
use crate::services::ledger::merkletree::tree::{Tree, TreeLeafData}; use indy_utils::crypto::hash::Hash; use indy_api_types::errors::prelude::*; /// An inclusion proof represent the fact that a `value` is a member /// of a `MerkleTree` with root hash `root_hash`. #[derive(Clone, Debug)] pub struct Proof { /// The hash of the root of the original `MerkleTree` pub root_hash: Vec<u8>, /// The first `Lemma` of the `Proof` pub lemma: Lemma, /// The value concerned by this `Proof` pub value: TreeLeafData } impl Proof { /// Constructs a new `Proof` pub fn new(root_hash: Vec<u8>, lemma: Lemma, value: TreeLeafData) -> Self { Proof { root_hash, lemma, value } } /// Checks whether this inclusion proof is well-formed, /// and whether its root hash matches the given `root_hash`. pub fn validate(&self, root_hash: &[u8]) -> IndyResult<bool> { if self.root_hash!= root_hash || self.lemma.node_hash!= root_hash { return Ok(false) } Ok(self.validate_lemma(&self.lemma)?) } fn validate_lemma(&self, lemma: &Lemma) -> IndyResult<bool> { match lemma.sub_lemma {
match lemma.sibling_hash { None => Ok(false), Some(Positioned::Left(ref hash)) => { let combined = Hash::hash_nodes(hash, &sub.node_hash)?; let hashes_match = combined.to_vec().as_slice() == lemma.node_hash.as_slice(); Ok(hashes_match && self.validate_lemma(sub)?) } Some(Positioned::Right(ref hash)) => { let combined = Hash::hash_nodes(&sub.node_hash, hash)?; let hashes_match = combined.to_vec().as_slice() == lemma.node_hash.as_slice(); Ok(hashes_match && self.validate_lemma(sub)?) } } } } } /// A `Lemma` holds the hash of a node, the hash of its sibling node, /// and a sub lemma, whose `node_hash`, when combined with this `sibling_hash` /// must be equal to this `node_hash`. #[derive(Clone, Debug, PartialEq)] pub struct Lemma { pub node_hash: Vec<u8>, pub sibling_hash: Option<Positioned<Vec<u8>>>, pub sub_lemma: Option<Box<Lemma>> } impl Lemma { /// Attempts to generate a proof that the a value with hash `needle` is a member of the given `tree`. pub fn new(tree: &Tree, needle: &[u8]) -> Option<Lemma> { match *tree { Tree::Empty {.. } => None, Tree::Leaf { ref hash,.. } => Lemma::new_leaf_proof(hash, needle), Tree::Node { ref hash, ref left, ref right } => Lemma::new_tree_proof(hash, needle, left, right) } } fn new_leaf_proof(hash: &[u8], needle: &[u8]) -> Option<Lemma> { if *hash == *needle { Some(Lemma { node_hash: hash.into(), sibling_hash: None, sub_lemma: None }) } else { None } } fn new_tree_proof(hash: &[u8], needle: &[u8], left: &Tree, right: &Tree) -> Option<Lemma> { Lemma::new(left, needle) .map(|lemma| { let right_hash = right.hash().clone(); let sub_lemma = Some(Positioned::Right(right_hash)); (lemma, sub_lemma) }) .or_else(|| { let sub_lemma = Lemma::new(right, needle); sub_lemma.map(|lemma| { let left_hash = left.hash().clone(); let sub_lemma = Some(Positioned::Left(left_hash)); (lemma, sub_lemma) }) }) .map(|(sub_lemma, sibling_hash)| { Lemma { node_hash: hash.into(), sibling_hash, sub_lemma: Some(Box::new(sub_lemma)) } }) } } /// Tags a value so that we know from which branch of a `Tree` (if any) it was found. #[derive(Clone, Debug, PartialEq)] pub enum Positioned<T> { /// The value was found in the left branch Left(T), /// The value was found in the right branch Right(T) }
None => Ok(lemma.sibling_hash.is_none()), Some(ref sub) =>
random_line_split
number.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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. //! Immutable numbers. #[allow(non_uppercase_statics)]; use base::{CFAllocatorRef, CFRelease, CFTypeID, TCFType, kCFAllocatorDefault}; use std::cast; use std::libc::c_void; pub type CFNumberType = u32; // members of enum CFNumberType // static kCFNumberSInt8Type: CFNumberType = 1; // static kCFNumberSInt16Type: CFNumberType = 2; // static kCFNumberSInt32Type: CFNumberType = 3; static kCFNumberSInt64Type: CFNumberType = 4; // static kCFNumberFloat32Type: CFNumberType = 5; static kCFNumberFloat64Type: CFNumberType = 6; // static kCFNumberCharType: CFNumberType = 7; // static kCFNumberShortType: CFNumberType = 8; // static kCFNumberIntType: CFNumberType = 9; // static kCFNumberLongType: CFNumberType = 10; // static kCFNumberLongLongType: CFNumberType = 11; // static kCFNumberFloatType: CFNumberType = 12; // static kCFNumberDoubleType: CFNumberType = 13; // static kCFNumberCFIndexType: CFNumberType = 14; // static kCFNumberNSIntegerType: CFNumberType = 15; // static kCFNumberCGFloatType: CFNumberType = 16; // static kCFNumberMaxType: CFNumberType = 16; struct __CFNumber; pub type CFNumberRef = *__CFNumber; /// An immutable numeric value. /// /// FIXME(pcwalton): Should be a newtype struct, but that fails due to a Rust compiler bug. pub struct CFNumber { priv obj: CFNumberRef, } impl Drop for CFNumber { fn drop(&mut self) { unsafe { CFRelease(self.as_CFTypeRef()) } } } impl TCFType<CFNumberRef> for CFNumber { fn as_concrete_TypeRef(&self) -> CFNumberRef { self.obj } unsafe fn wrap_under_create_rule(obj: CFNumberRef) -> CFNumber { CFNumber { obj: obj, } } #[inline] fn type_id(_: Option<CFNumber>) -> CFTypeID { unsafe { CFNumberGetTypeID() } } } // TODO(pcwalton): Floating point. impl ToPrimitive for CFNumber { #[inline] fn to_i64(&self) -> Option<i64> { unsafe { let mut value: i64 = 0; let ok = CFNumberGetValue(self.obj, kCFNumberSInt64Type, cast::transmute(&mut value)); assert!(ok); Some(value) } } #[inline] fn to_u64(&self) -> Option<u64> { // CFNumber does not support unsigned 64-bit values. None } #[inline] fn to_f64(&self) -> Option<f64> { unsafe { let mut value: f64 = 0.0; let ok = CFNumberGetValue(self.obj, kCFNumberFloat64Type, cast::transmute(&mut value)); assert!(ok); Some(value) } } } // TODO(pcwalton): Floating point. impl FromPrimitive for CFNumber { #[inline] fn from_i64(value: i64) -> Option<CFNumber> { unsafe { let number_ref = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, cast::transmute(&value)); Some(TCFType::wrap_under_create_rule(number_ref)) } } #[inline] fn from_u64(_: u64) -> Option<CFNumber> { // CFNumber does not support unsigned 64-bit values. None } #[inline] fn from_f64(value: f64) -> Option<CFNumber> { unsafe { let number_ref = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloat64Type, cast::transmute(&value)); Some(TCFType::wrap_under_create_rule(number_ref)) } } } /// A convenience function to create CFNumbers. pub fn number(value: i64) -> CFNumber
#[link(name = "CoreFoundation", kind = "framework")] extern { /* * CFNumber.h */ fn CFNumberCreate(allocator: CFAllocatorRef, theType: CFNumberType, valuePtr: *c_void) -> CFNumberRef; //fn CFNumberGetByteSize fn CFNumberGetValue(number: CFNumberRef, theType: CFNumberType, valuePtr: *mut c_void) -> bool; //fn CFNumberCompare fn CFNumberGetTypeID() -> CFTypeID; }
{ FromPrimitive::from_i64(value).unwrap() }
identifier_body
number.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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. //! Immutable numbers. #[allow(non_uppercase_statics)]; use base::{CFAllocatorRef, CFRelease, CFTypeID, TCFType, kCFAllocatorDefault}; use std::cast; use std::libc::c_void; pub type CFNumberType = u32; // members of enum CFNumberType // static kCFNumberSInt8Type: CFNumberType = 1; // static kCFNumberSInt16Type: CFNumberType = 2; // static kCFNumberSInt32Type: CFNumberType = 3; static kCFNumberSInt64Type: CFNumberType = 4; // static kCFNumberFloat32Type: CFNumberType = 5; static kCFNumberFloat64Type: CFNumberType = 6; // static kCFNumberCharType: CFNumberType = 7; // static kCFNumberShortType: CFNumberType = 8; // static kCFNumberIntType: CFNumberType = 9; // static kCFNumberLongType: CFNumberType = 10; // static kCFNumberLongLongType: CFNumberType = 11; // static kCFNumberFloatType: CFNumberType = 12; // static kCFNumberDoubleType: CFNumberType = 13; // static kCFNumberCFIndexType: CFNumberType = 14; // static kCFNumberNSIntegerType: CFNumberType = 15; // static kCFNumberCGFloatType: CFNumberType = 16; // static kCFNumberMaxType: CFNumberType = 16; struct __CFNumber; pub type CFNumberRef = *__CFNumber; /// An immutable numeric value. /// /// FIXME(pcwalton): Should be a newtype struct, but that fails due to a Rust compiler bug. pub struct CFNumber { priv obj: CFNumberRef, } impl Drop for CFNumber { fn drop(&mut self) { unsafe { CFRelease(self.as_CFTypeRef()) } } } impl TCFType<CFNumberRef> for CFNumber { fn as_concrete_TypeRef(&self) -> CFNumberRef { self.obj } unsafe fn wrap_under_create_rule(obj: CFNumberRef) -> CFNumber { CFNumber { obj: obj, } } #[inline] fn type_id(_: Option<CFNumber>) -> CFTypeID { unsafe { CFNumberGetTypeID() } } } // TODO(pcwalton): Floating point. impl ToPrimitive for CFNumber { #[inline] fn
(&self) -> Option<i64> { unsafe { let mut value: i64 = 0; let ok = CFNumberGetValue(self.obj, kCFNumberSInt64Type, cast::transmute(&mut value)); assert!(ok); Some(value) } } #[inline] fn to_u64(&self) -> Option<u64> { // CFNumber does not support unsigned 64-bit values. None } #[inline] fn to_f64(&self) -> Option<f64> { unsafe { let mut value: f64 = 0.0; let ok = CFNumberGetValue(self.obj, kCFNumberFloat64Type, cast::transmute(&mut value)); assert!(ok); Some(value) } } } // TODO(pcwalton): Floating point. impl FromPrimitive for CFNumber { #[inline] fn from_i64(value: i64) -> Option<CFNumber> { unsafe { let number_ref = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, cast::transmute(&value)); Some(TCFType::wrap_under_create_rule(number_ref)) } } #[inline] fn from_u64(_: u64) -> Option<CFNumber> { // CFNumber does not support unsigned 64-bit values. None } #[inline] fn from_f64(value: f64) -> Option<CFNumber> { unsafe { let number_ref = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloat64Type, cast::transmute(&value)); Some(TCFType::wrap_under_create_rule(number_ref)) } } } /// A convenience function to create CFNumbers. pub fn number(value: i64) -> CFNumber { FromPrimitive::from_i64(value).unwrap() } #[link(name = "CoreFoundation", kind = "framework")] extern { /* * CFNumber.h */ fn CFNumberCreate(allocator: CFAllocatorRef, theType: CFNumberType, valuePtr: *c_void) -> CFNumberRef; //fn CFNumberGetByteSize fn CFNumberGetValue(number: CFNumberRef, theType: CFNumberType, valuePtr: *mut c_void) -> bool; //fn CFNumberCompare fn CFNumberGetTypeID() -> CFTypeID; }
to_i64
identifier_name
number.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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. //! Immutable numbers. #[allow(non_uppercase_statics)]; use base::{CFAllocatorRef, CFRelease, CFTypeID, TCFType, kCFAllocatorDefault}; use std::cast; use std::libc::c_void; pub type CFNumberType = u32; // members of enum CFNumberType // static kCFNumberSInt8Type: CFNumberType = 1; // static kCFNumberSInt16Type: CFNumberType = 2; // static kCFNumberSInt32Type: CFNumberType = 3; static kCFNumberSInt64Type: CFNumberType = 4; // static kCFNumberFloat32Type: CFNumberType = 5; static kCFNumberFloat64Type: CFNumberType = 6; // static kCFNumberCharType: CFNumberType = 7; // static kCFNumberShortType: CFNumberType = 8; // static kCFNumberIntType: CFNumberType = 9; // static kCFNumberLongType: CFNumberType = 10; // static kCFNumberLongLongType: CFNumberType = 11; // static kCFNumberFloatType: CFNumberType = 12; // static kCFNumberDoubleType: CFNumberType = 13; // static kCFNumberCFIndexType: CFNumberType = 14; // static kCFNumberNSIntegerType: CFNumberType = 15; // static kCFNumberCGFloatType: CFNumberType = 16; // static kCFNumberMaxType: CFNumberType = 16; struct __CFNumber; pub type CFNumberRef = *__CFNumber; /// An immutable numeric value. /// /// FIXME(pcwalton): Should be a newtype struct, but that fails due to a Rust compiler bug. pub struct CFNumber { priv obj: CFNumberRef, } impl Drop for CFNumber { fn drop(&mut self) { unsafe { CFRelease(self.as_CFTypeRef()) } } } impl TCFType<CFNumberRef> for CFNumber { fn as_concrete_TypeRef(&self) -> CFNumberRef { self.obj } unsafe fn wrap_under_create_rule(obj: CFNumberRef) -> CFNumber { CFNumber { obj: obj, } } #[inline] fn type_id(_: Option<CFNumber>) -> CFTypeID { unsafe { CFNumberGetTypeID() } } } // TODO(pcwalton): Floating point. impl ToPrimitive for CFNumber { #[inline] fn to_i64(&self) -> Option<i64> { unsafe { let mut value: i64 = 0; let ok = CFNumberGetValue(self.obj, kCFNumberSInt64Type, cast::transmute(&mut value)); assert!(ok); Some(value) } } #[inline] fn to_u64(&self) -> Option<u64> { // CFNumber does not support unsigned 64-bit values. None } #[inline] fn to_f64(&self) -> Option<f64> { unsafe { let mut value: f64 = 0.0; let ok = CFNumberGetValue(self.obj, kCFNumberFloat64Type, cast::transmute(&mut value)); assert!(ok); Some(value) } } } // TODO(pcwalton): Floating point. impl FromPrimitive for CFNumber { #[inline] fn from_i64(value: i64) -> Option<CFNumber> { unsafe { let number_ref = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, cast::transmute(&value)); Some(TCFType::wrap_under_create_rule(number_ref)) } } #[inline] fn from_u64(_: u64) -> Option<CFNumber> { // CFNumber does not support unsigned 64-bit values. None }
#[inline] fn from_f64(value: f64) -> Option<CFNumber> { unsafe { let number_ref = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloat64Type, cast::transmute(&value)); Some(TCFType::wrap_under_create_rule(number_ref)) } } } /// A convenience function to create CFNumbers. pub fn number(value: i64) -> CFNumber { FromPrimitive::from_i64(value).unwrap() } #[link(name = "CoreFoundation", kind = "framework")] extern { /* * CFNumber.h */ fn CFNumberCreate(allocator: CFAllocatorRef, theType: CFNumberType, valuePtr: *c_void) -> CFNumberRef; //fn CFNumberGetByteSize fn CFNumberGetValue(number: CFNumberRef, theType: CFNumberType, valuePtr: *mut c_void) -> bool; //fn CFNumberCompare fn CFNumberGetTypeID() -> CFTypeID; }
random_line_split
main.rs
//! The N-body benchmark from the [benchmarks game][bg]. //! //! [bg]: https://benchmarksgame-team.pages.debian.net/benchmarksgame/description/nbody.html#nbody #![deny(warnings, rust_2018_idioms)] fn run<O: std::io::Write>(o: &mut O, n: usize, alg: usize) { let (energy_before, energy_after) = nbody_lib::run(n, alg); writeln!(o, "{:.9}", energy_before); writeln!(o, "{:.9}", energy_after); } fn main() { let n: usize = std::env::args() .nth(1) .expect("need one arg") .parse() .expect("argument should be a usize"); let alg: usize = if let Some(v) = std::env::args().nth(2) { v.parse().expect("second argument must be a usize") } else { 1 // SIMD algorithm }; run(&mut std::io::stdout(), n, alg); } #[cfg(test)] mod tests { use super::*; static OUTPUT: &'static [u8] = include_bytes!("nbody-output.txt"); #[test] fn verify_output_simd() { let mut out: Vec<u8> = Vec::new(); run(&mut out, 1000, 0); assert_eq!(out.len(), OUTPUT.len()); if out!= OUTPUT { for i in 0..out.len() { assert_eq!( out[i], OUTPUT[i], "byte {} differs - is: {:#08b} - should: {:#08b}", i, out[i], OUTPUT[i] );
} } #[test] fn verify_output_scalar() { let mut out: Vec<u8> = Vec::new(); run(&mut out, 1000, 1); assert_eq!(out.len(), OUTPUT.len()); if out!= OUTPUT { for i in 0..out.len() { assert_eq!( out[i], OUTPUT[i], "byte {} differs - is: {:#08b} - should: {:#08b}", i, out[i], OUTPUT[i] ); } } } }
}
random_line_split
main.rs
//! The N-body benchmark from the [benchmarks game][bg]. //! //! [bg]: https://benchmarksgame-team.pages.debian.net/benchmarksgame/description/nbody.html#nbody #![deny(warnings, rust_2018_idioms)] fn run<O: std::io::Write>(o: &mut O, n: usize, alg: usize) { let (energy_before, energy_after) = nbody_lib::run(n, alg); writeln!(o, "{:.9}", energy_before); writeln!(o, "{:.9}", energy_after); } fn main() { let n: usize = std::env::args() .nth(1) .expect("need one arg") .parse() .expect("argument should be a usize"); let alg: usize = if let Some(v) = std::env::args().nth(2)
else { 1 // SIMD algorithm }; run(&mut std::io::stdout(), n, alg); } #[cfg(test)] mod tests { use super::*; static OUTPUT: &'static [u8] = include_bytes!("nbody-output.txt"); #[test] fn verify_output_simd() { let mut out: Vec<u8> = Vec::new(); run(&mut out, 1000, 0); assert_eq!(out.len(), OUTPUT.len()); if out!= OUTPUT { for i in 0..out.len() { assert_eq!( out[i], OUTPUT[i], "byte {} differs - is: {:#08b} - should: {:#08b}", i, out[i], OUTPUT[i] ); } } } #[test] fn verify_output_scalar() { let mut out: Vec<u8> = Vec::new(); run(&mut out, 1000, 1); assert_eq!(out.len(), OUTPUT.len()); if out!= OUTPUT { for i in 0..out.len() { assert_eq!( out[i], OUTPUT[i], "byte {} differs - is: {:#08b} - should: {:#08b}", i, out[i], OUTPUT[i] ); } } } }
{ v.parse().expect("second argument must be a usize") }
conditional_block
main.rs
//! The N-body benchmark from the [benchmarks game][bg]. //! //! [bg]: https://benchmarksgame-team.pages.debian.net/benchmarksgame/description/nbody.html#nbody #![deny(warnings, rust_2018_idioms)] fn run<O: std::io::Write>(o: &mut O, n: usize, alg: usize) { let (energy_before, energy_after) = nbody_lib::run(n, alg); writeln!(o, "{:.9}", energy_before); writeln!(o, "{:.9}", energy_after); } fn main() { let n: usize = std::env::args() .nth(1) .expect("need one arg") .parse() .expect("argument should be a usize"); let alg: usize = if let Some(v) = std::env::args().nth(2) { v.parse().expect("second argument must be a usize") } else { 1 // SIMD algorithm }; run(&mut std::io::stdout(), n, alg); } #[cfg(test)] mod tests { use super::*; static OUTPUT: &'static [u8] = include_bytes!("nbody-output.txt"); #[test] fn verify_output_simd() { let mut out: Vec<u8> = Vec::new(); run(&mut out, 1000, 0); assert_eq!(out.len(), OUTPUT.len()); if out!= OUTPUT { for i in 0..out.len() { assert_eq!( out[i], OUTPUT[i], "byte {} differs - is: {:#08b} - should: {:#08b}", i, out[i], OUTPUT[i] ); } } } #[test] fn verify_output_scalar()
}
{ let mut out: Vec<u8> = Vec::new(); run(&mut out, 1000, 1); assert_eq!(out.len(), OUTPUT.len()); if out != OUTPUT { for i in 0..out.len() { assert_eq!( out[i], OUTPUT[i], "byte {} differs - is: {:#08b} - should: {:#08b}", i, out[i], OUTPUT[i] ); } } }
identifier_body
main.rs
//! The N-body benchmark from the [benchmarks game][bg]. //! //! [bg]: https://benchmarksgame-team.pages.debian.net/benchmarksgame/description/nbody.html#nbody #![deny(warnings, rust_2018_idioms)] fn
<O: std::io::Write>(o: &mut O, n: usize, alg: usize) { let (energy_before, energy_after) = nbody_lib::run(n, alg); writeln!(o, "{:.9}", energy_before); writeln!(o, "{:.9}", energy_after); } fn main() { let n: usize = std::env::args() .nth(1) .expect("need one arg") .parse() .expect("argument should be a usize"); let alg: usize = if let Some(v) = std::env::args().nth(2) { v.parse().expect("second argument must be a usize") } else { 1 // SIMD algorithm }; run(&mut std::io::stdout(), n, alg); } #[cfg(test)] mod tests { use super::*; static OUTPUT: &'static [u8] = include_bytes!("nbody-output.txt"); #[test] fn verify_output_simd() { let mut out: Vec<u8> = Vec::new(); run(&mut out, 1000, 0); assert_eq!(out.len(), OUTPUT.len()); if out!= OUTPUT { for i in 0..out.len() { assert_eq!( out[i], OUTPUT[i], "byte {} differs - is: {:#08b} - should: {:#08b}", i, out[i], OUTPUT[i] ); } } } #[test] fn verify_output_scalar() { let mut out: Vec<u8> = Vec::new(); run(&mut out, 1000, 1); assert_eq!(out.len(), OUTPUT.len()); if out!= OUTPUT { for i in 0..out.len() { assert_eq!( out[i], OUTPUT[i], "byte {} differs - is: {:#08b} - should: {:#08b}", i, out[i], OUTPUT[i] ); } } } }
run
identifier_name
autogen.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. //! Thrift compiler auto-generated support. //! //! //! Types and functions used internally by the Thrift compiler's Rust plugin //! to implement required functionality. Users should never have to use code //! in this module directly. use protocol::{TInputProtocol, TOutputProtocol}; /// Specifies the minimum functionality an auto-generated client should provide /// to communicate with a Thrift server. pub trait TThriftClient { /// Returns the input protocol used to read serialized Thrift messages /// from the Thrift server. fn i_prot_mut(&mut self) -> &mut dyn TInputProtocol; /// Returns the output protocol used to write serialized Thrift messages /// to the Thrift server. fn o_prot_mut(&mut self) -> &mut dyn TOutputProtocol; /// Returns the sequence number of the last message written to the Thrift /// server. Returns `0` if no messages have been written. Sequence /// numbers should *never* be negative, and this method returns an `i32` /// simply because the Thrift protocol encodes sequence numbers as `i32` on /// the wire. fn sequence_number(&self) -> i32; // FIXME: consider returning a u32 /// Increments the sequence number, indicating that a message with that /// number has been sent to the Thrift server. fn increment_sequence_number(&mut self) -> i32; }
random_line_split
lib.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This crate provides a native implementation of regular expressions that is //! heavily based on RE2 both in syntax and in implementation. Notably, //! backreferences and arbitrary lookahead/lookbehind assertions are not //! provided. In return, regular expression searching provided by this package //! has excellent worst-case performance. The specific syntax supported is //! documented further down. //! //! This crate's documentation provides some simple examples, describes Unicode //! support and exhaustively lists the supported syntax. For more specific //! details on the API, please see the documentation for the `Regex` type. //! //! # Usage //! //! This crate is [on crates.io](https://crates.io/crates/regex) and can be //! used by adding `regex` to your dependencies in your project's `Cargo.toml`. //! //! ```toml //! [dependencies] //! regex = "0.1.8" //! ``` //! //! and this to your crate root: //! //! ```rust //! extern crate regex; //! ``` //! //! # First example: find a date //! //! General use of regular expressions in this package involves compiling an //! expression and then using it to search, split or replace text. For example, //! to confirm that some text resembles a date: //! //! ```rust //! use regex::Regex; //! let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(); //! assert!(re.is_match("2014-01-01")); //! ``` //! //! Notice the use of the `^` and `$` anchors. In this crate, every expression //! is executed with an implicit `.*?` at the beginning and end, which allows //! it to match anywhere in the text. Anchors can be used to ensure that the //! full text matches an expression. //! //! This example also demonstrates the utility of //! [raw strings](http://doc.rust-lang.org/stable/reference.html#raw-byte-string-literals) //! in Rust, which //! are just like regular strings except they are prefixed with an `r` and do //! not process any escape sequences. For example, `"\\d"` is the same //! expression as `r"\d"`. //! //! # The `regex!` macro //! //! Rust's compile-time meta-programming facilities provide a way to write a //! `regex!` macro which compiles regular expressions *when your program //! compiles*. Said differently, if you only use `regex!` to build regular //! expressions in your program, then your program cannot compile with an //! invalid regular expression. Moreover, the `regex!` macro compiles the //! given expression to native Rust code, which ideally makes it faster. //! Unfortunately (or fortunately), the dynamic implementation has had a lot //! more optimization work put it into it currently, so it is faster than //! the `regex!` macro in most cases. //! //! To use the `regex!` macro, you must add `regex_macros` to your dependencies //! in your project's `Cargo.toml`: //! //! ```toml //! [dependencies] //! regex = "0.1.8" //! regex_macros = "0.1.8" //! ``` //! //! and then enable the `plugin` feature and import the `regex_macros` crate as //! a syntax extension: //! //! ```ignore //! #![feature(plugin)] //! #![plugin(regex_macros)] //! extern crate regex; //! //! fn main() { //! let re = regex!(r"^\d{4}-\d{2}-\d{2}$"); //! assert!(re.is_match("2014-01-01")); //! } //! ``` //! //! There are a few things worth mentioning about using the `regex!` macro. //! Firstly, the `regex!` macro *only* accepts string *literals*. //! Secondly, the `regex` crate *must* be linked with the name `regex` since //! the generated code depends on finding symbols in the `regex` crate. //! //! One downside of using the `regex!` macro is that it can increase the //! size of your program's binary since it generates specialized Rust code. //! The extra size probably won't be significant for a small number of //! expressions, but 100+ calls to `regex!` will probably result in a //! noticeably bigger binary. //! //! **NOTE**: This is implemented using a compiler plugin, which is not //! available on the Rust 1.0 beta/stable channels. Therefore, you'll only //! be able to use `regex!` on the nightlies. //! //! # Example: iterating over capture groups //! //! This crate provides convenient iterators for matching an expression //! repeatedly against a search string to find successive non-overlapping //! matches. For example, to find all dates in a string and be able to access //! them by their component pieces: //! //! ```rust //! # extern crate regex; use regex::Regex; //! # fn main() { //! let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap(); //! let text = "2012-03-14, 2013-01-01 and 2014-07-05"; //! for cap in re.captures_iter(text) { //! println!("Month: {} Day: {} Year: {}", //! cap.at(2).unwrap_or(""), cap.at(3).unwrap_or(""), //! cap.at(1).unwrap_or("")); //! } //! // Output: //! // Month: 03 Day: 14 Year: 2012 //! // Month: 01 Day: 01 Year: 2013 //! // Month: 07 Day: 05 Year: 2014 //! # } //! ``` //! //! Notice that the year is in the capture group indexed at `1`. This is //! because the *entire match* is stored in the capture group at index `0`. //! //! # Example: replacement with named capture groups //! //! Building on the previous example, perhaps we'd like to rearrange the date //! formats. This can be done with text replacement. But to make the code //! clearer, we can *name* our capture groups and use those names as variables //! in our replacement text: //! //! ```rust //! # extern crate regex; use regex::Regex; //! # fn main() { //! let re = Regex::new(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})").unwrap(); //! let before = "2012-03-14, 2013-01-01 and 2014-07-05"; //! let after = re.replace_all(before, "$m/$d/$y"); //! assert_eq!(after, "03/14/2012, 01/01/2013 and 07/05/2014"); //! # } //! ``` //! //! The `replace` methods are actually polymorphic in the replacement, which //! provides more flexibility than is seen here. (See the documentation for //! `Regex::replace` for more details.) //! //! Note that if your regex gets complicated, you can use the `x` flag to //! enable insigificant whitespace mode, which also lets you write comments: //! //! ```rust //! # extern crate regex; use regex::Regex; //! # fn main() { //! let re = Regex::new(r"(?x) //! (?P<y>\d{4}) # the year //! - //! (?P<m>\d{2}) # the month //! - //! (?P<d>\d{2}) # the day //! ").unwrap();
//! //! # Pay for what you use //! //! With respect to searching text with a regular expression, there are three //! questions that can be asked: //! //! 1. Does the text match this expression? //! 2. If so, where does it match? //! 3. Where are the submatches? //! //! Generally speaking, this crate could provide a function to answer only #3, //! which would subsume #1 and #2 automatically. However, it can be //! significantly more expensive to compute the location of submatches, so it's //! best not to do it if you don't need to. //! //! Therefore, only use what you need. For example, don't use `find` if you //! only need to test if an expression matches a string. (Use `is_match` //! instead.) //! //! # Unicode //! //! This implementation executes regular expressions **only** on sequences of //! Unicode scalar values while exposing match locations as byte indices into //! the search string. //! //! Currently, only simple case folding is supported. Namely, when matching //! case-insensitively, the characters are first mapped using the //! [simple case folding](ftp://ftp.unicode.org/Public/UNIDATA/CaseFolding.txt) //! mapping. //! //! Regular expressions themselves are also **only** interpreted as a sequence //! of Unicode scalar values. This means you can use Unicode characters //! directly in your expression: //! //! ```rust //! # extern crate regex; use regex::Regex; //! # fn main() { //! let re = Regex::new(r"(?i)Δ+").unwrap(); //! assert_eq!(re.find("ΔδΔ"), Some((0, 6))); //! # } //! ``` //! //! Finally, Unicode general categories and scripts are available as character //! classes. For example, you can match a sequence of numerals, Greek or //! Cherokee letters: //! //! ```rust //! # extern crate regex; use regex::Regex; //! # fn main() { //! let re = Regex::new(r"[\pN\p{Greek}\p{Cherokee}]+").unwrap(); //! assert_eq!(re.find("abcΔᎠβⅠᏴγδⅡxyz"), Some((3, 23))); //! # } //! ``` //! //! # Syntax //! //! The syntax supported in this crate is almost in an exact correspondence //! with the syntax supported by RE2. It is documented below. //! //! Note that the regular expression parser and abstract syntax are exposed in //! a separate crate, //! [`regex-syntax`](../regex_syntax/index.html). //! //! ## Matching one character //! //! <pre class="rust"> //!. any character except new line (includes new line with s flag) //! [xyz] A character class matching either x, y or z. //! [^xyz] A character class matching any character except x, y and z. //! [a-z] A character class matching any character in range a-z. //! \d digit (\p{Nd}) //! \D not digit //! [:alpha:] ASCII character class ([A-Za-z]) //! [:^alpha:] Negated ASCII character class ([^A-Za-z]) //! \pN One-letter name Unicode character class //! \p{Greek} Unicode character class (general category or script) //! \PN Negated one-letter name Unicode character class //! \P{Greek} negated Unicode character class (general category or script) //! </pre> //! //! Any named character class may appear inside a bracketed `[...]` character //! class. For example, `[\p{Greek}\pN]` matches any Greek or numeral //! character. //! //! ## Composites //! //! <pre class="rust"> //! xy concatenation (x followed by y) //! x|y alternation (x or y, prefer x) //! </pre> //! //! ## Repetitions //! //! <pre class="rust"> //! x* zero or more of x (greedy) //! x+ one or more of x (greedy) //! x? zero or one of x (greedy) //! x*? zero or more of x (ungreedy) //! x+? one or more of x (ungreedy) //! x?? zero or one of x (ungreedy) //! x{n,m} at least n x and at most m x (greedy) //! x{n,} at least n x (greedy) //! x{n} exactly n x //! x{n,m}? at least n x and at most m x (ungreedy) //! x{n,}? at least n x (ungreedy) //! x{n}? exactly n x //! </pre> //! //! ## Empty matches //! //! <pre class="rust"> //! ^ the beginning of text (or start-of-line with multi-line mode) //! $ the end of text (or end-of-line with multi-line mode) //! \A only the beginning of text (even with multi-line mode enabled) //! \z only the end of text (even with multi-line mode enabled) //! \b a Unicode word boundary (\w on one side and \W, \A, or \z on other) //! \B not a Unicode word boundary //! </pre> //! //! ## Grouping and flags //! //! <pre class="rust"> //! (exp) numbered capture group (indexed by opening parenthesis) //! (?P&lt;name&gt;exp) named (also numbered) capture group (allowed chars: [_0-9a-zA-Z]) //! (?:exp) non-capturing group //! (?flags) set flags within current group //! (?flags:exp) set flags for exp (non-capturing) //! </pre> //! //! Flags are each a single character. For example, `(?x)` sets the flag `x` //! and `(?-x)` clears the flag `x`. Multiple flags can be set or cleared at //! the same time: `(?xy)` sets both the `x` and `y` flags and `(?x-y)` sets //! the `x` flag and clears the `y` flag. //! //! All flags are by default disabled. They are: //! //! <pre class="rust"> //! i case-insensitive //! m multi-line mode: ^ and $ match begin/end of line //! s allow. to match \n //! U swap the meaning of x* and x*? //! x ignore whitespace and allow line comments (starting with `#`) //! </pre> //! //! Here's an example that matches case-insensitively for only part of the //! expression: //! //! ```rust //! # extern crate regex; use regex::Regex; //! # fn main() { //! let re = Regex::new(r"(?i)a+(?-i)b+").unwrap(); //! let cap = re.captures("AaAaAbbBBBb").unwrap(); //! assert_eq!(cap.at(0), Some("AaAaAbb")); //! # } //! ``` //! //! Notice that the `a+` matches either `a` or `A`, but the `b+` only matches //! `b`. //! //! ## Escape sequences //! //! <pre class="rust"> //! \* literal *, works for any punctuation character: \.+*?()|[]{}^$ //! \a bell (\x07) //! \f form feed (\x0C) //! \t horizontal tab //! \n new line //! \r carriage return //! \v vertical tab (\x0B) //! \123 octal character code (up to three digits) //! \x7F hex character code (exactly two digits) //! \x{10FFFF} any hex character code corresponding to a Unicode code point //! </pre> //! //! ## Perl character classes (Unicode friendly) //! //! These classes are based on the definitions provided in //! [UTS#18](http://www.unicode.org/reports/tr18/#Compatibility_Properties): //! //! <pre class="rust"> //! \d digit (\p{Nd}) //! \D not digit //! \s whitespace (\p{White_Space}) //! \S not whitespace //! \w word character (\p{Alphabetic} + \p{M} + \d + \p{Pc} + \p{Join_Control}) //! \W not word character //! </pre> //! //! ## ASCII character classes //! //! <pre class="rust"> //! [:alnum:] alphanumeric ([0-9A-Za-z]) //! [:alpha:] alphabetic ([A-Za-z]) //! [:ascii:] ASCII ([\x00-\x7F]) //! [:blank:] blank ([\t ]) //! [:cntrl:] control ([\x00-\x1F\x7F]) //! [:digit:] digits ([0-9]) //! [:graph:] graphical ([!-~]) //! [:lower:] lower case ([a-z]) //! [:print:] printable ([ -~]) //! [:punct:] punctuation ([!-/:-@[-`{-~]) //! [:space:] whitespace ([\t\n\v\f\r ]) //! [:upper:] upper case ([A-Z]) //! [:word:] word characters ([0-9A-Za-z_]) //! [:xdigit:] hex digit ([0-9A-Fa-f]) //! </pre> //! //! # Untrusted input //! //! This crate can handle both untrusted regular expressions and untrusted //! search text. //! //! Untrusted regular expressions are handled by capping the size of a compiled //! regular expression. (See `Regex::with_size_limit`.) Without this, it would //! be trivial for an attacker to exhaust your system's memory with expressions //! like `a{100}{100}{100}`. //! //! Untrusted search text is allowed because the matching engine(s) in this //! crate have time complexity `O(mn)` (with `m ~ regex` and `n ~ search //! text`), which means there's no way to cause exponential blow-up like with //! some other regular expression engines. (We pay for this by disallowing //! features like arbitrary look-ahead and back-references.) #![deny(missing_docs)] #![cfg_attr(test, deny(warnings))] #![cfg_attr(feature = "pattern", feature(pattern))] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/regex/")] extern crate aho_corasick; extern crate memchr; extern crate regex_syntax as syntax; pub use re::{ Regex, Error, Captures, SubCaptures, SubCapturesPos, SubCapturesNamed, FindCaptures, FindMatches, Replacer, NoExpand, RegexSplits, RegexSplitsN, quote, is_match, }; mod backtrack; mod char; mod compile; mod input; mod pool; mod prefix; mod program; mod nfa; mod re; /// The `internal` module exists to support the `regex!` macro and other /// suspicious activity, such as testing different matching engines. #[doc(hidden)] pub mod internal { pub use char::Char; pub use input::{Input, CharInput, InputAt}; pub use program::{Program, MatchEngine, CharRanges, Inst, LookInst}; pub use re::ExNative; pub use re::Regex::{Dynamic, Native}; }
//! let before = "2012-03-14, 2013-01-01 and 2014-07-05"; //! let after = re.replace_all(before, "$m/$d/$y"); //! assert_eq!(after, "03/14/2012, 01/01/2013 and 07/05/2014"); //! # } //! ```
random_line_split
code_flow_blob.rs
use azure_sdk_auth_aad::*; use oauth2::{ClientId, ClientSecret, TokenResponse}; use std::env; use std::error::Error; use url::Url; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { let client_id = ClientId::new(env::var("CLIENT_ID").expect("Missing CLIENT_ID environment variable.")); let client_secret = ClientSecret::new( env::var("CLIENT_SECRET").expect("Missing CLIENT_SECRET environment variable."), ); let tenant_id = env::var("TENANT_ID").expect("Missing TENANT_ID environment variable."); let storage_account_name = std::env::args() .nth(1) .expect("please specify the storage account name as first command line parameter"); let container_name = std::env::args() .nth(2) .expect("please specify the container name as second command line parameter"); // Create URL to browse for initial authorization let c = authorize_code_flow( client_id, Some(client_secret), &tenant_id, Url::parse("http://localhost:3003/redirect").unwrap(), &format!( "https://{}.blob.core.windows.net/user_impersonation", storage_account_name ), ); println!("c == {:?}", c); println!("\nbrowse this url:\n{}", c.authorize_url); // Start a naive server to receive the redirect // with the token. This naive server is blocking // so you should use something better. let code = naive_server(&c, 3003).unwrap(); println!("code received: {:?}", code); // Exchange the token with one that can be // used for authorization let token = exchange(c, code).await.unwrap();
let dt = chrono::Utc::now(); let time = format!("{}", dt.format("%a, %d %h %Y %T GMT")); println!("x-ms-date ==> {}", time); let resp = reqwest::Client::new() .get(&format!( "https://{}.blob.core.windows.net/{}?restype=container&comp=list", storage_account_name, container_name )) .header( "Authorization", format!("Bearer {}", token.access_token().secret()), ) .header("x-ms-version", "2019-07-07") .header("x-ms-date", time) .send() .await? .text() .await?; println!("\n\nresp {:?}", resp); Ok(()) }
println!("token received: {:?}", token); println!("token secret: {}", token.access_token().secret());
random_line_split
code_flow_blob.rs
use azure_sdk_auth_aad::*; use oauth2::{ClientId, ClientSecret, TokenResponse}; use std::env; use std::error::Error; use url::Url; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>>
Url::parse("http://localhost:3003/redirect").unwrap(), &format!( "https://{}.blob.core.windows.net/user_impersonation", storage_account_name ), ); println!("c == {:?}", c); println!("\nbrowse this url:\n{}", c.authorize_url); // Start a naive server to receive the redirect // with the token. This naive server is blocking // so you should use something better. let code = naive_server(&c, 3003).unwrap(); println!("code received: {:?}", code); // Exchange the token with one that can be // used for authorization let token = exchange(c, code).await.unwrap(); println!("token received: {:?}", token); println!("token secret: {}", token.access_token().secret()); let dt = chrono::Utc::now(); let time = format!("{}", dt.format("%a, %d %h %Y %T GMT")); println!("x-ms-date ==> {}", time); let resp = reqwest::Client::new() .get(&format!( "https://{}.blob.core.windows.net/{}?restype=container&comp=list", storage_account_name, container_name )) .header( "Authorization", format!("Bearer {}", token.access_token().secret()), ) .header("x-ms-version", "2019-07-07") .header("x-ms-date", time) .send() .await? .text() .await?; println!("\n\nresp {:?}", resp); Ok(()) }
{ let client_id = ClientId::new(env::var("CLIENT_ID").expect("Missing CLIENT_ID environment variable.")); let client_secret = ClientSecret::new( env::var("CLIENT_SECRET").expect("Missing CLIENT_SECRET environment variable."), ); let tenant_id = env::var("TENANT_ID").expect("Missing TENANT_ID environment variable."); let storage_account_name = std::env::args() .nth(1) .expect("please specify the storage account name as first command line parameter"); let container_name = std::env::args() .nth(2) .expect("please specify the container name as second command line parameter"); // Create URL to browse for initial authorization let c = authorize_code_flow( client_id, Some(client_secret), &tenant_id,
identifier_body
code_flow_blob.rs
use azure_sdk_auth_aad::*; use oauth2::{ClientId, ClientSecret, TokenResponse}; use std::env; use std::error::Error; use url::Url; #[tokio::main] async fn
() -> Result<(), Box<dyn Error>> { let client_id = ClientId::new(env::var("CLIENT_ID").expect("Missing CLIENT_ID environment variable.")); let client_secret = ClientSecret::new( env::var("CLIENT_SECRET").expect("Missing CLIENT_SECRET environment variable."), ); let tenant_id = env::var("TENANT_ID").expect("Missing TENANT_ID environment variable."); let storage_account_name = std::env::args() .nth(1) .expect("please specify the storage account name as first command line parameter"); let container_name = std::env::args() .nth(2) .expect("please specify the container name as second command line parameter"); // Create URL to browse for initial authorization let c = authorize_code_flow( client_id, Some(client_secret), &tenant_id, Url::parse("http://localhost:3003/redirect").unwrap(), &format!( "https://{}.blob.core.windows.net/user_impersonation", storage_account_name ), ); println!("c == {:?}", c); println!("\nbrowse this url:\n{}", c.authorize_url); // Start a naive server to receive the redirect // with the token. This naive server is blocking // so you should use something better. let code = naive_server(&c, 3003).unwrap(); println!("code received: {:?}", code); // Exchange the token with one that can be // used for authorization let token = exchange(c, code).await.unwrap(); println!("token received: {:?}", token); println!("token secret: {}", token.access_token().secret()); let dt = chrono::Utc::now(); let time = format!("{}", dt.format("%a, %d %h %Y %T GMT")); println!("x-ms-date ==> {}", time); let resp = reqwest::Client::new() .get(&format!( "https://{}.blob.core.windows.net/{}?restype=container&comp=list", storage_account_name, container_name )) .header( "Authorization", format!("Bearer {}", token.access_token().secret()), ) .header("x-ms-version", "2019-07-07") .header("x-ms-date", time) .send() .await? .text() .await?; println!("\n\nresp {:?}", resp); Ok(()) }
main
identifier_name
selection.rs
use std::ptr; use std::mem; use std::vec::Vec; /// Implementation of selection sort. /// CLRS pg 29. `O(n^2)`. pub fn selection_sort<T: Ord>(mut a: Vec<T>) -> Vec<T> { let len = a.len(); let cap = a.capacity(); let p = a.as_mut_ptr(); unsafe { mem::forget(a); for j in range(0, (len - 1) as int) { let mut smallest = j; for i in range(j + 1, (len) as int) { let elem = ptr::read(p.offset(i) as *const T); let smallest_elem = ptr::read(p.offset(smallest) as *const T); if elem < smallest_elem { smallest = i; } } if smallest!= j
} Vec::from_raw_parts(len, cap, p) } } #[cfg(test)] mod tests { use sorting; #[test] fn test_selection_sort_example() { // Example from CLRS pg 18 (originally for insertion sort). let mut sorted = vec!(5i32, 2, 4, 6, 1, 3); sorted = sorting::selection_sort(sorted); assert_eq!(sorted, vec!(1i32, 2, 3, 4, 5, 6)); } #[test] fn test_selection_sort_duplicates() { let mut sorted = vec!(5i32, 5, 4); sorted = sorting::selection_sort(sorted); assert_eq!(sorted, vec!(4, 5, 5)); } #[test] fn test_selection_sort_single_element() { let mut sorted = vec!(0i32); sorted = sorting::selection_sort(sorted); assert_eq!(sorted, vec!(0)); } #[test] fn test_selection_sort_empty() { let mut sorted = vec!(); sorted = sorting::selection_sort::<i32>(sorted); assert_eq!(sorted, vec!()); } }
{ ptr::swap(p.offset(smallest), p.offset(j)); }
conditional_block
selection.rs
use std::ptr; use std::mem; use std::vec::Vec; /// Implementation of selection sort. /// CLRS pg 29. `O(n^2)`. pub fn selection_sort<T: Ord>(mut a: Vec<T>) -> Vec<T> { let len = a.len(); let cap = a.capacity(); let p = a.as_mut_ptr(); unsafe { mem::forget(a); for j in range(0, (len - 1) as int) { let mut smallest = j; for i in range(j + 1, (len) as int) { let elem = ptr::read(p.offset(i) as *const T); let smallest_elem = ptr::read(p.offset(smallest) as *const T); if elem < smallest_elem { smallest = i; } } if smallest!= j { ptr::swap(p.offset(smallest), p.offset(j)); } } Vec::from_raw_parts(len, cap, p) } } #[cfg(test)] mod tests { use sorting; #[test] fn test_selection_sort_example() { // Example from CLRS pg 18 (originally for insertion sort). let mut sorted = vec!(5i32, 2, 4, 6, 1, 3); sorted = sorting::selection_sort(sorted); assert_eq!(sorted, vec!(1i32, 2, 3, 4, 5, 6)); } #[test] fn test_selection_sort_duplicates() { let mut sorted = vec!(5i32, 5, 4); sorted = sorting::selection_sort(sorted); assert_eq!(sorted, vec!(4, 5, 5)); } #[test] fn test_selection_sort_single_element() { let mut sorted = vec!(0i32); sorted = sorting::selection_sort(sorted); assert_eq!(sorted, vec!(0)); } #[test] fn test_selection_sort_empty()
}
{ let mut sorted = vec!(); sorted = sorting::selection_sort::<i32>(sorted); assert_eq!(sorted, vec!()); }
identifier_body
selection.rs
use std::ptr; use std::mem; use std::vec::Vec; /// Implementation of selection sort. /// CLRS pg 29. `O(n^2)`. pub fn selection_sort<T: Ord>(mut a: Vec<T>) -> Vec<T> { let len = a.len(); let cap = a.capacity(); let p = a.as_mut_ptr(); unsafe { mem::forget(a); for j in range(0, (len - 1) as int) { let mut smallest = j; for i in range(j + 1, (len) as int) { let elem = ptr::read(p.offset(i) as *const T); let smallest_elem = ptr::read(p.offset(smallest) as *const T); if elem < smallest_elem { smallest = i; } } if smallest!= j { ptr::swap(p.offset(smallest), p.offset(j));
} #[cfg(test)] mod tests { use sorting; #[test] fn test_selection_sort_example() { // Example from CLRS pg 18 (originally for insertion sort). let mut sorted = vec!(5i32, 2, 4, 6, 1, 3); sorted = sorting::selection_sort(sorted); assert_eq!(sorted, vec!(1i32, 2, 3, 4, 5, 6)); } #[test] fn test_selection_sort_duplicates() { let mut sorted = vec!(5i32, 5, 4); sorted = sorting::selection_sort(sorted); assert_eq!(sorted, vec!(4, 5, 5)); } #[test] fn test_selection_sort_single_element() { let mut sorted = vec!(0i32); sorted = sorting::selection_sort(sorted); assert_eq!(sorted, vec!(0)); } #[test] fn test_selection_sort_empty() { let mut sorted = vec!(); sorted = sorting::selection_sort::<i32>(sorted); assert_eq!(sorted, vec!()); } }
} } Vec::from_raw_parts(len, cap, p) }
random_line_split
selection.rs
use std::ptr; use std::mem; use std::vec::Vec; /// Implementation of selection sort. /// CLRS pg 29. `O(n^2)`. pub fn selection_sort<T: Ord>(mut a: Vec<T>) -> Vec<T> { let len = a.len(); let cap = a.capacity(); let p = a.as_mut_ptr(); unsafe { mem::forget(a); for j in range(0, (len - 1) as int) { let mut smallest = j; for i in range(j + 1, (len) as int) { let elem = ptr::read(p.offset(i) as *const T); let smallest_elem = ptr::read(p.offset(smallest) as *const T); if elem < smallest_elem { smallest = i; } } if smallest!= j { ptr::swap(p.offset(smallest), p.offset(j)); } } Vec::from_raw_parts(len, cap, p) } } #[cfg(test)] mod tests { use sorting; #[test] fn test_selection_sort_example() { // Example from CLRS pg 18 (originally for insertion sort). let mut sorted = vec!(5i32, 2, 4, 6, 1, 3); sorted = sorting::selection_sort(sorted); assert_eq!(sorted, vec!(1i32, 2, 3, 4, 5, 6)); } #[test] fn test_selection_sort_duplicates() { let mut sorted = vec!(5i32, 5, 4); sorted = sorting::selection_sort(sorted); assert_eq!(sorted, vec!(4, 5, 5)); } #[test] fn test_selection_sort_single_element() { let mut sorted = vec!(0i32); sorted = sorting::selection_sort(sorted); assert_eq!(sorted, vec!(0)); } #[test] fn
() { let mut sorted = vec!(); sorted = sorting::selection_sort::<i32>(sorted); assert_eq!(sorted, vec!()); } }
test_selection_sort_empty
identifier_name
service.rs
use tokio_io::codec::{Encoder, Decoder, Framed}; use tokio_proto::multiplex::RequestId; use bytes::BytesMut; use bytes::BigEndian; use std::str; use std::io::Error as IOError; use bytes::buf::IntoBuf; use bytes::Buf; use bytes::BufMut; use tokio_proto::multiplex::ServerProto; use tokio_io::{AsyncRead, AsyncWrite}; use std::io::Error as SiderError; use futures::BoxFuture; use futures::future; use futures::Future; use tokio_service::Service; pub struct SiderCodec; pub struct SiderProto; pub struct
; pub struct SiderRequest { data: String } pub struct SiderReponse { data: String } impl Decoder for SiderCodec { type Item = (RequestId, SiderRequest); type Error = SiderError; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { if src.len() < 10 { return Ok(None) } let request_id: u64; let payload_len: usize; let goon: bool; // Make compiler happy { let mut buf = (src as &BytesMut).into_buf(); request_id = buf.get_u64::<BigEndian>(); payload_len = buf.get_u16::<BigEndian>() as usize; let left_len = buf.remaining(); goon = left_len >= payload_len; } if goon { src.split_to(6); let data = str::from_utf8(&src.as_ref()[0..payload_len]).unwrap().to_string(); src.split_to(payload_len); Ok(Some((request_id, SiderRequest { data: data }))) } else { Ok(None) } } } impl Encoder for SiderCodec { type Item = (RequestId, SiderReponse); type Error = SiderError; fn encode(&mut self, msg: Self::Item, buf: &mut BytesMut) -> Result<(), Self::Error> { let (id, msg) = msg; buf.put_u64::<BigEndian>(id); buf.put_u16::<BigEndian>(msg.data.len() as u16); buf.put_slice(msg.data.as_bytes()); Ok(()) } } impl<T: AsyncRead + AsyncWrite +'static> ServerProto<T> for SiderProto { type Request = SiderRequest; type Response = SiderReponse; // `Framed<T, LineCodec>` is the return value // of `io.framed(LineCodec)` type Transport = Framed<T, SiderCodec>; type BindTransport = Result<Self::Transport, IOError>; fn bind_transport(&self, io: T) -> Self::BindTransport { Ok(io.framed(SiderCodec)) } } impl Service for SiderService { type Request = SiderRequest; type Response = SiderReponse; type Error = SiderError; type Future = BoxFuture<Self::Response, Self::Error>; fn call(&self, req: Self::Request) -> Self::Future { future::ok(SiderReponse { data: req.data } ).boxed() } }
SiderService
identifier_name
service.rs
use tokio_io::codec::{Encoder, Decoder, Framed}; use tokio_proto::multiplex::RequestId; use bytes::BytesMut; use bytes::BigEndian; use std::str; use std::io::Error as IOError; use bytes::buf::IntoBuf; use bytes::Buf; use bytes::BufMut; use tokio_proto::multiplex::ServerProto; use tokio_io::{AsyncRead, AsyncWrite}; use std::io::Error as SiderError; use futures::BoxFuture; use futures::future; use futures::Future; use tokio_service::Service; pub struct SiderCodec; pub struct SiderProto; pub struct SiderService; pub struct SiderRequest { data: String } pub struct SiderReponse { data: String } impl Decoder for SiderCodec { type Item = (RequestId, SiderRequest); type Error = SiderError; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { if src.len() < 10 { return Ok(None) } let request_id: u64; let payload_len: usize; let goon: bool; // Make compiler happy { let mut buf = (src as &BytesMut).into_buf(); request_id = buf.get_u64::<BigEndian>(); payload_len = buf.get_u16::<BigEndian>() as usize; let left_len = buf.remaining(); goon = left_len >= payload_len; } if goon { src.split_to(6); let data = str::from_utf8(&src.as_ref()[0..payload_len]).unwrap().to_string(); src.split_to(payload_len); Ok(Some((request_id, SiderRequest { data: data }))) } else
} } impl Encoder for SiderCodec { type Item = (RequestId, SiderReponse); type Error = SiderError; fn encode(&mut self, msg: Self::Item, buf: &mut BytesMut) -> Result<(), Self::Error> { let (id, msg) = msg; buf.put_u64::<BigEndian>(id); buf.put_u16::<BigEndian>(msg.data.len() as u16); buf.put_slice(msg.data.as_bytes()); Ok(()) } } impl<T: AsyncRead + AsyncWrite +'static> ServerProto<T> for SiderProto { type Request = SiderRequest; type Response = SiderReponse; // `Framed<T, LineCodec>` is the return value // of `io.framed(LineCodec)` type Transport = Framed<T, SiderCodec>; type BindTransport = Result<Self::Transport, IOError>; fn bind_transport(&self, io: T) -> Self::BindTransport { Ok(io.framed(SiderCodec)) } } impl Service for SiderService { type Request = SiderRequest; type Response = SiderReponse; type Error = SiderError; type Future = BoxFuture<Self::Response, Self::Error>; fn call(&self, req: Self::Request) -> Self::Future { future::ok(SiderReponse { data: req.data } ).boxed() } }
{ Ok(None) }
conditional_block
service.rs
use tokio_io::codec::{Encoder, Decoder, Framed}; use tokio_proto::multiplex::RequestId; use bytes::BytesMut; use bytes::BigEndian; use std::str; use std::io::Error as IOError; use bytes::buf::IntoBuf; use bytes::Buf; use bytes::BufMut; use tokio_proto::multiplex::ServerProto; use tokio_io::{AsyncRead, AsyncWrite}; use std::io::Error as SiderError; use futures::BoxFuture; use futures::future; use futures::Future; use tokio_service::Service; pub struct SiderCodec; pub struct SiderProto; pub struct SiderService; pub struct SiderRequest { data: String } pub struct SiderReponse { data: String } impl Decoder for SiderCodec { type Item = (RequestId, SiderRequest); type Error = SiderError; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { if src.len() < 10 { return Ok(None) } let request_id: u64; let payload_len: usize; let goon: bool; // Make compiler happy { let mut buf = (src as &BytesMut).into_buf(); request_id = buf.get_u64::<BigEndian>(); payload_len = buf.get_u16::<BigEndian>() as usize; let left_len = buf.remaining(); goon = left_len >= payload_len; } if goon { src.split_to(6); let data = str::from_utf8(&src.as_ref()[0..payload_len]).unwrap().to_string(); src.split_to(payload_len); Ok(Some((request_id, SiderRequest { data: data }))) } else { Ok(None) } } } impl Encoder for SiderCodec { type Item = (RequestId, SiderReponse); type Error = SiderError; fn encode(&mut self, msg: Self::Item, buf: &mut BytesMut) -> Result<(), Self::Error> { let (id, msg) = msg; buf.put_u64::<BigEndian>(id); buf.put_u16::<BigEndian>(msg.data.len() as u16); buf.put_slice(msg.data.as_bytes()); Ok(()) } } impl<T: AsyncRead + AsyncWrite +'static> ServerProto<T> for SiderProto { type Request = SiderRequest; type Response = SiderReponse; // `Framed<T, LineCodec>` is the return value // of `io.framed(LineCodec)` type Transport = Framed<T, SiderCodec>;
} } impl Service for SiderService { type Request = SiderRequest; type Response = SiderReponse; type Error = SiderError; type Future = BoxFuture<Self::Response, Self::Error>; fn call(&self, req: Self::Request) -> Self::Future { future::ok(SiderReponse { data: req.data } ).boxed() } }
type BindTransport = Result<Self::Transport, IOError>; fn bind_transport(&self, io: T) -> Self::BindTransport { Ok(io.framed(SiderCodec))
random_line_split
t_test.rs
use error::Error; use summary::Summary; /// The results and parameters of a two-sided, unequal-variances t-test. pub struct TTest { pub p: f64, pub t: f64, pub df: f64, } fn t_test_2_sided(t: f64, df: f64) -> Result<TTest, Error> { let p = 1.0 - t_atv(t.abs(), df as f64)?; Ok(TTest { df, p, t }) } /// Conduct a two-sided t-test that does not assume equal population variances. pub fn welch_t_test(s1: &Summary, s2: &Summary) -> Result<TTest, Error> { let (t, df) = welch_t_statistic(s1, s2); t_test_2_sided(t, df) } fn welch_t_statistic(s1: &Summary, s2: &Summary) -> (f64, f64) { let n1 = s1.size(); let m1 = s1.mean(); let var1 = s1.unbiased_variance(); let n2 = s2.size(); let m2 = s2.mean(); let var2 = s2.unbiased_variance(); let s_delta_bar = ((var1 / n1) + (var2 / n2)).sqrt(); let t = (m1 - m2) / s_delta_bar; let df = welch_satterthwaite_df(var1, n1, var2, n2); (t, df) } /// Degrees of freedom, approximated using the Welch-Satterthwaite equation [1]. /// /// [1]: http://www.itl.nist.gov/div898/handbook/mpc/section5/mpc571.htm fn welch_satterthwaite_df(var1: f64, n1: f64, var2: f64, n2: f64) -> f64
/// The definite integral of the density function of Student's t-distribution /// over an interval [-t, t]. Also called the A(t|ν) function. /// /// See equation 6.4.9 in [1]. /// /// [1]: "Numerical Recipes in C", 2nd Ed., p. 228 fn t_atv(t: f64, df: f64) -> Result<f64, Error> { use num; let x = df / (df + t.powi(2)); let a = 0.5 * df; let b = 0.5; let ib = num::inc_beta(x, a, b)?; Ok(1.0 - ib) }
{ let df1 = n1 - 1.0; let df2 = n2 - 1.0; let num = ((var1 / n1) + (var2 / n2)).powi(2); let den = var1.powi(2) / (n1.powi(2) * df1) + var2.powi(2) / (n2.powi(2) * df2); let appx = num / den; appx }
identifier_body
t_test.rs
use error::Error; use summary::Summary; /// The results and parameters of a two-sided, unequal-variances t-test. pub struct TTest { pub p: f64, pub t: f64, pub df: f64, } fn t_test_2_sided(t: f64, df: f64) -> Result<TTest, Error> { let p = 1.0 - t_atv(t.abs(), df as f64)?; Ok(TTest { df, p, t }) } /// Conduct a two-sided t-test that does not assume equal population variances. pub fn welch_t_test(s1: &Summary, s2: &Summary) -> Result<TTest, Error> { let (t, df) = welch_t_statistic(s1, s2); t_test_2_sided(t, df) } fn welch_t_statistic(s1: &Summary, s2: &Summary) -> (f64, f64) { let n1 = s1.size(); let m1 = s1.mean(); let var1 = s1.unbiased_variance(); let n2 = s2.size(); let m2 = s2.mean(); let var2 = s2.unbiased_variance(); let s_delta_bar = ((var1 / n1) + (var2 / n2)).sqrt(); let t = (m1 - m2) / s_delta_bar; let df = welch_satterthwaite_df(var1, n1, var2, n2); (t, df) } /// Degrees of freedom, approximated using the Welch-Satterthwaite equation [1]. /// /// [1]: http://www.itl.nist.gov/div898/handbook/mpc/section5/mpc571.htm fn welch_satterthwaite_df(var1: f64, n1: f64, var2: f64, n2: f64) -> f64 { let df1 = n1 - 1.0; let df2 = n2 - 1.0; let num = ((var1 / n1) + (var2 / n2)).powi(2); let den = var1.powi(2) / (n1.powi(2) * df1) + var2.powi(2) / (n2.powi(2) * df2); let appx = num / den; appx } /// The definite integral of the density function of Student's t-distribution /// over an interval [-t, t]. Also called the A(t|ν) function. /// /// See equation 6.4.9 in [1]. /// /// [1]: "Numerical Recipes in C", 2nd Ed., p. 228 fn t
t: f64, df: f64) -> Result<f64, Error> { use num; let x = df / (df + t.powi(2)); let a = 0.5 * df; let b = 0.5; let ib = num::inc_beta(x, a, b)?; Ok(1.0 - ib) }
_atv(
identifier_name
t_test.rs
use error::Error; use summary::Summary; /// The results and parameters of a two-sided, unequal-variances t-test. pub struct TTest { pub p: f64, pub t: f64, pub df: f64, } fn t_test_2_sided(t: f64, df: f64) -> Result<TTest, Error> { let p = 1.0 - t_atv(t.abs(), df as f64)?; Ok(TTest { df, p, t }) } /// Conduct a two-sided t-test that does not assume equal population variances. pub fn welch_t_test(s1: &Summary, s2: &Summary) -> Result<TTest, Error> { let (t, df) = welch_t_statistic(s1, s2); t_test_2_sided(t, df) } fn welch_t_statistic(s1: &Summary, s2: &Summary) -> (f64, f64) { let n1 = s1.size(); let m1 = s1.mean(); let var1 = s1.unbiased_variance(); let n2 = s2.size(); let m2 = s2.mean(); let var2 = s2.unbiased_variance(); let s_delta_bar = ((var1 / n1) + (var2 / n2)).sqrt();
} /// Degrees of freedom, approximated using the Welch-Satterthwaite equation [1]. /// /// [1]: http://www.itl.nist.gov/div898/handbook/mpc/section5/mpc571.htm fn welch_satterthwaite_df(var1: f64, n1: f64, var2: f64, n2: f64) -> f64 { let df1 = n1 - 1.0; let df2 = n2 - 1.0; let num = ((var1 / n1) + (var2 / n2)).powi(2); let den = var1.powi(2) / (n1.powi(2) * df1) + var2.powi(2) / (n2.powi(2) * df2); let appx = num / den; appx } /// The definite integral of the density function of Student's t-distribution /// over an interval [-t, t]. Also called the A(t|ν) function. /// /// See equation 6.4.9 in [1]. /// /// [1]: "Numerical Recipes in C", 2nd Ed., p. 228 fn t_atv(t: f64, df: f64) -> Result<f64, Error> { use num; let x = df / (df + t.powi(2)); let a = 0.5 * df; let b = 0.5; let ib = num::inc_beta(x, a, b)?; Ok(1.0 - ib) }
let t = (m1 - m2) / s_delta_bar; let df = welch_satterthwaite_df(var1, n1, var2, n2); (t, df)
random_line_split
net.rs
//! A chat server that broadcasts a message to all connections. //! //! This example is explicitly more verbose than it has to be. This is to //! illustrate more concepts. //! //! A chat server for telnet clients. After a telnet client connects, the first //! line should contain the client's name. After that, all lines sent by a //! client are broadcasted to all other connected clients. //! //! Because the client is telnet, lines are delimited by "\r\n". //! //! You can test this out by running: //! //! cargo run --example chat //! //! And then in another terminal run: //! //! telnet localhost 6142 //! //! You can run the `telnet` command in any number of additional windows. //! //! You can run the second command in multiple windows and then chat between the //! two, seeing the messages from the other client as they're received. For all //! connected clients they'll all join the same room and see everyone else's //! messages. #![deny(deprecated)] extern crate tokio; extern crate futures; extern crate bytes; extern crate libspp; use tokio::net::{TcpListener}; use tokio::prelude::*; use libspp::prelude::*; use std::io; fn
<'a, R, W>(reader: R, writer: W) -> SppHandle<'a, R, W> where R: AsyncRead, W: AsyncWrite { SppHandle { reader, writer, mapper: libspp::mapper::new(), } } #[derive(Debug)] pub struct SppHandle<'a, R, W> { reader: Option<R>, writer: Option<W>, mapper: SppMapper<'a> } impl<R, W> Future for SppHandle<R, W> where R: AsyncRead, W: AsyncWrite, { type Item = (R, W); type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { loop { } } } #[test] pub fn main() { let address = "127.0.0.1:6142".parse().unwrap(); let listener = TcpListener::bind(&address).unwrap(); println!("server running on localhost:6142"); let server = listener.incoming().for_each(move |stream| { let address = stream.peer_addr().unwrap(); println!("New connection from {} ", address); let (reader, writer) = stream.split(); tokio::spawn( tokio::io::copy(reader, writer).map(|amt| { println!("wrote {:?} bytes", amt) }).map_err(|err| { eprintln!("IO error {:?}", err) }) ); Ok(()) }) .map_err(|err| { println!("accept error = {:?}", err); }); tokio::run(server); }
new_spp_handle
identifier_name
net.rs
//! A chat server that broadcasts a message to all connections. //! //! This example is explicitly more verbose than it has to be. This is to //! illustrate more concepts. //! //! A chat server for telnet clients. After a telnet client connects, the first //! line should contain the client's name. After that, all lines sent by a //! client are broadcasted to all other connected clients. //! //! Because the client is telnet, lines are delimited by "\r\n". //! //! You can test this out by running: //! //! cargo run --example chat //! //! And then in another terminal run: //! //! telnet localhost 6142 //! //! You can run the `telnet` command in any number of additional windows. //! //! You can run the second command in multiple windows and then chat between the //! two, seeing the messages from the other client as they're received. For all //! connected clients they'll all join the same room and see everyone else's //! messages. #![deny(deprecated)] extern crate tokio; extern crate futures; extern crate bytes; extern crate libspp; use tokio::net::{TcpListener}; use tokio::prelude::*; use libspp::prelude::*; use std::io; fn new_spp_handle<'a, R, W>(reader: R, writer: W) -> SppHandle<'a, R, W> where R: AsyncRead, W: AsyncWrite { SppHandle { reader, writer, mapper: libspp::mapper::new(), } } #[derive(Debug)] pub struct SppHandle<'a, R, W> { reader: Option<R>, writer: Option<W>, mapper: SppMapper<'a> } impl<R, W> Future for SppHandle<R, W> where R: AsyncRead, W: AsyncWrite, { type Item = (R, W); type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error>
} #[test] pub fn main() { let address = "127.0.0.1:6142".parse().unwrap(); let listener = TcpListener::bind(&address).unwrap(); println!("server running on localhost:6142"); let server = listener.incoming().for_each(move |stream| { let address = stream.peer_addr().unwrap(); println!("New connection from {} ", address); let (reader, writer) = stream.split(); tokio::spawn( tokio::io::copy(reader, writer).map(|amt| { println!("wrote {:?} bytes", amt) }).map_err(|err| { eprintln!("IO error {:?}", err) }) ); Ok(()) }) .map_err(|err| { println!("accept error = {:?}", err); }); tokio::run(server); }
{ loop { } }
identifier_body
net.rs
//! A chat server that broadcasts a message to all connections. //! //! This example is explicitly more verbose than it has to be. This is to //! illustrate more concepts. //! //! A chat server for telnet clients. After a telnet client connects, the first //! line should contain the client's name. After that, all lines sent by a //! client are broadcasted to all other connected clients. //! //! Because the client is telnet, lines are delimited by "\r\n". //! //! You can test this out by running: //! //! cargo run --example chat //! //! And then in another terminal run: //! //! telnet localhost 6142 //! //! You can run the `telnet` command in any number of additional windows. //! //! You can run the second command in multiple windows and then chat between the //! two, seeing the messages from the other client as they're received. For all //! connected clients they'll all join the same room and see everyone else's //! messages. #![deny(deprecated)] extern crate tokio; extern crate futures; extern crate bytes; extern crate libspp; use tokio::net::{TcpListener}; use tokio::prelude::*; use libspp::prelude::*; use std::io; fn new_spp_handle<'a, R, W>(reader: R, writer: W) -> SppHandle<'a, R, W>
writer, mapper: libspp::mapper::new(), } } #[derive(Debug)] pub struct SppHandle<'a, R, W> { reader: Option<R>, writer: Option<W>, mapper: SppMapper<'a> } impl<R, W> Future for SppHandle<R, W> where R: AsyncRead, W: AsyncWrite, { type Item = (R, W); type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { loop { } } } #[test] pub fn main() { let address = "127.0.0.1:6142".parse().unwrap(); let listener = TcpListener::bind(&address).unwrap(); println!("server running on localhost:6142"); let server = listener.incoming().for_each(move |stream| { let address = stream.peer_addr().unwrap(); println!("New connection from {} ", address); let (reader, writer) = stream.split(); tokio::spawn( tokio::io::copy(reader, writer).map(|amt| { println!("wrote {:?} bytes", amt) }).map_err(|err| { eprintln!("IO error {:?}", err) }) ); Ok(()) }) .map_err(|err| { println!("accept error = {:?}", err); }); tokio::run(server); }
where R: AsyncRead, W: AsyncWrite { SppHandle { reader,
random_line_split
utils.rs
//! //! Various utility functions used throughout Conrod. //! use num::{Float, NumCast, PrimInt, ToPrimitive}; use position::{Dimensions, Point}; use vecmath::vec2_sub; /// Clamp a value between a given min and max. pub fn
<T: PartialOrd>(n: T, min: T, max: T) -> T { if n < min { min } else if n > max { max } else { n } } /// Return whether or not a given point is over a rectangle at a given point on a cartesian plane. pub fn is_over_rect(rect_point: Point, mouse_point: Point, rect_dim: Dimensions) -> bool { let point = vec2_sub(rect_point, mouse_point); if point[0].abs() < rect_dim[0] / 2.0 && point[1].abs() < rect_dim[1] / 2.0 { true } else { false } } /// Get value percentage between max and min. pub fn percentage<T: Float + NumCast>(value: T, min: T, max: T) -> f32 { let v: f32 = NumCast::from(value).unwrap(); let mn: f32 = NumCast::from(min).unwrap(); let mx: f32 = NumCast::from(max).unwrap(); (v - mn) / (mx - mn) } /// Adjust the value to the given percentage. pub fn value_from_perc<T: Float + NumCast + ToPrimitive>(perc: f32, min: T, max: T) -> T { let f: f32 = (max - min).to_f32().unwrap() * perc; min + NumCast::from(f).unwrap() } /// Map a value from a given range to a new given range. pub fn map_range<X: Float + NumCast, Y: Float + NumCast> (val: X, in_min: X, in_max: X, out_min: Y, out_max: Y) -> Y { let val_f: f64 = NumCast::from(val).unwrap(); let in_min_f: f64 = NumCast::from(in_min).unwrap(); let in_max_f: f64 = NumCast::from(in_max).unwrap(); let out_min_f: f64 = NumCast::from(out_min).unwrap(); let out_max_f: f64 = NumCast::from(out_max).unwrap(); NumCast::from( (val_f - in_min_f) / (in_max_f - in_min_f) * (out_max_f - out_min_f) + out_min_f ).unwrap() } /// Get a suitable string from the value, its max and the pixel range. pub fn val_to_string<T: ToString + NumCast> (val: T, max: T, val_rng: T, pixel_range: usize) -> String { let mut s = val.to_string(); let decimal = s.chars().position(|ch| ch == '.'); match decimal { None => s, Some(idx) => { // Find the minimum string length by determing // what power of ten both the max and range are. let val_rng_f: f64 = NumCast::from(val_rng).unwrap(); let max_f: f64 = NumCast::from(max).unwrap(); let mut n: f64 = 0.0; let mut pow_ten = 0.0; while pow_ten < val_rng_f || pow_ten < max_f { pow_ten = (10.0).powf(n); n += 1.0 } let min_string_len = n as usize + 1; // Find out how many pixels there are to actually use // and judge a reasonable precision from this. let mut n = 1; while 10.pow(n) < pixel_range { n += 1 } let precision = n as usize; // Truncate the length to the pixel precision as // long as this doesn't cause it to be smaller // than the necessary decimal place. let mut truncate_len = min_string_len + (precision - 1); if idx + precision < truncate_len { truncate_len = idx + precision } if s.len() > truncate_len { s.truncate(truncate_len) } s } } }
clamp
identifier_name
utils.rs
//! //! Various utility functions used throughout Conrod. //! use num::{Float, NumCast, PrimInt, ToPrimitive}; use position::{Dimensions, Point}; use vecmath::vec2_sub; /// Clamp a value between a given min and max. pub fn clamp<T: PartialOrd>(n: T, min: T, max: T) -> T { if n < min { min } else if n > max { max } else { n } } /// Return whether or not a given point is over a rectangle at a given point on a cartesian plane. pub fn is_over_rect(rect_point: Point, mouse_point: Point, rect_dim: Dimensions) -> bool { let point = vec2_sub(rect_point, mouse_point); if point[0].abs() < rect_dim[0] / 2.0 && point[1].abs() < rect_dim[1] / 2.0 { true } else { false } } /// Get value percentage between max and min. pub fn percentage<T: Float + NumCast>(value: T, min: T, max: T) -> f32 { let v: f32 = NumCast::from(value).unwrap(); let mn: f32 = NumCast::from(min).unwrap(); let mx: f32 = NumCast::from(max).unwrap(); (v - mn) / (mx - mn) } /// Adjust the value to the given percentage. pub fn value_from_perc<T: Float + NumCast + ToPrimitive>(perc: f32, min: T, max: T) -> T { let f: f32 = (max - min).to_f32().unwrap() * perc; min + NumCast::from(f).unwrap() } /// Map a value from a given range to a new given range. pub fn map_range<X: Float + NumCast, Y: Float + NumCast> (val: X, in_min: X, in_max: X, out_min: Y, out_max: Y) -> Y
/// Get a suitable string from the value, its max and the pixel range. pub fn val_to_string<T: ToString + NumCast> (val: T, max: T, val_rng: T, pixel_range: usize) -> String { let mut s = val.to_string(); let decimal = s.chars().position(|ch| ch == '.'); match decimal { None => s, Some(idx) => { // Find the minimum string length by determing // what power of ten both the max and range are. let val_rng_f: f64 = NumCast::from(val_rng).unwrap(); let max_f: f64 = NumCast::from(max).unwrap(); let mut n: f64 = 0.0; let mut pow_ten = 0.0; while pow_ten < val_rng_f || pow_ten < max_f { pow_ten = (10.0).powf(n); n += 1.0 } let min_string_len = n as usize + 1; // Find out how many pixels there are to actually use // and judge a reasonable precision from this. let mut n = 1; while 10.pow(n) < pixel_range { n += 1 } let precision = n as usize; // Truncate the length to the pixel precision as // long as this doesn't cause it to be smaller // than the necessary decimal place. let mut truncate_len = min_string_len + (precision - 1); if idx + precision < truncate_len { truncate_len = idx + precision } if s.len() > truncate_len { s.truncate(truncate_len) } s } } }
{ let val_f: f64 = NumCast::from(val).unwrap(); let in_min_f: f64 = NumCast::from(in_min).unwrap(); let in_max_f: f64 = NumCast::from(in_max).unwrap(); let out_min_f: f64 = NumCast::from(out_min).unwrap(); let out_max_f: f64 = NumCast::from(out_max).unwrap(); NumCast::from( (val_f - in_min_f) / (in_max_f - in_min_f) * (out_max_f - out_min_f) + out_min_f ).unwrap() }
identifier_body
utils.rs
//! //! Various utility functions used throughout Conrod. //! use num::{Float, NumCast, PrimInt, ToPrimitive}; use position::{Dimensions, Point}; use vecmath::vec2_sub; /// Clamp a value between a given min and max. pub fn clamp<T: PartialOrd>(n: T, min: T, max: T) -> T { if n < min { min } else if n > max { max } else { n } } /// Return whether or not a given point is over a rectangle at a given point on a cartesian plane. pub fn is_over_rect(rect_point: Point, mouse_point: Point, rect_dim: Dimensions) -> bool { let point = vec2_sub(rect_point, mouse_point); if point[0].abs() < rect_dim[0] / 2.0 && point[1].abs() < rect_dim[1] / 2.0 { true } else { false } } /// Get value percentage between max and min. pub fn percentage<T: Float + NumCast>(value: T, min: T, max: T) -> f32 { let v: f32 = NumCast::from(value).unwrap(); let mn: f32 = NumCast::from(min).unwrap(); let mx: f32 = NumCast::from(max).unwrap(); (v - mn) / (mx - mn) } /// Adjust the value to the given percentage. pub fn value_from_perc<T: Float + NumCast + ToPrimitive>(perc: f32, min: T, max: T) -> T { let f: f32 = (max - min).to_f32().unwrap() * perc; min + NumCast::from(f).unwrap() }
/// Map a value from a given range to a new given range. pub fn map_range<X: Float + NumCast, Y: Float + NumCast> (val: X, in_min: X, in_max: X, out_min: Y, out_max: Y) -> Y { let val_f: f64 = NumCast::from(val).unwrap(); let in_min_f: f64 = NumCast::from(in_min).unwrap(); let in_max_f: f64 = NumCast::from(in_max).unwrap(); let out_min_f: f64 = NumCast::from(out_min).unwrap(); let out_max_f: f64 = NumCast::from(out_max).unwrap(); NumCast::from( (val_f - in_min_f) / (in_max_f - in_min_f) * (out_max_f - out_min_f) + out_min_f ).unwrap() } /// Get a suitable string from the value, its max and the pixel range. pub fn val_to_string<T: ToString + NumCast> (val: T, max: T, val_rng: T, pixel_range: usize) -> String { let mut s = val.to_string(); let decimal = s.chars().position(|ch| ch == '.'); match decimal { None => s, Some(idx) => { // Find the minimum string length by determing // what power of ten both the max and range are. let val_rng_f: f64 = NumCast::from(val_rng).unwrap(); let max_f: f64 = NumCast::from(max).unwrap(); let mut n: f64 = 0.0; let mut pow_ten = 0.0; while pow_ten < val_rng_f || pow_ten < max_f { pow_ten = (10.0).powf(n); n += 1.0 } let min_string_len = n as usize + 1; // Find out how many pixels there are to actually use // and judge a reasonable precision from this. let mut n = 1; while 10.pow(n) < pixel_range { n += 1 } let precision = n as usize; // Truncate the length to the pixel precision as // long as this doesn't cause it to be smaller // than the necessary decimal place. let mut truncate_len = min_string_len + (precision - 1); if idx + precision < truncate_len { truncate_len = idx + precision } if s.len() > truncate_len { s.truncate(truncate_len) } s } } }
random_line_split
utils.rs
//! //! Various utility functions used throughout Conrod. //! use num::{Float, NumCast, PrimInt, ToPrimitive}; use position::{Dimensions, Point}; use vecmath::vec2_sub; /// Clamp a value between a given min and max. pub fn clamp<T: PartialOrd>(n: T, min: T, max: T) -> T { if n < min
else if n > max { max } else { n } } /// Return whether or not a given point is over a rectangle at a given point on a cartesian plane. pub fn is_over_rect(rect_point: Point, mouse_point: Point, rect_dim: Dimensions) -> bool { let point = vec2_sub(rect_point, mouse_point); if point[0].abs() < rect_dim[0] / 2.0 && point[1].abs() < rect_dim[1] / 2.0 { true } else { false } } /// Get value percentage between max and min. pub fn percentage<T: Float + NumCast>(value: T, min: T, max: T) -> f32 { let v: f32 = NumCast::from(value).unwrap(); let mn: f32 = NumCast::from(min).unwrap(); let mx: f32 = NumCast::from(max).unwrap(); (v - mn) / (mx - mn) } /// Adjust the value to the given percentage. pub fn value_from_perc<T: Float + NumCast + ToPrimitive>(perc: f32, min: T, max: T) -> T { let f: f32 = (max - min).to_f32().unwrap() * perc; min + NumCast::from(f).unwrap() } /// Map a value from a given range to a new given range. pub fn map_range<X: Float + NumCast, Y: Float + NumCast> (val: X, in_min: X, in_max: X, out_min: Y, out_max: Y) -> Y { let val_f: f64 = NumCast::from(val).unwrap(); let in_min_f: f64 = NumCast::from(in_min).unwrap(); let in_max_f: f64 = NumCast::from(in_max).unwrap(); let out_min_f: f64 = NumCast::from(out_min).unwrap(); let out_max_f: f64 = NumCast::from(out_max).unwrap(); NumCast::from( (val_f - in_min_f) / (in_max_f - in_min_f) * (out_max_f - out_min_f) + out_min_f ).unwrap() } /// Get a suitable string from the value, its max and the pixel range. pub fn val_to_string<T: ToString + NumCast> (val: T, max: T, val_rng: T, pixel_range: usize) -> String { let mut s = val.to_string(); let decimal = s.chars().position(|ch| ch == '.'); match decimal { None => s, Some(idx) => { // Find the minimum string length by determing // what power of ten both the max and range are. let val_rng_f: f64 = NumCast::from(val_rng).unwrap(); let max_f: f64 = NumCast::from(max).unwrap(); let mut n: f64 = 0.0; let mut pow_ten = 0.0; while pow_ten < val_rng_f || pow_ten < max_f { pow_ten = (10.0).powf(n); n += 1.0 } let min_string_len = n as usize + 1; // Find out how many pixels there are to actually use // and judge a reasonable precision from this. let mut n = 1; while 10.pow(n) < pixel_range { n += 1 } let precision = n as usize; // Truncate the length to the pixel precision as // long as this doesn't cause it to be smaller // than the necessary decimal place. let mut truncate_len = min_string_len + (precision - 1); if idx + precision < truncate_len { truncate_len = idx + precision } if s.len() > truncate_len { s.truncate(truncate_len) } s } } }
{ min }
conditional_block
future-proofing-locals.rs
// edition:2018 #![allow(non_camel_case_types)] #![allow(unused_imports)] mod T { pub struct U; } mod x { pub struct y; } fn type_param<T>() { use T as _; //~ ERROR imports cannot refer to type parameters use T::U; //~ ERROR imports cannot refer to type parameters use T::*; //~ ERROR imports cannot refer to type parameters } fn self_import<T>() { use T; //~ ERROR imports cannot refer to type parameters } fn let_binding() { let x = 10; use x as _; //~ ERROR imports cannot refer to local variables use x::y; // OK use x::*; // OK } fn param_binding(x: u8) { use x; //~ ERROR imports cannot refer to local variables } fn match_binding() { match 0 { x => { use x; //~ ERROR imports cannot refer to local variables } } } fn
<T>() { let x = 10; use {T as _, x}; //~ ERROR imports cannot refer to type parameters //~| ERROR imports cannot refer to local variables } fn main() {}
nested
identifier_name
future-proofing-locals.rs
// edition:2018 #![allow(non_camel_case_types)] #![allow(unused_imports)] mod T { pub struct U; } mod x { pub struct y; } fn type_param<T>() { use T as _; //~ ERROR imports cannot refer to type parameters use T::U; //~ ERROR imports cannot refer to type parameters use T::*; //~ ERROR imports cannot refer to type parameters } fn self_import<T>() { use T; //~ ERROR imports cannot refer to type parameters } fn let_binding() { let x = 10; use x as _; //~ ERROR imports cannot refer to local variables use x::y; // OK use x::*; // OK } fn param_binding(x: u8) { use x; //~ ERROR imports cannot refer to local variables } fn match_binding() { match 0 { x => { use x; //~ ERROR imports cannot refer to local variables } } } fn nested<T>()
fn main() {}
{ let x = 10; use {T as _, x}; //~ ERROR imports cannot refer to type parameters //~| ERROR imports cannot refer to local variables }
identifier_body
future-proofing-locals.rs
// edition:2018 #![allow(non_camel_case_types)] #![allow(unused_imports)] mod T { pub struct U;
} mod x { pub struct y; } fn type_param<T>() { use T as _; //~ ERROR imports cannot refer to type parameters use T::U; //~ ERROR imports cannot refer to type parameters use T::*; //~ ERROR imports cannot refer to type parameters } fn self_import<T>() { use T; //~ ERROR imports cannot refer to type parameters } fn let_binding() { let x = 10; use x as _; //~ ERROR imports cannot refer to local variables use x::y; // OK use x::*; // OK } fn param_binding(x: u8) { use x; //~ ERROR imports cannot refer to local variables } fn match_binding() { match 0 { x => { use x; //~ ERROR imports cannot refer to local variables } } } fn nested<T>() { let x = 10; use {T as _, x}; //~ ERROR imports cannot refer to type parameters //~| ERROR imports cannot refer to local variables } fn main() {}
random_line_split
style.rs
use conrod::color::{TRANSPARENT, WHITE}; use conrod::widget::Button; /// Set the button style to a one that looks :+1: on the canvas. /// /// # Examples /// /// ``` /// # extern crate poke_a_mango; /// # extern crate conrod; /// # use poke_a_mango::ops::set_button_style; /// # use conrod::widget::{Button, Id}; /// # use conrod::{UiBuilder, Widget}; /// # fn main() { /// # let mut ui = UiBuilder::new([1.0, 2.0]).build(); /// # let mut ui_widgets = ui.set_widgets(); /// # let buttid = Id::new(1); /// let mut butan = Button::new(); /// // Probably more positioning options /// set_button_style(&mut butan); /// /// butan.set(buttid, &mut ui_widgets); /// # } /// ``` pub fn
<S>(button: &mut Button<S>) { button.style.color = Some(TRANSPARENT); button.style.border = None; button.style.border_color = Some(TRANSPARENT); button.style.label_color = Some(WHITE); }
set_button_style
identifier_name
style.rs
use conrod::color::{TRANSPARENT, WHITE}; use conrod::widget::Button; /// Set the button style to a one that looks :+1: on the canvas. /// /// # Examples /// /// ``` /// # extern crate poke_a_mango; /// # extern crate conrod; /// # use poke_a_mango::ops::set_button_style; /// # use conrod::widget::{Button, Id}; /// # use conrod::{UiBuilder, Widget}; /// # fn main() { /// # let mut ui = UiBuilder::new([1.0, 2.0]).build(); /// # let mut ui_widgets = ui.set_widgets(); /// # let buttid = Id::new(1); /// let mut butan = Button::new(); /// // Probably more positioning options /// set_button_style(&mut butan); /// /// butan.set(buttid, &mut ui_widgets); /// # } /// ``` pub fn set_button_style<S>(button: &mut Button<S>)
{ button.style.color = Some(TRANSPARENT); button.style.border = None; button.style.border_color = Some(TRANSPARENT); button.style.label_color = Some(WHITE); }
identifier_body
style.rs
use conrod::color::{TRANSPARENT, WHITE}; use conrod::widget::Button; /// Set the button style to a one that looks :+1: on the canvas. /// /// # Examples /// /// ``` /// # extern crate poke_a_mango; /// # extern crate conrod; /// # use poke_a_mango::ops::set_button_style;
/// # let mut ui = UiBuilder::new([1.0, 2.0]).build(); /// # let mut ui_widgets = ui.set_widgets(); /// # let buttid = Id::new(1); /// let mut butan = Button::new(); /// // Probably more positioning options /// set_button_style(&mut butan); /// /// butan.set(buttid, &mut ui_widgets); /// # } /// ``` pub fn set_button_style<S>(button: &mut Button<S>) { button.style.color = Some(TRANSPARENT); button.style.border = None; button.style.border_color = Some(TRANSPARENT); button.style.label_color = Some(WHITE); }
/// # use conrod::widget::{Button, Id}; /// # use conrod::{UiBuilder, Widget}; /// # fn main() {
random_line_split
blockdev.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use dbus; use dbus::arg::IterAppend; use dbus::tree::{ Access, EmitsChangedSignal, Factory, MTFn, MethodErr, MethodInfo, MethodResult, PropInfo, }; use dbus::Message; use uuid::Uuid; use crate::dbus_api::consts; use crate::engine::{BlockDev, BlockDevTier, MaybeDbusPath}; use crate::dbus_api::types::{DbusContext, DbusErrorEnum, OPContext, TData}; use crate::dbus_api::util::{ engine_to_dbus_err_tuple, get_next_arg, get_parent, get_uuid, make_object_path, msg_code_ok, msg_string_ok, }; pub fn create_dbus_blockdev<'a>( dbus_context: &DbusContext, parent: dbus::Path<'static>, uuid: Uuid, blockdev: &mut BlockDev, ) -> dbus::Path<'a> { let f = Factory::new_fn(); let set_userid_method = f .method("SetUserInfo", (), set_user_info) .in_arg(("id", "s")) .out_arg(("changed", "b")) .out_arg(("return_code", "q")) .out_arg(("return_string", "s")); let devnode_property = f .property::<&str, _>("Devnode", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_blockdev_devnode); let hardware_info_property = f .property::<&str, _>("HardwareInfo", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_blockdev_hardware_info); let user_info_property = f .property::<&str, _>("UserInfo", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::False) .on_get(get_blockdev_user_info); let initialization_time_property = f .property::<u64, _>("InitializationTime", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_blockdev_initialization_time); let total_physical_size_property = f .property::<&str, _>("TotalPhysicalSize", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::False) .on_get(get_blockdev_physical_size); let state_property = f .property::<u16, _>(consts::BLOCKDEV_STATE_PROP, ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::True) .on_get(get_blockdev_state); let pool_property = f .property::<&dbus::Path, _>("Pool", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_parent); let uuid_property = f .property::<&str, _>("Uuid", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_uuid); let tier_property = f .property::<u16, _>("Tier", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::False) .on_get(get_blockdev_tier); let object_name = make_object_path(dbus_context); let object_path = f .object_path(object_name, Some(OPContext::new(parent, uuid))) .introspectable() .add( f.interface(consts::BLOCKDEV_INTERFACE_NAME, ()) .add_m(set_userid_method) .add_p(devnode_property) .add_p(hardware_info_property) .add_p(initialization_time_property) .add_p(total_physical_size_property) .add_p(pool_property) .add_p(state_property) .add_p(tier_property) .add_p(user_info_property) .add_p(uuid_property), ); let path = object_path.get_name().to_owned(); dbus_context.actions.borrow_mut().push_add(object_path); blockdev.set_dbus_path(MaybeDbusPath(Some(path.clone()))); path } fn set_user_info(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult { let message: &Message = m.msg; let mut iter = message.iter_init(); let new_id: Option<&str> = match get_next_arg(&mut iter, 0)? { "" => None, val => Some(val), }; let dbus_context = m.tree.get_data(); let object_path = m.path.get_name(); let return_message = message.method_return(); let default_return = false; let blockdev_path = m .tree .get(object_path) .expect("implicit argument must be in tree"); let blockdev_data = get_data!(blockdev_path; default_return; return_message); let pool_path = get_parent!(m; blockdev_data; default_return; return_message); let pool_uuid = get_data!(pool_path; default_return; return_message).uuid; let mut engine = dbus_context.engine.borrow_mut(); let (pool_name, pool) = get_mut_pool!(engine; pool_uuid; default_return; return_message); let result = pool.set_blockdev_user_info(&pool_name, blockdev_data.uuid, new_id); let msg = match result { Ok(id_changed) => return_message.append3(id_changed, msg_code_ok(), msg_string_ok()), Err(err) =>
}; Ok(vec![msg]) } /// Get a blockdev property and place it on the D-Bus. The property is /// found by means of the getter method which takes a reference to a /// blockdev and obtains the property from the blockdev. fn get_blockdev_property<F, R>( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, getter: F, ) -> Result<(), MethodErr> where F: Fn(BlockDevTier, &BlockDev) -> Result<R, MethodErr>, R: dbus::arg::Append, { let dbus_context = p.tree.get_data(); let object_path = p.path.get_name(); let blockdev_path = p .tree .get(object_path) .expect("tree must contain implicit argument"); let blockdev_data = blockdev_path .get_data() .as_ref() .ok_or_else(|| MethodErr::failed(&format!("no data for object path {}", object_path)))?; let pool_path = p.tree.get(&blockdev_data.parent).ok_or_else(|| { MethodErr::failed(&format!( "no path for parent object path {}", &blockdev_data.parent )) })?; let pool_uuid = pool_path .get_data() .as_ref() .ok_or_else(|| MethodErr::failed(&format!("no data for object path {}", object_path)))? .uuid; let engine = dbus_context.engine.borrow(); let (_, pool) = engine.get_pool(pool_uuid).ok_or_else(|| { MethodErr::failed(&format!("no pool corresponding to uuid {}", &pool_uuid)) })?; let (tier, blockdev) = pool.get_blockdev(blockdev_data.uuid).ok_or_else(|| { MethodErr::failed(&format!("no blockdev with uuid {}", blockdev_data.uuid)) })?; i.append(getter(tier, blockdev)?); Ok(()) } /// Get the devnode for an object path. fn get_blockdev_devnode( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(format!("{}", p.devnode().display()))) } fn get_blockdev_hardware_info( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.hardware_info().unwrap_or("").to_owned())) } fn get_blockdev_user_info( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.user_info().unwrap_or("").to_owned())) } fn get_blockdev_initialization_time( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.initialization_time().timestamp() as u64)) } fn get_blockdev_physical_size( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(format!("{}", *p.size()))) } fn get_blockdev_state( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.state() as u16)) } fn get_blockdev_tier( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |t, _| Ok(t as u16)) }
{ let (rc, rs) = engine_to_dbus_err_tuple(&err); return_message.append3(default_return, rc, rs) }
conditional_block
blockdev.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use dbus; use dbus::arg::IterAppend; use dbus::tree::{ Access, EmitsChangedSignal, Factory, MTFn, MethodErr, MethodInfo, MethodResult, PropInfo, }; use dbus::Message; use uuid::Uuid; use crate::dbus_api::consts; use crate::engine::{BlockDev, BlockDevTier, MaybeDbusPath}; use crate::dbus_api::types::{DbusContext, DbusErrorEnum, OPContext, TData}; use crate::dbus_api::util::{ engine_to_dbus_err_tuple, get_next_arg, get_parent, get_uuid, make_object_path, msg_code_ok, msg_string_ok, }; pub fn create_dbus_blockdev<'a>( dbus_context: &DbusContext, parent: dbus::Path<'static>, uuid: Uuid, blockdev: &mut BlockDev, ) -> dbus::Path<'a> { let f = Factory::new_fn(); let set_userid_method = f .method("SetUserInfo", (), set_user_info) .in_arg(("id", "s")) .out_arg(("changed", "b")) .out_arg(("return_code", "q")) .out_arg(("return_string", "s")); let devnode_property = f .property::<&str, _>("Devnode", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_blockdev_devnode); let hardware_info_property = f .property::<&str, _>("HardwareInfo", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_blockdev_hardware_info); let user_info_property = f .property::<&str, _>("UserInfo", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::False) .on_get(get_blockdev_user_info); let initialization_time_property = f .property::<u64, _>("InitializationTime", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_blockdev_initialization_time); let total_physical_size_property = f .property::<&str, _>("TotalPhysicalSize", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::False) .on_get(get_blockdev_physical_size); let state_property = f .property::<u16, _>(consts::BLOCKDEV_STATE_PROP, ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::True) .on_get(get_blockdev_state); let pool_property = f .property::<&dbus::Path, _>("Pool", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_parent); let uuid_property = f .property::<&str, _>("Uuid", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_uuid); let tier_property = f .property::<u16, _>("Tier", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::False) .on_get(get_blockdev_tier); let object_name = make_object_path(dbus_context); let object_path = f .object_path(object_name, Some(OPContext::new(parent, uuid))) .introspectable() .add( f.interface(consts::BLOCKDEV_INTERFACE_NAME, ()) .add_m(set_userid_method) .add_p(devnode_property) .add_p(hardware_info_property) .add_p(initialization_time_property) .add_p(total_physical_size_property) .add_p(pool_property) .add_p(state_property) .add_p(tier_property) .add_p(user_info_property) .add_p(uuid_property), ); let path = object_path.get_name().to_owned(); dbus_context.actions.borrow_mut().push_add(object_path); blockdev.set_dbus_path(MaybeDbusPath(Some(path.clone()))); path } fn set_user_info(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult { let message: &Message = m.msg; let mut iter = message.iter_init(); let new_id: Option<&str> = match get_next_arg(&mut iter, 0)? { "" => None, val => Some(val), }; let dbus_context = m.tree.get_data(); let object_path = m.path.get_name(); let return_message = message.method_return(); let default_return = false; let blockdev_path = m .tree .get(object_path) .expect("implicit argument must be in tree"); let blockdev_data = get_data!(blockdev_path; default_return; return_message); let pool_path = get_parent!(m; blockdev_data; default_return; return_message); let pool_uuid = get_data!(pool_path; default_return; return_message).uuid; let mut engine = dbus_context.engine.borrow_mut(); let (pool_name, pool) = get_mut_pool!(engine; pool_uuid; default_return; return_message); let result = pool.set_blockdev_user_info(&pool_name, blockdev_data.uuid, new_id); let msg = match result { Ok(id_changed) => return_message.append3(id_changed, msg_code_ok(), msg_string_ok()), Err(err) => { let (rc, rs) = engine_to_dbus_err_tuple(&err); return_message.append3(default_return, rc, rs) } }; Ok(vec![msg]) } /// Get a blockdev property and place it on the D-Bus. The property is /// found by means of the getter method which takes a reference to a /// blockdev and obtains the property from the blockdev. fn get_blockdev_property<F, R>( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, getter: F, ) -> Result<(), MethodErr> where F: Fn(BlockDevTier, &BlockDev) -> Result<R, MethodErr>, R: dbus::arg::Append, { let dbus_context = p.tree.get_data(); let object_path = p.path.get_name(); let blockdev_path = p .tree .get(object_path) .expect("tree must contain implicit argument"); let blockdev_data = blockdev_path .get_data() .as_ref() .ok_or_else(|| MethodErr::failed(&format!("no data for object path {}", object_path)))?; let pool_path = p.tree.get(&blockdev_data.parent).ok_or_else(|| { MethodErr::failed(&format!( "no path for parent object path {}", &blockdev_data.parent )) })?; let pool_uuid = pool_path .get_data() .as_ref() .ok_or_else(|| MethodErr::failed(&format!("no data for object path {}", object_path)))? .uuid; let engine = dbus_context.engine.borrow(); let (_, pool) = engine.get_pool(pool_uuid).ok_or_else(|| { MethodErr::failed(&format!("no pool corresponding to uuid {}", &pool_uuid)) })?; let (tier, blockdev) = pool.get_blockdev(blockdev_data.uuid).ok_or_else(|| { MethodErr::failed(&format!("no blockdev with uuid {}", blockdev_data.uuid)) })?; i.append(getter(tier, blockdev)?); Ok(()) } /// Get the devnode for an object path. fn get_blockdev_devnode( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> {
fn get_blockdev_hardware_info( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.hardware_info().unwrap_or("").to_owned())) } fn get_blockdev_user_info( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.user_info().unwrap_or("").to_owned())) } fn get_blockdev_initialization_time( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.initialization_time().timestamp() as u64)) } fn get_blockdev_physical_size( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(format!("{}", *p.size()))) } fn get_blockdev_state( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.state() as u16)) } fn get_blockdev_tier( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |t, _| Ok(t as u16)) }
get_blockdev_property(i, p, |_, p| Ok(format!("{}", p.devnode().display()))) }
random_line_split
blockdev.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use dbus; use dbus::arg::IterAppend; use dbus::tree::{ Access, EmitsChangedSignal, Factory, MTFn, MethodErr, MethodInfo, MethodResult, PropInfo, }; use dbus::Message; use uuid::Uuid; use crate::dbus_api::consts; use crate::engine::{BlockDev, BlockDevTier, MaybeDbusPath}; use crate::dbus_api::types::{DbusContext, DbusErrorEnum, OPContext, TData}; use crate::dbus_api::util::{ engine_to_dbus_err_tuple, get_next_arg, get_parent, get_uuid, make_object_path, msg_code_ok, msg_string_ok, }; pub fn create_dbus_blockdev<'a>( dbus_context: &DbusContext, parent: dbus::Path<'static>, uuid: Uuid, blockdev: &mut BlockDev, ) -> dbus::Path<'a> { let f = Factory::new_fn(); let set_userid_method = f .method("SetUserInfo", (), set_user_info) .in_arg(("id", "s")) .out_arg(("changed", "b")) .out_arg(("return_code", "q")) .out_arg(("return_string", "s")); let devnode_property = f .property::<&str, _>("Devnode", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_blockdev_devnode); let hardware_info_property = f .property::<&str, _>("HardwareInfo", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_blockdev_hardware_info); let user_info_property = f .property::<&str, _>("UserInfo", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::False) .on_get(get_blockdev_user_info); let initialization_time_property = f .property::<u64, _>("InitializationTime", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_blockdev_initialization_time); let total_physical_size_property = f .property::<&str, _>("TotalPhysicalSize", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::False) .on_get(get_blockdev_physical_size); let state_property = f .property::<u16, _>(consts::BLOCKDEV_STATE_PROP, ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::True) .on_get(get_blockdev_state); let pool_property = f .property::<&dbus::Path, _>("Pool", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_parent); let uuid_property = f .property::<&str, _>("Uuid", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_uuid); let tier_property = f .property::<u16, _>("Tier", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::False) .on_get(get_blockdev_tier); let object_name = make_object_path(dbus_context); let object_path = f .object_path(object_name, Some(OPContext::new(parent, uuid))) .introspectable() .add( f.interface(consts::BLOCKDEV_INTERFACE_NAME, ()) .add_m(set_userid_method) .add_p(devnode_property) .add_p(hardware_info_property) .add_p(initialization_time_property) .add_p(total_physical_size_property) .add_p(pool_property) .add_p(state_property) .add_p(tier_property) .add_p(user_info_property) .add_p(uuid_property), ); let path = object_path.get_name().to_owned(); dbus_context.actions.borrow_mut().push_add(object_path); blockdev.set_dbus_path(MaybeDbusPath(Some(path.clone()))); path } fn set_user_info(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult { let message: &Message = m.msg; let mut iter = message.iter_init(); let new_id: Option<&str> = match get_next_arg(&mut iter, 0)? { "" => None, val => Some(val), }; let dbus_context = m.tree.get_data(); let object_path = m.path.get_name(); let return_message = message.method_return(); let default_return = false; let blockdev_path = m .tree .get(object_path) .expect("implicit argument must be in tree"); let blockdev_data = get_data!(blockdev_path; default_return; return_message); let pool_path = get_parent!(m; blockdev_data; default_return; return_message); let pool_uuid = get_data!(pool_path; default_return; return_message).uuid; let mut engine = dbus_context.engine.borrow_mut(); let (pool_name, pool) = get_mut_pool!(engine; pool_uuid; default_return; return_message); let result = pool.set_blockdev_user_info(&pool_name, blockdev_data.uuid, new_id); let msg = match result { Ok(id_changed) => return_message.append3(id_changed, msg_code_ok(), msg_string_ok()), Err(err) => { let (rc, rs) = engine_to_dbus_err_tuple(&err); return_message.append3(default_return, rc, rs) } }; Ok(vec![msg]) } /// Get a blockdev property and place it on the D-Bus. The property is /// found by means of the getter method which takes a reference to a /// blockdev and obtains the property from the blockdev. fn get_blockdev_property<F, R>( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, getter: F, ) -> Result<(), MethodErr> where F: Fn(BlockDevTier, &BlockDev) -> Result<R, MethodErr>, R: dbus::arg::Append, { let dbus_context = p.tree.get_data(); let object_path = p.path.get_name(); let blockdev_path = p .tree .get(object_path) .expect("tree must contain implicit argument"); let blockdev_data = blockdev_path .get_data() .as_ref() .ok_or_else(|| MethodErr::failed(&format!("no data for object path {}", object_path)))?; let pool_path = p.tree.get(&blockdev_data.parent).ok_or_else(|| { MethodErr::failed(&format!( "no path for parent object path {}", &blockdev_data.parent )) })?; let pool_uuid = pool_path .get_data() .as_ref() .ok_or_else(|| MethodErr::failed(&format!("no data for object path {}", object_path)))? .uuid; let engine = dbus_context.engine.borrow(); let (_, pool) = engine.get_pool(pool_uuid).ok_or_else(|| { MethodErr::failed(&format!("no pool corresponding to uuid {}", &pool_uuid)) })?; let (tier, blockdev) = pool.get_blockdev(blockdev_data.uuid).ok_or_else(|| { MethodErr::failed(&format!("no blockdev with uuid {}", blockdev_data.uuid)) })?; i.append(getter(tier, blockdev)?); Ok(()) } /// Get the devnode for an object path. fn get_blockdev_devnode( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(format!("{}", p.devnode().display()))) } fn get_blockdev_hardware_info( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.hardware_info().unwrap_or("").to_owned())) } fn get_blockdev_user_info( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.user_info().unwrap_or("").to_owned())) } fn get_blockdev_initialization_time( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.initialization_time().timestamp() as u64)) } fn
( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(format!("{}", *p.size()))) } fn get_blockdev_state( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.state() as u16)) } fn get_blockdev_tier( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |t, _| Ok(t as u16)) }
get_blockdev_physical_size
identifier_name
blockdev.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use dbus; use dbus::arg::IterAppend; use dbus::tree::{ Access, EmitsChangedSignal, Factory, MTFn, MethodErr, MethodInfo, MethodResult, PropInfo, }; use dbus::Message; use uuid::Uuid; use crate::dbus_api::consts; use crate::engine::{BlockDev, BlockDevTier, MaybeDbusPath}; use crate::dbus_api::types::{DbusContext, DbusErrorEnum, OPContext, TData}; use crate::dbus_api::util::{ engine_to_dbus_err_tuple, get_next_arg, get_parent, get_uuid, make_object_path, msg_code_ok, msg_string_ok, }; pub fn create_dbus_blockdev<'a>( dbus_context: &DbusContext, parent: dbus::Path<'static>, uuid: Uuid, blockdev: &mut BlockDev, ) -> dbus::Path<'a> { let f = Factory::new_fn(); let set_userid_method = f .method("SetUserInfo", (), set_user_info) .in_arg(("id", "s")) .out_arg(("changed", "b")) .out_arg(("return_code", "q")) .out_arg(("return_string", "s")); let devnode_property = f .property::<&str, _>("Devnode", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_blockdev_devnode); let hardware_info_property = f .property::<&str, _>("HardwareInfo", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_blockdev_hardware_info); let user_info_property = f .property::<&str, _>("UserInfo", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::False) .on_get(get_blockdev_user_info); let initialization_time_property = f .property::<u64, _>("InitializationTime", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_blockdev_initialization_time); let total_physical_size_property = f .property::<&str, _>("TotalPhysicalSize", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::False) .on_get(get_blockdev_physical_size); let state_property = f .property::<u16, _>(consts::BLOCKDEV_STATE_PROP, ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::True) .on_get(get_blockdev_state); let pool_property = f .property::<&dbus::Path, _>("Pool", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_parent); let uuid_property = f .property::<&str, _>("Uuid", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::Const) .on_get(get_uuid); let tier_property = f .property::<u16, _>("Tier", ()) .access(Access::Read) .emits_changed(EmitsChangedSignal::False) .on_get(get_blockdev_tier); let object_name = make_object_path(dbus_context); let object_path = f .object_path(object_name, Some(OPContext::new(parent, uuid))) .introspectable() .add( f.interface(consts::BLOCKDEV_INTERFACE_NAME, ()) .add_m(set_userid_method) .add_p(devnode_property) .add_p(hardware_info_property) .add_p(initialization_time_property) .add_p(total_physical_size_property) .add_p(pool_property) .add_p(state_property) .add_p(tier_property) .add_p(user_info_property) .add_p(uuid_property), ); let path = object_path.get_name().to_owned(); dbus_context.actions.borrow_mut().push_add(object_path); blockdev.set_dbus_path(MaybeDbusPath(Some(path.clone()))); path } fn set_user_info(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult { let message: &Message = m.msg; let mut iter = message.iter_init(); let new_id: Option<&str> = match get_next_arg(&mut iter, 0)? { "" => None, val => Some(val), }; let dbus_context = m.tree.get_data(); let object_path = m.path.get_name(); let return_message = message.method_return(); let default_return = false; let blockdev_path = m .tree .get(object_path) .expect("implicit argument must be in tree"); let blockdev_data = get_data!(blockdev_path; default_return; return_message); let pool_path = get_parent!(m; blockdev_data; default_return; return_message); let pool_uuid = get_data!(pool_path; default_return; return_message).uuid; let mut engine = dbus_context.engine.borrow_mut(); let (pool_name, pool) = get_mut_pool!(engine; pool_uuid; default_return; return_message); let result = pool.set_blockdev_user_info(&pool_name, blockdev_data.uuid, new_id); let msg = match result { Ok(id_changed) => return_message.append3(id_changed, msg_code_ok(), msg_string_ok()), Err(err) => { let (rc, rs) = engine_to_dbus_err_tuple(&err); return_message.append3(default_return, rc, rs) } }; Ok(vec![msg]) } /// Get a blockdev property and place it on the D-Bus. The property is /// found by means of the getter method which takes a reference to a /// blockdev and obtains the property from the blockdev. fn get_blockdev_property<F, R>( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, getter: F, ) -> Result<(), MethodErr> where F: Fn(BlockDevTier, &BlockDev) -> Result<R, MethodErr>, R: dbus::arg::Append, { let dbus_context = p.tree.get_data(); let object_path = p.path.get_name(); let blockdev_path = p .tree .get(object_path) .expect("tree must contain implicit argument"); let blockdev_data = blockdev_path .get_data() .as_ref() .ok_or_else(|| MethodErr::failed(&format!("no data for object path {}", object_path)))?; let pool_path = p.tree.get(&blockdev_data.parent).ok_or_else(|| { MethodErr::failed(&format!( "no path for parent object path {}", &blockdev_data.parent )) })?; let pool_uuid = pool_path .get_data() .as_ref() .ok_or_else(|| MethodErr::failed(&format!("no data for object path {}", object_path)))? .uuid; let engine = dbus_context.engine.borrow(); let (_, pool) = engine.get_pool(pool_uuid).ok_or_else(|| { MethodErr::failed(&format!("no pool corresponding to uuid {}", &pool_uuid)) })?; let (tier, blockdev) = pool.get_blockdev(blockdev_data.uuid).ok_or_else(|| { MethodErr::failed(&format!("no blockdev with uuid {}", blockdev_data.uuid)) })?; i.append(getter(tier, blockdev)?); Ok(()) } /// Get the devnode for an object path. fn get_blockdev_devnode( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(format!("{}", p.devnode().display()))) } fn get_blockdev_hardware_info( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.hardware_info().unwrap_or("").to_owned())) } fn get_blockdev_user_info( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr>
fn get_blockdev_initialization_time( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.initialization_time().timestamp() as u64)) } fn get_blockdev_physical_size( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(format!("{}", *p.size()))) } fn get_blockdev_state( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |_, p| Ok(p.state() as u16)) } fn get_blockdev_tier( i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>, ) -> Result<(), MethodErr> { get_blockdev_property(i, p, |t, _| Ok(t as u16)) }
{ get_blockdev_property(i, p, |_, p| Ok(p.user_info().unwrap_or("").to_owned())) }
identifier_body
common.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] use std::cast; use syntax::crateid::CrateId; use back::svh::Svh; // EBML enum definitions and utils shared by the encoder and decoder pub static tag_items: uint = 0x00; pub static tag_paths_data_name: uint = 0x01; pub static tag_def_id: uint = 0x02; pub static tag_items_data: uint = 0x03; pub static tag_items_data_item: uint = 0x04; pub static tag_items_data_item_family: uint = 0x05; pub static tag_items_data_item_ty_param_bounds: uint = 0x06; pub static tag_items_data_item_type: uint = 0x07; pub static tag_items_data_item_symbol: uint = 0x08; pub static tag_items_data_item_variant: uint = 0x09; pub static tag_items_data_parent_item: uint = 0x0a; pub static tag_items_data_item_is_tuple_struct_ctor: uint = 0x0b; pub static tag_index: uint = 0x0c; pub static tag_index_buckets: uint = 0x0d; pub static tag_index_buckets_bucket: uint = 0x0e; pub static tag_index_buckets_bucket_elt: uint = 0x0f; pub static tag_index_table: uint = 0x10; pub static tag_meta_item_name_value: uint = 0x11; pub static tag_meta_item_name: uint = 0x12; pub static tag_meta_item_value: uint = 0x13; pub static tag_attributes: uint = 0x14; pub static tag_attribute: uint = 0x15; pub static tag_meta_item_word: uint = 0x16; pub static tag_meta_item_list: uint = 0x17; // The list of crates that this crate depends on pub static tag_crate_deps: uint = 0x18; // A single crate dependency pub static tag_crate_dep: uint = 0x19; pub static tag_crate_hash: uint = 0x1a; pub static tag_crate_crateid: uint = 0x1b; pub static tag_crate_dep_crateid: uint = 0x1d; pub static tag_crate_dep_hash: uint = 0x1e; pub static tag_mod_impl: uint = 0x1f; pub static tag_item_trait_method: uint = 0x20; pub static tag_item_trait_ref: uint = 0x21; pub static tag_item_super_trait_ref: uint = 0x22; // discriminator value for variants pub static tag_disr_val: uint = 0x23; // used to encode ast_map::PathElem pub static tag_path: uint = 0x24; pub static tag_path_len: uint = 0x25; pub static tag_path_elem_mod: uint = 0x26; pub static tag_path_elem_name: uint = 0x27; pub static tag_item_field: uint = 0x28; pub static tag_item_variances: uint = 0x2a; /* trait items contain tag_item_trait_method elements, impl items contain tag_item_impl_method elements, and classes have both. That's because some code treats classes like traits, and other code treats them like impls. Because classes can contain both, tag_item_trait_method and tag_item_impl_method have to be two different tags. */ pub static tag_item_impl_method: uint = 0x2c; pub static tag_item_trait_method_explicit_self: uint = 0x2d; // Reexports are found within module tags. Each reexport contains def_ids // and names. pub static tag_items_data_item_reexport: uint = 0x2f; pub static tag_items_data_item_reexport_def_id: uint = 0x30; pub static tag_items_data_item_reexport_name: uint = 0x31; // used to encode crate_ctxt side tables #[deriving(Eq)] #[repr(uint)]
tag_ast = 0x32, tag_tree = 0x33, tag_id_range = 0x34, tag_table = 0x35, tag_table_id = 0x36, tag_table_val = 0x37, tag_table_def = 0x38, tag_table_node_type = 0x39, tag_table_node_type_subst = 0x3a, tag_table_freevars = 0x3b, tag_table_tcache = 0x3c, tag_table_param_defs = 0x3d, tag_table_mutbl = 0x3e, tag_table_last_use = 0x3f, tag_table_spill = 0x40, tag_table_method_map = 0x41, tag_table_vtable_map = 0x42, tag_table_adjustments = 0x43, tag_table_moves_map = 0x44, tag_table_capture_map = 0x45 } static first_astencode_tag: uint = tag_ast as uint; static last_astencode_tag: uint = tag_table_capture_map as uint; impl astencode_tag { pub fn from_uint(value : uint) -> Option<astencode_tag> { let is_a_tag = first_astencode_tag <= value && value <= last_astencode_tag; if!is_a_tag { None } else { Some(unsafe { cast::transmute(value) }) } } } pub static tag_item_trait_method_sort: uint = 0x46; pub static tag_item_impl_type_basename: uint = 0x47; // Language items are a top-level directory (for speed). Hierarchy: // // tag_lang_items // - tag_lang_items_item // - tag_lang_items_item_id: u32 // - tag_lang_items_item_node_id: u32 pub static tag_lang_items: uint = 0x48; pub static tag_lang_items_item: uint = 0x49; pub static tag_lang_items_item_id: uint = 0x4a; pub static tag_lang_items_item_node_id: uint = 0x4b; pub static tag_item_unnamed_field: uint = 0x4c; pub static tag_items_data_item_visibility: uint = 0x4e; pub static tag_item_method_tps: uint = 0x51; pub static tag_item_method_fty: uint = 0x52; pub static tag_mod_child: uint = 0x53; pub static tag_misc_info: uint = 0x54; pub static tag_misc_info_crate_items: uint = 0x55; pub static tag_item_method_provided_source: uint = 0x56; pub static tag_item_impl_vtables: uint = 0x57; pub static tag_impls: uint = 0x58; pub static tag_impls_impl: uint = 0x59; pub static tag_items_data_item_inherent_impl: uint = 0x5a; pub static tag_items_data_item_extension_impl: uint = 0x5b; pub static tag_region_param_def: uint = 0x5c; pub static tag_region_param_def_ident: uint = 0x5d; pub static tag_region_param_def_def_id: uint = 0x5e; pub static tag_native_libraries: uint = 0x5f; pub static tag_native_libraries_lib: uint = 0x60; pub static tag_native_libraries_name: uint = 0x61; pub static tag_native_libraries_kind: uint = 0x62; pub static tag_macro_registrar_fn: uint = 0x63; pub static tag_exported_macros: uint = 0x64; pub static tag_macro_def: uint = 0x65; #[deriving(Clone, Show)] pub struct LinkMeta { pub crateid: CrateId, pub crate_hash: Svh, }
pub enum astencode_tag { // Reserves 0x32 -- 0x45
random_line_split
common.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] use std::cast; use syntax::crateid::CrateId; use back::svh::Svh; // EBML enum definitions and utils shared by the encoder and decoder pub static tag_items: uint = 0x00; pub static tag_paths_data_name: uint = 0x01; pub static tag_def_id: uint = 0x02; pub static tag_items_data: uint = 0x03; pub static tag_items_data_item: uint = 0x04; pub static tag_items_data_item_family: uint = 0x05; pub static tag_items_data_item_ty_param_bounds: uint = 0x06; pub static tag_items_data_item_type: uint = 0x07; pub static tag_items_data_item_symbol: uint = 0x08; pub static tag_items_data_item_variant: uint = 0x09; pub static tag_items_data_parent_item: uint = 0x0a; pub static tag_items_data_item_is_tuple_struct_ctor: uint = 0x0b; pub static tag_index: uint = 0x0c; pub static tag_index_buckets: uint = 0x0d; pub static tag_index_buckets_bucket: uint = 0x0e; pub static tag_index_buckets_bucket_elt: uint = 0x0f; pub static tag_index_table: uint = 0x10; pub static tag_meta_item_name_value: uint = 0x11; pub static tag_meta_item_name: uint = 0x12; pub static tag_meta_item_value: uint = 0x13; pub static tag_attributes: uint = 0x14; pub static tag_attribute: uint = 0x15; pub static tag_meta_item_word: uint = 0x16; pub static tag_meta_item_list: uint = 0x17; // The list of crates that this crate depends on pub static tag_crate_deps: uint = 0x18; // A single crate dependency pub static tag_crate_dep: uint = 0x19; pub static tag_crate_hash: uint = 0x1a; pub static tag_crate_crateid: uint = 0x1b; pub static tag_crate_dep_crateid: uint = 0x1d; pub static tag_crate_dep_hash: uint = 0x1e; pub static tag_mod_impl: uint = 0x1f; pub static tag_item_trait_method: uint = 0x20; pub static tag_item_trait_ref: uint = 0x21; pub static tag_item_super_trait_ref: uint = 0x22; // discriminator value for variants pub static tag_disr_val: uint = 0x23; // used to encode ast_map::PathElem pub static tag_path: uint = 0x24; pub static tag_path_len: uint = 0x25; pub static tag_path_elem_mod: uint = 0x26; pub static tag_path_elem_name: uint = 0x27; pub static tag_item_field: uint = 0x28; pub static tag_item_variances: uint = 0x2a; /* trait items contain tag_item_trait_method elements, impl items contain tag_item_impl_method elements, and classes have both. That's because some code treats classes like traits, and other code treats them like impls. Because classes can contain both, tag_item_trait_method and tag_item_impl_method have to be two different tags. */ pub static tag_item_impl_method: uint = 0x2c; pub static tag_item_trait_method_explicit_self: uint = 0x2d; // Reexports are found within module tags. Each reexport contains def_ids // and names. pub static tag_items_data_item_reexport: uint = 0x2f; pub static tag_items_data_item_reexport_def_id: uint = 0x30; pub static tag_items_data_item_reexport_name: uint = 0x31; // used to encode crate_ctxt side tables #[deriving(Eq)] #[repr(uint)] pub enum
{ // Reserves 0x32 -- 0x45 tag_ast = 0x32, tag_tree = 0x33, tag_id_range = 0x34, tag_table = 0x35, tag_table_id = 0x36, tag_table_val = 0x37, tag_table_def = 0x38, tag_table_node_type = 0x39, tag_table_node_type_subst = 0x3a, tag_table_freevars = 0x3b, tag_table_tcache = 0x3c, tag_table_param_defs = 0x3d, tag_table_mutbl = 0x3e, tag_table_last_use = 0x3f, tag_table_spill = 0x40, tag_table_method_map = 0x41, tag_table_vtable_map = 0x42, tag_table_adjustments = 0x43, tag_table_moves_map = 0x44, tag_table_capture_map = 0x45 } static first_astencode_tag: uint = tag_ast as uint; static last_astencode_tag: uint = tag_table_capture_map as uint; impl astencode_tag { pub fn from_uint(value : uint) -> Option<astencode_tag> { let is_a_tag = first_astencode_tag <= value && value <= last_astencode_tag; if!is_a_tag { None } else { Some(unsafe { cast::transmute(value) }) } } } pub static tag_item_trait_method_sort: uint = 0x46; pub static tag_item_impl_type_basename: uint = 0x47; // Language items are a top-level directory (for speed). Hierarchy: // // tag_lang_items // - tag_lang_items_item // - tag_lang_items_item_id: u32 // - tag_lang_items_item_node_id: u32 pub static tag_lang_items: uint = 0x48; pub static tag_lang_items_item: uint = 0x49; pub static tag_lang_items_item_id: uint = 0x4a; pub static tag_lang_items_item_node_id: uint = 0x4b; pub static tag_item_unnamed_field: uint = 0x4c; pub static tag_items_data_item_visibility: uint = 0x4e; pub static tag_item_method_tps: uint = 0x51; pub static tag_item_method_fty: uint = 0x52; pub static tag_mod_child: uint = 0x53; pub static tag_misc_info: uint = 0x54; pub static tag_misc_info_crate_items: uint = 0x55; pub static tag_item_method_provided_source: uint = 0x56; pub static tag_item_impl_vtables: uint = 0x57; pub static tag_impls: uint = 0x58; pub static tag_impls_impl: uint = 0x59; pub static tag_items_data_item_inherent_impl: uint = 0x5a; pub static tag_items_data_item_extension_impl: uint = 0x5b; pub static tag_region_param_def: uint = 0x5c; pub static tag_region_param_def_ident: uint = 0x5d; pub static tag_region_param_def_def_id: uint = 0x5e; pub static tag_native_libraries: uint = 0x5f; pub static tag_native_libraries_lib: uint = 0x60; pub static tag_native_libraries_name: uint = 0x61; pub static tag_native_libraries_kind: uint = 0x62; pub static tag_macro_registrar_fn: uint = 0x63; pub static tag_exported_macros: uint = 0x64; pub static tag_macro_def: uint = 0x65; #[deriving(Clone, Show)] pub struct LinkMeta { pub crateid: CrateId, pub crate_hash: Svh, }
astencode_tag
identifier_name
common.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] use std::cast; use syntax::crateid::CrateId; use back::svh::Svh; // EBML enum definitions and utils shared by the encoder and decoder pub static tag_items: uint = 0x00; pub static tag_paths_data_name: uint = 0x01; pub static tag_def_id: uint = 0x02; pub static tag_items_data: uint = 0x03; pub static tag_items_data_item: uint = 0x04; pub static tag_items_data_item_family: uint = 0x05; pub static tag_items_data_item_ty_param_bounds: uint = 0x06; pub static tag_items_data_item_type: uint = 0x07; pub static tag_items_data_item_symbol: uint = 0x08; pub static tag_items_data_item_variant: uint = 0x09; pub static tag_items_data_parent_item: uint = 0x0a; pub static tag_items_data_item_is_tuple_struct_ctor: uint = 0x0b; pub static tag_index: uint = 0x0c; pub static tag_index_buckets: uint = 0x0d; pub static tag_index_buckets_bucket: uint = 0x0e; pub static tag_index_buckets_bucket_elt: uint = 0x0f; pub static tag_index_table: uint = 0x10; pub static tag_meta_item_name_value: uint = 0x11; pub static tag_meta_item_name: uint = 0x12; pub static tag_meta_item_value: uint = 0x13; pub static tag_attributes: uint = 0x14; pub static tag_attribute: uint = 0x15; pub static tag_meta_item_word: uint = 0x16; pub static tag_meta_item_list: uint = 0x17; // The list of crates that this crate depends on pub static tag_crate_deps: uint = 0x18; // A single crate dependency pub static tag_crate_dep: uint = 0x19; pub static tag_crate_hash: uint = 0x1a; pub static tag_crate_crateid: uint = 0x1b; pub static tag_crate_dep_crateid: uint = 0x1d; pub static tag_crate_dep_hash: uint = 0x1e; pub static tag_mod_impl: uint = 0x1f; pub static tag_item_trait_method: uint = 0x20; pub static tag_item_trait_ref: uint = 0x21; pub static tag_item_super_trait_ref: uint = 0x22; // discriminator value for variants pub static tag_disr_val: uint = 0x23; // used to encode ast_map::PathElem pub static tag_path: uint = 0x24; pub static tag_path_len: uint = 0x25; pub static tag_path_elem_mod: uint = 0x26; pub static tag_path_elem_name: uint = 0x27; pub static tag_item_field: uint = 0x28; pub static tag_item_variances: uint = 0x2a; /* trait items contain tag_item_trait_method elements, impl items contain tag_item_impl_method elements, and classes have both. That's because some code treats classes like traits, and other code treats them like impls. Because classes can contain both, tag_item_trait_method and tag_item_impl_method have to be two different tags. */ pub static tag_item_impl_method: uint = 0x2c; pub static tag_item_trait_method_explicit_self: uint = 0x2d; // Reexports are found within module tags. Each reexport contains def_ids // and names. pub static tag_items_data_item_reexport: uint = 0x2f; pub static tag_items_data_item_reexport_def_id: uint = 0x30; pub static tag_items_data_item_reexport_name: uint = 0x31; // used to encode crate_ctxt side tables #[deriving(Eq)] #[repr(uint)] pub enum astencode_tag { // Reserves 0x32 -- 0x45 tag_ast = 0x32, tag_tree = 0x33, tag_id_range = 0x34, tag_table = 0x35, tag_table_id = 0x36, tag_table_val = 0x37, tag_table_def = 0x38, tag_table_node_type = 0x39, tag_table_node_type_subst = 0x3a, tag_table_freevars = 0x3b, tag_table_tcache = 0x3c, tag_table_param_defs = 0x3d, tag_table_mutbl = 0x3e, tag_table_last_use = 0x3f, tag_table_spill = 0x40, tag_table_method_map = 0x41, tag_table_vtable_map = 0x42, tag_table_adjustments = 0x43, tag_table_moves_map = 0x44, tag_table_capture_map = 0x45 } static first_astencode_tag: uint = tag_ast as uint; static last_astencode_tag: uint = tag_table_capture_map as uint; impl astencode_tag { pub fn from_uint(value : uint) -> Option<astencode_tag> { let is_a_tag = first_astencode_tag <= value && value <= last_astencode_tag; if!is_a_tag
else { Some(unsafe { cast::transmute(value) }) } } } pub static tag_item_trait_method_sort: uint = 0x46; pub static tag_item_impl_type_basename: uint = 0x47; // Language items are a top-level directory (for speed). Hierarchy: // // tag_lang_items // - tag_lang_items_item // - tag_lang_items_item_id: u32 // - tag_lang_items_item_node_id: u32 pub static tag_lang_items: uint = 0x48; pub static tag_lang_items_item: uint = 0x49; pub static tag_lang_items_item_id: uint = 0x4a; pub static tag_lang_items_item_node_id: uint = 0x4b; pub static tag_item_unnamed_field: uint = 0x4c; pub static tag_items_data_item_visibility: uint = 0x4e; pub static tag_item_method_tps: uint = 0x51; pub static tag_item_method_fty: uint = 0x52; pub static tag_mod_child: uint = 0x53; pub static tag_misc_info: uint = 0x54; pub static tag_misc_info_crate_items: uint = 0x55; pub static tag_item_method_provided_source: uint = 0x56; pub static tag_item_impl_vtables: uint = 0x57; pub static tag_impls: uint = 0x58; pub static tag_impls_impl: uint = 0x59; pub static tag_items_data_item_inherent_impl: uint = 0x5a; pub static tag_items_data_item_extension_impl: uint = 0x5b; pub static tag_region_param_def: uint = 0x5c; pub static tag_region_param_def_ident: uint = 0x5d; pub static tag_region_param_def_def_id: uint = 0x5e; pub static tag_native_libraries: uint = 0x5f; pub static tag_native_libraries_lib: uint = 0x60; pub static tag_native_libraries_name: uint = 0x61; pub static tag_native_libraries_kind: uint = 0x62; pub static tag_macro_registrar_fn: uint = 0x63; pub static tag_exported_macros: uint = 0x64; pub static tag_macro_def: uint = 0x65; #[deriving(Clone, Show)] pub struct LinkMeta { pub crateid: CrateId, pub crate_hash: Svh, }
{ None }
conditional_block
bucket_sort.rs
/// 桶排序 /// 时间复杂度:O(n), 稳定排序 // 桶排序 pub fn bucket_sort(mut nums: Vec<i32>, step: i32) -> Vec<i32> { let (mut min, mut max) = (nums[0], nums[0]); for i in 0..nums.len() { if min > nums[i] { min = nums[i]; } if max < nums[i] { max = nums[i]; } } // 设置需要的桶的数量 let bucket_num = (max - min) / step + 1; let mut bucket_list: Vec<Vec<i32>> = vec![vec![]; bucket_num as usize]; // 将 nums 数组中元素分别装入桶中 for i in 0..nums.len() { // 计算桶 index let index = (nums[i] - min) / step; bucket_list[index as usize].push(nums[i]); } let mut index = 0; for i in 0..bucket_num { let bucket = &bucket_list[i as usize]; // 对每个桶中元素使用快排进行排序 let new_bucket = quick_sort(bucket.to_vec()); // 将已经排序好的桶中元素拷贝到 nums 数组中 for num in new_bucket.into_iter() { nums[index as usize] = num; index += 1; } } nums } pub fn quick_sort(mut nums: Vec<i32>) -> Vec<i32> { if nums.is_empty() { return nums; } let n = nums.len() - 1; quick_sort_internally(&mut nums, 0, n); nums } fn quick_sort_internally(nums: &mut Vec<i3
, end: usize) { if start >= end { return; } // 分区点 let pivot = partition(nums, start, end); if pivot!= 0 { quick_sort_internally(nums, start, pivot-1); } quick_sort_internally(nums, pivot+1, end); } fn partition(nums: &mut Vec<i32>, start: usize, end: usize) -> usize { let pivot = nums[end]; let mut i = start; for j in start..end { if nums[j] < pivot { swap(nums, i, j); i += 1; } } swap(nums, i, end); i } fn swap(nums: &mut Vec<i32>, i: usize, j: usize) { if i == j { return; } let tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } fn main() { let nums = vec![2, 5, 3, 0, 2, 3, 0, 3]; let m = bucket_sort(nums, 3); println!("{:?}", m); }
2>, start: usize
conditional_block
bucket_sort.rs
/// 桶排序 /// 时间复杂度:O(n), 稳定排序 // 桶排序 pub fn bucket_sort(mut nums: Vec<i32>, step: i32) -> Vec<i32> { let (mut min, mut max) = (nums[0], nums[0]); for i in 0..nums.len() { if min > nums[i] { min = nums[i]; } if max < nums[i] { max = nums[i]; } } // 设置需要的桶的数量 let bucket_num = (max - min) / step + 1; let mut bucket_list: Vec<Vec<i32>> = vec![vec![]; bucket_num as usize]; // 将 nums 数组中元素分别装入桶中 for i in 0..nums.len() { // 计算桶 index let index = (nums[i] - min) / step; bucket_list[index as usize].push(nums[i]); } let mut index = 0; for i in 0..bucket_num { let bucket = &bucket_list[i as usize]; // 对每个桶中元素使用快排进行排序 let new_bucket = quick_sort(bucket.to_vec()); // 将已经排序好的桶中元素拷贝到 nums 数组中 for num in new_bucket.into_iter() { nums[index as usize] = num; index += 1; } } nums } pub fn quick_sort(mut nums: Vec<i32>) -> Vec<i32> { if nums.is_empty() { return nums; } let n = nums.len() - 1; quick_sort_internally(&mut nums, 0, n); nums } fn quick_sort_internally(nums: &mut Vec<i32>, start: usize, end: usize) { if start >= end { return; } // 分区点 let pivot = partition(nums, start, end); if pivot!= 0 { quick_sort_internally(nums, start, pivot-1); } quick_sort_internally(nums, pivot+1, end); } fn partition(nums: &mut Vec<i32>, start: usize, end: usize) -> usize { let pivot = nums[end]; let mut i = start; for j in start..end { if nums[j] < pivot { swap(nums, i, j); i += 1; } } swap(nums, i, end); i } fn swap(nums: &mut Vec<i32>, i: usize, j: usize) { if i == j { return; } let tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } fn main
let nums = vec![2, 5, 3, 0, 2, 3, 0, 3]; let m = bucket_sort(nums, 3); println!("{:?}", m); }
() {
identifier_name
bucket_sort.rs
/// 桶排序 /// 时间复杂度:O(n), 稳定排序 // 桶排序 pub fn bucket_sort(mut nums: Vec<i32>, step: i32) -> Vec<i32> { let (mut min, mut max) = (nums[0], nums[0]); for i in 0..nums.len() { if min > nums[i] { min = nums[i]; } if max < nums[i] { max = nums[i]; } } // 设置需要的桶的数量 let bucket_num = (max - min) / step + 1; let mut bucket_list: Vec<Vec<i32>> = vec![vec![]; bucket_num as usize]; // 将 nums 数组中元素分别装入桶中 for i in 0..nums.len() { // 计算桶 index let index = (nums[i] - min) / step; bucket_list[index as usize].push(nums[i]); } let mut index = 0; for i in 0..bucket_num { let bucket = &bucket_list[i as usize]; // 对每个桶中元素使用快排进行排序 let new_bucket = quick_sort(bucket.to_vec()); // 将已经排序好的桶中元素拷贝到 nums 数组中 for num in new_bucket.into_iter() { nums[index as usize] = num; index += 1; } } nums } pub fn quick_sort(mut nums: Vec<i32>) -> Vec<i32> { if nums.is_empty() { return nums; } let n = nums.len() - 1; quick_sort_internally(&mut nums, 0, n); nums } fn quick_sort_internally(nums: &mut Vec<i32>, start: usize, end: usize) { if start >= end { return; } // 分区点 let pivot = partition(nums, start, end); if pivot!= 0 { quick_sort_internally(nums, start, pivot-1); } quick_sort_internally(nums, pivot+1, end); } fn partition(nums: &mut Vec<i32>, start: usize, end: usize) -> usize { let pivot = nums[end]; let mut i = start; for j in start..end { if nums[j] < pivot { swap(nums, i, j); i
main() { let nums = vec![2, 5, 3, 0, 2, 3, 0, 3]; let m = bucket_sort(nums, 3); println!("{:?}", m); }
+= 1; } } swap(nums, i, end); i } fn swap(nums: &mut Vec<i32>, i: usize, j: usize) { if i == j { return; } let tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } fn
identifier_body
bucket_sort.rs
/// 桶排序 /// 时间复杂度:O(n), 稳定排序 // 桶排序 pub fn bucket_sort(mut nums: Vec<i32>, step: i32) -> Vec<i32> { let (mut min, mut max) = (nums[0], nums[0]); for i in 0..nums.len() { if min > nums[i] { min = nums[i]; } if max < nums[i] { max = nums[i]; } } // 设置需要的桶的数量 let bucket_num = (max - min) / step + 1; let mut bucket_list: Vec<Vec<i32>> = vec![vec![]; bucket_num as usize]; // 将 nums 数组中元素分别装入桶中 for i in 0..nums.len() { // 计算桶 index let index = (nums[i] - min) / step; bucket_list[index as usize].push(nums[i]); } let mut index = 0; for i in 0..bucket_num { let bucket = &bucket_list[i as usize]; // 对每个桶中元素使用快排进行排序 let new_bucket = quick_sort(bucket.to_vec()); // 将已经排序好的桶中元素拷贝到 nums 数组中 for num in new_bucket.into_iter() {
index += 1; } } nums } pub fn quick_sort(mut nums: Vec<i32>) -> Vec<i32> { if nums.is_empty() { return nums; } let n = nums.len() - 1; quick_sort_internally(&mut nums, 0, n); nums } fn quick_sort_internally(nums: &mut Vec<i32>, start: usize, end: usize) { if start >= end { return; } // 分区点 let pivot = partition(nums, start, end); if pivot!= 0 { quick_sort_internally(nums, start, pivot-1); } quick_sort_internally(nums, pivot+1, end); } fn partition(nums: &mut Vec<i32>, start: usize, end: usize) -> usize { let pivot = nums[end]; let mut i = start; for j in start..end { if nums[j] < pivot { swap(nums, i, j); i += 1; } } swap(nums, i, end); i } fn swap(nums: &mut Vec<i32>, i: usize, j: usize) { if i == j { return; } let tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } fn main() { let nums = vec![2, 5, 3, 0, 2, 3, 0, 3]; let m = bucket_sort(nums, 3); println!("{:?}", m); }
nums[index as usize] = num;
random_line_split
main.rs
// Configure jemalloc as the `global_allocator` when configured. This is // so that we use the sized deallocation apis jemalloc provides // (namely `sdallocx`). // // The symbol overrides documented below are also performed so that we can // ensure that we use a consistent allocator across the rustc <-> llvm boundary #[cfg(feature = "jemalloc")] #[global_allocator] static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; #[cfg(feature = "tikv-jemalloc-sys")] use tikv_jemalloc_sys as jemalloc_sys; fn
() { // Pull in jemalloc when enabled. // // Note that we're pulling in a static copy of jemalloc which means that to // pull it in we need to actually reference its symbols for it to get // linked. The two crates we link to here, std and rustc_driver, are both // dynamic libraries. That means to pull in jemalloc we actually need to // reference allocation symbols one way or another (as this file is the only // object code in the rustc executable). #[cfg(feature = "tikv-jemalloc-sys")] { use std::os::raw::{c_int, c_void}; #[used] static _F1: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::calloc; #[used] static _F2: unsafe extern "C" fn(*mut *mut c_void, usize, usize) -> c_int = jemalloc_sys::posix_memalign; #[used] static _F3: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::aligned_alloc; #[used] static _F4: unsafe extern "C" fn(usize) -> *mut c_void = jemalloc_sys::malloc; #[used] static _F5: unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void = jemalloc_sys::realloc; #[used] static _F6: unsafe extern "C" fn(*mut c_void) = jemalloc_sys::free; // On OSX, jemalloc doesn't directly override malloc/free, but instead // registers itself with the allocator's zone APIs in a ctor. However, // the linker doesn't seem to consider ctors as "used" when statically // linking, so we need to explicitly depend on the function. #[cfg(target_os = "macos")] { extern "C" { fn _rjem_je_zone_register(); } #[used] static _F7: unsafe extern "C" fn() = _rjem_je_zone_register; } } rustc_driver::set_sigpipe_handler(); rustc_driver::main() }
main
identifier_name
main.rs
// Configure jemalloc as the `global_allocator` when configured. This is // so that we use the sized deallocation apis jemalloc provides // (namely `sdallocx`). // // The symbol overrides documented below are also performed so that we can // ensure that we use a consistent allocator across the rustc <-> llvm boundary #[cfg(feature = "jemalloc")] #[global_allocator] static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; #[cfg(feature = "tikv-jemalloc-sys")] use tikv_jemalloc_sys as jemalloc_sys; fn main()
#[used] static _F4: unsafe extern "C" fn(usize) -> *mut c_void = jemalloc_sys::malloc; #[used] static _F5: unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void = jemalloc_sys::realloc; #[used] static _F6: unsafe extern "C" fn(*mut c_void) = jemalloc_sys::free; // On OSX, jemalloc doesn't directly override malloc/free, but instead // registers itself with the allocator's zone APIs in a ctor. However, // the linker doesn't seem to consider ctors as "used" when statically // linking, so we need to explicitly depend on the function. #[cfg(target_os = "macos")] { extern "C" { fn _rjem_je_zone_register(); } #[used] static _F7: unsafe extern "C" fn() = _rjem_je_zone_register; } } rustc_driver::set_sigpipe_handler(); rustc_driver::main() }
{ // Pull in jemalloc when enabled. // // Note that we're pulling in a static copy of jemalloc which means that to // pull it in we need to actually reference its symbols for it to get // linked. The two crates we link to here, std and rustc_driver, are both // dynamic libraries. That means to pull in jemalloc we actually need to // reference allocation symbols one way or another (as this file is the only // object code in the rustc executable). #[cfg(feature = "tikv-jemalloc-sys")] { use std::os::raw::{c_int, c_void}; #[used] static _F1: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::calloc; #[used] static _F2: unsafe extern "C" fn(*mut *mut c_void, usize, usize) -> c_int = jemalloc_sys::posix_memalign; #[used] static _F3: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::aligned_alloc;
identifier_body
main.rs
// Configure jemalloc as the `global_allocator` when configured. This is // so that we use the sized deallocation apis jemalloc provides // (namely `sdallocx`). //
// The symbol overrides documented below are also performed so that we can // ensure that we use a consistent allocator across the rustc <-> llvm boundary #[cfg(feature = "jemalloc")] #[global_allocator] static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; #[cfg(feature = "tikv-jemalloc-sys")] use tikv_jemalloc_sys as jemalloc_sys; fn main() { // Pull in jemalloc when enabled. // // Note that we're pulling in a static copy of jemalloc which means that to // pull it in we need to actually reference its symbols for it to get // linked. The two crates we link to here, std and rustc_driver, are both // dynamic libraries. That means to pull in jemalloc we actually need to // reference allocation symbols one way or another (as this file is the only // object code in the rustc executable). #[cfg(feature = "tikv-jemalloc-sys")] { use std::os::raw::{c_int, c_void}; #[used] static _F1: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::calloc; #[used] static _F2: unsafe extern "C" fn(*mut *mut c_void, usize, usize) -> c_int = jemalloc_sys::posix_memalign; #[used] static _F3: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::aligned_alloc; #[used] static _F4: unsafe extern "C" fn(usize) -> *mut c_void = jemalloc_sys::malloc; #[used] static _F5: unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void = jemalloc_sys::realloc; #[used] static _F6: unsafe extern "C" fn(*mut c_void) = jemalloc_sys::free; // On OSX, jemalloc doesn't directly override malloc/free, but instead // registers itself with the allocator's zone APIs in a ctor. However, // the linker doesn't seem to consider ctors as "used" when statically // linking, so we need to explicitly depend on the function. #[cfg(target_os = "macos")] { extern "C" { fn _rjem_je_zone_register(); } #[used] static _F7: unsafe extern "C" fn() = _rjem_je_zone_register; } } rustc_driver::set_sigpipe_handler(); rustc_driver::main() }
random_line_split
name_pool.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 std::cast; use std::libc::c_char; pub struct NamePool { strbufs: ~[~[u8]] } pub fn NamePool() -> @mut NamePool
impl NamePool { pub fn add(&mut self, s: ~str) -> *c_char { unsafe { let mut strbuf = ~[]; for i in range(0, s.len()) { strbuf.push(s[i]); } strbuf.push(0); self.strbufs.push(strbuf); return cast::transmute(&self.strbufs[self.strbufs.len() - 1][0]); } } }
{ @mut NamePool { strbufs: ~[] } }
identifier_body
name_pool.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 std::cast; use std::libc::c_char; pub struct NamePool { strbufs: ~[~[u8]]
pub fn NamePool() -> @mut NamePool { @mut NamePool { strbufs: ~[] } } impl NamePool { pub fn add(&mut self, s: ~str) -> *c_char { unsafe { let mut strbuf = ~[]; for i in range(0, s.len()) { strbuf.push(s[i]); } strbuf.push(0); self.strbufs.push(strbuf); return cast::transmute(&self.strbufs[self.strbufs.len() - 1][0]); } } }
}
random_line_split
name_pool.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 std::cast; use std::libc::c_char; pub struct NamePool { strbufs: ~[~[u8]] } pub fn NamePool() -> @mut NamePool { @mut NamePool { strbufs: ~[] } } impl NamePool { pub fn
(&mut self, s: ~str) -> *c_char { unsafe { let mut strbuf = ~[]; for i in range(0, s.len()) { strbuf.push(s[i]); } strbuf.push(0); self.strbufs.push(strbuf); return cast::transmute(&self.strbufs[self.strbufs.len() - 1][0]); } } }
add
identifier_name
run.rs
// Copyright 2017, 2019 Guanhao Yin <[email protected]> // This file is part of TiTun. // TiTun 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. // TiTun 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 TiTun. If not, see <https://www.gnu.org/licenses/>. use crate::async_utils::AsyncScope; #[cfg(unix)] use crate::cli::daemonize::NotifyHandle; use crate::cli::network_config::network_config; use crate::cli::Config; use crate::ipc::ipc_server; use crate::wireguard::*; use anyhow::Context; use std::net::*; use tokio::sync::oneshot; #[cfg(not(unix))] type NotifyHandle = (); #[cfg(unix)] async fn do_reload( config_file_path: std::path::PathBuf, wg: &std::sync::Arc<WgState>, ) -> anyhow::Result<()> { let new_config = tokio::task::spawn_blocking(move || super::load_config_from_path(&config_file_path, false)) .await .expect("join load_config_from_path")?; crate::cli::reload(wg, new_config).await } #[cfg(unix)] async fn reload_on_sighup( config_file_path: Option<std::path::PathBuf>, weak: std::sync::Weak<WgState>, ) -> anyhow::Result<()> { use tokio::signal::unix::{signal, SignalKind}; let mut hangups = signal(SignalKind::hangup())?; while hangups.recv().await.is_some() { if let Some(ref config_file_path) = config_file_path { if let Some(wg) = weak.upgrade() { info!("reloading"); do_reload(config_file_path.clone(), &wg) .await .unwrap_or_else(|e| warn!("error in reloading: {:#}", e)); } } } Ok(()) } pub async fn run( c: Config<SocketAddr>, notify: Option<NotifyHandle>, stop_rx: Option<oneshot::Receiver<()>>, ) -> anyhow::Result<()> { #[cfg(unix)] let mut c = c; let scope0 = AsyncScope::new(); scope0.spawn_canceller(async move { tokio::signal::ctrl_c() .await .unwrap_or_else(|e| warn!("ctrl_c failed: {:#}", e)); info!("Received SIGINT or Ctrl-C, shutting down."); }); if let Some(stop_rx) = stop_rx { scope0.spawn_canceller(async move { stop_rx.await.unwrap(); }); } #[cfg(unix)] scope0.spawn_canceller(async move { use tokio::signal::unix::{signal, SignalKind}; let mut term = signal(SignalKind::terminate()).unwrap(); term.recv().await; info!("Received SIGTERM, shutting down."); }); let dev_name = c.interface.name.clone().unwrap(); let tun = AsyncTun::open(&dev_name).context("failed to open tun interface")?; if let Err(e) = network_config(&c).await { warn!("failed to configure network: {:#}", e); } let wg = WgState::new(tun)?; info!("setting privatge key"); wg.set_key(c.interface.private_key); if let Some(port) = c.interface.listen_port { info!("setting port"); wg.set_port(port).await.context("failed to set port")?; } if let Some(fwmark) = c.interface.fwmark { info!("setting fwmark"); wg.set_fwmark(fwmark).context("failed to set fwmark")?; } for p in c.peers { info!("adding peer {}", base64::encode(&p.public_key)); wg.add_peer(&p.public_key)?; wg.set_peer(SetPeerCommand { public_key: p.public_key, preshared_key: p.preshared_key, endpoint: p.endpoint, keepalive: p.keepalive.map(|x| x.get()), replace_allowed_ips: true, allowed_ips: p.allowed_ips, })?; } let weak = std::sync::Arc::downgrade(&wg); scope0.spawn_canceller(wg.clone().task_update_cookie_secret()); #[cfg(not(windows))] scope0.spawn_canceller(wg.clone().task_update_mtu()); scope0.spawn_canceller(wg.clone().task_rx()); scope0.spawn_canceller(wg.clone().task_tx()); #[cfg(unix)] { let weak1 = weak.clone(); let config_file_path = c.general.config_file_path.take(); scope0.spawn_canceller(async move { reload_on_sighup(config_file_path, weak1) .await .unwrap_or_else(|e| warn!("error in reload_on_sighup: {:#}", e)) }); } let (ready_tx, ready_rx) = tokio::sync::oneshot::channel::<()>(); scope0.spawn_canceller(async move { ipc_server(weak, &dev_name, ready_tx) .await .unwrap_or_else(|e| error!("IPC server error: {:#}", e)) }); if ready_rx.await.is_ok() { #[cfg(unix)] { if c.general.group.is_some() || c.general.user.is_some() { let p = privdrop::PrivDrop::default(); let p = if let Some(ref user) = c.general.user { p.user(user) } else { p }; let p = if let Some(ref group) = c.general.group { p.group(group) } else { p }; p.apply().context("failed to change user and group")?; } if c.general.foreground
else { notify .unwrap() .notify(0) .context("failed to notify grand parent")?; } } // So rustc does not warn about unused. #[cfg(not(unix))] let _notify = notify; } scope0.cancelled().await; Ok(()) }
{ super::systemd::notify_ready() .unwrap_or_else(|e| warn!("failed to notify systemd: {:#}", e)); }
conditional_block
run.rs
// Copyright 2017, 2019 Guanhao Yin <[email protected]> // This file is part of TiTun. // TiTun 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. // TiTun 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 TiTun. If not, see <https://www.gnu.org/licenses/>. use crate::async_utils::AsyncScope; #[cfg(unix)] use crate::cli::daemonize::NotifyHandle; use crate::cli::network_config::network_config; use crate::cli::Config; use crate::ipc::ipc_server; use crate::wireguard::*; use anyhow::Context; use std::net::*; use tokio::sync::oneshot; #[cfg(not(unix))] type NotifyHandle = (); #[cfg(unix)] async fn do_reload( config_file_path: std::path::PathBuf, wg: &std::sync::Arc<WgState>, ) -> anyhow::Result<()> { let new_config = tokio::task::spawn_blocking(move || super::load_config_from_path(&config_file_path, false)) .await .expect("join load_config_from_path")?; crate::cli::reload(wg, new_config).await } #[cfg(unix)] async fn reload_on_sighup( config_file_path: Option<std::path::PathBuf>, weak: std::sync::Weak<WgState>, ) -> anyhow::Result<()> { use tokio::signal::unix::{signal, SignalKind}; let mut hangups = signal(SignalKind::hangup())?; while hangups.recv().await.is_some() { if let Some(ref config_file_path) = config_file_path { if let Some(wg) = weak.upgrade() { info!("reloading"); do_reload(config_file_path.clone(), &wg) .await .unwrap_or_else(|e| warn!("error in reloading: {:#}", e)); } } } Ok(()) } pub async fn run( c: Config<SocketAddr>, notify: Option<NotifyHandle>, stop_rx: Option<oneshot::Receiver<()>>, ) -> anyhow::Result<()>
use tokio::signal::unix::{signal, SignalKind}; let mut term = signal(SignalKind::terminate()).unwrap(); term.recv().await; info!("Received SIGTERM, shutting down."); }); let dev_name = c.interface.name.clone().unwrap(); let tun = AsyncTun::open(&dev_name).context("failed to open tun interface")?; if let Err(e) = network_config(&c).await { warn!("failed to configure network: {:#}", e); } let wg = WgState::new(tun)?; info!("setting privatge key"); wg.set_key(c.interface.private_key); if let Some(port) = c.interface.listen_port { info!("setting port"); wg.set_port(port).await.context("failed to set port")?; } if let Some(fwmark) = c.interface.fwmark { info!("setting fwmark"); wg.set_fwmark(fwmark).context("failed to set fwmark")?; } for p in c.peers { info!("adding peer {}", base64::encode(&p.public_key)); wg.add_peer(&p.public_key)?; wg.set_peer(SetPeerCommand { public_key: p.public_key, preshared_key: p.preshared_key, endpoint: p.endpoint, keepalive: p.keepalive.map(|x| x.get()), replace_allowed_ips: true, allowed_ips: p.allowed_ips, })?; } let weak = std::sync::Arc::downgrade(&wg); scope0.spawn_canceller(wg.clone().task_update_cookie_secret()); #[cfg(not(windows))] scope0.spawn_canceller(wg.clone().task_update_mtu()); scope0.spawn_canceller(wg.clone().task_rx()); scope0.spawn_canceller(wg.clone().task_tx()); #[cfg(unix)] { let weak1 = weak.clone(); let config_file_path = c.general.config_file_path.take(); scope0.spawn_canceller(async move { reload_on_sighup(config_file_path, weak1) .await .unwrap_or_else(|e| warn!("error in reload_on_sighup: {:#}", e)) }); } let (ready_tx, ready_rx) = tokio::sync::oneshot::channel::<()>(); scope0.spawn_canceller(async move { ipc_server(weak, &dev_name, ready_tx) .await .unwrap_or_else(|e| error!("IPC server error: {:#}", e)) }); if ready_rx.await.is_ok() { #[cfg(unix)] { if c.general.group.is_some() || c.general.user.is_some() { let p = privdrop::PrivDrop::default(); let p = if let Some(ref user) = c.general.user { p.user(user) } else { p }; let p = if let Some(ref group) = c.general.group { p.group(group) } else { p }; p.apply().context("failed to change user and group")?; } if c.general.foreground { super::systemd::notify_ready() .unwrap_or_else(|e| warn!("failed to notify systemd: {:#}", e)); } else { notify .unwrap() .notify(0) .context("failed to notify grand parent")?; } } // So rustc does not warn about unused. #[cfg(not(unix))] let _notify = notify; } scope0.cancelled().await; Ok(()) }
{ #[cfg(unix)] let mut c = c; let scope0 = AsyncScope::new(); scope0.spawn_canceller(async move { tokio::signal::ctrl_c() .await .unwrap_or_else(|e| warn!("ctrl_c failed: {:#}", e)); info!("Received SIGINT or Ctrl-C, shutting down."); }); if let Some(stop_rx) = stop_rx { scope0.spawn_canceller(async move { stop_rx.await.unwrap(); }); } #[cfg(unix)] scope0.spawn_canceller(async move {
identifier_body
run.rs
// Copyright 2017, 2019 Guanhao Yin <[email protected]> // This file is part of TiTun. // TiTun 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. // TiTun 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 TiTun. If not, see <https://www.gnu.org/licenses/>. use crate::async_utils::AsyncScope; #[cfg(unix)] use crate::cli::daemonize::NotifyHandle; use crate::cli::network_config::network_config; use crate::cli::Config; use crate::ipc::ipc_server; use crate::wireguard::*; use anyhow::Context; use std::net::*; use tokio::sync::oneshot; #[cfg(not(unix))] type NotifyHandle = (); #[cfg(unix)] async fn do_reload( config_file_path: std::path::PathBuf, wg: &std::sync::Arc<WgState>, ) -> anyhow::Result<()> { let new_config = tokio::task::spawn_blocking(move || super::load_config_from_path(&config_file_path, false)) .await .expect("join load_config_from_path")?; crate::cli::reload(wg, new_config).await } #[cfg(unix)] async fn
( config_file_path: Option<std::path::PathBuf>, weak: std::sync::Weak<WgState>, ) -> anyhow::Result<()> { use tokio::signal::unix::{signal, SignalKind}; let mut hangups = signal(SignalKind::hangup())?; while hangups.recv().await.is_some() { if let Some(ref config_file_path) = config_file_path { if let Some(wg) = weak.upgrade() { info!("reloading"); do_reload(config_file_path.clone(), &wg) .await .unwrap_or_else(|e| warn!("error in reloading: {:#}", e)); } } } Ok(()) } pub async fn run( c: Config<SocketAddr>, notify: Option<NotifyHandle>, stop_rx: Option<oneshot::Receiver<()>>, ) -> anyhow::Result<()> { #[cfg(unix)] let mut c = c; let scope0 = AsyncScope::new(); scope0.spawn_canceller(async move { tokio::signal::ctrl_c() .await .unwrap_or_else(|e| warn!("ctrl_c failed: {:#}", e)); info!("Received SIGINT or Ctrl-C, shutting down."); }); if let Some(stop_rx) = stop_rx { scope0.spawn_canceller(async move { stop_rx.await.unwrap(); }); } #[cfg(unix)] scope0.spawn_canceller(async move { use tokio::signal::unix::{signal, SignalKind}; let mut term = signal(SignalKind::terminate()).unwrap(); term.recv().await; info!("Received SIGTERM, shutting down."); }); let dev_name = c.interface.name.clone().unwrap(); let tun = AsyncTun::open(&dev_name).context("failed to open tun interface")?; if let Err(e) = network_config(&c).await { warn!("failed to configure network: {:#}", e); } let wg = WgState::new(tun)?; info!("setting privatge key"); wg.set_key(c.interface.private_key); if let Some(port) = c.interface.listen_port { info!("setting port"); wg.set_port(port).await.context("failed to set port")?; } if let Some(fwmark) = c.interface.fwmark { info!("setting fwmark"); wg.set_fwmark(fwmark).context("failed to set fwmark")?; } for p in c.peers { info!("adding peer {}", base64::encode(&p.public_key)); wg.add_peer(&p.public_key)?; wg.set_peer(SetPeerCommand { public_key: p.public_key, preshared_key: p.preshared_key, endpoint: p.endpoint, keepalive: p.keepalive.map(|x| x.get()), replace_allowed_ips: true, allowed_ips: p.allowed_ips, })?; } let weak = std::sync::Arc::downgrade(&wg); scope0.spawn_canceller(wg.clone().task_update_cookie_secret()); #[cfg(not(windows))] scope0.spawn_canceller(wg.clone().task_update_mtu()); scope0.spawn_canceller(wg.clone().task_rx()); scope0.spawn_canceller(wg.clone().task_tx()); #[cfg(unix)] { let weak1 = weak.clone(); let config_file_path = c.general.config_file_path.take(); scope0.spawn_canceller(async move { reload_on_sighup(config_file_path, weak1) .await .unwrap_or_else(|e| warn!("error in reload_on_sighup: {:#}", e)) }); } let (ready_tx, ready_rx) = tokio::sync::oneshot::channel::<()>(); scope0.spawn_canceller(async move { ipc_server(weak, &dev_name, ready_tx) .await .unwrap_or_else(|e| error!("IPC server error: {:#}", e)) }); if ready_rx.await.is_ok() { #[cfg(unix)] { if c.general.group.is_some() || c.general.user.is_some() { let p = privdrop::PrivDrop::default(); let p = if let Some(ref user) = c.general.user { p.user(user) } else { p }; let p = if let Some(ref group) = c.general.group { p.group(group) } else { p }; p.apply().context("failed to change user and group")?; } if c.general.foreground { super::systemd::notify_ready() .unwrap_or_else(|e| warn!("failed to notify systemd: {:#}", e)); } else { notify .unwrap() .notify(0) .context("failed to notify grand parent")?; } } // So rustc does not warn about unused. #[cfg(not(unix))] let _notify = notify; } scope0.cancelled().await; Ok(()) }
reload_on_sighup
identifier_name
run.rs
// Copyright 2017, 2019 Guanhao Yin <[email protected]> // This file is part of TiTun. // TiTun 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. // TiTun 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 TiTun. If not, see <https://www.gnu.org/licenses/>. use crate::async_utils::AsyncScope; #[cfg(unix)] use crate::cli::daemonize::NotifyHandle; use crate::cli::network_config::network_config; use crate::cli::Config; use crate::ipc::ipc_server; use crate::wireguard::*; use anyhow::Context; use std::net::*; use tokio::sync::oneshot; #[cfg(not(unix))] type NotifyHandle = (); #[cfg(unix)] async fn do_reload( config_file_path: std::path::PathBuf, wg: &std::sync::Arc<WgState>, ) -> anyhow::Result<()> { let new_config = tokio::task::spawn_blocking(move || super::load_config_from_path(&config_file_path, false)) .await .expect("join load_config_from_path")?; crate::cli::reload(wg, new_config).await } #[cfg(unix)] async fn reload_on_sighup( config_file_path: Option<std::path::PathBuf>, weak: std::sync::Weak<WgState>, ) -> anyhow::Result<()> { use tokio::signal::unix::{signal, SignalKind}; let mut hangups = signal(SignalKind::hangup())?; while hangups.recv().await.is_some() { if let Some(ref config_file_path) = config_file_path { if let Some(wg) = weak.upgrade() { info!("reloading"); do_reload(config_file_path.clone(), &wg) .await .unwrap_or_else(|e| warn!("error in reloading: {:#}", e)); } } } Ok(()) } pub async fn run( c: Config<SocketAddr>, notify: Option<NotifyHandle>, stop_rx: Option<oneshot::Receiver<()>>, ) -> anyhow::Result<()> { #[cfg(unix)] let mut c = c;
.await .unwrap_or_else(|e| warn!("ctrl_c failed: {:#}", e)); info!("Received SIGINT or Ctrl-C, shutting down."); }); if let Some(stop_rx) = stop_rx { scope0.spawn_canceller(async move { stop_rx.await.unwrap(); }); } #[cfg(unix)] scope0.spawn_canceller(async move { use tokio::signal::unix::{signal, SignalKind}; let mut term = signal(SignalKind::terminate()).unwrap(); term.recv().await; info!("Received SIGTERM, shutting down."); }); let dev_name = c.interface.name.clone().unwrap(); let tun = AsyncTun::open(&dev_name).context("failed to open tun interface")?; if let Err(e) = network_config(&c).await { warn!("failed to configure network: {:#}", e); } let wg = WgState::new(tun)?; info!("setting privatge key"); wg.set_key(c.interface.private_key); if let Some(port) = c.interface.listen_port { info!("setting port"); wg.set_port(port).await.context("failed to set port")?; } if let Some(fwmark) = c.interface.fwmark { info!("setting fwmark"); wg.set_fwmark(fwmark).context("failed to set fwmark")?; } for p in c.peers { info!("adding peer {}", base64::encode(&p.public_key)); wg.add_peer(&p.public_key)?; wg.set_peer(SetPeerCommand { public_key: p.public_key, preshared_key: p.preshared_key, endpoint: p.endpoint, keepalive: p.keepalive.map(|x| x.get()), replace_allowed_ips: true, allowed_ips: p.allowed_ips, })?; } let weak = std::sync::Arc::downgrade(&wg); scope0.spawn_canceller(wg.clone().task_update_cookie_secret()); #[cfg(not(windows))] scope0.spawn_canceller(wg.clone().task_update_mtu()); scope0.spawn_canceller(wg.clone().task_rx()); scope0.spawn_canceller(wg.clone().task_tx()); #[cfg(unix)] { let weak1 = weak.clone(); let config_file_path = c.general.config_file_path.take(); scope0.spawn_canceller(async move { reload_on_sighup(config_file_path, weak1) .await .unwrap_or_else(|e| warn!("error in reload_on_sighup: {:#}", e)) }); } let (ready_tx, ready_rx) = tokio::sync::oneshot::channel::<()>(); scope0.spawn_canceller(async move { ipc_server(weak, &dev_name, ready_tx) .await .unwrap_or_else(|e| error!("IPC server error: {:#}", e)) }); if ready_rx.await.is_ok() { #[cfg(unix)] { if c.general.group.is_some() || c.general.user.is_some() { let p = privdrop::PrivDrop::default(); let p = if let Some(ref user) = c.general.user { p.user(user) } else { p }; let p = if let Some(ref group) = c.general.group { p.group(group) } else { p }; p.apply().context("failed to change user and group")?; } if c.general.foreground { super::systemd::notify_ready() .unwrap_or_else(|e| warn!("failed to notify systemd: {:#}", e)); } else { notify .unwrap() .notify(0) .context("failed to notify grand parent")?; } } // So rustc does not warn about unused. #[cfg(not(unix))] let _notify = notify; } scope0.cancelled().await; Ok(()) }
let scope0 = AsyncScope::new(); scope0.spawn_canceller(async move { tokio::signal::ctrl_c()
random_line_split
incremental.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 std::fmt; use std::sync::Arc; use style::ComputedValues; bitflags! { #[doc = "Individual layout actions that may be necessary after restyling."] flags RestyleDamage: int { #[doc = "Repaint the node itself."] #[doc = "Currently unused; need to decide how this propagates."] static Repaint = 0x01, #[doc = "Recompute intrinsic inline_sizes (minimum and preferred)."] #[doc = "Propagates down the flow tree because the computation is"] #[doc = "bottom-up."] static BubbleISizes = 0x02, #[doc = "Recompute actual inline_sizes and block_sizes."] #[doc = "Propagates up the flow tree because the computation is"] #[doc = "top-down."] static Reflow = 0x04 } } impl RestyleDamage { /// Elements of self which should also get set on any ancestor flow. pub fn
(self) -> RestyleDamage { self & Reflow } /// Elements of self which should also get set on any child flows. pub fn propagate_down(self) -> RestyleDamage { self & BubbleISizes } } impl fmt::Show for RestyleDamage { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::FormatError> { let mut first_elem = true; let to_iter = [ (Repaint, "Repaint") , (BubbleISizes, "BubbleISizes") , (Reflow, "Reflow") ]; for &(damage, damage_str) in to_iter.iter() { if self.contains(damage) { if!first_elem { try!(write!(f, " | ")); } try!(write!(f, "{}", damage_str)); first_elem = false; } } if first_elem { try!(write!(f, "NoDamage")); } Ok(()) } } // NB: We need the braces inside the RHS due to Rust #8012. This particular // version of this macro might be safe anyway, but we want to avoid silent // breakage on modifications. macro_rules! add_if_not_equal( ($old:ident, $new:ident, $damage:ident, [ $($effect:ident),* ], [ $($style_struct_getter:ident.$name:ident),* ]) => ({ if $( ($old.$style_struct_getter().$name!= $new.$style_struct_getter().$name) )||* { $damage.insert($($effect)|*); } }) ) pub fn compute_damage(old: &Option<Arc<ComputedValues>>, new: &ComputedValues) -> RestyleDamage { let old: &ComputedValues = match old.as_ref() { None => return Repaint | BubbleISizes | Reflow, Some(cv) => &**cv, }; let mut damage = RestyleDamage::empty(); // This checks every CSS property, as enumerated in // impl<'self> CssComputedStyle<'self> // in src/support/netsurfcss/rust-netsurfcss/netsurfcss.rc. // FIXME: We can short-circuit more of this. add_if_not_equal!(old, new, damage, [ Repaint ], [ get_color.color, get_background.background_color, get_border.border_top_color, get_border.border_right_color, get_border.border_bottom_color, get_border.border_left_color ]); add_if_not_equal!(old, new, damage, [ Repaint, BubbleISizes, Reflow ], [ get_border.border_top_width, get_border.border_right_width, get_border.border_bottom_width, get_border.border_left_width, get_margin.margin_top, get_margin.margin_right, get_margin.margin_bottom, get_margin.margin_left, get_padding.padding_top, get_padding.padding_right, get_padding.padding_bottom, get_padding.padding_left, get_box.position, get_box.width, get_box.height, get_box.float, get_box.display, get_font.font_family, get_font.font_size, get_font.font_style, get_font.font_weight, get_inheritedtext.text_align, get_text.text_decoration, get_inheritedbox.line_height ]); // FIXME: test somehow that we checked every CSS property damage }
propagate_up
identifier_name
incremental.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 std::fmt; use std::sync::Arc; use style::ComputedValues; bitflags! { #[doc = "Individual layout actions that may be necessary after restyling."] flags RestyleDamage: int { #[doc = "Repaint the node itself."] #[doc = "Currently unused; need to decide how this propagates."] static Repaint = 0x01, #[doc = "Recompute intrinsic inline_sizes (minimum and preferred)."] #[doc = "Propagates down the flow tree because the computation is"] #[doc = "bottom-up."] static BubbleISizes = 0x02, #[doc = "Recompute actual inline_sizes and block_sizes."] #[doc = "Propagates up the flow tree because the computation is"] #[doc = "top-down."] static Reflow = 0x04 } } impl RestyleDamage { /// Elements of self which should also get set on any ancestor flow. pub fn propagate_up(self) -> RestyleDamage { self & Reflow } /// Elements of self which should also get set on any child flows. pub fn propagate_down(self) -> RestyleDamage { self & BubbleISizes } } impl fmt::Show for RestyleDamage { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::FormatError> { let mut first_elem = true; let to_iter = [ (Repaint, "Repaint") , (BubbleISizes, "BubbleISizes") , (Reflow, "Reflow") ]; for &(damage, damage_str) in to_iter.iter() {
if self.contains(damage) { if!first_elem { try!(write!(f, " | ")); } try!(write!(f, "{}", damage_str)); first_elem = false; } } if first_elem { try!(write!(f, "NoDamage")); } Ok(()) } } // NB: We need the braces inside the RHS due to Rust #8012. This particular // version of this macro might be safe anyway, but we want to avoid silent // breakage on modifications. macro_rules! add_if_not_equal( ($old:ident, $new:ident, $damage:ident, [ $($effect:ident),* ], [ $($style_struct_getter:ident.$name:ident),* ]) => ({ if $( ($old.$style_struct_getter().$name!= $new.$style_struct_getter().$name) )||* { $damage.insert($($effect)|*); } }) ) pub fn compute_damage(old: &Option<Arc<ComputedValues>>, new: &ComputedValues) -> RestyleDamage { let old: &ComputedValues = match old.as_ref() { None => return Repaint | BubbleISizes | Reflow, Some(cv) => &**cv, }; let mut damage = RestyleDamage::empty(); // This checks every CSS property, as enumerated in // impl<'self> CssComputedStyle<'self> // in src/support/netsurfcss/rust-netsurfcss/netsurfcss.rc. // FIXME: We can short-circuit more of this. add_if_not_equal!(old, new, damage, [ Repaint ], [ get_color.color, get_background.background_color, get_border.border_top_color, get_border.border_right_color, get_border.border_bottom_color, get_border.border_left_color ]); add_if_not_equal!(old, new, damage, [ Repaint, BubbleISizes, Reflow ], [ get_border.border_top_width, get_border.border_right_width, get_border.border_bottom_width, get_border.border_left_width, get_margin.margin_top, get_margin.margin_right, get_margin.margin_bottom, get_margin.margin_left, get_padding.padding_top, get_padding.padding_right, get_padding.padding_bottom, get_padding.padding_left, get_box.position, get_box.width, get_box.height, get_box.float, get_box.display, get_font.font_family, get_font.font_size, get_font.font_style, get_font.font_weight, get_inheritedtext.text_align, get_text.text_decoration, get_inheritedbox.line_height ]); // FIXME: test somehow that we checked every CSS property damage }
random_line_split
incremental.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 std::fmt; use std::sync::Arc; use style::ComputedValues; bitflags! { #[doc = "Individual layout actions that may be necessary after restyling."] flags RestyleDamage: int { #[doc = "Repaint the node itself."] #[doc = "Currently unused; need to decide how this propagates."] static Repaint = 0x01, #[doc = "Recompute intrinsic inline_sizes (minimum and preferred)."] #[doc = "Propagates down the flow tree because the computation is"] #[doc = "bottom-up."] static BubbleISizes = 0x02, #[doc = "Recompute actual inline_sizes and block_sizes."] #[doc = "Propagates up the flow tree because the computation is"] #[doc = "top-down."] static Reflow = 0x04 } } impl RestyleDamage { /// Elements of self which should also get set on any ancestor flow. pub fn propagate_up(self) -> RestyleDamage { self & Reflow } /// Elements of self which should also get set on any child flows. pub fn propagate_down(self) -> RestyleDamage { self & BubbleISizes } } impl fmt::Show for RestyleDamage { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::FormatError> { let mut first_elem = true; let to_iter = [ (Repaint, "Repaint") , (BubbleISizes, "BubbleISizes") , (Reflow, "Reflow") ]; for &(damage, damage_str) in to_iter.iter() { if self.contains(damage)
} if first_elem { try!(write!(f, "NoDamage")); } Ok(()) } } // NB: We need the braces inside the RHS due to Rust #8012. This particular // version of this macro might be safe anyway, but we want to avoid silent // breakage on modifications. macro_rules! add_if_not_equal( ($old:ident, $new:ident, $damage:ident, [ $($effect:ident),* ], [ $($style_struct_getter:ident.$name:ident),* ]) => ({ if $( ($old.$style_struct_getter().$name!= $new.$style_struct_getter().$name) )||* { $damage.insert($($effect)|*); } }) ) pub fn compute_damage(old: &Option<Arc<ComputedValues>>, new: &ComputedValues) -> RestyleDamage { let old: &ComputedValues = match old.as_ref() { None => return Repaint | BubbleISizes | Reflow, Some(cv) => &**cv, }; let mut damage = RestyleDamage::empty(); // This checks every CSS property, as enumerated in // impl<'self> CssComputedStyle<'self> // in src/support/netsurfcss/rust-netsurfcss/netsurfcss.rc. // FIXME: We can short-circuit more of this. add_if_not_equal!(old, new, damage, [ Repaint ], [ get_color.color, get_background.background_color, get_border.border_top_color, get_border.border_right_color, get_border.border_bottom_color, get_border.border_left_color ]); add_if_not_equal!(old, new, damage, [ Repaint, BubbleISizes, Reflow ], [ get_border.border_top_width, get_border.border_right_width, get_border.border_bottom_width, get_border.border_left_width, get_margin.margin_top, get_margin.margin_right, get_margin.margin_bottom, get_margin.margin_left, get_padding.padding_top, get_padding.padding_right, get_padding.padding_bottom, get_padding.padding_left, get_box.position, get_box.width, get_box.height, get_box.float, get_box.display, get_font.font_family, get_font.font_size, get_font.font_style, get_font.font_weight, get_inheritedtext.text_align, get_text.text_decoration, get_inheritedbox.line_height ]); // FIXME: test somehow that we checked every CSS property damage }
{ if !first_elem { try!(write!(f, " | ")); } try!(write!(f, "{}", damage_str)); first_elem = false; }
conditional_block
incremental.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 std::fmt; use std::sync::Arc; use style::ComputedValues; bitflags! { #[doc = "Individual layout actions that may be necessary after restyling."] flags RestyleDamage: int { #[doc = "Repaint the node itself."] #[doc = "Currently unused; need to decide how this propagates."] static Repaint = 0x01, #[doc = "Recompute intrinsic inline_sizes (minimum and preferred)."] #[doc = "Propagates down the flow tree because the computation is"] #[doc = "bottom-up."] static BubbleISizes = 0x02, #[doc = "Recompute actual inline_sizes and block_sizes."] #[doc = "Propagates up the flow tree because the computation is"] #[doc = "top-down."] static Reflow = 0x04 } } impl RestyleDamage { /// Elements of self which should also get set on any ancestor flow. pub fn propagate_up(self) -> RestyleDamage { self & Reflow } /// Elements of self which should also get set on any child flows. pub fn propagate_down(self) -> RestyleDamage { self & BubbleISizes } } impl fmt::Show for RestyleDamage { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::FormatError>
Ok(()) } } // NB: We need the braces inside the RHS due to Rust #8012. This particular // version of this macro might be safe anyway, but we want to avoid silent // breakage on modifications. macro_rules! add_if_not_equal( ($old:ident, $new:ident, $damage:ident, [ $($effect:ident),* ], [ $($style_struct_getter:ident.$name:ident),* ]) => ({ if $( ($old.$style_struct_getter().$name!= $new.$style_struct_getter().$name) )||* { $damage.insert($($effect)|*); } }) ) pub fn compute_damage(old: &Option<Arc<ComputedValues>>, new: &ComputedValues) -> RestyleDamage { let old: &ComputedValues = match old.as_ref() { None => return Repaint | BubbleISizes | Reflow, Some(cv) => &**cv, }; let mut damage = RestyleDamage::empty(); // This checks every CSS property, as enumerated in // impl<'self> CssComputedStyle<'self> // in src/support/netsurfcss/rust-netsurfcss/netsurfcss.rc. // FIXME: We can short-circuit more of this. add_if_not_equal!(old, new, damage, [ Repaint ], [ get_color.color, get_background.background_color, get_border.border_top_color, get_border.border_right_color, get_border.border_bottom_color, get_border.border_left_color ]); add_if_not_equal!(old, new, damage, [ Repaint, BubbleISizes, Reflow ], [ get_border.border_top_width, get_border.border_right_width, get_border.border_bottom_width, get_border.border_left_width, get_margin.margin_top, get_margin.margin_right, get_margin.margin_bottom, get_margin.margin_left, get_padding.padding_top, get_padding.padding_right, get_padding.padding_bottom, get_padding.padding_left, get_box.position, get_box.width, get_box.height, get_box.float, get_box.display, get_font.font_family, get_font.font_size, get_font.font_style, get_font.font_weight, get_inheritedtext.text_align, get_text.text_decoration, get_inheritedbox.line_height ]); // FIXME: test somehow that we checked every CSS property damage }
{ let mut first_elem = true; let to_iter = [ (Repaint, "Repaint") , (BubbleISizes, "BubbleISizes") , (Reflow, "Reflow") ]; for &(damage, damage_str) in to_iter.iter() { if self.contains(damage) { if !first_elem { try!(write!(f, " | ")); } try!(write!(f, "{}", damage_str)); first_elem = false; } } if first_elem { try!(write!(f, "NoDamage")); }
identifier_body
mod.rs
//! This module provides the interface to different solvers. //! //! Both [`coin_cbc`](https://docs.rs/coin_cbc/latest/coin_cbc/) and //! [`minilp`](https://docs.rs/minilp/0.2.2/minilp/) are available as cargo //! [features](https://doc.rust-lang.org/cargo/reference/features.html). To use //! them, specify your dependency to `lp_modeler` accordingly in your `Cargo.toml` //! (note the name difference of the `native_coin_cbc` feature for the `coin_cbc` crate): //! ```toml //! [dependencies.lp_modeler] //! version = "4.3" //! features = "native_coin_cbc" //! ``` //! or: //! ```toml //! [dependencies.lp_modeler] //! version = "4.3" //! features = "minilp" //! ``` //! For `coin_cbc` to compile, the `Cbc` library files need to be available on your system. //! See the [`coin_cbc` project README](https://github.com/KardinalAI/coin_cbc) for more infos. //! //! The other solvers need to be installed externally on your system. //! The respective information is provided in the project's README in the section on //! [installing external solvers](https://github.com/jcavat/rust-lp-modeler#installing-external-solvers). use std::collections::HashMap; use dsl::{Problem, LpContinuous, LpBinary, LpInteger, LpProblem, LpExprNode, LpExprOp, LpExprArenaIndex}; pub mod cbc; pub use self::cbc::*; pub mod gurobi; pub use self::gurobi::*; pub mod glpk; pub use self::glpk::*; #[cfg(feature = "minilp")] pub mod minilp; #[cfg(feature = "minilp")] pub use self::minilp::*; #[cfg(feature = "native_coin_cbc")] pub mod native_cbc; #[cfg(feature = "native_coin_cbc")] pub use self::native_cbc::*; use std::fs::File; use std::fs; use util::is_zero; #[derive(Debug, PartialEq, Clone)] pub enum Status { Optimal, SubOptimal, Infeasible, Unbounded, NotSolved, } #[derive(Debug, Clone)] pub struct Solution<'a> { pub status: Status, pub results: HashMap<String, f32>, pub related_problem: Option<&'a LpProblem> } impl Solution<'_> { pub fn new<'a>(status: Status, results: HashMap<String, f32>) -> Solution<'a> { Solution { status, results, related_problem: None } } pub fn with_problem(status: Status, results: HashMap<String, f32>, problem: &LpProblem) -> Solution { Solution { status, results, related_problem: Some(problem) } } fn check_possible_solution(&self) { match &self.status { Status::Unbounded | Status::NotSolved | Status::Infeasible => panic!("Solution must be optimal or suboptimal"), _ => () } } pub fn get_raw_value(&self, name: &str) -> f32 { self.check_possible_solution(); *self.results.get(name).expect("No value found for this variable. Check if the variable has been used in the related problem.") } pub fn get_bool(&self, var: &LpBinary) -> bool { self.check_possible_solution(); self.results.get(&var.name).and_then(|&f| if is_zero(1.0-f) { Some(true) } else if is_zero(f) { Some(false) } else { None } ).expect("Result value cannot be interpreted as boolean") } pub fn get_float(&self, var: &LpContinuous) -> f32 { self.check_possible_solution(); *self.results.get(&var.name).expect("No value found for this variable. Check if the variable has been used in the related problem.") } pub fn get_int(&self, var: &LpInteger) -> i32 { self.check_possible_solution(); let &f = self.results.get(&var.name).expect("No value found for this variable. Check if the variable has been used in the related problem."); let i = f as i32; assert!( is_zero( f-(i as f32)), format!("Value {} cannot be interpreted as integer.", f) ); i } pub fn eval(&self) -> Option<f32> { self.related_problem .and_then( |problem| { match &problem.obj_expr_arena {
None => None } }) } fn eval_with(&self, index: &LpExprArenaIndex, values: &HashMap<String, f32>) -> f32 { match self.related_problem.unwrap().obj_expr_arena.as_ref().unwrap().expr_ref_at(*index) { LpExprNode::LpCompExpr(operation, left, right) => { match operation { LpExprOp::Addition => self.eval_with(left, values) + self.eval_with(right, values), LpExprOp::Multiplication => self.eval_with(left, values) * self.eval_with(right, values), LpExprOp::Subtraction => self.eval_with(left, values) - self.eval_with(right, values), } }, LpExprNode::ConsBin(LpBinary { name }) | LpExprNode::ConsCont(LpContinuous { name,.. }) | LpExprNode::ConsInt(LpInteger { name,.. }) => *values.get(name).unwrap_or(&0f32), LpExprNode::LitVal(n) => *n, LpExprNode::EmptyExpr => 0.0 } } } pub trait SolverTrait { type P: Problem; fn run<'a>(&self, problem: &'a Self::P) -> Result<Solution<'a>, String>; } pub trait SolverWithSolutionParsing { fn read_solution<'a>(&self, temp_solution_file: &String, problem: Option<&'a LpProblem>) -> Result<Solution<'a>, String> { match File::open( temp_solution_file ) { Ok(f) => { let res = self.read_specific_solution(&f, problem)?; let _ = fs::remove_file(temp_solution_file); Ok(res) } Err(_) => return Err("Cannot open file".to_string()), } } fn read_specific_solution<'a>(&self, f: &File, problem: Option<&'a LpProblem>) -> Result<Solution<'a>, String>; } pub trait WithMaxSeconds<T> { fn max_seconds(&self) -> Option<u32>; fn with_max_seconds(&self, seconds: u32) -> T; } pub trait WithNbThreads<T> { fn nb_threads(&self) -> Option<u32>; fn with_nb_threads(&self, threads: u32) -> T; }
Some(obj_expr_arena) => Some( self.eval_with(&obj_expr_arena.get_root_index(), &self.results) ),
random_line_split
mod.rs
//! This module provides the interface to different solvers. //! //! Both [`coin_cbc`](https://docs.rs/coin_cbc/latest/coin_cbc/) and //! [`minilp`](https://docs.rs/minilp/0.2.2/minilp/) are available as cargo //! [features](https://doc.rust-lang.org/cargo/reference/features.html). To use //! them, specify your dependency to `lp_modeler` accordingly in your `Cargo.toml` //! (note the name difference of the `native_coin_cbc` feature for the `coin_cbc` crate): //! ```toml //! [dependencies.lp_modeler] //! version = "4.3" //! features = "native_coin_cbc" //! ``` //! or: //! ```toml //! [dependencies.lp_modeler] //! version = "4.3" //! features = "minilp" //! ``` //! For `coin_cbc` to compile, the `Cbc` library files need to be available on your system. //! See the [`coin_cbc` project README](https://github.com/KardinalAI/coin_cbc) for more infos. //! //! The other solvers need to be installed externally on your system. //! The respective information is provided in the project's README in the section on //! [installing external solvers](https://github.com/jcavat/rust-lp-modeler#installing-external-solvers). use std::collections::HashMap; use dsl::{Problem, LpContinuous, LpBinary, LpInteger, LpProblem, LpExprNode, LpExprOp, LpExprArenaIndex}; pub mod cbc; pub use self::cbc::*; pub mod gurobi; pub use self::gurobi::*; pub mod glpk; pub use self::glpk::*; #[cfg(feature = "minilp")] pub mod minilp; #[cfg(feature = "minilp")] pub use self::minilp::*; #[cfg(feature = "native_coin_cbc")] pub mod native_cbc; #[cfg(feature = "native_coin_cbc")] pub use self::native_cbc::*; use std::fs::File; use std::fs; use util::is_zero; #[derive(Debug, PartialEq, Clone)] pub enum Status { Optimal, SubOptimal, Infeasible, Unbounded, NotSolved, } #[derive(Debug, Clone)] pub struct Solution<'a> { pub status: Status, pub results: HashMap<String, f32>, pub related_problem: Option<&'a LpProblem> } impl Solution<'_> { pub fn new<'a>(status: Status, results: HashMap<String, f32>) -> Solution<'a>
pub fn with_problem(status: Status, results: HashMap<String, f32>, problem: &LpProblem) -> Solution { Solution { status, results, related_problem: Some(problem) } } fn check_possible_solution(&self) { match &self.status { Status::Unbounded | Status::NotSolved | Status::Infeasible => panic!("Solution must be optimal or suboptimal"), _ => () } } pub fn get_raw_value(&self, name: &str) -> f32 { self.check_possible_solution(); *self.results.get(name).expect("No value found for this variable. Check if the variable has been used in the related problem.") } pub fn get_bool(&self, var: &LpBinary) -> bool { self.check_possible_solution(); self.results.get(&var.name).and_then(|&f| if is_zero(1.0-f) { Some(true) } else if is_zero(f) { Some(false) } else { None } ).expect("Result value cannot be interpreted as boolean") } pub fn get_float(&self, var: &LpContinuous) -> f32 { self.check_possible_solution(); *self.results.get(&var.name).expect("No value found for this variable. Check if the variable has been used in the related problem.") } pub fn get_int(&self, var: &LpInteger) -> i32 { self.check_possible_solution(); let &f = self.results.get(&var.name).expect("No value found for this variable. Check if the variable has been used in the related problem."); let i = f as i32; assert!( is_zero( f-(i as f32)), format!("Value {} cannot be interpreted as integer.", f) ); i } pub fn eval(&self) -> Option<f32> { self.related_problem .and_then( |problem| { match &problem.obj_expr_arena { Some(obj_expr_arena) => Some( self.eval_with(&obj_expr_arena.get_root_index(), &self.results) ), None => None } }) } fn eval_with(&self, index: &LpExprArenaIndex, values: &HashMap<String, f32>) -> f32 { match self.related_problem.unwrap().obj_expr_arena.as_ref().unwrap().expr_ref_at(*index) { LpExprNode::LpCompExpr(operation, left, right) => { match operation { LpExprOp::Addition => self.eval_with(left, values) + self.eval_with(right, values), LpExprOp::Multiplication => self.eval_with(left, values) * self.eval_with(right, values), LpExprOp::Subtraction => self.eval_with(left, values) - self.eval_with(right, values), } }, LpExprNode::ConsBin(LpBinary { name }) | LpExprNode::ConsCont(LpContinuous { name,.. }) | LpExprNode::ConsInt(LpInteger { name,.. }) => *values.get(name).unwrap_or(&0f32), LpExprNode::LitVal(n) => *n, LpExprNode::EmptyExpr => 0.0 } } } pub trait SolverTrait { type P: Problem; fn run<'a>(&self, problem: &'a Self::P) -> Result<Solution<'a>, String>; } pub trait SolverWithSolutionParsing { fn read_solution<'a>(&self, temp_solution_file: &String, problem: Option<&'a LpProblem>) -> Result<Solution<'a>, String> { match File::open( temp_solution_file ) { Ok(f) => { let res = self.read_specific_solution(&f, problem)?; let _ = fs::remove_file(temp_solution_file); Ok(res) } Err(_) => return Err("Cannot open file".to_string()), } } fn read_specific_solution<'a>(&self, f: &File, problem: Option<&'a LpProblem>) -> Result<Solution<'a>, String>; } pub trait WithMaxSeconds<T> { fn max_seconds(&self) -> Option<u32>; fn with_max_seconds(&self, seconds: u32) -> T; } pub trait WithNbThreads<T> { fn nb_threads(&self) -> Option<u32>; fn with_nb_threads(&self, threads: u32) -> T; }
{ Solution { status, results, related_problem: None } }
identifier_body
mod.rs
//! This module provides the interface to different solvers. //! //! Both [`coin_cbc`](https://docs.rs/coin_cbc/latest/coin_cbc/) and //! [`minilp`](https://docs.rs/minilp/0.2.2/minilp/) are available as cargo //! [features](https://doc.rust-lang.org/cargo/reference/features.html). To use //! them, specify your dependency to `lp_modeler` accordingly in your `Cargo.toml` //! (note the name difference of the `native_coin_cbc` feature for the `coin_cbc` crate): //! ```toml //! [dependencies.lp_modeler] //! version = "4.3" //! features = "native_coin_cbc" //! ``` //! or: //! ```toml //! [dependencies.lp_modeler] //! version = "4.3" //! features = "minilp" //! ``` //! For `coin_cbc` to compile, the `Cbc` library files need to be available on your system. //! See the [`coin_cbc` project README](https://github.com/KardinalAI/coin_cbc) for more infos. //! //! The other solvers need to be installed externally on your system. //! The respective information is provided in the project's README in the section on //! [installing external solvers](https://github.com/jcavat/rust-lp-modeler#installing-external-solvers). use std::collections::HashMap; use dsl::{Problem, LpContinuous, LpBinary, LpInteger, LpProblem, LpExprNode, LpExprOp, LpExprArenaIndex}; pub mod cbc; pub use self::cbc::*; pub mod gurobi; pub use self::gurobi::*; pub mod glpk; pub use self::glpk::*; #[cfg(feature = "minilp")] pub mod minilp; #[cfg(feature = "minilp")] pub use self::minilp::*; #[cfg(feature = "native_coin_cbc")] pub mod native_cbc; #[cfg(feature = "native_coin_cbc")] pub use self::native_cbc::*; use std::fs::File; use std::fs; use util::is_zero; #[derive(Debug, PartialEq, Clone)] pub enum Status { Optimal, SubOptimal, Infeasible, Unbounded, NotSolved, } #[derive(Debug, Clone)] pub struct Solution<'a> { pub status: Status, pub results: HashMap<String, f32>, pub related_problem: Option<&'a LpProblem> } impl Solution<'_> { pub fn
<'a>(status: Status, results: HashMap<String, f32>) -> Solution<'a> { Solution { status, results, related_problem: None } } pub fn with_problem(status: Status, results: HashMap<String, f32>, problem: &LpProblem) -> Solution { Solution { status, results, related_problem: Some(problem) } } fn check_possible_solution(&self) { match &self.status { Status::Unbounded | Status::NotSolved | Status::Infeasible => panic!("Solution must be optimal or suboptimal"), _ => () } } pub fn get_raw_value(&self, name: &str) -> f32 { self.check_possible_solution(); *self.results.get(name).expect("No value found for this variable. Check if the variable has been used in the related problem.") } pub fn get_bool(&self, var: &LpBinary) -> bool { self.check_possible_solution(); self.results.get(&var.name).and_then(|&f| if is_zero(1.0-f) { Some(true) } else if is_zero(f) { Some(false) } else { None } ).expect("Result value cannot be interpreted as boolean") } pub fn get_float(&self, var: &LpContinuous) -> f32 { self.check_possible_solution(); *self.results.get(&var.name).expect("No value found for this variable. Check if the variable has been used in the related problem.") } pub fn get_int(&self, var: &LpInteger) -> i32 { self.check_possible_solution(); let &f = self.results.get(&var.name).expect("No value found for this variable. Check if the variable has been used in the related problem."); let i = f as i32; assert!( is_zero( f-(i as f32)), format!("Value {} cannot be interpreted as integer.", f) ); i } pub fn eval(&self) -> Option<f32> { self.related_problem .and_then( |problem| { match &problem.obj_expr_arena { Some(obj_expr_arena) => Some( self.eval_with(&obj_expr_arena.get_root_index(), &self.results) ), None => None } }) } fn eval_with(&self, index: &LpExprArenaIndex, values: &HashMap<String, f32>) -> f32 { match self.related_problem.unwrap().obj_expr_arena.as_ref().unwrap().expr_ref_at(*index) { LpExprNode::LpCompExpr(operation, left, right) => { match operation { LpExprOp::Addition => self.eval_with(left, values) + self.eval_with(right, values), LpExprOp::Multiplication => self.eval_with(left, values) * self.eval_with(right, values), LpExprOp::Subtraction => self.eval_with(left, values) - self.eval_with(right, values), } }, LpExprNode::ConsBin(LpBinary { name }) | LpExprNode::ConsCont(LpContinuous { name,.. }) | LpExprNode::ConsInt(LpInteger { name,.. }) => *values.get(name).unwrap_or(&0f32), LpExprNode::LitVal(n) => *n, LpExprNode::EmptyExpr => 0.0 } } } pub trait SolverTrait { type P: Problem; fn run<'a>(&self, problem: &'a Self::P) -> Result<Solution<'a>, String>; } pub trait SolverWithSolutionParsing { fn read_solution<'a>(&self, temp_solution_file: &String, problem: Option<&'a LpProblem>) -> Result<Solution<'a>, String> { match File::open( temp_solution_file ) { Ok(f) => { let res = self.read_specific_solution(&f, problem)?; let _ = fs::remove_file(temp_solution_file); Ok(res) } Err(_) => return Err("Cannot open file".to_string()), } } fn read_specific_solution<'a>(&self, f: &File, problem: Option<&'a LpProblem>) -> Result<Solution<'a>, String>; } pub trait WithMaxSeconds<T> { fn max_seconds(&self) -> Option<u32>; fn with_max_seconds(&self, seconds: u32) -> T; } pub trait WithNbThreads<T> { fn nb_threads(&self) -> Option<u32>; fn with_nb_threads(&self, threads: u32) -> T; }
new
identifier_name
x86stdcall2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub type HANDLE = u32; pub type DWORD = u32; pub type SIZE_T = u32; pub type LPVOID = uint; pub type BOOL = u8; #[cfg(windows)] mod kernel32 { use super::{HANDLE, DWORD, SIZE_T, LPVOID, BOOL}; extern "system" { pub fn GetProcessHeap() -> HANDLE; pub fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID; pub fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID) -> BOOL; } } #[cfg(windows)] pub fn main() { let heap = unsafe { kernel32::GetProcessHeap() }; let mem = unsafe { kernel32::HeapAlloc(heap, 0u32, 100u32) }; assert!(mem!= 0u); let res = unsafe { kernel32::HeapFree(heap, 0u32, mem) };
assert!(res != 0u8); } #[cfg(not(windows))] pub fn main() { }
random_line_split
x86stdcall2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub type HANDLE = u32; pub type DWORD = u32; pub type SIZE_T = u32; pub type LPVOID = uint; pub type BOOL = u8; #[cfg(windows)] mod kernel32 { use super::{HANDLE, DWORD, SIZE_T, LPVOID, BOOL}; extern "system" { pub fn GetProcessHeap() -> HANDLE; pub fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID; pub fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID) -> BOOL; } } #[cfg(windows)] pub fn
() { let heap = unsafe { kernel32::GetProcessHeap() }; let mem = unsafe { kernel32::HeapAlloc(heap, 0u32, 100u32) }; assert!(mem!= 0u); let res = unsafe { kernel32::HeapFree(heap, 0u32, mem) }; assert!(res!= 0u8); } #[cfg(not(windows))] pub fn main() { }
main
identifier_name
x86stdcall2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub type HANDLE = u32; pub type DWORD = u32; pub type SIZE_T = u32; pub type LPVOID = uint; pub type BOOL = u8; #[cfg(windows)] mod kernel32 { use super::{HANDLE, DWORD, SIZE_T, LPVOID, BOOL}; extern "system" { pub fn GetProcessHeap() -> HANDLE; pub fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID; pub fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID) -> BOOL; } } #[cfg(windows)] pub fn main()
#[cfg(not(windows))] pub fn main() { }
{ let heap = unsafe { kernel32::GetProcessHeap() }; let mem = unsafe { kernel32::HeapAlloc(heap, 0u32, 100u32) }; assert!(mem != 0u); let res = unsafe { kernel32::HeapFree(heap, 0u32, mem) }; assert!(res != 0u8); }
identifier_body
inlining-issue67557-ice.rs
// This used to cause an ICE for an internal index out of range due to simd_shuffle_indices being // passed the wrong Instance, causing issues with inlining. See #67557. // // run-pass // compile-flags: -Zmir-opt-level=4 #![feature(platform_intrinsics, repr_simd)] extern "platform-intrinsic" { fn simd_shuffle2<T, U>(x: T, y: T, idx: [u32; 2]) -> U; } #[repr(simd)]
#[derive(Debug, PartialEq)] struct Simd2(u8, u8); fn main() { unsafe { let _: Simd2 = inline_me(); } } #[inline(always)] unsafe fn inline_me() -> Simd2 { const IDX: [u32; 2] = [0, 3]; simd_shuffle2(Simd2(10, 11), Simd2(12, 13), IDX) }
random_line_split
inlining-issue67557-ice.rs
// This used to cause an ICE for an internal index out of range due to simd_shuffle_indices being // passed the wrong Instance, causing issues with inlining. See #67557. // // run-pass // compile-flags: -Zmir-opt-level=4 #![feature(platform_intrinsics, repr_simd)] extern "platform-intrinsic" { fn simd_shuffle2<T, U>(x: T, y: T, idx: [u32; 2]) -> U; } #[repr(simd)] #[derive(Debug, PartialEq)] struct Simd2(u8, u8); fn main() { unsafe { let _: Simd2 = inline_me(); } } #[inline(always)] unsafe fn inline_me() -> Simd2
{ const IDX: [u32; 2] = [0, 3]; simd_shuffle2(Simd2(10, 11), Simd2(12, 13), IDX) }
identifier_body
inlining-issue67557-ice.rs
// This used to cause an ICE for an internal index out of range due to simd_shuffle_indices being // passed the wrong Instance, causing issues with inlining. See #67557. // // run-pass // compile-flags: -Zmir-opt-level=4 #![feature(platform_intrinsics, repr_simd)] extern "platform-intrinsic" { fn simd_shuffle2<T, U>(x: T, y: T, idx: [u32; 2]) -> U; } #[repr(simd)] #[derive(Debug, PartialEq)] struct Simd2(u8, u8); fn
() { unsafe { let _: Simd2 = inline_me(); } } #[inline(always)] unsafe fn inline_me() -> Simd2 { const IDX: [u32; 2] = [0, 3]; simd_shuffle2(Simd2(10, 11), Simd2(12, 13), IDX) }
main
identifier_name
error.rs
use std::error::Error; use std::fmt::{Display, Formatter}; use std::fmt::Result as FmtResult; use fmt::Format; pub type CliResult<T> = Result<T, CliError>; #[derive(Debug)] #[allow(dead_code)] pub enum CliError { Generic(String), UnknownExt(String), Unknown } // Copies clog::error::Error; impl CliError { /// Return whether this was a fatal error or not. #[allow(dead_code)] pub fn is_fatal(&self) -> bool { // For now all errors are fatal true } /// Print this error and immediately exit the program. /// /// If the error is non-fatal then the error is printed to stdout and the /// exit status will be `0`. Otherwise, when the error is fatal, the error /// is printed to stderr and the exit status will be `1`. pub fn exit(&self) ->! { if self.is_fatal() { wlnerr!("{}", self); ::std::process::exit(1) } else { println!("{}", self); ::std::process::exit(0) } } } impl Display for CliError { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "{} {}", Format::Error("error:"), self.description()) } } impl Error for CliError { fn
<'a>(&'a self) -> &'a str { match *self { CliError::Generic(ref d) => &*d, CliError::UnknownExt(ref d) => &*d, CliError::Unknown => "An unknown fatal error has occurred, please consider filing a bug-report!" } } fn cause(&self) -> Option<&Error> { match *self { CliError::Generic(..) => None, CliError::UnknownExt(..) => None, CliError::Unknown => None, } } }
description
identifier_name
error.rs
use std::error::Error; use std::fmt::{Display, Formatter}; use std::fmt::Result as FmtResult; use fmt::Format; pub type CliResult<T> = Result<T, CliError>; #[derive(Debug)] #[allow(dead_code)] pub enum CliError { Generic(String), UnknownExt(String), Unknown } // Copies clog::error::Error; impl CliError { /// Return whether this was a fatal error or not. #[allow(dead_code)] pub fn is_fatal(&self) -> bool { // For now all errors are fatal true } /// Print this error and immediately exit the program. /// /// If the error is non-fatal then the error is printed to stdout and the /// exit status will be `0`. Otherwise, when the error is fatal, the error /// is printed to stderr and the exit status will be `1`. pub fn exit(&self) ->! { if self.is_fatal() { wlnerr!("{}", self); ::std::process::exit(1) } else { println!("{}", self); ::std::process::exit(0) } } } impl Display for CliError { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "{} {}", Format::Error("error:"), self.description()) } } impl Error for CliError { fn description<'a>(&'a self) -> &'a str
fn cause(&self) -> Option<&Error> { match *self { CliError::Generic(..) => None, CliError::UnknownExt(..) => None, CliError::Unknown => None, } } }
{ match *self { CliError::Generic(ref d) => &*d, CliError::UnknownExt(ref d) => &*d, CliError::Unknown => "An unknown fatal error has occurred, please consider filing a bug-report!" } }
identifier_body
error.rs
use std::error::Error; use std::fmt::{Display, Formatter}; use std::fmt::Result as FmtResult; use fmt::Format; pub type CliResult<T> = Result<T, CliError>; #[derive(Debug)] #[allow(dead_code)] pub enum CliError { Generic(String), UnknownExt(String), Unknown } // Copies clog::error::Error; impl CliError { /// Return whether this was a fatal error or not. #[allow(dead_code)] pub fn is_fatal(&self) -> bool { // For now all errors are fatal true } /// Print this error and immediately exit the program. /// /// If the error is non-fatal then the error is printed to stdout and the /// exit status will be `0`. Otherwise, when the error is fatal, the error /// is printed to stderr and the exit status will be `1`. pub fn exit(&self) ->! { if self.is_fatal() { wlnerr!("{}", self); ::std::process::exit(1)
::std::process::exit(0) } } } impl Display for CliError { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "{} {}", Format::Error("error:"), self.description()) } } impl Error for CliError { fn description<'a>(&'a self) -> &'a str { match *self { CliError::Generic(ref d) => &*d, CliError::UnknownExt(ref d) => &*d, CliError::Unknown => "An unknown fatal error has occurred, please consider filing a bug-report!" } } fn cause(&self) -> Option<&Error> { match *self { CliError::Generic(..) => None, CliError::UnknownExt(..) => None, CliError::Unknown => None, } } }
} else { println!("{}", self);
random_line_split
no-redundancy.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub struct Inner<T> { field: T, }
} // @has no_redundancy/struct.Outer.html // @has - '//*[@id="synthetic-implementations-list"]/*[@class="impl"]//*/code' "impl<T> Send for \ // Outer<T> where T: Copy + Send" pub struct Outer<T> { inner_field: Inner<T>, }
unsafe impl<T> Send for Inner<T> where T: Copy + Send, {
random_line_split
no-redundancy.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub struct Inner<T> { field: T, } unsafe impl<T> Send for Inner<T> where T: Copy + Send, { } // @has no_redundancy/struct.Outer.html // @has - '//*[@id="synthetic-implementations-list"]/*[@class="impl"]//*/code' "impl<T> Send for \ // Outer<T> where T: Copy + Send" pub struct
<T> { inner_field: Inner<T>, }
Outer
identifier_name
macos.rs
use std::{io, path, ptr, mem, ffi, slice, time}; use libc::{c_void, c_int, c_schar, c_uchar, size_t, uid_t, sysctl, sysctlnametomib, timeval, statfs}; use data::*; use super::common::*; use super::unix; pub struct PlatformImpl; macro_rules! sysctl_mib { ($len:expr, $name:expr) => { { let mut mib: [c_int; $len] = [0; $len]; let mut sz: size_t = mib.len(); let s = ffi::CString::new($name).unwrap(); unsafe { sysctlnametomib(s.as_ptr(), &mut mib[0], &mut sz) }; mib } } } macro_rules! sysctl { ($mib:expr, $dataptr:expr, $size:expr, $shouldcheck:expr) => { { let mib = &$mib; let mut size = $size; if unsafe { sysctl(&mib[0] as *const _ as *mut _, mib.len() as u32, $dataptr as *mut _ as *mut c_void, &mut size, ptr::null_mut(), 0) }!= 0 && $shouldcheck { return Err(io::Error::new(io::ErrorKind::Other, "sysctl() failed")) } size } }; ($mib:expr, $dataptr:expr, $size:expr) => { sysctl!($mib, $dataptr, $size, true) } } lazy_static! { static ref KERN_BOOTTIME: [c_int; 2] = sysctl_mib!(2, "kern.boottime"); } /// An implementation of `Platform` for macOS. /// See `Platform` for documentation. impl Platform for PlatformImpl { #[inline(always)] fn new() -> Self { PlatformImpl } fn cpu_load(&self) -> io::Result<DelayedMeasurement<Vec<CPULoad>>> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn load_average(&self) -> io::Result<LoadAverage> { unix::load_average() } fn memory(&self) -> io::Result<Memory> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn boot_time(&self) -> io::Result<DateTime<Utc>> { let mut data: timeval = unsafe { mem::zeroed() }; sysctl!(KERN_BOOTTIME, &mut data, mem::size_of::<timeval>()); Ok(DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(data.tv_sec.into(), data.tv_usec as u32), Utc)) } fn battery_life(&self) -> io::Result<BatteryLife> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn on_ac_power(&self) -> io::Result<bool> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn mounts(&self) -> io::Result<Vec<Filesystem>> { let mut mptr: *mut statfs = ptr::null_mut(); let len = unsafe { getmntinfo(&mut mptr, 2 as i32) }; if len < 1
let mounts = unsafe { slice::from_raw_parts(mptr, len as usize) }; Ok(mounts.iter().map(statfs_to_fs).collect::<Vec<_>>()) } fn block_device_statistics(&self) -> io::Result<BTreeMap<String, BlockDeviceStats>> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn networks(&self) -> io::Result<BTreeMap<String, Network>> { unix::networks() } fn network_stats(&self, interface: &str) -> io::Result<NetworkStats> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn cpu_temp(&self) -> io::Result<f32> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn socket_stats(&self) -> io::Result<SocketStats> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } } fn statfs_to_fs(x: &statfs) -> Filesystem { Filesystem { files: (x.f_files as usize).saturating_sub(x.f_ffree as usize), files_total: x.f_files as usize, files_avail: x.f_ffree as usize, free: ByteSize::b(x.f_bfree * x.f_bsize as u64), avail: ByteSize::b(x.f_bavail * x.f_bsize as u64), total: ByteSize::b(x.f_blocks * x.f_bsize as u64), name_max: 256, fs_type: unsafe { ffi::CStr::from_ptr(&x.f_fstypename[0]).to_string_lossy().into_owned() }, fs_mounted_from: unsafe { ffi::CStr::from_ptr(&x.f_mntfromname[0]).to_string_lossy().into_owned() }, fs_mounted_on: unsafe { ffi::CStr::from_ptr(&x.f_mntonname[0]).to_string_lossy().into_owned() }, } } #[link(name = "c")] extern "C" { #[link_name = "getmntinfo$INODE64"] fn getmntinfo(mntbufp: *mut *mut statfs, flags: c_int) -> c_int; }
{ return Err(io::Error::new(io::ErrorKind::Other, "getmntinfo() failed")) }
conditional_block
macos.rs
use std::{io, path, ptr, mem, ffi, slice, time}; use libc::{c_void, c_int, c_schar, c_uchar, size_t, uid_t, sysctl, sysctlnametomib, timeval, statfs}; use data::*; use super::common::*; use super::unix; pub struct PlatformImpl; macro_rules! sysctl_mib { ($len:expr, $name:expr) => { { let mut mib: [c_int; $len] = [0; $len]; let mut sz: size_t = mib.len(); let s = ffi::CString::new($name).unwrap(); unsafe { sysctlnametomib(s.as_ptr(), &mut mib[0], &mut sz) }; mib } } } macro_rules! sysctl { ($mib:expr, $dataptr:expr, $size:expr, $shouldcheck:expr) => { { let mib = &$mib; let mut size = $size; if unsafe { sysctl(&mib[0] as *const _ as *mut _, mib.len() as u32, $dataptr as *mut _ as *mut c_void, &mut size, ptr::null_mut(), 0) }!= 0 && $shouldcheck { return Err(io::Error::new(io::ErrorKind::Other, "sysctl() failed")) } size } }; ($mib:expr, $dataptr:expr, $size:expr) => { sysctl!($mib, $dataptr, $size, true) } } lazy_static! { static ref KERN_BOOTTIME: [c_int; 2] = sysctl_mib!(2, "kern.boottime"); } /// An implementation of `Platform` for macOS. /// See `Platform` for documentation. impl Platform for PlatformImpl { #[inline(always)] fn new() -> Self { PlatformImpl } fn cpu_load(&self) -> io::Result<DelayedMeasurement<Vec<CPULoad>>> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn load_average(&self) -> io::Result<LoadAverage> { unix::load_average() } fn memory(&self) -> io::Result<Memory> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn boot_time(&self) -> io::Result<DateTime<Utc>> { let mut data: timeval = unsafe { mem::zeroed() }; sysctl!(KERN_BOOTTIME, &mut data, mem::size_of::<timeval>()); Ok(DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(data.tv_sec.into(), data.tv_usec as u32), Utc)) } fn battery_life(&self) -> io::Result<BatteryLife> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn on_ac_power(&self) -> io::Result<bool> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn mounts(&self) -> io::Result<Vec<Filesystem>> { let mut mptr: *mut statfs = ptr::null_mut(); let len = unsafe { getmntinfo(&mut mptr, 2 as i32) }; if len < 1 { return Err(io::Error::new(io::ErrorKind::Other, "getmntinfo() failed")) } let mounts = unsafe { slice::from_raw_parts(mptr, len as usize) }; Ok(mounts.iter().map(statfs_to_fs).collect::<Vec<_>>()) } fn block_device_statistics(&self) -> io::Result<BTreeMap<String, BlockDeviceStats>> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn networks(&self) -> io::Result<BTreeMap<String, Network>> { unix::networks() } fn network_stats(&self, interface: &str) -> io::Result<NetworkStats> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn cpu_temp(&self) -> io::Result<f32> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn socket_stats(&self) -> io::Result<SocketStats> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } } fn statfs_to_fs(x: &statfs) -> Filesystem
#[link(name = "c")] extern "C" { #[link_name = "getmntinfo$INODE64"] fn getmntinfo(mntbufp: *mut *mut statfs, flags: c_int) -> c_int; }
{ Filesystem { files: (x.f_files as usize).saturating_sub(x.f_ffree as usize), files_total: x.f_files as usize, files_avail: x.f_ffree as usize, free: ByteSize::b(x.f_bfree * x.f_bsize as u64), avail: ByteSize::b(x.f_bavail * x.f_bsize as u64), total: ByteSize::b(x.f_blocks * x.f_bsize as u64), name_max: 256, fs_type: unsafe { ffi::CStr::from_ptr(&x.f_fstypename[0]).to_string_lossy().into_owned() }, fs_mounted_from: unsafe { ffi::CStr::from_ptr(&x.f_mntfromname[0]).to_string_lossy().into_owned() }, fs_mounted_on: unsafe { ffi::CStr::from_ptr(&x.f_mntonname[0]).to_string_lossy().into_owned() }, } }
identifier_body
macos.rs
use std::{io, path, ptr, mem, ffi, slice, time}; use libc::{c_void, c_int, c_schar, c_uchar, size_t, uid_t, sysctl, sysctlnametomib, timeval, statfs}; use data::*; use super::common::*; use super::unix; pub struct PlatformImpl; macro_rules! sysctl_mib { ($len:expr, $name:expr) => { { let mut mib: [c_int; $len] = [0; $len]; let mut sz: size_t = mib.len(); let s = ffi::CString::new($name).unwrap(); unsafe { sysctlnametomib(s.as_ptr(), &mut mib[0], &mut sz) }; mib } } } macro_rules! sysctl { ($mib:expr, $dataptr:expr, $size:expr, $shouldcheck:expr) => { { let mib = &$mib; let mut size = $size; if unsafe { sysctl(&mib[0] as *const _ as *mut _, mib.len() as u32, $dataptr as *mut _ as *mut c_void, &mut size, ptr::null_mut(), 0) }!= 0 && $shouldcheck { return Err(io::Error::new(io::ErrorKind::Other, "sysctl() failed")) } size } }; ($mib:expr, $dataptr:expr, $size:expr) => { sysctl!($mib, $dataptr, $size, true) } } lazy_static! { static ref KERN_BOOTTIME: [c_int; 2] = sysctl_mib!(2, "kern.boottime"); } /// An implementation of `Platform` for macOS. /// See `Platform` for documentation. impl Platform for PlatformImpl { #[inline(always)] fn new() -> Self { PlatformImpl } fn cpu_load(&self) -> io::Result<DelayedMeasurement<Vec<CPULoad>>> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn load_average(&self) -> io::Result<LoadAverage> { unix::load_average() } fn memory(&self) -> io::Result<Memory> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn boot_time(&self) -> io::Result<DateTime<Utc>> {
fn battery_life(&self) -> io::Result<BatteryLife> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn on_ac_power(&self) -> io::Result<bool> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn mounts(&self) -> io::Result<Vec<Filesystem>> { let mut mptr: *mut statfs = ptr::null_mut(); let len = unsafe { getmntinfo(&mut mptr, 2 as i32) }; if len < 1 { return Err(io::Error::new(io::ErrorKind::Other, "getmntinfo() failed")) } let mounts = unsafe { slice::from_raw_parts(mptr, len as usize) }; Ok(mounts.iter().map(statfs_to_fs).collect::<Vec<_>>()) } fn block_device_statistics(&self) -> io::Result<BTreeMap<String, BlockDeviceStats>> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn networks(&self) -> io::Result<BTreeMap<String, Network>> { unix::networks() } fn network_stats(&self, interface: &str) -> io::Result<NetworkStats> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn cpu_temp(&self) -> io::Result<f32> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn socket_stats(&self) -> io::Result<SocketStats> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } } fn statfs_to_fs(x: &statfs) -> Filesystem { Filesystem { files: (x.f_files as usize).saturating_sub(x.f_ffree as usize), files_total: x.f_files as usize, files_avail: x.f_ffree as usize, free: ByteSize::b(x.f_bfree * x.f_bsize as u64), avail: ByteSize::b(x.f_bavail * x.f_bsize as u64), total: ByteSize::b(x.f_blocks * x.f_bsize as u64), name_max: 256, fs_type: unsafe { ffi::CStr::from_ptr(&x.f_fstypename[0]).to_string_lossy().into_owned() }, fs_mounted_from: unsafe { ffi::CStr::from_ptr(&x.f_mntfromname[0]).to_string_lossy().into_owned() }, fs_mounted_on: unsafe { ffi::CStr::from_ptr(&x.f_mntonname[0]).to_string_lossy().into_owned() }, } } #[link(name = "c")] extern "C" { #[link_name = "getmntinfo$INODE64"] fn getmntinfo(mntbufp: *mut *mut statfs, flags: c_int) -> c_int; }
let mut data: timeval = unsafe { mem::zeroed() }; sysctl!(KERN_BOOTTIME, &mut data, mem::size_of::<timeval>()); Ok(DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(data.tv_sec.into(), data.tv_usec as u32), Utc)) }
random_line_split
macos.rs
use std::{io, path, ptr, mem, ffi, slice, time}; use libc::{c_void, c_int, c_schar, c_uchar, size_t, uid_t, sysctl, sysctlnametomib, timeval, statfs}; use data::*; use super::common::*; use super::unix; pub struct
; macro_rules! sysctl_mib { ($len:expr, $name:expr) => { { let mut mib: [c_int; $len] = [0; $len]; let mut sz: size_t = mib.len(); let s = ffi::CString::new($name).unwrap(); unsafe { sysctlnametomib(s.as_ptr(), &mut mib[0], &mut sz) }; mib } } } macro_rules! sysctl { ($mib:expr, $dataptr:expr, $size:expr, $shouldcheck:expr) => { { let mib = &$mib; let mut size = $size; if unsafe { sysctl(&mib[0] as *const _ as *mut _, mib.len() as u32, $dataptr as *mut _ as *mut c_void, &mut size, ptr::null_mut(), 0) }!= 0 && $shouldcheck { return Err(io::Error::new(io::ErrorKind::Other, "sysctl() failed")) } size } }; ($mib:expr, $dataptr:expr, $size:expr) => { sysctl!($mib, $dataptr, $size, true) } } lazy_static! { static ref KERN_BOOTTIME: [c_int; 2] = sysctl_mib!(2, "kern.boottime"); } /// An implementation of `Platform` for macOS. /// See `Platform` for documentation. impl Platform for PlatformImpl { #[inline(always)] fn new() -> Self { PlatformImpl } fn cpu_load(&self) -> io::Result<DelayedMeasurement<Vec<CPULoad>>> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn load_average(&self) -> io::Result<LoadAverage> { unix::load_average() } fn memory(&self) -> io::Result<Memory> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn boot_time(&self) -> io::Result<DateTime<Utc>> { let mut data: timeval = unsafe { mem::zeroed() }; sysctl!(KERN_BOOTTIME, &mut data, mem::size_of::<timeval>()); Ok(DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(data.tv_sec.into(), data.tv_usec as u32), Utc)) } fn battery_life(&self) -> io::Result<BatteryLife> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn on_ac_power(&self) -> io::Result<bool> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn mounts(&self) -> io::Result<Vec<Filesystem>> { let mut mptr: *mut statfs = ptr::null_mut(); let len = unsafe { getmntinfo(&mut mptr, 2 as i32) }; if len < 1 { return Err(io::Error::new(io::ErrorKind::Other, "getmntinfo() failed")) } let mounts = unsafe { slice::from_raw_parts(mptr, len as usize) }; Ok(mounts.iter().map(statfs_to_fs).collect::<Vec<_>>()) } fn block_device_statistics(&self) -> io::Result<BTreeMap<String, BlockDeviceStats>> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn networks(&self) -> io::Result<BTreeMap<String, Network>> { unix::networks() } fn network_stats(&self, interface: &str) -> io::Result<NetworkStats> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn cpu_temp(&self) -> io::Result<f32> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } fn socket_stats(&self) -> io::Result<SocketStats> { Err(io::Error::new(io::ErrorKind::Other, "Not supported")) } } fn statfs_to_fs(x: &statfs) -> Filesystem { Filesystem { files: (x.f_files as usize).saturating_sub(x.f_ffree as usize), files_total: x.f_files as usize, files_avail: x.f_ffree as usize, free: ByteSize::b(x.f_bfree * x.f_bsize as u64), avail: ByteSize::b(x.f_bavail * x.f_bsize as u64), total: ByteSize::b(x.f_blocks * x.f_bsize as u64), name_max: 256, fs_type: unsafe { ffi::CStr::from_ptr(&x.f_fstypename[0]).to_string_lossy().into_owned() }, fs_mounted_from: unsafe { ffi::CStr::from_ptr(&x.f_mntfromname[0]).to_string_lossy().into_owned() }, fs_mounted_on: unsafe { ffi::CStr::from_ptr(&x.f_mntonname[0]).to_string_lossy().into_owned() }, } } #[link(name = "c")] extern "C" { #[link_name = "getmntinfo$INODE64"] fn getmntinfo(mntbufp: *mut *mut statfs, flags: c_int) -> c_int; }
PlatformImpl
identifier_name
move_error.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. use middle::mem_categorization as mc; use middle::borrowck::BorrowckCtxt; use middle::ty; use std::cell::RefCell; use syntax::ast; use syntax::codemap; use syntax::print::pprust; use util::ppaux::UserString; pub struct MoveErrorCollector { errors: RefCell<Vec<MoveError>> } impl MoveErrorCollector { pub fn new() -> MoveErrorCollector { MoveErrorCollector { errors: RefCell::new(Vec::new()) } } pub fn add_error(&self, error: MoveError) { self.errors.borrow_mut().push(error); }
pub struct MoveError { move_from: mc::cmt, move_to: Option<MoveSpanAndPath> } impl MoveError { pub fn with_move_info(move_from: mc::cmt, move_to: Option<MoveSpanAndPath>) -> MoveError { MoveError { move_from: move_from, move_to: move_to, } } } #[deriving(Clone)] pub struct MoveSpanAndPath { pub span: codemap::Span, pub ident: ast::Ident } pub struct GroupedMoveErrors { move_from: mc::cmt, move_to_places: Vec<MoveSpanAndPath> } fn report_move_errors(bccx: &BorrowckCtxt, errors: &Vec<MoveError>) { let grouped_errors = group_errors_with_same_origin(errors); for error in grouped_errors.iter() { report_cannot_move_out_of(bccx, error.move_from.clone()); let mut is_first_note = true; for move_to in error.move_to_places.iter() { note_move_destination(bccx, move_to.span, &move_to.ident, is_first_note); is_first_note = false; } } } fn group_errors_with_same_origin(errors: &Vec<MoveError>) -> Vec<GroupedMoveErrors> { let mut grouped_errors = Vec::new(); for error in errors.iter() { append_to_grouped_errors(&mut grouped_errors, error) } return grouped_errors; fn append_to_grouped_errors(grouped_errors: &mut Vec<GroupedMoveErrors>, error: &MoveError) { let move_from_id = error.move_from.id; debug!("append_to_grouped_errors(move_from_id={})", move_from_id); let move_to = if error.move_to.is_some() { vec!(error.move_to.clone().unwrap()) } else { Vec::new() }; for ge in grouped_errors.iter_mut() { if move_from_id == ge.move_from.id && error.move_to.is_some() { debug!("appending move_to to list"); ge.move_to_places.extend(move_to.into_iter()); return } } debug!("found a new move from location"); grouped_errors.push(GroupedMoveErrors { move_from: error.move_from.clone(), move_to_places: move_to }) } } fn report_cannot_move_out_of(bccx: &BorrowckCtxt, move_from: mc::cmt) { match move_from.cat { mc::cat_deref(_, _, mc::BorrowedPtr(..)) | mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) | mc::cat_static_item => { bccx.span_err( move_from.span, format!("cannot move out of {}", bccx.cmt_to_string(&*move_from)).as_slice()); } mc::cat_downcast(ref b) | mc::cat_interior(ref b, _) => { match ty::get(b.ty).sty { ty::ty_struct(did, _) | ty::ty_enum(did, _) if ty::has_dtor(bccx.tcx, did) => { bccx.span_err( move_from.span, format!("cannot move out of type `{}`, \ which defines the `Drop` trait", b.ty.user_string(bccx.tcx)).as_slice()); }, _ => panic!("this path should not cause illegal move") } } _ => panic!("this path should not cause illegal move") } } fn note_move_destination(bccx: &BorrowckCtxt, move_to_span: codemap::Span, pat_ident: &ast::Ident, is_first_note: bool) { let pat_name = pprust::ident_to_string(pat_ident); if is_first_note { bccx.span_note( move_to_span, "attempting to move value to here"); bccx.span_help( move_to_span, format!("to prevent the move, \ use `ref {0}` or `ref mut {0}` to capture value by \ reference", pat_name).as_slice()); } else { bccx.span_note(move_to_span, format!("and here (use `ref {0}` or `ref mut {0}`)", pat_name).as_slice()); } }
pub fn report_potential_errors(&self, bccx: &BorrowckCtxt) { report_move_errors(bccx, self.errors.borrow().deref()) } }
random_line_split
move_error.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. use middle::mem_categorization as mc; use middle::borrowck::BorrowckCtxt; use middle::ty; use std::cell::RefCell; use syntax::ast; use syntax::codemap; use syntax::print::pprust; use util::ppaux::UserString; pub struct MoveErrorCollector { errors: RefCell<Vec<MoveError>> } impl MoveErrorCollector { pub fn new() -> MoveErrorCollector { MoveErrorCollector { errors: RefCell::new(Vec::new()) } } pub fn add_error(&self, error: MoveError) { self.errors.borrow_mut().push(error); } pub fn report_potential_errors(&self, bccx: &BorrowckCtxt) { report_move_errors(bccx, self.errors.borrow().deref()) } } pub struct MoveError { move_from: mc::cmt, move_to: Option<MoveSpanAndPath> } impl MoveError { pub fn with_move_info(move_from: mc::cmt, move_to: Option<MoveSpanAndPath>) -> MoveError { MoveError { move_from: move_from, move_to: move_to, } } } #[deriving(Clone)] pub struct MoveSpanAndPath { pub span: codemap::Span, pub ident: ast::Ident } pub struct GroupedMoveErrors { move_from: mc::cmt, move_to_places: Vec<MoveSpanAndPath> } fn report_move_errors(bccx: &BorrowckCtxt, errors: &Vec<MoveError>) { let grouped_errors = group_errors_with_same_origin(errors); for error in grouped_errors.iter() { report_cannot_move_out_of(bccx, error.move_from.clone()); let mut is_first_note = true; for move_to in error.move_to_places.iter() { note_move_destination(bccx, move_to.span, &move_to.ident, is_first_note); is_first_note = false; } } } fn
(errors: &Vec<MoveError>) -> Vec<GroupedMoveErrors> { let mut grouped_errors = Vec::new(); for error in errors.iter() { append_to_grouped_errors(&mut grouped_errors, error) } return grouped_errors; fn append_to_grouped_errors(grouped_errors: &mut Vec<GroupedMoveErrors>, error: &MoveError) { let move_from_id = error.move_from.id; debug!("append_to_grouped_errors(move_from_id={})", move_from_id); let move_to = if error.move_to.is_some() { vec!(error.move_to.clone().unwrap()) } else { Vec::new() }; for ge in grouped_errors.iter_mut() { if move_from_id == ge.move_from.id && error.move_to.is_some() { debug!("appending move_to to list"); ge.move_to_places.extend(move_to.into_iter()); return } } debug!("found a new move from location"); grouped_errors.push(GroupedMoveErrors { move_from: error.move_from.clone(), move_to_places: move_to }) } } fn report_cannot_move_out_of(bccx: &BorrowckCtxt, move_from: mc::cmt) { match move_from.cat { mc::cat_deref(_, _, mc::BorrowedPtr(..)) | mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) | mc::cat_static_item => { bccx.span_err( move_from.span, format!("cannot move out of {}", bccx.cmt_to_string(&*move_from)).as_slice()); } mc::cat_downcast(ref b) | mc::cat_interior(ref b, _) => { match ty::get(b.ty).sty { ty::ty_struct(did, _) | ty::ty_enum(did, _) if ty::has_dtor(bccx.tcx, did) => { bccx.span_err( move_from.span, format!("cannot move out of type `{}`, \ which defines the `Drop` trait", b.ty.user_string(bccx.tcx)).as_slice()); }, _ => panic!("this path should not cause illegal move") } } _ => panic!("this path should not cause illegal move") } } fn note_move_destination(bccx: &BorrowckCtxt, move_to_span: codemap::Span, pat_ident: &ast::Ident, is_first_note: bool) { let pat_name = pprust::ident_to_string(pat_ident); if is_first_note { bccx.span_note( move_to_span, "attempting to move value to here"); bccx.span_help( move_to_span, format!("to prevent the move, \ use `ref {0}` or `ref mut {0}` to capture value by \ reference", pat_name).as_slice()); } else { bccx.span_note(move_to_span, format!("and here (use `ref {0}` or `ref mut {0}`)", pat_name).as_slice()); } }
group_errors_with_same_origin
identifier_name
lib.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use future::BoxFuture; use futures::{future, FutureExt, TryFutureExt}; use iml_postgres::{ alert, sqlx::{self, PgPool}, }; use iml_service_queue::service_queue::ImlServiceQueueError; use iml_wire_types::{AlertRecordType, AlertSeverity}; use lazy_static::lazy_static; use regex::Regex; use std::collections::HashMap; use thiserror::Error; #[derive(Error, Debug)] pub enum ImlJournalError { #[error(transparent)] ImlRabbitError(#[from] iml_rabbit::ImlRabbitError), #[error(transparent)] ImlServiceQueueError(#[from] ImlServiceQueueError), #[error(transparent)] SerdeJsonError(#[from] serde_json::Error), #[error(transparent)] SqlxCoreError(#[from] sqlx::error::Error), #[error(transparent)] TryFromIntError(#[from] std::num::TryFromIntError), } #[derive(Debug, Eq, PartialEq)] #[repr(i16)] pub enum LogMessageClass { Normal, Lustre, LustreError, Copytool, CopytoolError, } lazy_static! { static ref LUSTRE_ERROR_TS: Regex = Regex::new(r"^\[\d+\.\d+\] LustreError:").unwrap(); static ref LUSTRE_TS: Regex = Regex::new(r"^\[\d+\.\d+\] Lustre:").unwrap(); static ref LUSTRE_ERROR: Regex = Regex::new(r"^LustreError:").unwrap(); static ref LUSTRE: Regex = Regex::new(r"^Lustre:").unwrap(); } type HandlerFut<'a> = BoxFuture<'a, Result<(), ImlJournalError>>; type Handler = for<'a> fn(&'a PgPool, &'a str, i32, i32) -> HandlerFut<'a>; lazy_static! { static ref HANDLERS: HashMap<&'static str, Handler> = { let mut hm: HashMap<&'static str, Handler> = HashMap::new(); hm.insert("Can't start acceptor on port", port_used_handler); hm.insert("Can't create socket:", port_used_handler); hm.insert(": connection from ", client_connection_handler); hm.insert(": select flavor ", server_security_flavor_handler); hm.insert( ": obd_export_evict_by_uuid()", admin_client_eviction_handler, ); hm.insert(": evicting client at ", client_eviction_handler); hm }; } pub fn get_message_class(message: &str) -> LogMessageClass { if LUSTRE_ERROR_TS.is_match(message) || LUSTRE_ERROR.is_match(message) { LogMessageClass::LustreError } else if LUSTRE_TS.is_match(message) || LUSTRE.is_match(message) { LogMessageClass::Lustre } else { LogMessageClass::Normal } } fn port_used_handler<'a>( pool: &'a PgPool, _: &str, host_id: i32, host_content_type_id: i32, ) -> BoxFuture<'a, Result<(), ImlJournalError>> { alert::raise( pool, AlertRecordType::SyslogEvent, "Lustre port already being used".into(), host_content_type_id, None, AlertSeverity::ERROR, host_id, ) .err_into() .boxed() } fn client_connection_handler<'a>( pool: &'a PgPool, msg: &str, host_id: i32, host_content_type_id: i32, ) -> HandlerFut<'a> { if let Some((lustre_pid, msg)) = client_connection_parser(msg) { return alert::raise( pool, AlertRecordType::ClientConnectEvent, msg, host_content_type_id, Some(lustre_pid), AlertSeverity::INFO, host_id, ) .err_into() .boxed(); }; future::ok(()).boxed() } /// Parses a client connected to a target fn client_connection_parser(msg: &str) -> Option<(i32, String)> { lazy_static! { static ref TARGET_END: Regex = Regex::new(r":\s+connection from").unwrap(); } // get the client NID out of the string let nid_start = msg.find('@')? + 1; let nid_len = msg[nid_start..].find(' ')?; // and the UUID let uuid_start = msg.find(" from ")? + 6; let uuid_len = msg[uuid_start..].find('@')?; // and of course the target let target_end = TARGET_END.find(msg)?.start(); let target_start = msg[0..target_end].rfind(' ')? + 1; let lustre_pid = msg[9..9 + msg[9..].find(':')?].parse::<i32>().ok()?; let msg = format!( "client {} from {} connected to target {}", &msg[uuid_start..uuid_start + uuid_len], &msg[nid_start..nid_start + nid_len], &msg[target_start..target_end], ); Some((lustre_pid, msg)) } fn server_security_flavor_parser(msg: &str) -> Option<(i32, String)> { // get the flavor out of the string let flavor_start = msg.rfind(' ')? + 1; let flavor = &msg[flavor_start..]; let lustre_pid = msg[9..9 + msg[9..].find(':')?].parse::<i32>().ok()?; Some((lustre_pid, format!("with security flavor {}", flavor))) } fn server_security_flavor_handler<'a>( pool: &'a PgPool, msg: &str, _: i32, _: i32, ) -> HandlerFut<'a> { let (lustre_pid, msg) = match server_security_flavor_parser(msg) { Some(x) => x, None => return future::ok(()).boxed(), }; struct Row { id: i32, message: Option<String>, } async move { let row = sqlx::query_as!(Row, "SELECT id, message FROM chroma_core_alertstate WHERE lustre_pid = $1 ORDER BY id DESC LIMIT 1", Some(lustre_pid) ) .fetch_optional(pool) .await?; let (id, msg) = match row { Some(Row { id, message: Some(message) }) => (id, format!("{} {}", message, msg)), Some(Row { message:None,..}) | None => return Ok(()), }; sqlx::query!( r#" UPDATE chroma_core_alertstate SET message = $1 WHERE id = $2 "#, msg, id ) .execute(pool) .await?; Ok(()) } .boxed() } fn admin_client_eviction_parser(msg: &str) -> Option<(i32, String)> { let uuid = get_item_after(msg, "evicting ")?; let x = format!("client {} evicted by the administrator", uuid); let lustre_pid = msg[9..9 + msg[9..].find(':')?].parse::<i32>().ok()?; Some((lustre_pid, x)) } fn admin_client_eviction_handler<'a>( pool: &'a PgPool, msg: &str, host_id: i32, host_content_type_id: i32, ) -> HandlerFut<'a> { if let Some((lustre_pid, msg)) = admin_client_eviction_parser(msg) { return alert::raise( pool, AlertRecordType::ClientConnectEvent, msg, host_content_type_id, Some(lustre_pid), AlertSeverity::WARNING, host_id, ) .err_into() .boxed(); }; future::ok(()).boxed() } fn client_eviction_parser(msg: &str) -> Option<(i32, String)> { let s = msg.find("### ")? + 4; let l = msg[s..].find(": evicting client at ")?; let reason = &msg[s..s + l]; let client = get_item_after(msg, ": evicting client at ")?; let lustre_pid = get_item_after(msg, "pid: ")?.parse::<i32>().ok()?; Some((lustre_pid, format!("client {} evicted: {}", client, reason))) } fn client_eviction_handler<'a>( pool: &'a PgPool, msg: &str, host_id: i32, host_content_type_id: i32, ) -> HandlerFut<'a> { if let Some((lustre_pid, msg)) = client_eviction_parser(msg) { return alert::raise( pool, AlertRecordType::ClientConnectEvent, msg, host_content_type_id, Some(lustre_pid), AlertSeverity::WARNING, host_id, ) .err_into() .boxed(); }; future::ok(()).boxed() } fn get_item_after<'a>(s: &'a str, after: &str) -> Option<&'a str> { let sub = s.find(after)? + after.len(); let l = s[sub..].find(' ')?; Some(&s[sub..sub + l]) } fn find_one_in_many<'a>(msg: &str, handlers: &'a HashMap<&str, Handler>) -> Option<&'a Handler> { handlers .iter() .find(|(k, _)| k.find(msg).is_some()) .map(|(_, v)| v) } pub async fn execute_handlers( msg: &str, host_id: i32, host_content_type_id: i32, pool: &PgPool, ) -> Result<(), ImlJournalError> { let handler = match find_one_in_many(msg, &HANDLERS) { Some(h) => h, None => return Ok(()), }; handler(pool, msg, host_id, host_content_type_id).await?; Ok(()) } #[cfg(test)] mod tests { use super::*; use insta::assert_debug_snapshot; #[test] fn test_get_message_class() { let tests = vec![ ( "[NOT A TIME STAMP ] Lustre: Lustre output here", LogMessageClass::Normal, ), ("Lustre: Lustre output here", LogMessageClass::Lustre), ( "LustreError: Lustre output here", LogMessageClass::LustreError, ), ( "[1234567A89] LustreError: Not A Time Stamp", LogMessageClass::Normal, ), ( "[123456789.123456789A] LustreError: Not A Time Stamp", LogMessageClass::Normal, ), ("Nothing to see here", LogMessageClass::Normal), ]; for (msg, expected) in tests { assert_eq!(get_message_class(msg), expected, "{}", msg); assert_eq!( get_message_class(&format!("[9830337.7944560] {}", msg)), expected, "[9830337.7944560] {} ", msg ); } } #[test] fn test_client_connection_parser() { let inputs = vec![ " Lustre: 5629:0:(ldlm_lib.c:877:target_handle_connect()) lustre-MDT0000: connection from [email protected]@tcp t0 exp 0000000000000000 cur 1317994929 last 0", " Lustre: 27559:0:(ldlm_lib.c:871:target_handle_connect()) lustre-OST0001: connection from [email protected]@tcp t0 exp 0000000000000000 cur 1317994930 last 0", " Lustre: 9150:0:(ldlm_lib.c:871:target_handle_connect()) lustre-OST0000: connection from [email protected]@tcp t0 exp 0000000000000000 cur 1317994930 last 0", " Lustre: 31793:0:(ldlm_lib.c:877:target_handle_connect()) MGS: connection from [email protected]@tcp t0 exp 0000000000000000 cur 1317994928 last 0", ]; for input in inputs { assert_debug_snapshot!(client_connection_parser(input).unwrap()); } } #[test] fn test_server_security_flavor_parser() { let inputs = vec![ " Lustre: 5629:0:(sec.c:1474:sptlrpc_import_sec_adapt()) import lustre-MDT0000->NET_0x20000c0a87ada_UUID netid 20000: select flavor null", "Lustre: 20380:0:(sec.c:1474:sptlrpc_import_sec_adapt()) import MGC192.168.122.105@tcp->MGC192.168.122.105@tcp_0 netid 20000: select flavor null" ]; for input in inputs { assert_debug_snapshot!(server_security_flavor_parser(input).unwrap()); } } #[test] fn test_admin_client_eviction_parser()
#[test] fn test_client_eviction_parser() { let inputs = vec![ " LustreError: 0:0:(ldlm_lockd.c:356:waiting_locks_callback()) ### lock callback timer expired after 101s: evicting client at 0@lo ns: mdt-ffff8801cd5be000 lock: ffff880126f8f480/0xe99a593b682aed45 lrc: 3/0,0 mode: PR/PR res: 8589935876/10593 bits 0x3 rrc: 2 type: IBT flags: 0x4000020 remote: 0xe99a593b682aecea expref: 14 pid: 3636 timeout: 4389324308'", " LustreError: 0:0:(ldlm_lockd.c:356:waiting_locks_callback()) ### lock callback timer expired after 151s: evicting client at 10.10.6.127@tcp ns: mdt-ffff880027554000 lock: ffff8800345b9480/0x7e9e6dc241f05651 lrc: 3/0,0 mode: PR/PR res: 8589935619/19678 bits 0x3 rrc: 2 type: IBT flags: 0x4000020 remote: 0xebc1380d8b532fd7 expref: 5104 pid: 23056 timeout: 4313115550"]; for input in inputs { assert_debug_snapshot!(client_eviction_parser(input).unwrap()); } } }
{ let x = " Lustre: 2689:0:(genops.c:1379:obd_export_evict_by_uuid()) lustre-OST0001: evicting 26959b68-1208-1fca-1f07-da2dc872c55f at adminstrative request"; assert_debug_snapshot!(admin_client_eviction_parser(x).unwrap()); }
identifier_body
lib.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use future::BoxFuture; use futures::{future, FutureExt, TryFutureExt}; use iml_postgres::{ alert, sqlx::{self, PgPool}, }; use iml_service_queue::service_queue::ImlServiceQueueError; use iml_wire_types::{AlertRecordType, AlertSeverity}; use lazy_static::lazy_static; use regex::Regex; use std::collections::HashMap; use thiserror::Error; #[derive(Error, Debug)] pub enum ImlJournalError { #[error(transparent)] ImlRabbitError(#[from] iml_rabbit::ImlRabbitError), #[error(transparent)] ImlServiceQueueError(#[from] ImlServiceQueueError), #[error(transparent)] SerdeJsonError(#[from] serde_json::Error), #[error(transparent)] SqlxCoreError(#[from] sqlx::error::Error), #[error(transparent)] TryFromIntError(#[from] std::num::TryFromIntError), } #[derive(Debug, Eq, PartialEq)] #[repr(i16)] pub enum LogMessageClass { Normal, Lustre, LustreError, Copytool, CopytoolError, } lazy_static! { static ref LUSTRE_ERROR_TS: Regex = Regex::new(r"^\[\d+\.\d+\] LustreError:").unwrap(); static ref LUSTRE_TS: Regex = Regex::new(r"^\[\d+\.\d+\] Lustre:").unwrap(); static ref LUSTRE_ERROR: Regex = Regex::new(r"^LustreError:").unwrap(); static ref LUSTRE: Regex = Regex::new(r"^Lustre:").unwrap(); } type HandlerFut<'a> = BoxFuture<'a, Result<(), ImlJournalError>>; type Handler = for<'a> fn(&'a PgPool, &'a str, i32, i32) -> HandlerFut<'a>; lazy_static! { static ref HANDLERS: HashMap<&'static str, Handler> = { let mut hm: HashMap<&'static str, Handler> = HashMap::new(); hm.insert("Can't start acceptor on port", port_used_handler); hm.insert("Can't create socket:", port_used_handler); hm.insert(": connection from ", client_connection_handler); hm.insert(": select flavor ", server_security_flavor_handler); hm.insert( ": obd_export_evict_by_uuid()", admin_client_eviction_handler, ); hm.insert(": evicting client at ", client_eviction_handler); hm }; } pub fn get_message_class(message: &str) -> LogMessageClass { if LUSTRE_ERROR_TS.is_match(message) || LUSTRE_ERROR.is_match(message) { LogMessageClass::LustreError } else if LUSTRE_TS.is_match(message) || LUSTRE.is_match(message) { LogMessageClass::Lustre } else { LogMessageClass::Normal } } fn port_used_handler<'a>( pool: &'a PgPool, _: &str, host_id: i32, host_content_type_id: i32, ) -> BoxFuture<'a, Result<(), ImlJournalError>> { alert::raise( pool, AlertRecordType::SyslogEvent, "Lustre port already being used".into(), host_content_type_id,
.boxed() } fn client_connection_handler<'a>( pool: &'a PgPool, msg: &str, host_id: i32, host_content_type_id: i32, ) -> HandlerFut<'a> { if let Some((lustre_pid, msg)) = client_connection_parser(msg) { return alert::raise( pool, AlertRecordType::ClientConnectEvent, msg, host_content_type_id, Some(lustre_pid), AlertSeverity::INFO, host_id, ) .err_into() .boxed(); }; future::ok(()).boxed() } /// Parses a client connected to a target fn client_connection_parser(msg: &str) -> Option<(i32, String)> { lazy_static! { static ref TARGET_END: Regex = Regex::new(r":\s+connection from").unwrap(); } // get the client NID out of the string let nid_start = msg.find('@')? + 1; let nid_len = msg[nid_start..].find(' ')?; // and the UUID let uuid_start = msg.find(" from ")? + 6; let uuid_len = msg[uuid_start..].find('@')?; // and of course the target let target_end = TARGET_END.find(msg)?.start(); let target_start = msg[0..target_end].rfind(' ')? + 1; let lustre_pid = msg[9..9 + msg[9..].find(':')?].parse::<i32>().ok()?; let msg = format!( "client {} from {} connected to target {}", &msg[uuid_start..uuid_start + uuid_len], &msg[nid_start..nid_start + nid_len], &msg[target_start..target_end], ); Some((lustre_pid, msg)) } fn server_security_flavor_parser(msg: &str) -> Option<(i32, String)> { // get the flavor out of the string let flavor_start = msg.rfind(' ')? + 1; let flavor = &msg[flavor_start..]; let lustre_pid = msg[9..9 + msg[9..].find(':')?].parse::<i32>().ok()?; Some((lustre_pid, format!("with security flavor {}", flavor))) } fn server_security_flavor_handler<'a>( pool: &'a PgPool, msg: &str, _: i32, _: i32, ) -> HandlerFut<'a> { let (lustre_pid, msg) = match server_security_flavor_parser(msg) { Some(x) => x, None => return future::ok(()).boxed(), }; struct Row { id: i32, message: Option<String>, } async move { let row = sqlx::query_as!(Row, "SELECT id, message FROM chroma_core_alertstate WHERE lustre_pid = $1 ORDER BY id DESC LIMIT 1", Some(lustre_pid) ) .fetch_optional(pool) .await?; let (id, msg) = match row { Some(Row { id, message: Some(message) }) => (id, format!("{} {}", message, msg)), Some(Row { message:None,..}) | None => return Ok(()), }; sqlx::query!( r#" UPDATE chroma_core_alertstate SET message = $1 WHERE id = $2 "#, msg, id ) .execute(pool) .await?; Ok(()) } .boxed() } fn admin_client_eviction_parser(msg: &str) -> Option<(i32, String)> { let uuid = get_item_after(msg, "evicting ")?; let x = format!("client {} evicted by the administrator", uuid); let lustre_pid = msg[9..9 + msg[9..].find(':')?].parse::<i32>().ok()?; Some((lustre_pid, x)) } fn admin_client_eviction_handler<'a>( pool: &'a PgPool, msg: &str, host_id: i32, host_content_type_id: i32, ) -> HandlerFut<'a> { if let Some((lustre_pid, msg)) = admin_client_eviction_parser(msg) { return alert::raise( pool, AlertRecordType::ClientConnectEvent, msg, host_content_type_id, Some(lustre_pid), AlertSeverity::WARNING, host_id, ) .err_into() .boxed(); }; future::ok(()).boxed() } fn client_eviction_parser(msg: &str) -> Option<(i32, String)> { let s = msg.find("### ")? + 4; let l = msg[s..].find(": evicting client at ")?; let reason = &msg[s..s + l]; let client = get_item_after(msg, ": evicting client at ")?; let lustre_pid = get_item_after(msg, "pid: ")?.parse::<i32>().ok()?; Some((lustre_pid, format!("client {} evicted: {}", client, reason))) } fn client_eviction_handler<'a>( pool: &'a PgPool, msg: &str, host_id: i32, host_content_type_id: i32, ) -> HandlerFut<'a> { if let Some((lustre_pid, msg)) = client_eviction_parser(msg) { return alert::raise( pool, AlertRecordType::ClientConnectEvent, msg, host_content_type_id, Some(lustre_pid), AlertSeverity::WARNING, host_id, ) .err_into() .boxed(); }; future::ok(()).boxed() } fn get_item_after<'a>(s: &'a str, after: &str) -> Option<&'a str> { let sub = s.find(after)? + after.len(); let l = s[sub..].find(' ')?; Some(&s[sub..sub + l]) } fn find_one_in_many<'a>(msg: &str, handlers: &'a HashMap<&str, Handler>) -> Option<&'a Handler> { handlers .iter() .find(|(k, _)| k.find(msg).is_some()) .map(|(_, v)| v) } pub async fn execute_handlers( msg: &str, host_id: i32, host_content_type_id: i32, pool: &PgPool, ) -> Result<(), ImlJournalError> { let handler = match find_one_in_many(msg, &HANDLERS) { Some(h) => h, None => return Ok(()), }; handler(pool, msg, host_id, host_content_type_id).await?; Ok(()) } #[cfg(test)] mod tests { use super::*; use insta::assert_debug_snapshot; #[test] fn test_get_message_class() { let tests = vec![ ( "[NOT A TIME STAMP ] Lustre: Lustre output here", LogMessageClass::Normal, ), ("Lustre: Lustre output here", LogMessageClass::Lustre), ( "LustreError: Lustre output here", LogMessageClass::LustreError, ), ( "[1234567A89] LustreError: Not A Time Stamp", LogMessageClass::Normal, ), ( "[123456789.123456789A] LustreError: Not A Time Stamp", LogMessageClass::Normal, ), ("Nothing to see here", LogMessageClass::Normal), ]; for (msg, expected) in tests { assert_eq!(get_message_class(msg), expected, "{}", msg); assert_eq!( get_message_class(&format!("[9830337.7944560] {}", msg)), expected, "[9830337.7944560] {} ", msg ); } } #[test] fn test_client_connection_parser() { let inputs = vec![ " Lustre: 5629:0:(ldlm_lib.c:877:target_handle_connect()) lustre-MDT0000: connection from [email protected]@tcp t0 exp 0000000000000000 cur 1317994929 last 0", " Lustre: 27559:0:(ldlm_lib.c:871:target_handle_connect()) lustre-OST0001: connection from [email protected]@tcp t0 exp 0000000000000000 cur 1317994930 last 0", " Lustre: 9150:0:(ldlm_lib.c:871:target_handle_connect()) lustre-OST0000: connection from [email protected]@tcp t0 exp 0000000000000000 cur 1317994930 last 0", " Lustre: 31793:0:(ldlm_lib.c:877:target_handle_connect()) MGS: connection from [email protected]@tcp t0 exp 0000000000000000 cur 1317994928 last 0", ]; for input in inputs { assert_debug_snapshot!(client_connection_parser(input).unwrap()); } } #[test] fn test_server_security_flavor_parser() { let inputs = vec![ " Lustre: 5629:0:(sec.c:1474:sptlrpc_import_sec_adapt()) import lustre-MDT0000->NET_0x20000c0a87ada_UUID netid 20000: select flavor null", "Lustre: 20380:0:(sec.c:1474:sptlrpc_import_sec_adapt()) import MGC192.168.122.105@tcp->MGC192.168.122.105@tcp_0 netid 20000: select flavor null" ]; for input in inputs { assert_debug_snapshot!(server_security_flavor_parser(input).unwrap()); } } #[test] fn test_admin_client_eviction_parser() { let x = " Lustre: 2689:0:(genops.c:1379:obd_export_evict_by_uuid()) lustre-OST0001: evicting 26959b68-1208-1fca-1f07-da2dc872c55f at adminstrative request"; assert_debug_snapshot!(admin_client_eviction_parser(x).unwrap()); } #[test] fn test_client_eviction_parser() { let inputs = vec![ " LustreError: 0:0:(ldlm_lockd.c:356:waiting_locks_callback()) ### lock callback timer expired after 101s: evicting client at 0@lo ns: mdt-ffff8801cd5be000 lock: ffff880126f8f480/0xe99a593b682aed45 lrc: 3/0,0 mode: PR/PR res: 8589935876/10593 bits 0x3 rrc: 2 type: IBT flags: 0x4000020 remote: 0xe99a593b682aecea expref: 14 pid: 3636 timeout: 4389324308'", " LustreError: 0:0:(ldlm_lockd.c:356:waiting_locks_callback()) ### lock callback timer expired after 151s: evicting client at 10.10.6.127@tcp ns: mdt-ffff880027554000 lock: ffff8800345b9480/0x7e9e6dc241f05651 lrc: 3/0,0 mode: PR/PR res: 8589935619/19678 bits 0x3 rrc: 2 type: IBT flags: 0x4000020 remote: 0xebc1380d8b532fd7 expref: 5104 pid: 23056 timeout: 4313115550"]; for input in inputs { assert_debug_snapshot!(client_eviction_parser(input).unwrap()); } } }
None, AlertSeverity::ERROR, host_id, ) .err_into()
random_line_split
lib.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use future::BoxFuture; use futures::{future, FutureExt, TryFutureExt}; use iml_postgres::{ alert, sqlx::{self, PgPool}, }; use iml_service_queue::service_queue::ImlServiceQueueError; use iml_wire_types::{AlertRecordType, AlertSeverity}; use lazy_static::lazy_static; use regex::Regex; use std::collections::HashMap; use thiserror::Error; #[derive(Error, Debug)] pub enum ImlJournalError { #[error(transparent)] ImlRabbitError(#[from] iml_rabbit::ImlRabbitError), #[error(transparent)] ImlServiceQueueError(#[from] ImlServiceQueueError), #[error(transparent)] SerdeJsonError(#[from] serde_json::Error), #[error(transparent)] SqlxCoreError(#[from] sqlx::error::Error), #[error(transparent)] TryFromIntError(#[from] std::num::TryFromIntError), } #[derive(Debug, Eq, PartialEq)] #[repr(i16)] pub enum LogMessageClass { Normal, Lustre, LustreError, Copytool, CopytoolError, } lazy_static! { static ref LUSTRE_ERROR_TS: Regex = Regex::new(r"^\[\d+\.\d+\] LustreError:").unwrap(); static ref LUSTRE_TS: Regex = Regex::new(r"^\[\d+\.\d+\] Lustre:").unwrap(); static ref LUSTRE_ERROR: Regex = Regex::new(r"^LustreError:").unwrap(); static ref LUSTRE: Regex = Regex::new(r"^Lustre:").unwrap(); } type HandlerFut<'a> = BoxFuture<'a, Result<(), ImlJournalError>>; type Handler = for<'a> fn(&'a PgPool, &'a str, i32, i32) -> HandlerFut<'a>; lazy_static! { static ref HANDLERS: HashMap<&'static str, Handler> = { let mut hm: HashMap<&'static str, Handler> = HashMap::new(); hm.insert("Can't start acceptor on port", port_used_handler); hm.insert("Can't create socket:", port_used_handler); hm.insert(": connection from ", client_connection_handler); hm.insert(": select flavor ", server_security_flavor_handler); hm.insert( ": obd_export_evict_by_uuid()", admin_client_eviction_handler, ); hm.insert(": evicting client at ", client_eviction_handler); hm }; } pub fn get_message_class(message: &str) -> LogMessageClass { if LUSTRE_ERROR_TS.is_match(message) || LUSTRE_ERROR.is_match(message) { LogMessageClass::LustreError } else if LUSTRE_TS.is_match(message) || LUSTRE.is_match(message) { LogMessageClass::Lustre } else { LogMessageClass::Normal } } fn port_used_handler<'a>( pool: &'a PgPool, _: &str, host_id: i32, host_content_type_id: i32, ) -> BoxFuture<'a, Result<(), ImlJournalError>> { alert::raise( pool, AlertRecordType::SyslogEvent, "Lustre port already being used".into(), host_content_type_id, None, AlertSeverity::ERROR, host_id, ) .err_into() .boxed() } fn client_connection_handler<'a>( pool: &'a PgPool, msg: &str, host_id: i32, host_content_type_id: i32, ) -> HandlerFut<'a> { if let Some((lustre_pid, msg)) = client_connection_parser(msg) { return alert::raise( pool, AlertRecordType::ClientConnectEvent, msg, host_content_type_id, Some(lustre_pid), AlertSeverity::INFO, host_id, ) .err_into() .boxed(); }; future::ok(()).boxed() } /// Parses a client connected to a target fn
(msg: &str) -> Option<(i32, String)> { lazy_static! { static ref TARGET_END: Regex = Regex::new(r":\s+connection from").unwrap(); } // get the client NID out of the string let nid_start = msg.find('@')? + 1; let nid_len = msg[nid_start..].find(' ')?; // and the UUID let uuid_start = msg.find(" from ")? + 6; let uuid_len = msg[uuid_start..].find('@')?; // and of course the target let target_end = TARGET_END.find(msg)?.start(); let target_start = msg[0..target_end].rfind(' ')? + 1; let lustre_pid = msg[9..9 + msg[9..].find(':')?].parse::<i32>().ok()?; let msg = format!( "client {} from {} connected to target {}", &msg[uuid_start..uuid_start + uuid_len], &msg[nid_start..nid_start + nid_len], &msg[target_start..target_end], ); Some((lustre_pid, msg)) } fn server_security_flavor_parser(msg: &str) -> Option<(i32, String)> { // get the flavor out of the string let flavor_start = msg.rfind(' ')? + 1; let flavor = &msg[flavor_start..]; let lustre_pid = msg[9..9 + msg[9..].find(':')?].parse::<i32>().ok()?; Some((lustre_pid, format!("with security flavor {}", flavor))) } fn server_security_flavor_handler<'a>( pool: &'a PgPool, msg: &str, _: i32, _: i32, ) -> HandlerFut<'a> { let (lustre_pid, msg) = match server_security_flavor_parser(msg) { Some(x) => x, None => return future::ok(()).boxed(), }; struct Row { id: i32, message: Option<String>, } async move { let row = sqlx::query_as!(Row, "SELECT id, message FROM chroma_core_alertstate WHERE lustre_pid = $1 ORDER BY id DESC LIMIT 1", Some(lustre_pid) ) .fetch_optional(pool) .await?; let (id, msg) = match row { Some(Row { id, message: Some(message) }) => (id, format!("{} {}", message, msg)), Some(Row { message:None,..}) | None => return Ok(()), }; sqlx::query!( r#" UPDATE chroma_core_alertstate SET message = $1 WHERE id = $2 "#, msg, id ) .execute(pool) .await?; Ok(()) } .boxed() } fn admin_client_eviction_parser(msg: &str) -> Option<(i32, String)> { let uuid = get_item_after(msg, "evicting ")?; let x = format!("client {} evicted by the administrator", uuid); let lustre_pid = msg[9..9 + msg[9..].find(':')?].parse::<i32>().ok()?; Some((lustre_pid, x)) } fn admin_client_eviction_handler<'a>( pool: &'a PgPool, msg: &str, host_id: i32, host_content_type_id: i32, ) -> HandlerFut<'a> { if let Some((lustre_pid, msg)) = admin_client_eviction_parser(msg) { return alert::raise( pool, AlertRecordType::ClientConnectEvent, msg, host_content_type_id, Some(lustre_pid), AlertSeverity::WARNING, host_id, ) .err_into() .boxed(); }; future::ok(()).boxed() } fn client_eviction_parser(msg: &str) -> Option<(i32, String)> { let s = msg.find("### ")? + 4; let l = msg[s..].find(": evicting client at ")?; let reason = &msg[s..s + l]; let client = get_item_after(msg, ": evicting client at ")?; let lustre_pid = get_item_after(msg, "pid: ")?.parse::<i32>().ok()?; Some((lustre_pid, format!("client {} evicted: {}", client, reason))) } fn client_eviction_handler<'a>( pool: &'a PgPool, msg: &str, host_id: i32, host_content_type_id: i32, ) -> HandlerFut<'a> { if let Some((lustre_pid, msg)) = client_eviction_parser(msg) { return alert::raise( pool, AlertRecordType::ClientConnectEvent, msg, host_content_type_id, Some(lustre_pid), AlertSeverity::WARNING, host_id, ) .err_into() .boxed(); }; future::ok(()).boxed() } fn get_item_after<'a>(s: &'a str, after: &str) -> Option<&'a str> { let sub = s.find(after)? + after.len(); let l = s[sub..].find(' ')?; Some(&s[sub..sub + l]) } fn find_one_in_many<'a>(msg: &str, handlers: &'a HashMap<&str, Handler>) -> Option<&'a Handler> { handlers .iter() .find(|(k, _)| k.find(msg).is_some()) .map(|(_, v)| v) } pub async fn execute_handlers( msg: &str, host_id: i32, host_content_type_id: i32, pool: &PgPool, ) -> Result<(), ImlJournalError> { let handler = match find_one_in_many(msg, &HANDLERS) { Some(h) => h, None => return Ok(()), }; handler(pool, msg, host_id, host_content_type_id).await?; Ok(()) } #[cfg(test)] mod tests { use super::*; use insta::assert_debug_snapshot; #[test] fn test_get_message_class() { let tests = vec![ ( "[NOT A TIME STAMP ] Lustre: Lustre output here", LogMessageClass::Normal, ), ("Lustre: Lustre output here", LogMessageClass::Lustre), ( "LustreError: Lustre output here", LogMessageClass::LustreError, ), ( "[1234567A89] LustreError: Not A Time Stamp", LogMessageClass::Normal, ), ( "[123456789.123456789A] LustreError: Not A Time Stamp", LogMessageClass::Normal, ), ("Nothing to see here", LogMessageClass::Normal), ]; for (msg, expected) in tests { assert_eq!(get_message_class(msg), expected, "{}", msg); assert_eq!( get_message_class(&format!("[9830337.7944560] {}", msg)), expected, "[9830337.7944560] {} ", msg ); } } #[test] fn test_client_connection_parser() { let inputs = vec![ " Lustre: 5629:0:(ldlm_lib.c:877:target_handle_connect()) lustre-MDT0000: connection from [email protected]@tcp t0 exp 0000000000000000 cur 1317994929 last 0", " Lustre: 27559:0:(ldlm_lib.c:871:target_handle_connect()) lustre-OST0001: connection from [email protected]@tcp t0 exp 0000000000000000 cur 1317994930 last 0", " Lustre: 9150:0:(ldlm_lib.c:871:target_handle_connect()) lustre-OST0000: connection from [email protected]@tcp t0 exp 0000000000000000 cur 1317994930 last 0", " Lustre: 31793:0:(ldlm_lib.c:877:target_handle_connect()) MGS: connection from [email protected]@tcp t0 exp 0000000000000000 cur 1317994928 last 0", ]; for input in inputs { assert_debug_snapshot!(client_connection_parser(input).unwrap()); } } #[test] fn test_server_security_flavor_parser() { let inputs = vec![ " Lustre: 5629:0:(sec.c:1474:sptlrpc_import_sec_adapt()) import lustre-MDT0000->NET_0x20000c0a87ada_UUID netid 20000: select flavor null", "Lustre: 20380:0:(sec.c:1474:sptlrpc_import_sec_adapt()) import MGC192.168.122.105@tcp->MGC192.168.122.105@tcp_0 netid 20000: select flavor null" ]; for input in inputs { assert_debug_snapshot!(server_security_flavor_parser(input).unwrap()); } } #[test] fn test_admin_client_eviction_parser() { let x = " Lustre: 2689:0:(genops.c:1379:obd_export_evict_by_uuid()) lustre-OST0001: evicting 26959b68-1208-1fca-1f07-da2dc872c55f at adminstrative request"; assert_debug_snapshot!(admin_client_eviction_parser(x).unwrap()); } #[test] fn test_client_eviction_parser() { let inputs = vec![ " LustreError: 0:0:(ldlm_lockd.c:356:waiting_locks_callback()) ### lock callback timer expired after 101s: evicting client at 0@lo ns: mdt-ffff8801cd5be000 lock: ffff880126f8f480/0xe99a593b682aed45 lrc: 3/0,0 mode: PR/PR res: 8589935876/10593 bits 0x3 rrc: 2 type: IBT flags: 0x4000020 remote: 0xe99a593b682aecea expref: 14 pid: 3636 timeout: 4389324308'", " LustreError: 0:0:(ldlm_lockd.c:356:waiting_locks_callback()) ### lock callback timer expired after 151s: evicting client at 10.10.6.127@tcp ns: mdt-ffff880027554000 lock: ffff8800345b9480/0x7e9e6dc241f05651 lrc: 3/0,0 mode: PR/PR res: 8589935619/19678 bits 0x3 rrc: 2 type: IBT flags: 0x4000020 remote: 0xebc1380d8b532fd7 expref: 5104 pid: 23056 timeout: 4313115550"]; for input in inputs { assert_debug_snapshot!(client_eviction_parser(input).unwrap()); } } }
client_connection_parser
identifier_name
dom.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/. */ //! Types and traits used to access the DOM from style calculation. #![allow(unsafe_code)] use context::SharedStyleContext; use data::PrivateStyleData; use element_state::ElementState; use properties::{ComputedValues, PropertyDeclaration, PropertyDeclarationBlock}; use refcell::{Ref, RefMut}; use restyle_hints::{RESTYLE_DESCENDANTS, RESTYLE_LATER_SIBLINGS, RESTYLE_SELF, RestyleHint}; use selector_impl::{ElementExt, PseudoElement}; use selectors::matching::DeclarationBlock; use sink::Push; use std::fmt::Debug; use std::ops::BitOr; use std::sync::Arc; use string_cache::{Atom, Namespace}; /// Opaque type stored in type-unsafe work queues for parallel layout. /// Must be transmutable to and from TNode. pub type UnsafeNode = (usize, usize); /// An opaque handle to a node, which, unlike UnsafeNode, cannot be transformed /// back into a non-opaque representation. The only safe operation that can be /// performed on this node is to compare it to another opaque handle or to another /// OpaqueNode. /// /// Layout and Graphics use this to safely represent nodes for comparison purposes. /// Because the script task's GC does not trace layout, node data cannot be safely stored in layout /// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for /// locality reasons. Using `OpaqueNode` enforces this invariant. #[derive(Clone, PartialEq, Copy, Debug, Hash, Eq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))] pub struct OpaqueNode(pub usize); impl OpaqueNode { /// Returns the address of this node, for debugging purposes. #[inline] pub fn id(&self) -> usize { self.0 } } pub trait TRestyleDamage : Debug + PartialEq + BitOr<Output=Self> + Copy { /// The source for our current computed values in the cascade. This is a /// ComputedValues in Servo and a StyleContext in Gecko. /// /// This is needed because Gecko has a few optimisations for the calculation /// of the difference depending on which values have been used during /// layout. /// /// This should be obtained via TNode::existing_style_for_restyle_damage type PreExistingComputedValues; fn compute(old: &Self::PreExistingComputedValues, new: &Arc<ComputedValues>) -> Self; fn empty() -> Self; fn rebuild_and_reflow() -> Self; } pub trait TNode : Sized + Copy + Clone { type ConcreteElement: TElement<ConcreteNode = Self, ConcreteDocument = Self::ConcreteDocument>; type ConcreteDocument: TDocument<ConcreteNode = Self, ConcreteElement = Self::ConcreteElement>; type ConcreteRestyleDamage: TRestyleDamage; fn to_unsafe(&self) -> UnsafeNode; unsafe fn from_unsafe(n: &UnsafeNode) -> Self; /// Returns whether this is a text node. It turns out that this is all the style system cares /// about, and thus obviates the need to compute the full type id, which would be expensive in /// Gecko. fn is_text_node(&self) -> bool; fn is_element(&self) -> bool; fn dump(self); fn dump_style(self); fn traverse_preorder(self) -> TreeIterator<Self> { TreeIterator::new(self) } /// Returns an iterator over this node's children. fn children(self) -> ChildrenIterator<Self> { ChildrenIterator { current: self.first_child(), } } fn rev_children(self) -> ReverseChildrenIterator<Self> { ReverseChildrenIterator { current: self.last_child(), } } /// Converts self into an `OpaqueNode`. fn opaque(&self) -> OpaqueNode; /// While doing a reflow, the node at the root has no parent, as far as we're /// concerned. This method returns `None` at the reflow root. fn layout_parent_node(self, reflow_root: OpaqueNode) -> Option<Self>; fn debug_id(self) -> usize; fn as_element(&self) -> Option<Self::ConcreteElement>; fn as_document(&self) -> Option<Self::ConcreteDocument>; fn children_count(&self) -> u32; fn has_changed(&self) -> bool; unsafe fn set_changed(&self, value: bool); fn is_dirty(&self) -> bool; unsafe fn set_dirty(&self, value: bool); fn has_dirty_descendants(&self) -> bool; unsafe fn set_dirty_descendants(&self, value: bool); fn needs_dirty_on_viewport_size_changed(&self) -> bool; unsafe fn set_dirty_on_viewport_size_changed(&self); fn can_be_fragmented(&self) -> bool; unsafe fn set_can_be_fragmented(&self, value: bool); /// Borrows the PrivateStyleData without checks. #[inline(always)] unsafe fn borrow_data_unchecked(&self) -> Option<*const PrivateStyleData>; /// Borrows the PrivateStyleData immutably. Fails on a conflicting borrow. #[inline(always)] fn borrow_data(&self) -> Option<Ref<PrivateStyleData>>; /// Borrows the PrivateStyleData mutably. Fails on a conflicting borrow. #[inline(always)] fn mutate_data(&self) -> Option<RefMut<PrivateStyleData>>; /// Get the description of how to account for recent style changes. fn restyle_damage(self) -> Self::ConcreteRestyleDamage; /// Set the restyle damage field. fn set_restyle_damage(self, damage: Self::ConcreteRestyleDamage); fn parent_node(&self) -> Option<Self>; fn first_child(&self) -> Option<Self>; fn last_child(&self) -> Option<Self>; fn prev_sibling(&self) -> Option<Self>; fn next_sibling(&self) -> Option<Self>; /// Returns the style results for the given node. If CSS selector matching /// has not yet been performed, fails. fn style(&self, _context: &SharedStyleContext) -> Ref<Arc<ComputedValues>> { Ref::map(self.borrow_data().unwrap(), |data| data.style.as_ref().unwrap()) } /// Removes the style from this node. fn unstyle(self) { self.mutate_data().unwrap().style = None; } /// XXX: It's a bit unfortunate we need to pass the current computed values /// as an argument here, but otherwise Servo would crash due to double /// borrows to return it. fn existing_style_for_restyle_damage<'a>(&'a self, current_computed_values: Option<&'a Arc<ComputedValues>>, pseudo: Option<&PseudoElement>) -> Option<&'a <Self::ConcreteRestyleDamage as TRestyleDamage>::PreExistingComputedValues>; } pub trait TDocument : Sized + Copy + Clone { type ConcreteNode: TNode<ConcreteElement = Self::ConcreteElement, ConcreteDocument = Self>; type ConcreteElement: TElement<ConcreteNode = Self::ConcreteNode, ConcreteDocument = Self>; fn as_node(&self) -> Self::ConcreteNode; fn root_node(&self) -> Option<Self::ConcreteNode>; fn drain_modified_elements(&self) -> Vec<(Self::ConcreteElement, <Self::ConcreteElement as ElementExt>::Snapshot)>; } pub trait PresentationalHintsSynthetizer { fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, hints: &mut V) where V: Push<DeclarationBlock<Vec<PropertyDeclaration>>>; } pub trait TElement : Sized + Copy + Clone + ElementExt + PresentationalHintsSynthetizer { type ConcreteNode: TNode<ConcreteElement = Self, ConcreteDocument = Self::ConcreteDocument>; type ConcreteDocument: TDocument<ConcreteNode = Self::ConcreteNode, ConcreteElement = Self>; fn as_node(&self) -> Self::ConcreteNode; fn style_attribute(&self) -> &Option<PropertyDeclarationBlock>; fn get_state(&self) -> ElementState; fn has_attr(&self, namespace: &Namespace, attr: &Atom) -> bool; fn attr_equals(&self, namespace: &Namespace, attr: &Atom, value: &Atom) -> bool; /// Properly marks nodes as dirty in response to restyle hints. fn note_restyle_hint(&self, hint: RestyleHint) { // Bail early if there's no restyling to do. if hint.is_empty() { return; } // If the restyle hint is non-empty, we need to restyle either this element // or one of its siblings. Mark our ancestor chain as having dirty descendants. let node = self.as_node(); let mut curr = node; while let Some(parent) = curr.parent_node() { if parent.has_dirty_descendants() { break } unsafe { parent.set_dirty_descendants(true); } curr = parent; } // Process hints. if hint.contains(RESTYLE_SELF) { unsafe { node.set_dirty(true); } // XXX(emilio): For now, dirty implies dirty descendants if found. } else if hint.contains(RESTYLE_DESCENDANTS) { let mut current = node.first_child(); while let Some(node) = current { unsafe { node.set_dirty(true); } current = node.next_sibling(); } } if hint.contains(RESTYLE_LATER_SIBLINGS) { let mut next = ::selectors::Element::next_sibling_element(self); while let Some(sib) = next { let sib_node = sib.as_node(); unsafe { sib_node.set_dirty(true) }; next = ::selectors::Element::next_sibling_element(&sib); } } } } pub struct
<ConcreteNode> where ConcreteNode: TNode { stack: Vec<ConcreteNode>, } impl<ConcreteNode> TreeIterator<ConcreteNode> where ConcreteNode: TNode { fn new(root: ConcreteNode) -> TreeIterator<ConcreteNode> { let mut stack = vec![]; stack.push(root); TreeIterator { stack: stack, } } pub fn next_skipping_children(&mut self) -> Option<ConcreteNode> { self.stack.pop() } } impl<ConcreteNode> Iterator for TreeIterator<ConcreteNode> where ConcreteNode: TNode { type Item = ConcreteNode; fn next(&mut self) -> Option<ConcreteNode> { let ret = self.stack.pop(); ret.map(|node| self.stack.extend(node.rev_children())); ret } } pub struct ChildrenIterator<ConcreteNode> where ConcreteNode: TNode { current: Option<ConcreteNode>, } impl<ConcreteNode> Iterator for ChildrenIterator<ConcreteNode> where ConcreteNode: TNode { type Item = ConcreteNode; fn next(&mut self) -> Option<ConcreteNode> { let node = self.current; self.current = node.and_then(|node| node.next_sibling()); node } } pub struct ReverseChildrenIterator<ConcreteNode> where ConcreteNode: TNode { current: Option<ConcreteNode>, } impl<ConcreteNode> Iterator for ReverseChildrenIterator<ConcreteNode> where ConcreteNode: TNode { type Item = ConcreteNode; fn next(&mut self) -> Option<ConcreteNode> { let node = self.current; self.current = node.and_then(|node| node.prev_sibling()); node } }
TreeIterator
identifier_name
dom.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/. */ //! Types and traits used to access the DOM from style calculation. #![allow(unsafe_code)] use context::SharedStyleContext; use data::PrivateStyleData; use element_state::ElementState; use properties::{ComputedValues, PropertyDeclaration, PropertyDeclarationBlock}; use refcell::{Ref, RefMut}; use restyle_hints::{RESTYLE_DESCENDANTS, RESTYLE_LATER_SIBLINGS, RESTYLE_SELF, RestyleHint}; use selector_impl::{ElementExt, PseudoElement}; use selectors::matching::DeclarationBlock; use sink::Push; use std::fmt::Debug; use std::ops::BitOr; use std::sync::Arc; use string_cache::{Atom, Namespace}; /// Opaque type stored in type-unsafe work queues for parallel layout. /// Must be transmutable to and from TNode. pub type UnsafeNode = (usize, usize); /// An opaque handle to a node, which, unlike UnsafeNode, cannot be transformed /// back into a non-opaque representation. The only safe operation that can be /// performed on this node is to compare it to another opaque handle or to another /// OpaqueNode. /// /// Layout and Graphics use this to safely represent nodes for comparison purposes. /// Because the script task's GC does not trace layout, node data cannot be safely stored in layout /// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for /// locality reasons. Using `OpaqueNode` enforces this invariant. #[derive(Clone, PartialEq, Copy, Debug, Hash, Eq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))] pub struct OpaqueNode(pub usize); impl OpaqueNode { /// Returns the address of this node, for debugging purposes. #[inline] pub fn id(&self) -> usize { self.0 } } pub trait TRestyleDamage : Debug + PartialEq + BitOr<Output=Self> + Copy { /// The source for our current computed values in the cascade. This is a /// ComputedValues in Servo and a StyleContext in Gecko. /// /// This is needed because Gecko has a few optimisations for the calculation /// of the difference depending on which values have been used during /// layout. /// /// This should be obtained via TNode::existing_style_for_restyle_damage type PreExistingComputedValues; fn compute(old: &Self::PreExistingComputedValues, new: &Arc<ComputedValues>) -> Self; fn empty() -> Self; fn rebuild_and_reflow() -> Self; } pub trait TNode : Sized + Copy + Clone { type ConcreteElement: TElement<ConcreteNode = Self, ConcreteDocument = Self::ConcreteDocument>; type ConcreteDocument: TDocument<ConcreteNode = Self, ConcreteElement = Self::ConcreteElement>; type ConcreteRestyleDamage: TRestyleDamage; fn to_unsafe(&self) -> UnsafeNode; unsafe fn from_unsafe(n: &UnsafeNode) -> Self; /// Returns whether this is a text node. It turns out that this is all the style system cares /// about, and thus obviates the need to compute the full type id, which would be expensive in /// Gecko. fn is_text_node(&self) -> bool; fn is_element(&self) -> bool; fn dump(self); fn dump_style(self); fn traverse_preorder(self) -> TreeIterator<Self> { TreeIterator::new(self) } /// Returns an iterator over this node's children. fn children(self) -> ChildrenIterator<Self> { ChildrenIterator { current: self.first_child(), } } fn rev_children(self) -> ReverseChildrenIterator<Self> { ReverseChildrenIterator { current: self.last_child(), } } /// Converts self into an `OpaqueNode`. fn opaque(&self) -> OpaqueNode; /// While doing a reflow, the node at the root has no parent, as far as we're /// concerned. This method returns `None` at the reflow root. fn layout_parent_node(self, reflow_root: OpaqueNode) -> Option<Self>; fn debug_id(self) -> usize; fn as_element(&self) -> Option<Self::ConcreteElement>; fn as_document(&self) -> Option<Self::ConcreteDocument>; fn children_count(&self) -> u32; fn has_changed(&self) -> bool; unsafe fn set_changed(&self, value: bool); fn is_dirty(&self) -> bool; unsafe fn set_dirty(&self, value: bool); fn has_dirty_descendants(&self) -> bool; unsafe fn set_dirty_descendants(&self, value: bool); fn needs_dirty_on_viewport_size_changed(&self) -> bool; unsafe fn set_dirty_on_viewport_size_changed(&self); fn can_be_fragmented(&self) -> bool; unsafe fn set_can_be_fragmented(&self, value: bool); /// Borrows the PrivateStyleData without checks. #[inline(always)] unsafe fn borrow_data_unchecked(&self) -> Option<*const PrivateStyleData>; /// Borrows the PrivateStyleData immutably. Fails on a conflicting borrow. #[inline(always)] fn borrow_data(&self) -> Option<Ref<PrivateStyleData>>; /// Borrows the PrivateStyleData mutably. Fails on a conflicting borrow. #[inline(always)] fn mutate_data(&self) -> Option<RefMut<PrivateStyleData>>; /// Get the description of how to account for recent style changes. fn restyle_damage(self) -> Self::ConcreteRestyleDamage; /// Set the restyle damage field. fn set_restyle_damage(self, damage: Self::ConcreteRestyleDamage); fn parent_node(&self) -> Option<Self>; fn first_child(&self) -> Option<Self>; fn last_child(&self) -> Option<Self>; fn prev_sibling(&self) -> Option<Self>; fn next_sibling(&self) -> Option<Self>; /// Returns the style results for the given node. If CSS selector matching /// has not yet been performed, fails. fn style(&self, _context: &SharedStyleContext) -> Ref<Arc<ComputedValues>> { Ref::map(self.borrow_data().unwrap(), |data| data.style.as_ref().unwrap()) } /// Removes the style from this node. fn unstyle(self) { self.mutate_data().unwrap().style = None; } /// XXX: It's a bit unfortunate we need to pass the current computed values /// as an argument here, but otherwise Servo would crash due to double /// borrows to return it. fn existing_style_for_restyle_damage<'a>(&'a self, current_computed_values: Option<&'a Arc<ComputedValues>>, pseudo: Option<&PseudoElement>) -> Option<&'a <Self::ConcreteRestyleDamage as TRestyleDamage>::PreExistingComputedValues>; } pub trait TDocument : Sized + Copy + Clone { type ConcreteNode: TNode<ConcreteElement = Self::ConcreteElement, ConcreteDocument = Self>; type ConcreteElement: TElement<ConcreteNode = Self::ConcreteNode, ConcreteDocument = Self>; fn as_node(&self) -> Self::ConcreteNode; fn root_node(&self) -> Option<Self::ConcreteNode>; fn drain_modified_elements(&self) -> Vec<(Self::ConcreteElement, <Self::ConcreteElement as ElementExt>::Snapshot)>; } pub trait PresentationalHintsSynthetizer { fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, hints: &mut V) where V: Push<DeclarationBlock<Vec<PropertyDeclaration>>>; } pub trait TElement : Sized + Copy + Clone + ElementExt + PresentationalHintsSynthetizer { type ConcreteNode: TNode<ConcreteElement = Self, ConcreteDocument = Self::ConcreteDocument>; type ConcreteDocument: TDocument<ConcreteNode = Self::ConcreteNode, ConcreteElement = Self>; fn as_node(&self) -> Self::ConcreteNode; fn style_attribute(&self) -> &Option<PropertyDeclarationBlock>; fn get_state(&self) -> ElementState; fn has_attr(&self, namespace: &Namespace, attr: &Atom) -> bool; fn attr_equals(&self, namespace: &Namespace, attr: &Atom, value: &Atom) -> bool; /// Properly marks nodes as dirty in response to restyle hints. fn note_restyle_hint(&self, hint: RestyleHint) { // Bail early if there's no restyling to do. if hint.is_empty() { return; } // If the restyle hint is non-empty, we need to restyle either this element // or one of its siblings. Mark our ancestor chain as having dirty descendants. let node = self.as_node(); let mut curr = node; while let Some(parent) = curr.parent_node() { if parent.has_dirty_descendants() { break } unsafe { parent.set_dirty_descendants(true); } curr = parent; } // Process hints. if hint.contains(RESTYLE_SELF) { unsafe { node.set_dirty(true); } // XXX(emilio): For now, dirty implies dirty descendants if found. } else if hint.contains(RESTYLE_DESCENDANTS) { let mut current = node.first_child(); while let Some(node) = current { unsafe { node.set_dirty(true); } current = node.next_sibling(); } } if hint.contains(RESTYLE_LATER_SIBLINGS) { let mut next = ::selectors::Element::next_sibling_element(self); while let Some(sib) = next { let sib_node = sib.as_node(); unsafe { sib_node.set_dirty(true) }; next = ::selectors::Element::next_sibling_element(&sib); } } } } pub struct TreeIterator<ConcreteNode> where ConcreteNode: TNode { stack: Vec<ConcreteNode>, } impl<ConcreteNode> TreeIterator<ConcreteNode> where ConcreteNode: TNode { fn new(root: ConcreteNode) -> TreeIterator<ConcreteNode> { let mut stack = vec![]; stack.push(root); TreeIterator { stack: stack, } } pub fn next_skipping_children(&mut self) -> Option<ConcreteNode>
} impl<ConcreteNode> Iterator for TreeIterator<ConcreteNode> where ConcreteNode: TNode { type Item = ConcreteNode; fn next(&mut self) -> Option<ConcreteNode> { let ret = self.stack.pop(); ret.map(|node| self.stack.extend(node.rev_children())); ret } } pub struct ChildrenIterator<ConcreteNode> where ConcreteNode: TNode { current: Option<ConcreteNode>, } impl<ConcreteNode> Iterator for ChildrenIterator<ConcreteNode> where ConcreteNode: TNode { type Item = ConcreteNode; fn next(&mut self) -> Option<ConcreteNode> { let node = self.current; self.current = node.and_then(|node| node.next_sibling()); node } } pub struct ReverseChildrenIterator<ConcreteNode> where ConcreteNode: TNode { current: Option<ConcreteNode>, } impl<ConcreteNode> Iterator for ReverseChildrenIterator<ConcreteNode> where ConcreteNode: TNode { type Item = ConcreteNode; fn next(&mut self) -> Option<ConcreteNode> { let node = self.current; self.current = node.and_then(|node| node.prev_sibling()); node } }
{ self.stack.pop() }
identifier_body
dom.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/. */ //! Types and traits used to access the DOM from style calculation. #![allow(unsafe_code)] use context::SharedStyleContext; use data::PrivateStyleData; use element_state::ElementState; use properties::{ComputedValues, PropertyDeclaration, PropertyDeclarationBlock}; use refcell::{Ref, RefMut}; use restyle_hints::{RESTYLE_DESCENDANTS, RESTYLE_LATER_SIBLINGS, RESTYLE_SELF, RestyleHint}; use selector_impl::{ElementExt, PseudoElement}; use selectors::matching::DeclarationBlock; use sink::Push; use std::fmt::Debug; use std::ops::BitOr; use std::sync::Arc; use string_cache::{Atom, Namespace}; /// Opaque type stored in type-unsafe work queues for parallel layout. /// Must be transmutable to and from TNode. pub type UnsafeNode = (usize, usize); /// An opaque handle to a node, which, unlike UnsafeNode, cannot be transformed /// back into a non-opaque representation. The only safe operation that can be /// performed on this node is to compare it to another opaque handle or to another /// OpaqueNode. /// /// Layout and Graphics use this to safely represent nodes for comparison purposes. /// Because the script task's GC does not trace layout, node data cannot be safely stored in layout /// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for /// locality reasons. Using `OpaqueNode` enforces this invariant. #[derive(Clone, PartialEq, Copy, Debug, Hash, Eq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))] pub struct OpaqueNode(pub usize); impl OpaqueNode { /// Returns the address of this node, for debugging purposes. #[inline] pub fn id(&self) -> usize { self.0 } } pub trait TRestyleDamage : Debug + PartialEq + BitOr<Output=Self> + Copy { /// The source for our current computed values in the cascade. This is a /// ComputedValues in Servo and a StyleContext in Gecko. /// /// This is needed because Gecko has a few optimisations for the calculation /// of the difference depending on which values have been used during /// layout. /// /// This should be obtained via TNode::existing_style_for_restyle_damage type PreExistingComputedValues; fn compute(old: &Self::PreExistingComputedValues, new: &Arc<ComputedValues>) -> Self; fn empty() -> Self; fn rebuild_and_reflow() -> Self; } pub trait TNode : Sized + Copy + Clone { type ConcreteElement: TElement<ConcreteNode = Self, ConcreteDocument = Self::ConcreteDocument>; type ConcreteDocument: TDocument<ConcreteNode = Self, ConcreteElement = Self::ConcreteElement>; type ConcreteRestyleDamage: TRestyleDamage; fn to_unsafe(&self) -> UnsafeNode; unsafe fn from_unsafe(n: &UnsafeNode) -> Self; /// Returns whether this is a text node. It turns out that this is all the style system cares /// about, and thus obviates the need to compute the full type id, which would be expensive in /// Gecko. fn is_text_node(&self) -> bool; fn is_element(&self) -> bool; fn dump(self); fn dump_style(self); fn traverse_preorder(self) -> TreeIterator<Self> { TreeIterator::new(self) } /// Returns an iterator over this node's children. fn children(self) -> ChildrenIterator<Self> { ChildrenIterator { current: self.first_child(), } } fn rev_children(self) -> ReverseChildrenIterator<Self> { ReverseChildrenIterator { current: self.last_child(), } } /// Converts self into an `OpaqueNode`. fn opaque(&self) -> OpaqueNode; /// While doing a reflow, the node at the root has no parent, as far as we're /// concerned. This method returns `None` at the reflow root. fn layout_parent_node(self, reflow_root: OpaqueNode) -> Option<Self>; fn debug_id(self) -> usize; fn as_element(&self) -> Option<Self::ConcreteElement>; fn as_document(&self) -> Option<Self::ConcreteDocument>; fn children_count(&self) -> u32;
fn is_dirty(&self) -> bool; unsafe fn set_dirty(&self, value: bool); fn has_dirty_descendants(&self) -> bool; unsafe fn set_dirty_descendants(&self, value: bool); fn needs_dirty_on_viewport_size_changed(&self) -> bool; unsafe fn set_dirty_on_viewport_size_changed(&self); fn can_be_fragmented(&self) -> bool; unsafe fn set_can_be_fragmented(&self, value: bool); /// Borrows the PrivateStyleData without checks. #[inline(always)] unsafe fn borrow_data_unchecked(&self) -> Option<*const PrivateStyleData>; /// Borrows the PrivateStyleData immutably. Fails on a conflicting borrow. #[inline(always)] fn borrow_data(&self) -> Option<Ref<PrivateStyleData>>; /// Borrows the PrivateStyleData mutably. Fails on a conflicting borrow. #[inline(always)] fn mutate_data(&self) -> Option<RefMut<PrivateStyleData>>; /// Get the description of how to account for recent style changes. fn restyle_damage(self) -> Self::ConcreteRestyleDamage; /// Set the restyle damage field. fn set_restyle_damage(self, damage: Self::ConcreteRestyleDamage); fn parent_node(&self) -> Option<Self>; fn first_child(&self) -> Option<Self>; fn last_child(&self) -> Option<Self>; fn prev_sibling(&self) -> Option<Self>; fn next_sibling(&self) -> Option<Self>; /// Returns the style results for the given node. If CSS selector matching /// has not yet been performed, fails. fn style(&self, _context: &SharedStyleContext) -> Ref<Arc<ComputedValues>> { Ref::map(self.borrow_data().unwrap(), |data| data.style.as_ref().unwrap()) } /// Removes the style from this node. fn unstyle(self) { self.mutate_data().unwrap().style = None; } /// XXX: It's a bit unfortunate we need to pass the current computed values /// as an argument here, but otherwise Servo would crash due to double /// borrows to return it. fn existing_style_for_restyle_damage<'a>(&'a self, current_computed_values: Option<&'a Arc<ComputedValues>>, pseudo: Option<&PseudoElement>) -> Option<&'a <Self::ConcreteRestyleDamage as TRestyleDamage>::PreExistingComputedValues>; } pub trait TDocument : Sized + Copy + Clone { type ConcreteNode: TNode<ConcreteElement = Self::ConcreteElement, ConcreteDocument = Self>; type ConcreteElement: TElement<ConcreteNode = Self::ConcreteNode, ConcreteDocument = Self>; fn as_node(&self) -> Self::ConcreteNode; fn root_node(&self) -> Option<Self::ConcreteNode>; fn drain_modified_elements(&self) -> Vec<(Self::ConcreteElement, <Self::ConcreteElement as ElementExt>::Snapshot)>; } pub trait PresentationalHintsSynthetizer { fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, hints: &mut V) where V: Push<DeclarationBlock<Vec<PropertyDeclaration>>>; } pub trait TElement : Sized + Copy + Clone + ElementExt + PresentationalHintsSynthetizer { type ConcreteNode: TNode<ConcreteElement = Self, ConcreteDocument = Self::ConcreteDocument>; type ConcreteDocument: TDocument<ConcreteNode = Self::ConcreteNode, ConcreteElement = Self>; fn as_node(&self) -> Self::ConcreteNode; fn style_attribute(&self) -> &Option<PropertyDeclarationBlock>; fn get_state(&self) -> ElementState; fn has_attr(&self, namespace: &Namespace, attr: &Atom) -> bool; fn attr_equals(&self, namespace: &Namespace, attr: &Atom, value: &Atom) -> bool; /// Properly marks nodes as dirty in response to restyle hints. fn note_restyle_hint(&self, hint: RestyleHint) { // Bail early if there's no restyling to do. if hint.is_empty() { return; } // If the restyle hint is non-empty, we need to restyle either this element // or one of its siblings. Mark our ancestor chain as having dirty descendants. let node = self.as_node(); let mut curr = node; while let Some(parent) = curr.parent_node() { if parent.has_dirty_descendants() { break } unsafe { parent.set_dirty_descendants(true); } curr = parent; } // Process hints. if hint.contains(RESTYLE_SELF) { unsafe { node.set_dirty(true); } // XXX(emilio): For now, dirty implies dirty descendants if found. } else if hint.contains(RESTYLE_DESCENDANTS) { let mut current = node.first_child(); while let Some(node) = current { unsafe { node.set_dirty(true); } current = node.next_sibling(); } } if hint.contains(RESTYLE_LATER_SIBLINGS) { let mut next = ::selectors::Element::next_sibling_element(self); while let Some(sib) = next { let sib_node = sib.as_node(); unsafe { sib_node.set_dirty(true) }; next = ::selectors::Element::next_sibling_element(&sib); } } } } pub struct TreeIterator<ConcreteNode> where ConcreteNode: TNode { stack: Vec<ConcreteNode>, } impl<ConcreteNode> TreeIterator<ConcreteNode> where ConcreteNode: TNode { fn new(root: ConcreteNode) -> TreeIterator<ConcreteNode> { let mut stack = vec![]; stack.push(root); TreeIterator { stack: stack, } } pub fn next_skipping_children(&mut self) -> Option<ConcreteNode> { self.stack.pop() } } impl<ConcreteNode> Iterator for TreeIterator<ConcreteNode> where ConcreteNode: TNode { type Item = ConcreteNode; fn next(&mut self) -> Option<ConcreteNode> { let ret = self.stack.pop(); ret.map(|node| self.stack.extend(node.rev_children())); ret } } pub struct ChildrenIterator<ConcreteNode> where ConcreteNode: TNode { current: Option<ConcreteNode>, } impl<ConcreteNode> Iterator for ChildrenIterator<ConcreteNode> where ConcreteNode: TNode { type Item = ConcreteNode; fn next(&mut self) -> Option<ConcreteNode> { let node = self.current; self.current = node.and_then(|node| node.next_sibling()); node } } pub struct ReverseChildrenIterator<ConcreteNode> where ConcreteNode: TNode { current: Option<ConcreteNode>, } impl<ConcreteNode> Iterator for ReverseChildrenIterator<ConcreteNode> where ConcreteNode: TNode { type Item = ConcreteNode; fn next(&mut self) -> Option<ConcreteNode> { let node = self.current; self.current = node.and_then(|node| node.prev_sibling()); node } }
fn has_changed(&self) -> bool; unsafe fn set_changed(&self, value: bool);
random_line_split
compiler.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use std::path::PathBuf; use chrono::naive::NaiveDateTime; use chrono::Datelike; use chrono::Timelike; use libimagstore::storeid::StoreId; use crate::datepath::accuracy::Accuracy; use crate::datepath::format::Format; use anyhow::Result; pub struct DatePathCompiler { accuracy : Accuracy, format : Format, } impl DatePathCompiler { pub fn new(accuracy: Accuracy, format: Format) -> DatePathCompiler { DatePathCompiler { accuracy, format, } } /// Compile a NaiveDateTime object into a StoreId object. /// /// # More information /// /// See the documentations of the `Format` and the `Accuracy` types as well. /// /// # Warnings /// /// This does _not_ guarantee that the StoreId can be created, is not yet in the store or /// anything else. Overall, this is just a `spec->path` compiler which is really stupid. /// /// # Return value /// /// The `StoreId` object on success. /// pub fn compile(&self, module_name: &str, datetime: &NaiveDateTime) -> Result<StoreId> { let mut s = format!("{}/", module_name); if self.accuracy.has_year_accuracy() /* always true */ { s.push_str(&format!("{:04}", datetime.year())); } if self.accuracy.has_month_accuracy() { match self.format { Format::ElementIsFolder | Format::DaysAreFolder | Format::MonthIsFolder | Format::YearIsFolder => s.push_str(&format!("/{:02}", datetime.month())), } } if self.accuracy.has_day_accuracy() { match self.format { Format::ElementIsFolder | Format::DaysAreFolder | Format::MonthIsFolder => s.push_str(&format!("/{:02}", datetime.day())), Format::YearIsFolder => s.push_str(&format!("-{:02}", datetime.day())), } } if self.accuracy.has_hour_accuracy() { match self.format { Format::ElementIsFolder | Format::DaysAreFolder => s.push_str(&format!("/{:02}", datetime.hour())), Format::YearIsFolder | Format::MonthIsFolder => s.push_str(&format!("-{:02}", datetime.hour())), } } if self.accuracy.has_minute_accuracy() { match self.format { Format::ElementIsFolder => s.push_str(&format!("/{:02}", datetime.minute())), Format::YearIsFolder | Format::MonthIsFolder | Format::DaysAreFolder => s.push_str(&format!("-{:02}", datetime.minute())), } } if self.accuracy.has_second_accuracy() { match self.format { Format::ElementIsFolder => s.push_str(&format!("/{:02}", datetime.second())), Format::YearIsFolder | Format::MonthIsFolder | Format::DaysAreFolder => s.push_str(&format!("-{:02}", datetime.second())), } } StoreId::new(PathBuf::from(s)) } } #[cfg(test)] mod test { use super::*; use crate::datepath::accuracy::Accuracy; use crate::datepath::format::Format; use chrono::naive::NaiveDate; use chrono::naive::NaiveDateTime; #[test] fn test_compiler_compile_simple() { let dt = NaiveDate::from_ymd(2000, 1, 1).and_hms(0, 0, 0); let compiler = DatePathCompiler::new(Accuracy::default(), Format::default()); let res = compiler.compile("testmodule", &dt); assert!(res.is_ok()); let res = res.unwrap(); let s = res.to_str(); assert!(s.is_ok()); let s = s.unwrap(); assert_eq!("testmodule/2000/01/01/00/00/00", s); } fn
(acc: Accuracy, dt: NaiveDateTime, modname: &str, matchstr: &str) { let compiler = DatePathCompiler::new(acc, Format::default()); let res = compiler.compile(modname, &dt); assert!(res.is_ok()); let res = res.unwrap(); let s = res.to_str(); assert!(s.is_ok()); let s = s.unwrap(); assert_eq!(matchstr, s); } #[test] fn test_compiler_compile_year_accuracy() { let dt = NaiveDate::from_ymd(2000, 1, 1).and_hms(0, 0, 0); test_accuracy(Accuracy::Year, dt, "module", "module/2000"); } #[test] fn test_compiler_compile_month_accuracy() { let dt = NaiveDate::from_ymd(2000, 1, 1).and_hms(0, 0, 0); test_accuracy(Accuracy::Month, dt, "module", "module/2000/01"); } #[test] fn test_compiler_compile_day_accuracy() { let dt = NaiveDate::from_ymd(2000, 1, 1).and_hms(0, 0, 0); test_accuracy(Accuracy::Day, dt, "module", "module/2000/01/01"); } #[test] fn test_compiler_compile_year_paddning() { let dt = NaiveDate::from_ymd(1, 1, 1).and_hms(0, 0, 0); test_accuracy(Accuracy::Day, dt, "module", "module/0001/01/01"); } }
test_accuracy
identifier_name