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
dijkstra.rs
use std::hash::Hash; use collections::hashmap::HashMap; use collections::hashmap::HashSet; /// Build a Dijkstra map starting from the goal nodes and using the neighbors /// function to define the graph to up to limit distance. pub fn build_map<N: Hash + Eq + Clone>( goals: ~[N], neighbors: |&N| -> ~[N], limit: uint) -> HashMap<N, uint> {
// Init goal nodes to zero score. for k in goals.iter() { ret.insert(k.clone(), 0); } let mut edge = ~HashSet::new(); for k in goals.iter() { for n in neighbors(k).iter() { // XXX: Extra clone op here, should just shuffle references until // things get cloned for the ret structure. if!ret.contains_key(n) { edge.insert(n.clone()); } } } for dist in range(1, limit) { for k in edge.iter() { ret.insert(k.clone(), dist); } let mut new_edge = ~HashSet::new(); for k in edge.iter() { for n in neighbors(k).iter() { if!ret.contains_key(n) { new_edge.insert(n.clone()); } } } edge = new_edge; } ret }
assert!(goals.len() > 0); let mut ret = HashMap::new();
random_line_split
dijkstra.rs
use std::hash::Hash; use collections::hashmap::HashMap; use collections::hashmap::HashSet; /// Build a Dijkstra map starting from the goal nodes and using the neighbors /// function to define the graph to up to limit distance. pub fn build_map<N: Hash + Eq + Clone>( goals: ~[N], neighbors: |&N| -> ~[N], limit: uint) -> HashMap<N, uint>
for k in edge.iter() { ret.insert(k.clone(), dist); } let mut new_edge = ~HashSet::new(); for k in edge.iter() { for n in neighbors(k).iter() { if!ret.contains_key(n) { new_edge.insert(n.clone()); } } } edge = new_edge; } ret }
{ assert!(goals.len() > 0); let mut ret = HashMap::new(); // Init goal nodes to zero score. for k in goals.iter() { ret.insert(k.clone(), 0); } let mut edge = ~HashSet::new(); for k in goals.iter() { for n in neighbors(k).iter() { // XXX: Extra clone op here, should just shuffle references until // things get cloned for the ret structure. if !ret.contains_key(n) { edge.insert(n.clone()); } } } for dist in range(1, limit) {
identifier_body
state.rs
// Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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. // // cancer 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 cancer. If not, see <http://www.gnu.org/licenses/>. use std::sync::Arc; use util::clamp; use picto::Region; use config::Config; use font::Font; #[derive(Clone, Debug)] pub struct State { pub(super) config: Arc<Config>, pub(super) font: Arc<Font>, pub(super) width: u32, pub(super) height: u32, pub(super) margin: Margin, } /// Adaptable margins depending on the view size. #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct Margin { pub horizontal: u32, pub vertical: u32, } impl State { /// The terminal configuration. pub fn config(&self) -> &Arc<Config> { &self.config } /// The font being used. pub fn font(&self) -> &Arc<Font> { &self.font } /// The view width. pub fn width(&self) -> u32 { self.width } /// The view height. pub fn height(&self) -> u32 { self.height } /// How many rows fit the view. pub fn rows(&self) -> u32 { (self.height - (self.margin.vertical * 2)) / (self.font.height() + self.config.style().spacing()) } /// How many columns fit the view. pub fn columns(&self) -> u32 {
/// The current margins. pub fn margin(&self) -> &Margin { &self.margin } /// Resize the state. pub fn resize(&mut self, width: u32, height: u32) { let (m, s) = (self.config.style().margin(), self.config.style().spacing()); self.margin.horizontal = m + ((width - (m * 2)) % self.font.width()) / 2; self.margin.vertical = m + ((height - (m * 2)) % (self.font.height() + s)) / 2; self.width = width; self.height = height; } /// Find the cell position from the real position. pub fn position(&self, x: u32, y: u32) -> Option<(u32, u32)> { let (f, h, v, s) = (&self.font, self.margin.horizontal, self.margin.vertical, self.config.style().spacing()); // Check if the region falls exactly within a margin, if so bail out. if h!= 0 && v!= 0 && (x < h || x >= self.width - h || y < v || y >= self.height - v) { return None; } // Cache font dimensions. let width = f.width() as f32; let height = (f.height() + s) as f32; // Remove the margin from coordinates. let x = x.saturating_sub(h) as f32; let y = y.saturating_sub(v) as f32; let x = (x / width).floor() as u32; let y = (y / height).floor() as u32; Some((x, y)) } /// Turn the damaged region to cell-space. pub fn damaged(&self, region: &Region) -> Region { let (f, h, v, s) = (&self.font, self.margin.horizontal, self.margin.vertical, self.config.style().spacing()); // Check if the region falls exactly within a margin, if so bail out. if h!= 0 && v!= 0 && ((region.x < h && region.width <= h - region.x) || (region.x >= self.width - h) || (region.y < v && region.height <= v - region.y) || (region.y >= self.height - v)) { return Region::from(0, 0, 0, 0); } // Cache font dimensions. let width = f.width() as f32; let height = (f.height() + s) as f32; // Remove the margin from coordinates. let x = region.x.saturating_sub(h) as f32; let y = region.y.saturating_sub(v) as f32; // Remove margins from width. let w = region.width .saturating_sub(h.saturating_sub(region.x)) .saturating_sub(h.saturating_sub(self.width - (region.x + region.width))) as f32; // Remove margins from height. let h = region.height .saturating_sub(v.saturating_sub(region.y)) .saturating_sub(v.saturating_sub(self.height - (region.y + region.height))) as f32; let x = (x / width).floor() as u32; let y = (y / height).floor() as u32; let w = clamp((w / width).ceil() as u32, 0, self.columns()); let h = clamp((h / height).ceil() as u32, 0, self.rows()); // Increment width and height by one if it fits within dimensions. // // This is done because the dirty region is actually bigger than the one // reported, or because the algorithm is broken. Regardless, this way it // works properly. Region::from(x, y, w + if x + w < self.columns() { 1 } else { 0 }, h + if y + h < self.rows() { 1 } else { 0 }) } }
(self.width - (self.margin.horizontal * 2)) / self.font.width() }
identifier_body
state.rs
// Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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. // // cancer 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 cancer. If not, see <http://www.gnu.org/licenses/>. use std::sync::Arc; use util::clamp; use picto::Region; use config::Config; use font::Font; #[derive(Clone, Debug)] pub struct State { pub(super) config: Arc<Config>, pub(super) font: Arc<Font>, pub(super) width: u32, pub(super) height: u32, pub(super) margin: Margin, } /// Adaptable margins depending on the view size. #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct Margin { pub horizontal: u32, pub vertical: u32, } impl State { /// The terminal configuration. pub fn config(&self) -> &Arc<Config> { &self.config } /// The font being used. pub fn font(&self) -> &Arc<Font> { &self.font } /// The view width. pub fn width(&self) -> u32 { self.width } /// The view height. pub fn height(&self) -> u32 { self.height } /// How many rows fit the view. pub fn rows(&self) -> u32 { (self.height - (self.margin.vertical * 2)) / (self.font.height() + self.config.style().spacing()) } /// How many columns fit the view. pub fn columns(&self) -> u32 { (self.width - (self.margin.horizontal * 2)) / self.font.width() } /// The current margins. pub fn margin(&self) -> &Margin { &self.margin } /// Resize the state. pub fn resize(&mut self, width: u32, height: u32) { let (m, s) = (self.config.style().margin(), self.config.style().spacing()); self.margin.horizontal = m + ((width - (m * 2)) % self.font.width()) / 2; self.margin.vertical = m + ((height - (m * 2)) % (self.font.height() + s)) / 2; self.width = width; self.height = height; } /// Find the cell position from the real position. pub fn position(&self, x: u32, y: u32) -> Option<(u32, u32)> { let (f, h, v, s) = (&self.font, self.margin.horizontal, self.margin.vertical, self.config.style().spacing()); // Check if the region falls exactly within a margin, if so bail out. if h!= 0 && v!= 0 && (x < h || x >= self.width - h || y < v || y >= self.height - v) { return None; } // Cache font dimensions. let width = f.width() as f32; let height = (f.height() + s) as f32; // Remove the margin from coordinates. let x = x.saturating_sub(h) as f32; let y = y.saturating_sub(v) as f32; let x = (x / width).floor() as u32; let y = (y / height).floor() as u32; Some((x, y)) } /// Turn the damaged region to cell-space. pub fn damaged(&self, region: &Region) -> Region { let (f, h, v, s) = (&self.font, self.margin.horizontal, self.margin.vertical, self.config.style().spacing()); // Check if the region falls exactly within a margin, if so bail out. if h!= 0 && v!= 0 && ((region.x < h && region.width <= h - region.x) || (region.x >= self.width - h) || (region.y < v && region.height <= v - region.y) || (region.y >= self.height - v)) { return Region::from(0, 0, 0, 0); } // Cache font dimensions. let width = f.width() as f32; let height = (f.height() + s) as f32; // Remove the margin from coordinates. let x = region.x.saturating_sub(h) as f32; let y = region.y.saturating_sub(v) as f32; // Remove margins from width. let w = region.width .saturating_sub(h.saturating_sub(region.x)) .saturating_sub(h.saturating_sub(self.width - (region.x + region.width))) as f32; // Remove margins from height. let h = region.height .saturating_sub(v.saturating_sub(region.y)) .saturating_sub(v.saturating_sub(self.height - (region.y + region.height))) as f32; let x = (x / width).floor() as u32; let y = (y / height).floor() as u32; let w = clamp((w / width).ceil() as u32, 0, self.columns()); let h = clamp((h / height).ceil() as u32, 0, self.rows()); // Increment width and height by one if it fits within dimensions. // // This is done because the dirty region is actually bigger than the one // reported, or because the algorithm is broken. Regardless, this way it // works properly. Region::from(x, y, w + if x + w < self.columns() { 1 } else { 0 }, h + if y + h < self.rows() {
lse { 0 }) } }
1 } e
conditional_block
state.rs
// Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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. // // cancer 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 cancer. If not, see <http://www.gnu.org/licenses/>. use std::sync::Arc; use util::clamp; use picto::Region; use config::Config; use font::Font; #[derive(Clone, Debug)] pub struct State { pub(super) config: Arc<Config>, pub(super) font: Arc<Font>, pub(super) width: u32, pub(super) height: u32, pub(super) margin: Margin, } /// Adaptable margins depending on the view size. #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct Margin { pub horizontal: u32, pub vertical: u32, } impl State { /// The terminal configuration. pub fn config(&self) -> &Arc<Config> { &self.config } /// The font being used. pub fn font(&self) -> &Arc<Font> { &self.font } /// The view width. pub fn width(&self) -> u32 { self.width } /// The view height. pub fn height(&self) -> u32 { self.height } /// How many rows fit the view. pub fn rows(&self) -> u32 { (self.height - (self.margin.vertical * 2)) / (self.font.height() + self.config.style().spacing()) } /// How many columns fit the view. pub fn columns(&self) -> u32 { (self.width - (self.margin.horizontal * 2)) / self.font.width() } /// The current margins. pub fn margin(&self) -> &Margin { &self.margin } /// Resize the state. pub fn re
mut self, width: u32, height: u32) { let (m, s) = (self.config.style().margin(), self.config.style().spacing()); self.margin.horizontal = m + ((width - (m * 2)) % self.font.width()) / 2; self.margin.vertical = m + ((height - (m * 2)) % (self.font.height() + s)) / 2; self.width = width; self.height = height; } /// Find the cell position from the real position. pub fn position(&self, x: u32, y: u32) -> Option<(u32, u32)> { let (f, h, v, s) = (&self.font, self.margin.horizontal, self.margin.vertical, self.config.style().spacing()); // Check if the region falls exactly within a margin, if so bail out. if h!= 0 && v!= 0 && (x < h || x >= self.width - h || y < v || y >= self.height - v) { return None; } // Cache font dimensions. let width = f.width() as f32; let height = (f.height() + s) as f32; // Remove the margin from coordinates. let x = x.saturating_sub(h) as f32; let y = y.saturating_sub(v) as f32; let x = (x / width).floor() as u32; let y = (y / height).floor() as u32; Some((x, y)) } /// Turn the damaged region to cell-space. pub fn damaged(&self, region: &Region) -> Region { let (f, h, v, s) = (&self.font, self.margin.horizontal, self.margin.vertical, self.config.style().spacing()); // Check if the region falls exactly within a margin, if so bail out. if h!= 0 && v!= 0 && ((region.x < h && region.width <= h - region.x) || (region.x >= self.width - h) || (region.y < v && region.height <= v - region.y) || (region.y >= self.height - v)) { return Region::from(0, 0, 0, 0); } // Cache font dimensions. let width = f.width() as f32; let height = (f.height() + s) as f32; // Remove the margin from coordinates. let x = region.x.saturating_sub(h) as f32; let y = region.y.saturating_sub(v) as f32; // Remove margins from width. let w = region.width .saturating_sub(h.saturating_sub(region.x)) .saturating_sub(h.saturating_sub(self.width - (region.x + region.width))) as f32; // Remove margins from height. let h = region.height .saturating_sub(v.saturating_sub(region.y)) .saturating_sub(v.saturating_sub(self.height - (region.y + region.height))) as f32; let x = (x / width).floor() as u32; let y = (y / height).floor() as u32; let w = clamp((w / width).ceil() as u32, 0, self.columns()); let h = clamp((h / height).ceil() as u32, 0, self.rows()); // Increment width and height by one if it fits within dimensions. // // This is done because the dirty region is actually bigger than the one // reported, or because the algorithm is broken. Regardless, this way it // works properly. Region::from(x, y, w + if x + w < self.columns() { 1 } else { 0 }, h + if y + h < self.rows() { 1 } else { 0 }) } }
size(&
identifier_name
state.rs
// Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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. // // cancer 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 cancer. If not, see <http://www.gnu.org/licenses/>. use std::sync::Arc; use util::clamp; use picto::Region; use config::Config; use font::Font; #[derive(Clone, Debug)] pub struct State { pub(super) config: Arc<Config>, pub(super) font: Arc<Font>, pub(super) width: u32, pub(super) height: u32, pub(super) margin: Margin, } /// Adaptable margins depending on the view size. #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct Margin { pub horizontal: u32, pub vertical: u32, } impl State { /// The terminal configuration. pub fn config(&self) -> &Arc<Config> { &self.config } /// The font being used. pub fn font(&self) -> &Arc<Font> { &self.font } /// The view width. pub fn width(&self) -> u32 { self.width } /// The view height. pub fn height(&self) -> u32 { self.height } /// How many rows fit the view. pub fn rows(&self) -> u32 { (self.height - (self.margin.vertical * 2)) / (self.font.height() + self.config.style().spacing()) } /// How many columns fit the view. pub fn columns(&self) -> u32 { (self.width - (self.margin.horizontal * 2)) / self.font.width() } /// The current margins. pub fn margin(&self) -> &Margin { &self.margin } /// Resize the state. pub fn resize(&mut self, width: u32, height: u32) { let (m, s) = (self.config.style().margin(), self.config.style().spacing()); self.margin.horizontal = m + ((width - (m * 2)) % self.font.width()) / 2; self.margin.vertical = m + ((height - (m * 2)) % (self.font.height() + s)) / 2; self.width = width; self.height = height; } /// Find the cell position from the real position. pub fn position(&self, x: u32, y: u32) -> Option<(u32, u32)> { let (f, h, v, s) = (&self.font, self.margin.horizontal, self.margin.vertical, self.config.style().spacing()); // Check if the region falls exactly within a margin, if so bail out. if h!= 0 && v!= 0 && (x < h || x >= self.width - h || y < v || y >= self.height - v) { return None; } // Cache font dimensions. let width = f.width() as f32; let height = (f.height() + s) as f32; // Remove the margin from coordinates. let x = x.saturating_sub(h) as f32; let y = y.saturating_sub(v) as f32; let x = (x / width).floor() as u32; let y = (y / height).floor() as u32; Some((x, y)) } /// Turn the damaged region to cell-space. pub fn damaged(&self, region: &Region) -> Region { let (f, h, v, s) = (&self.font, self.margin.horizontal, self.margin.vertical, self.config.style().spacing()); // Check if the region falls exactly within a margin, if so bail out. if h!= 0 && v!= 0 && ((region.x < h && region.width <= h - region.x) || (region.x >= self.width - h) || (region.y < v && region.height <= v - region.y) || (region.y >= self.height - v)) { return Region::from(0, 0, 0, 0); } // Cache font dimensions. let width = f.width() as f32; let height = (f.height() + s) as f32; // Remove the margin from coordinates. let x = region.x.saturating_sub(h) as f32; let y = region.y.saturating_sub(v) as f32; // Remove margins from width. let w = region.width .saturating_sub(h.saturating_sub(region.x))
.saturating_sub(h.saturating_sub(self.width - (region.x + region.width))) as f32; // Remove margins from height. let h = region.height .saturating_sub(v.saturating_sub(region.y)) .saturating_sub(v.saturating_sub(self.height - (region.y + region.height))) as f32; let x = (x / width).floor() as u32; let y = (y / height).floor() as u32; let w = clamp((w / width).ceil() as u32, 0, self.columns()); let h = clamp((h / height).ceil() as u32, 0, self.rows()); // Increment width and height by one if it fits within dimensions. // // This is done because the dirty region is actually bigger than the one // reported, or because the algorithm is broken. Regardless, this way it // works properly. Region::from(x, y, w + if x + w < self.columns() { 1 } else { 0 }, h + if y + h < self.rows() { 1 } else { 0 }) } }
random_line_split
size_of_in_element_count.rs
//! Lint on use of `size_of` or `size_of_val` of T in an expression //! expecting a count of T use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, Ty, TyS, TypeAndMut}; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// ### What it does /// Detects expressions where /// `size_of::<T>` or `size_of_val::<T>` is used as a /// count of elements of type `T` /// /// ### Why is this bad? /// These functions expect a count /// of `T` and not a number of bytes /// /// ### Example /// ```rust,no_run /// # use std::ptr::copy_nonoverlapping; /// # use std::mem::size_of; /// const SIZE: usize = 128; /// let x = [2u8; SIZE]; /// let mut y = [2u8; SIZE]; /// unsafe { copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), size_of::<u8>() * SIZE) }; /// ``` pub SIZE_OF_IN_ELEMENT_COUNT, correctness, "using `size_of::<T>` or `size_of_val::<T>` where a count of elements of `T` is expected" } declare_lint_pass!(SizeOfInElementCount => [SIZE_OF_IN_ELEMENT_COUNT]); fn get_size_of_ty(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, inverted: bool) -> Option<Ty<'tcx>> { match expr.kind { ExprKind::Call(count_func, _func_args) => { if_chain! { if!inverted; if let ExprKind::Path(ref count_func_qpath) = count_func.kind; if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id(); if match_def_path(cx, def_id, &paths::MEM_SIZE_OF) || match_def_path(cx, def_id, &paths::MEM_SIZE_OF_VAL); then { cx.typeck_results().node_substs(count_func.hir_id).types().next() } else { None } } }, ExprKind::Binary(op, left, right) if BinOpKind::Mul == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right, inverted)) }, ExprKind::Binary(op, left, right) if BinOpKind::Div == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right,!inverted)) }, ExprKind::Cast(expr, _) => get_size_of_ty(cx, expr, inverted), _ => None, } } fn
(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(Ty<'tcx>, &'tcx Expr<'tcx>)> { const FUNCTIONS: [&[&str]; 8] = [ &paths::PTR_COPY_NONOVERLAPPING, &paths::PTR_COPY, &paths::PTR_WRITE_BYTES, &paths::PTR_SWAP_NONOVERLAPPING, &paths::PTR_SLICE_FROM_RAW_PARTS, &paths::PTR_SLICE_FROM_RAW_PARTS_MUT, &paths::SLICE_FROM_RAW_PARTS, &paths::SLICE_FROM_RAW_PARTS_MUT, ]; const METHODS: [&str; 11] = [ "write_bytes", "copy_to", "copy_from", "copy_to_nonoverlapping", "copy_from_nonoverlapping", "add", "wrapping_add", "sub", "wrapping_sub", "offset", "wrapping_offset", ]; if_chain! { // Find calls to ptr::{copy, copy_nonoverlapping} // and ptr::{swap_nonoverlapping, write_bytes}, if let ExprKind::Call(func, [.., count]) = expr.kind; if let ExprKind::Path(ref func_qpath) = func.kind; if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id(); if FUNCTIONS.iter().any(|func_path| match_def_path(cx, def_id, func_path)); // Get the pointee type if let Some(pointee_ty) = cx.typeck_results().node_substs(func.hir_id).types().next(); then { return Some((pointee_ty, count)); } }; if_chain! { // Find calls to copy_{from,to}{,_nonoverlapping} and write_bytes methods if let ExprKind::MethodCall(method_path, _, [ptr_self,.., count], _) = expr.kind; let method_ident = method_path.ident.as_str(); if METHODS.iter().any(|m| *m == &*method_ident); // Get the pointee type if let ty::RawPtr(TypeAndMut { ty: pointee_ty,.. }) = cx.typeck_results().expr_ty(ptr_self).kind(); then { return Some((pointee_ty, count)); } }; None } impl<'tcx> LateLintPass<'tcx> for SizeOfInElementCount { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { const HELP_MSG: &str = "use a count of elements instead of a count of bytes\ , it already gets multiplied by the size of the type"; const LINT_MSG: &str = "found a count of bytes \ instead of a count of elements of `T`"; if_chain! { // Find calls to functions with an element count parameter and get // the pointee type and count parameter expression if let Some((pointee_ty, count_expr)) = get_pointee_ty_and_count_expr(cx, expr); // Find a size_of call in the count parameter expression and // check that it's the same type if let Some(ty_used_for_size_of) = get_size_of_ty(cx, count_expr, false); if TyS::same_type(pointee_ty, ty_used_for_size_of); then { span_lint_and_help( cx, SIZE_OF_IN_ELEMENT_COUNT, count_expr.span, LINT_MSG, None, HELP_MSG ); } }; } }
get_pointee_ty_and_count_expr
identifier_name
size_of_in_element_count.rs
//! Lint on use of `size_of` or `size_of_val` of T in an expression //! expecting a count of T use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, Ty, TyS, TypeAndMut}; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// ### What it does /// Detects expressions where /// `size_of::<T>` or `size_of_val::<T>` is used as a /// count of elements of type `T` /// /// ### Why is this bad? /// These functions expect a count /// of `T` and not a number of bytes /// /// ### Example /// ```rust,no_run /// # use std::ptr::copy_nonoverlapping; /// # use std::mem::size_of; /// const SIZE: usize = 128; /// let x = [2u8; SIZE]; /// let mut y = [2u8; SIZE]; /// unsafe { copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), size_of::<u8>() * SIZE) }; /// ``` pub SIZE_OF_IN_ELEMENT_COUNT, correctness, "using `size_of::<T>` or `size_of_val::<T>` where a count of elements of `T` is expected" } declare_lint_pass!(SizeOfInElementCount => [SIZE_OF_IN_ELEMENT_COUNT]); fn get_size_of_ty(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, inverted: bool) -> Option<Ty<'tcx>> { match expr.kind { ExprKind::Call(count_func, _func_args) => { if_chain! { if!inverted; if let ExprKind::Path(ref count_func_qpath) = count_func.kind; if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id(); if match_def_path(cx, def_id, &paths::MEM_SIZE_OF) || match_def_path(cx, def_id, &paths::MEM_SIZE_OF_VAL); then { cx.typeck_results().node_substs(count_func.hir_id).types().next() } else { None } } }, ExprKind::Binary(op, left, right) if BinOpKind::Mul == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right, inverted)) }, ExprKind::Binary(op, left, right) if BinOpKind::Div == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right,!inverted)) }, ExprKind::Cast(expr, _) => get_size_of_ty(cx, expr, inverted), _ => None, } } fn get_pointee_ty_and_count_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(Ty<'tcx>, &'tcx Expr<'tcx>)> { const FUNCTIONS: [&[&str]; 8] = [ &paths::PTR_COPY_NONOVERLAPPING, &paths::PTR_COPY, &paths::PTR_WRITE_BYTES, &paths::PTR_SWAP_NONOVERLAPPING, &paths::PTR_SLICE_FROM_RAW_PARTS, &paths::PTR_SLICE_FROM_RAW_PARTS_MUT, &paths::SLICE_FROM_RAW_PARTS, &paths::SLICE_FROM_RAW_PARTS_MUT, ]; const METHODS: [&str; 11] = [ "write_bytes", "copy_to", "copy_from", "copy_to_nonoverlapping", "copy_from_nonoverlapping", "add", "wrapping_add", "sub", "wrapping_sub", "offset", "wrapping_offset", ]; if_chain! { // Find calls to ptr::{copy, copy_nonoverlapping} // and ptr::{swap_nonoverlapping, write_bytes}, if let ExprKind::Call(func, [.., count]) = expr.kind; if let ExprKind::Path(ref func_qpath) = func.kind; if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id(); if FUNCTIONS.iter().any(|func_path| match_def_path(cx, def_id, func_path)); // Get the pointee type if let Some(pointee_ty) = cx.typeck_results().node_substs(func.hir_id).types().next(); then { return Some((pointee_ty, count)); } }; if_chain! { // Find calls to copy_{from,to}{,_nonoverlapping} and write_bytes methods if let ExprKind::MethodCall(method_path, _, [ptr_self,.., count], _) = expr.kind; let method_ident = method_path.ident.as_str(); if METHODS.iter().any(|m| *m == &*method_ident); // Get the pointee type if let ty::RawPtr(TypeAndMut { ty: pointee_ty,.. }) = cx.typeck_results().expr_ty(ptr_self).kind(); then { return Some((pointee_ty, count)); } }; None } impl<'tcx> LateLintPass<'tcx> for SizeOfInElementCount { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>)
count_expr.span, LINT_MSG, None, HELP_MSG ); } }; } }
{ const HELP_MSG: &str = "use a count of elements instead of a count of bytes\ , it already gets multiplied by the size of the type"; const LINT_MSG: &str = "found a count of bytes \ instead of a count of elements of `T`"; if_chain! { // Find calls to functions with an element count parameter and get // the pointee type and count parameter expression if let Some((pointee_ty, count_expr)) = get_pointee_ty_and_count_expr(cx, expr); // Find a size_of call in the count parameter expression and // check that it's the same type if let Some(ty_used_for_size_of) = get_size_of_ty(cx, count_expr, false); if TyS::same_type(pointee_ty, ty_used_for_size_of); then { span_lint_and_help( cx, SIZE_OF_IN_ELEMENT_COUNT,
identifier_body
size_of_in_element_count.rs
//! Lint on use of `size_of` or `size_of_val` of T in an expression //! expecting a count of T use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, Ty, TyS, TypeAndMut}; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// ### What it does /// Detects expressions where /// `size_of::<T>` or `size_of_val::<T>` is used as a /// count of elements of type `T` /// /// ### Why is this bad? /// These functions expect a count /// of `T` and not a number of bytes /// /// ### Example /// ```rust,no_run /// # use std::ptr::copy_nonoverlapping; /// # use std::mem::size_of; /// const SIZE: usize = 128; /// let x = [2u8; SIZE]; /// let mut y = [2u8; SIZE]; /// unsafe { copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), size_of::<u8>() * SIZE) }; /// ``` pub SIZE_OF_IN_ELEMENT_COUNT, correctness, "using `size_of::<T>` or `size_of_val::<T>` where a count of elements of `T` is expected" } declare_lint_pass!(SizeOfInElementCount => [SIZE_OF_IN_ELEMENT_COUNT]); fn get_size_of_ty(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, inverted: bool) -> Option<Ty<'tcx>> { match expr.kind { ExprKind::Call(count_func, _func_args) => { if_chain! { if!inverted; if let ExprKind::Path(ref count_func_qpath) = count_func.kind; if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id(); if match_def_path(cx, def_id, &paths::MEM_SIZE_OF) || match_def_path(cx, def_id, &paths::MEM_SIZE_OF_VAL); then { cx.typeck_results().node_substs(count_func.hir_id).types().next() } else { None } } }, ExprKind::Binary(op, left, right) if BinOpKind::Mul == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right, inverted)) }, ExprKind::Binary(op, left, right) if BinOpKind::Div == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right,!inverted)) }, ExprKind::Cast(expr, _) => get_size_of_ty(cx, expr, inverted), _ => None, } } fn get_pointee_ty_and_count_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(Ty<'tcx>, &'tcx Expr<'tcx>)> { const FUNCTIONS: [&[&str]; 8] = [ &paths::PTR_COPY_NONOVERLAPPING, &paths::PTR_COPY, &paths::PTR_WRITE_BYTES, &paths::PTR_SWAP_NONOVERLAPPING, &paths::PTR_SLICE_FROM_RAW_PARTS, &paths::PTR_SLICE_FROM_RAW_PARTS_MUT, &paths::SLICE_FROM_RAW_PARTS, &paths::SLICE_FROM_RAW_PARTS_MUT, ]; const METHODS: [&str; 11] = [ "write_bytes", "copy_to", "copy_from", "copy_to_nonoverlapping", "copy_from_nonoverlapping", "add", "wrapping_add", "sub", "wrapping_sub", "offset", "wrapping_offset", ]; if_chain! { // Find calls to ptr::{copy, copy_nonoverlapping} // and ptr::{swap_nonoverlapping, write_bytes}, if let ExprKind::Call(func, [.., count]) = expr.kind; if let ExprKind::Path(ref func_qpath) = func.kind; if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id(); if FUNCTIONS.iter().any(|func_path| match_def_path(cx, def_id, func_path)); // Get the pointee type if let Some(pointee_ty) = cx.typeck_results().node_substs(func.hir_id).types().next(); then { return Some((pointee_ty, count)); } }; if_chain! { // Find calls to copy_{from,to}{,_nonoverlapping} and write_bytes methods if let ExprKind::MethodCall(method_path, _, [ptr_self,.., count], _) = expr.kind; let method_ident = method_path.ident.as_str(); if METHODS.iter().any(|m| *m == &*method_ident); // Get the pointee type if let ty::RawPtr(TypeAndMut { ty: pointee_ty,.. }) = cx.typeck_results().expr_ty(ptr_self).kind(); then { return Some((pointee_ty, count)); } }; None } impl<'tcx> LateLintPass<'tcx> for SizeOfInElementCount { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { const HELP_MSG: &str = "use a count of elements instead of a count of bytes\ , it already gets multiplied by the size of the type"; const LINT_MSG: &str = "found a count of bytes \ instead of a count of elements of `T`"; if_chain! { // Find calls to functions with an element count parameter and get // the pointee type and count parameter expression if let Some((pointee_ty, count_expr)) = get_pointee_ty_and_count_expr(cx, expr); // Find a size_of call in the count parameter expression and // check that it's the same type if let Some(ty_used_for_size_of) = get_size_of_ty(cx, count_expr, false); if TyS::same_type(pointee_ty, ty_used_for_size_of); then { span_lint_and_help( cx, SIZE_OF_IN_ELEMENT_COUNT, count_expr.span, LINT_MSG,
); } }; } }
None, HELP_MSG
random_line_split
crypto.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::fmt; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::ser::SerializeStruct; use serde::de::{Visitor, MapVisitor, Error}; use super::{Cipher, CipherSer, CipherSerParams, Kdf, KdfSer, KdfSerParams, H256, Bytes}; pub type CipherText = Bytes; #[derive(Debug, PartialEq)] pub struct Crypto { pub cipher: Cipher, pub ciphertext: CipherText, pub kdf: Kdf, pub mac: H256, } enum CryptoField { Cipher, CipherParams, CipherText, Kdf, KdfParams, Mac, } impl Deserialize for CryptoField { fn deserialize<D>(deserializer: D) -> Result<CryptoField, D::Error> where D: Deserializer { deserializer.deserialize(CryptoFieldVisitor) } } struct CryptoFieldVisitor; impl Visitor for CryptoFieldVisitor { type Value = CryptoField; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a valid crypto struct description") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: Error { match value { "cipher" => Ok(CryptoField::Cipher), "cipherparams" => Ok(CryptoField::CipherParams), "ciphertext" => Ok(CryptoField::CipherText), "kdf" => Ok(CryptoField::Kdf), "kdfparams" => Ok(CryptoField::KdfParams), "mac" => Ok(CryptoField::Mac), _ => Err(Error::custom(format!("Unknown field: '{}'", value))), } } } impl Deserialize for Crypto { fn deserialize<D>(deserializer: D) -> Result<Crypto, D::Error> where D: Deserializer { static FIELDS: &'static [&'static str] = &["id", "version", "crypto", "Crypto", "address"]; deserializer.deserialize_struct("Crypto", FIELDS, CryptoVisitor) } } struct CryptoVisitor; impl Visitor for CryptoVisitor { type Value = Crypto; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a valid vault crypto object") } fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> where V: MapVisitor { let mut cipher = None; let mut cipherparams = None; let mut ciphertext = None; let mut kdf = None; let mut kdfparams = None; let mut mac = None; loop { match visitor.visit_key()? { Some(CryptoField::Cipher) => { cipher = Some(visitor.visit_value()?); } Some(CryptoField::CipherParams) => { cipherparams = Some(visitor.visit_value()?); } Some(CryptoField::CipherText) => { ciphertext = Some(visitor.visit_value()?); } Some(CryptoField::Kdf) => { kdf = Some(visitor.visit_value()?); } Some(CryptoField::KdfParams) => { kdfparams = Some(visitor.visit_value()?); } Some(CryptoField::Mac) => { mac = Some(visitor.visit_value()?); } None => { break; } }
let cipher = match (cipher, cipherparams) { (Some(CipherSer::Aes128Ctr), Some(CipherSerParams::Aes128Ctr(params))) => Cipher::Aes128Ctr(params), (None, _) => return Err(V::Error::missing_field("cipher")), (Some(_), None) => return Err(V::Error::missing_field("cipherparams")), }; let ciphertext = match ciphertext { Some(ciphertext) => ciphertext, None => return Err(V::Error::missing_field("ciphertext")), }; let kdf = match (kdf, kdfparams) { (Some(KdfSer::Pbkdf2), Some(KdfSerParams::Pbkdf2(params))) => Kdf::Pbkdf2(params), (Some(KdfSer::Scrypt), Some(KdfSerParams::Scrypt(params))) => Kdf::Scrypt(params), (Some(_), Some(_)) => return Err(V::Error::custom("Invalid cipherparams")), (None, _) => return Err(V::Error::missing_field("kdf")), (Some(_), None) => return Err(V::Error::missing_field("kdfparams")), }; let mac = match mac { Some(mac) => mac, None => return Err(V::Error::missing_field("mac")), }; let result = Crypto { cipher: cipher, ciphertext: ciphertext, kdf: kdf, mac: mac, }; Ok(result) } } impl Serialize for Crypto { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { let mut crypto = serializer.serialize_struct("Crypto", 6)?; match self.cipher { Cipher::Aes128Ctr(ref params) => { crypto.serialize_field("cipher", &CipherSer::Aes128Ctr)?; crypto.serialize_field("cipherparams", params)?; }, } crypto.serialize_field("ciphertext", &self.ciphertext)?; match self.kdf { Kdf::Pbkdf2(ref params) => { crypto.serialize_field("kdf", &KdfSer::Pbkdf2)?; crypto.serialize_field("kdfparams", params)?; }, Kdf::Scrypt(ref params) => { crypto.serialize_field("kdf", &KdfSer::Scrypt)?; crypto.serialize_field("kdfparams", params)?; }, } crypto.serialize_field("mac", &self.mac)?; crypto.end() } }
}
random_line_split
crypto.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::fmt; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::ser::SerializeStruct; use serde::de::{Visitor, MapVisitor, Error}; use super::{Cipher, CipherSer, CipherSerParams, Kdf, KdfSer, KdfSerParams, H256, Bytes}; pub type CipherText = Bytes; #[derive(Debug, PartialEq)] pub struct Crypto { pub cipher: Cipher, pub ciphertext: CipherText, pub kdf: Kdf, pub mac: H256, } enum CryptoField { Cipher, CipherParams, CipherText, Kdf, KdfParams, Mac, } impl Deserialize for CryptoField { fn deserialize<D>(deserializer: D) -> Result<CryptoField, D::Error> where D: Deserializer { deserializer.deserialize(CryptoFieldVisitor) } } struct CryptoFieldVisitor; impl Visitor for CryptoFieldVisitor { type Value = CryptoField; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a valid crypto struct description") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: Error { match value { "cipher" => Ok(CryptoField::Cipher), "cipherparams" => Ok(CryptoField::CipherParams), "ciphertext" => Ok(CryptoField::CipherText), "kdf" => Ok(CryptoField::Kdf), "kdfparams" => Ok(CryptoField::KdfParams), "mac" => Ok(CryptoField::Mac), _ => Err(Error::custom(format!("Unknown field: '{}'", value))), } } } impl Deserialize for Crypto { fn deserialize<D>(deserializer: D) -> Result<Crypto, D::Error> where D: Deserializer { static FIELDS: &'static [&'static str] = &["id", "version", "crypto", "Crypto", "address"]; deserializer.deserialize_struct("Crypto", FIELDS, CryptoVisitor) } } struct CryptoVisitor; impl Visitor for CryptoVisitor { type Value = Crypto; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result
fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> where V: MapVisitor { let mut cipher = None; let mut cipherparams = None; let mut ciphertext = None; let mut kdf = None; let mut kdfparams = None; let mut mac = None; loop { match visitor.visit_key()? { Some(CryptoField::Cipher) => { cipher = Some(visitor.visit_value()?); } Some(CryptoField::CipherParams) => { cipherparams = Some(visitor.visit_value()?); } Some(CryptoField::CipherText) => { ciphertext = Some(visitor.visit_value()?); } Some(CryptoField::Kdf) => { kdf = Some(visitor.visit_value()?); } Some(CryptoField::KdfParams) => { kdfparams = Some(visitor.visit_value()?); } Some(CryptoField::Mac) => { mac = Some(visitor.visit_value()?); } None => { break; } } } let cipher = match (cipher, cipherparams) { (Some(CipherSer::Aes128Ctr), Some(CipherSerParams::Aes128Ctr(params))) => Cipher::Aes128Ctr(params), (None, _) => return Err(V::Error::missing_field("cipher")), (Some(_), None) => return Err(V::Error::missing_field("cipherparams")), }; let ciphertext = match ciphertext { Some(ciphertext) => ciphertext, None => return Err(V::Error::missing_field("ciphertext")), }; let kdf = match (kdf, kdfparams) { (Some(KdfSer::Pbkdf2), Some(KdfSerParams::Pbkdf2(params))) => Kdf::Pbkdf2(params), (Some(KdfSer::Scrypt), Some(KdfSerParams::Scrypt(params))) => Kdf::Scrypt(params), (Some(_), Some(_)) => return Err(V::Error::custom("Invalid cipherparams")), (None, _) => return Err(V::Error::missing_field("kdf")), (Some(_), None) => return Err(V::Error::missing_field("kdfparams")), }; let mac = match mac { Some(mac) => mac, None => return Err(V::Error::missing_field("mac")), }; let result = Crypto { cipher: cipher, ciphertext: ciphertext, kdf: kdf, mac: mac, }; Ok(result) } } impl Serialize for Crypto { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { let mut crypto = serializer.serialize_struct("Crypto", 6)?; match self.cipher { Cipher::Aes128Ctr(ref params) => { crypto.serialize_field("cipher", &CipherSer::Aes128Ctr)?; crypto.serialize_field("cipherparams", params)?; }, } crypto.serialize_field("ciphertext", &self.ciphertext)?; match self.kdf { Kdf::Pbkdf2(ref params) => { crypto.serialize_field("kdf", &KdfSer::Pbkdf2)?; crypto.serialize_field("kdfparams", params)?; }, Kdf::Scrypt(ref params) => { crypto.serialize_field("kdf", &KdfSer::Scrypt)?; crypto.serialize_field("kdfparams", params)?; }, } crypto.serialize_field("mac", &self.mac)?; crypto.end() } }
{ write!(formatter, "a valid vault crypto object") }
identifier_body
crypto.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::fmt; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::ser::SerializeStruct; use serde::de::{Visitor, MapVisitor, Error}; use super::{Cipher, CipherSer, CipherSerParams, Kdf, KdfSer, KdfSerParams, H256, Bytes}; pub type CipherText = Bytes; #[derive(Debug, PartialEq)] pub struct Crypto { pub cipher: Cipher, pub ciphertext: CipherText, pub kdf: Kdf, pub mac: H256, } enum CryptoField { Cipher, CipherParams, CipherText, Kdf, KdfParams, Mac, } impl Deserialize for CryptoField { fn deserialize<D>(deserializer: D) -> Result<CryptoField, D::Error> where D: Deserializer { deserializer.deserialize(CryptoFieldVisitor) } } struct CryptoFieldVisitor; impl Visitor for CryptoFieldVisitor { type Value = CryptoField; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a valid crypto struct description") } fn
<E>(self, value: &str) -> Result<Self::Value, E> where E: Error { match value { "cipher" => Ok(CryptoField::Cipher), "cipherparams" => Ok(CryptoField::CipherParams), "ciphertext" => Ok(CryptoField::CipherText), "kdf" => Ok(CryptoField::Kdf), "kdfparams" => Ok(CryptoField::KdfParams), "mac" => Ok(CryptoField::Mac), _ => Err(Error::custom(format!("Unknown field: '{}'", value))), } } } impl Deserialize for Crypto { fn deserialize<D>(deserializer: D) -> Result<Crypto, D::Error> where D: Deserializer { static FIELDS: &'static [&'static str] = &["id", "version", "crypto", "Crypto", "address"]; deserializer.deserialize_struct("Crypto", FIELDS, CryptoVisitor) } } struct CryptoVisitor; impl Visitor for CryptoVisitor { type Value = Crypto; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a valid vault crypto object") } fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> where V: MapVisitor { let mut cipher = None; let mut cipherparams = None; let mut ciphertext = None; let mut kdf = None; let mut kdfparams = None; let mut mac = None; loop { match visitor.visit_key()? { Some(CryptoField::Cipher) => { cipher = Some(visitor.visit_value()?); } Some(CryptoField::CipherParams) => { cipherparams = Some(visitor.visit_value()?); } Some(CryptoField::CipherText) => { ciphertext = Some(visitor.visit_value()?); } Some(CryptoField::Kdf) => { kdf = Some(visitor.visit_value()?); } Some(CryptoField::KdfParams) => { kdfparams = Some(visitor.visit_value()?); } Some(CryptoField::Mac) => { mac = Some(visitor.visit_value()?); } None => { break; } } } let cipher = match (cipher, cipherparams) { (Some(CipherSer::Aes128Ctr), Some(CipherSerParams::Aes128Ctr(params))) => Cipher::Aes128Ctr(params), (None, _) => return Err(V::Error::missing_field("cipher")), (Some(_), None) => return Err(V::Error::missing_field("cipherparams")), }; let ciphertext = match ciphertext { Some(ciphertext) => ciphertext, None => return Err(V::Error::missing_field("ciphertext")), }; let kdf = match (kdf, kdfparams) { (Some(KdfSer::Pbkdf2), Some(KdfSerParams::Pbkdf2(params))) => Kdf::Pbkdf2(params), (Some(KdfSer::Scrypt), Some(KdfSerParams::Scrypt(params))) => Kdf::Scrypt(params), (Some(_), Some(_)) => return Err(V::Error::custom("Invalid cipherparams")), (None, _) => return Err(V::Error::missing_field("kdf")), (Some(_), None) => return Err(V::Error::missing_field("kdfparams")), }; let mac = match mac { Some(mac) => mac, None => return Err(V::Error::missing_field("mac")), }; let result = Crypto { cipher: cipher, ciphertext: ciphertext, kdf: kdf, mac: mac, }; Ok(result) } } impl Serialize for Crypto { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { let mut crypto = serializer.serialize_struct("Crypto", 6)?; match self.cipher { Cipher::Aes128Ctr(ref params) => { crypto.serialize_field("cipher", &CipherSer::Aes128Ctr)?; crypto.serialize_field("cipherparams", params)?; }, } crypto.serialize_field("ciphertext", &self.ciphertext)?; match self.kdf { Kdf::Pbkdf2(ref params) => { crypto.serialize_field("kdf", &KdfSer::Pbkdf2)?; crypto.serialize_field("kdfparams", params)?; }, Kdf::Scrypt(ref params) => { crypto.serialize_field("kdf", &KdfSer::Scrypt)?; crypto.serialize_field("kdfparams", params)?; }, } crypto.serialize_field("mac", &self.mac)?; crypto.end() } }
visit_str
identifier_name
directive.rs
use std::collections::hash_map::Entry; use syn::parse; use syn::Token; use quote::quote; use proc_macro_error::emit_error; use crate::common::{Stmt, Size, delimited}; use crate::arch; use crate::DynasmContext; use crate::parse_helpers::ParseOptExt; pub(crate) fn evaluate_directive(invocation_context: &mut DynasmContext, stmts: &mut Vec<Stmt>, input: parse::ParseStream) -> parse::Result<()> { let directive: syn::Ident = input.parse()?; match directive.to_string().as_str() { // TODO: oword, qword, float, double, long double "arch" => { // ;.arch ident let arch: syn::Ident = input.parse()?; if let Some(a) = arch::from_str(arch.to_string().as_str()) { invocation_context.current_arch = a; } else { emit_error!(arch, "Unknown architecture '{}'", arch); } }, "feature" => { // ;.feature ident ("," ident) * let mut features = Vec::new(); let ident: syn::Ident = input.parse()?; features.push(ident); while input.peek(Token![,]) { let _: Token![,] = input.parse()?; let ident: syn::Ident = input.parse()?; features.push(ident); } // ;.feature none cancels all features if features.len() == 1 && features[0] == "none" { features.pop(); } invocation_context.current_arch.set_features(&features); }, // ;.byte (expr ("," expr)*)? "byte" => directive_const(invocation_context, stmts, input, Size::BYTE)?, "word" => directive_const(invocation_context, stmts, input, Size::WORD)?, "dword" => directive_const(invocation_context, stmts, input, Size::DWORD)?, "qword" => directive_const(invocation_context, stmts, input, Size::QWORD)?, "bytes" => { // ;.bytes expr let iterator: syn::Expr = input.parse()?; stmts.push(Stmt::ExprExtend(delimited(iterator))); }, "align" => { // ;.align expr ("," expr) // this might need to be architecture dependent let value: syn::Expr = input.parse()?; let with = if input.peek(Token![,]) { let _: Token![,] = input.parse()?; let with: syn::Expr = input.parse()?; delimited(with) } else { let with = invocation_context.current_arch.default_align(); delimited(quote!(#with)) }; stmts.push(Stmt::Align(delimited(value), with)); }, "alias" => { // ;.alias ident, ident // consider changing this to ;.alias ident = ident next breaking change let alias = input.parse::<syn::Ident>()?; let _: Token![,] = input.parse()?; let reg = input.parse::<syn::Ident>()?; let alias_name = alias.to_string(); match invocation_context.aliases.entry(alias_name) { Entry::Occupied(_) => { emit_error!(alias, "Duplicate alias definition, alias '{}' was already defined", alias); }, Entry::Vacant(v) => { v.insert(reg.to_string()); } } }, d => { // unknown directive. skip ahead until we hit a ; so the parser can recover emit_error!(directive, "unknown directive '{}'", d); skip_until_semicolon(input); } } Ok(()) } fn directive_const(invocation_context: &mut DynasmContext, stmts: &mut Vec<Stmt>, input: parse::ParseStream, size: Size) -> parse::Result<()> { // FIXME: this could be replaced by a Punctuated parser? // parse (expr (, expr)*)? if input.is_empty() || input.peek(Token![;]) { return Ok(()) } if let Some(jump) = input.parse_opt()? { invocation_context.current_arch.handle_static_reloc(stmts, jump, size); } else { let expr: syn::Expr = input.parse()?; stmts.push(Stmt::ExprSigned(delimited(expr), size)); } while input.peek(Token![,]) { let _: Token![,] = input.parse()?; if let Some(jump) = input.parse_opt()? { invocation_context.current_arch.handle_static_reloc(stmts, jump, size); } else
} Ok(()) } /// In case a directive is unknown, try to skip up to the next ; and resume parsing. fn skip_until_semicolon(input: parse::ParseStream) { let _ = input.step(|cursor| { let mut rest = *cursor; while let Some((tt, next)) = rest.token_tree() { match tt { ::proc_macro2::TokenTree::Punct(ref punct) if punct.as_char() == ';' => { return Ok(((), rest)); } _ => rest = next, } } Ok(((), rest)) }); }
{ let expr: syn::Expr = input.parse()?; stmts.push(Stmt::ExprSigned(delimited(expr), size)); }
conditional_block
directive.rs
use std::collections::hash_map::Entry; use syn::parse; use syn::Token; use quote::quote; use proc_macro_error::emit_error; use crate::common::{Stmt, Size, delimited}; use crate::arch; use crate::DynasmContext; use crate::parse_helpers::ParseOptExt; pub(crate) fn evaluate_directive(invocation_context: &mut DynasmContext, stmts: &mut Vec<Stmt>, input: parse::ParseStream) -> parse::Result<()> { let directive: syn::Ident = input.parse()?; match directive.to_string().as_str() { // TODO: oword, qword, float, double, long double "arch" => { // ;.arch ident let arch: syn::Ident = input.parse()?; if let Some(a) = arch::from_str(arch.to_string().as_str()) { invocation_context.current_arch = a; } else { emit_error!(arch, "Unknown architecture '{}'", arch); } }, "feature" => { // ;.feature ident ("," ident) * let mut features = Vec::new(); let ident: syn::Ident = input.parse()?; features.push(ident); while input.peek(Token![,]) { let _: Token![,] = input.parse()?; let ident: syn::Ident = input.parse()?; features.push(ident); } // ;.feature none cancels all features if features.len() == 1 && features[0] == "none" { features.pop(); }
"byte" => directive_const(invocation_context, stmts, input, Size::BYTE)?, "word" => directive_const(invocation_context, stmts, input, Size::WORD)?, "dword" => directive_const(invocation_context, stmts, input, Size::DWORD)?, "qword" => directive_const(invocation_context, stmts, input, Size::QWORD)?, "bytes" => { // ;.bytes expr let iterator: syn::Expr = input.parse()?; stmts.push(Stmt::ExprExtend(delimited(iterator))); }, "align" => { // ;.align expr ("," expr) // this might need to be architecture dependent let value: syn::Expr = input.parse()?; let with = if input.peek(Token![,]) { let _: Token![,] = input.parse()?; let with: syn::Expr = input.parse()?; delimited(with) } else { let with = invocation_context.current_arch.default_align(); delimited(quote!(#with)) }; stmts.push(Stmt::Align(delimited(value), with)); }, "alias" => { // ;.alias ident, ident // consider changing this to ;.alias ident = ident next breaking change let alias = input.parse::<syn::Ident>()?; let _: Token![,] = input.parse()?; let reg = input.parse::<syn::Ident>()?; let alias_name = alias.to_string(); match invocation_context.aliases.entry(alias_name) { Entry::Occupied(_) => { emit_error!(alias, "Duplicate alias definition, alias '{}' was already defined", alias); }, Entry::Vacant(v) => { v.insert(reg.to_string()); } } }, d => { // unknown directive. skip ahead until we hit a ; so the parser can recover emit_error!(directive, "unknown directive '{}'", d); skip_until_semicolon(input); } } Ok(()) } fn directive_const(invocation_context: &mut DynasmContext, stmts: &mut Vec<Stmt>, input: parse::ParseStream, size: Size) -> parse::Result<()> { // FIXME: this could be replaced by a Punctuated parser? // parse (expr (, expr)*)? if input.is_empty() || input.peek(Token![;]) { return Ok(()) } if let Some(jump) = input.parse_opt()? { invocation_context.current_arch.handle_static_reloc(stmts, jump, size); } else { let expr: syn::Expr = input.parse()?; stmts.push(Stmt::ExprSigned(delimited(expr), size)); } while input.peek(Token![,]) { let _: Token![,] = input.parse()?; if let Some(jump) = input.parse_opt()? { invocation_context.current_arch.handle_static_reloc(stmts, jump, size); } else { let expr: syn::Expr = input.parse()?; stmts.push(Stmt::ExprSigned(delimited(expr), size)); } } Ok(()) } /// In case a directive is unknown, try to skip up to the next ; and resume parsing. fn skip_until_semicolon(input: parse::ParseStream) { let _ = input.step(|cursor| { let mut rest = *cursor; while let Some((tt, next)) = rest.token_tree() { match tt { ::proc_macro2::TokenTree::Punct(ref punct) if punct.as_char() == ';' => { return Ok(((), rest)); } _ => rest = next, } } Ok(((), rest)) }); }
invocation_context.current_arch.set_features(&features); }, // ; .byte (expr ("," expr)*)?
random_line_split
directive.rs
use std::collections::hash_map::Entry; use syn::parse; use syn::Token; use quote::quote; use proc_macro_error::emit_error; use crate::common::{Stmt, Size, delimited}; use crate::arch; use crate::DynasmContext; use crate::parse_helpers::ParseOptExt; pub(crate) fn evaluate_directive(invocation_context: &mut DynasmContext, stmts: &mut Vec<Stmt>, input: parse::ParseStream) -> parse::Result<()>
while input.peek(Token![,]) { let _: Token![,] = input.parse()?; let ident: syn::Ident = input.parse()?; features.push(ident); } // ;.feature none cancels all features if features.len() == 1 && features[0] == "none" { features.pop(); } invocation_context.current_arch.set_features(&features); }, // ;.byte (expr ("," expr)*)? "byte" => directive_const(invocation_context, stmts, input, Size::BYTE)?, "word" => directive_const(invocation_context, stmts, input, Size::WORD)?, "dword" => directive_const(invocation_context, stmts, input, Size::DWORD)?, "qword" => directive_const(invocation_context, stmts, input, Size::QWORD)?, "bytes" => { // ;.bytes expr let iterator: syn::Expr = input.parse()?; stmts.push(Stmt::ExprExtend(delimited(iterator))); }, "align" => { // ;.align expr ("," expr) // this might need to be architecture dependent let value: syn::Expr = input.parse()?; let with = if input.peek(Token![,]) { let _: Token![,] = input.parse()?; let with: syn::Expr = input.parse()?; delimited(with) } else { let with = invocation_context.current_arch.default_align(); delimited(quote!(#with)) }; stmts.push(Stmt::Align(delimited(value), with)); }, "alias" => { // ;.alias ident, ident // consider changing this to ;.alias ident = ident next breaking change let alias = input.parse::<syn::Ident>()?; let _: Token![,] = input.parse()?; let reg = input.parse::<syn::Ident>()?; let alias_name = alias.to_string(); match invocation_context.aliases.entry(alias_name) { Entry::Occupied(_) => { emit_error!(alias, "Duplicate alias definition, alias '{}' was already defined", alias); }, Entry::Vacant(v) => { v.insert(reg.to_string()); } } }, d => { // unknown directive. skip ahead until we hit a ; so the parser can recover emit_error!(directive, "unknown directive '{}'", d); skip_until_semicolon(input); } } Ok(()) } fn directive_const(invocation_context: &mut DynasmContext, stmts: &mut Vec<Stmt>, input: parse::ParseStream, size: Size) -> parse::Result<()> { // FIXME: this could be replaced by a Punctuated parser? // parse (expr (, expr)*)? if input.is_empty() || input.peek(Token![;]) { return Ok(()) } if let Some(jump) = input.parse_opt()? { invocation_context.current_arch.handle_static_reloc(stmts, jump, size); } else { let expr: syn::Expr = input.parse()?; stmts.push(Stmt::ExprSigned(delimited(expr), size)); } while input.peek(Token![,]) { let _: Token![,] = input.parse()?; if let Some(jump) = input.parse_opt()? { invocation_context.current_arch.handle_static_reloc(stmts, jump, size); } else { let expr: syn::Expr = input.parse()?; stmts.push(Stmt::ExprSigned(delimited(expr), size)); } } Ok(()) } /// In case a directive is unknown, try to skip up to the next ; and resume parsing. fn skip_until_semicolon(input: parse::ParseStream) { let _ = input.step(|cursor| { let mut rest = *cursor; while let Some((tt, next)) = rest.token_tree() { match tt { ::proc_macro2::TokenTree::Punct(ref punct) if punct.as_char() == ';' => { return Ok(((), rest)); } _ => rest = next, } } Ok(((), rest)) }); }
{ let directive: syn::Ident = input.parse()?; match directive.to_string().as_str() { // TODO: oword, qword, float, double, long double "arch" => { // ; .arch ident let arch: syn::Ident = input.parse()?; if let Some(a) = arch::from_str(arch.to_string().as_str()) { invocation_context.current_arch = a; } else { emit_error!(arch, "Unknown architecture '{}'", arch); } }, "feature" => { // ; .feature ident ("," ident) * let mut features = Vec::new(); let ident: syn::Ident = input.parse()?; features.push(ident);
identifier_body
directive.rs
use std::collections::hash_map::Entry; use syn::parse; use syn::Token; use quote::quote; use proc_macro_error::emit_error; use crate::common::{Stmt, Size, delimited}; use crate::arch; use crate::DynasmContext; use crate::parse_helpers::ParseOptExt; pub(crate) fn
(invocation_context: &mut DynasmContext, stmts: &mut Vec<Stmt>, input: parse::ParseStream) -> parse::Result<()> { let directive: syn::Ident = input.parse()?; match directive.to_string().as_str() { // TODO: oword, qword, float, double, long double "arch" => { // ;.arch ident let arch: syn::Ident = input.parse()?; if let Some(a) = arch::from_str(arch.to_string().as_str()) { invocation_context.current_arch = a; } else { emit_error!(arch, "Unknown architecture '{}'", arch); } }, "feature" => { // ;.feature ident ("," ident) * let mut features = Vec::new(); let ident: syn::Ident = input.parse()?; features.push(ident); while input.peek(Token![,]) { let _: Token![,] = input.parse()?; let ident: syn::Ident = input.parse()?; features.push(ident); } // ;.feature none cancels all features if features.len() == 1 && features[0] == "none" { features.pop(); } invocation_context.current_arch.set_features(&features); }, // ;.byte (expr ("," expr)*)? "byte" => directive_const(invocation_context, stmts, input, Size::BYTE)?, "word" => directive_const(invocation_context, stmts, input, Size::WORD)?, "dword" => directive_const(invocation_context, stmts, input, Size::DWORD)?, "qword" => directive_const(invocation_context, stmts, input, Size::QWORD)?, "bytes" => { // ;.bytes expr let iterator: syn::Expr = input.parse()?; stmts.push(Stmt::ExprExtend(delimited(iterator))); }, "align" => { // ;.align expr ("," expr) // this might need to be architecture dependent let value: syn::Expr = input.parse()?; let with = if input.peek(Token![,]) { let _: Token![,] = input.parse()?; let with: syn::Expr = input.parse()?; delimited(with) } else { let with = invocation_context.current_arch.default_align(); delimited(quote!(#with)) }; stmts.push(Stmt::Align(delimited(value), with)); }, "alias" => { // ;.alias ident, ident // consider changing this to ;.alias ident = ident next breaking change let alias = input.parse::<syn::Ident>()?; let _: Token![,] = input.parse()?; let reg = input.parse::<syn::Ident>()?; let alias_name = alias.to_string(); match invocation_context.aliases.entry(alias_name) { Entry::Occupied(_) => { emit_error!(alias, "Duplicate alias definition, alias '{}' was already defined", alias); }, Entry::Vacant(v) => { v.insert(reg.to_string()); } } }, d => { // unknown directive. skip ahead until we hit a ; so the parser can recover emit_error!(directive, "unknown directive '{}'", d); skip_until_semicolon(input); } } Ok(()) } fn directive_const(invocation_context: &mut DynasmContext, stmts: &mut Vec<Stmt>, input: parse::ParseStream, size: Size) -> parse::Result<()> { // FIXME: this could be replaced by a Punctuated parser? // parse (expr (, expr)*)? if input.is_empty() || input.peek(Token![;]) { return Ok(()) } if let Some(jump) = input.parse_opt()? { invocation_context.current_arch.handle_static_reloc(stmts, jump, size); } else { let expr: syn::Expr = input.parse()?; stmts.push(Stmt::ExprSigned(delimited(expr), size)); } while input.peek(Token![,]) { let _: Token![,] = input.parse()?; if let Some(jump) = input.parse_opt()? { invocation_context.current_arch.handle_static_reloc(stmts, jump, size); } else { let expr: syn::Expr = input.parse()?; stmts.push(Stmt::ExprSigned(delimited(expr), size)); } } Ok(()) } /// In case a directive is unknown, try to skip up to the next ; and resume parsing. fn skip_until_semicolon(input: parse::ParseStream) { let _ = input.step(|cursor| { let mut rest = *cursor; while let Some((tt, next)) = rest.token_tree() { match tt { ::proc_macro2::TokenTree::Punct(ref punct) if punct.as_char() == ';' => { return Ok(((), rest)); } _ => rest = next, } } Ok(((), rest)) }); }
evaluate_directive
identifier_name
main.rs
use std::env; use std::path::Path; use std::process::{Command, Output}; fn check_html_file(file: &Path) -> usize { let to_mute = &[ // "disabled" on <link> or "autocomplete" on <select> emit this warning "PROPRIETARY_ATTRIBUTE", // It complains when multiple in the same page link to the same anchor for some reason... "ANCHOR_NOT_UNIQUE", // If a <span> contains only HTML elements and no text, it complains about it. "TRIM_EMPTY_ELEMENT", // FIXME: the three next warnings are about <pre> elements which are not supposed to // contain HTML. The solution here would be to replace them with a <div> "MISSING_ENDTAG_BEFORE", "INSERTING_TAG", "DISCARDING_UNEXPECTED", // This error is caused by nesting the Notable Traits tooltip within an <h4> tag. // The solution is to avoid doing that, but we need to have the <h4> tags for accessibility // reasons, and we need the Notable Traits tooltip to help everyone understand the Iterator // combinators "TAG_NOT_ALLOWED_IN", ]; let to_mute_s = to_mute.join(","); let mut command = Command::new("tidy"); command .arg("-errors") .arg("-quiet") .arg("--mute-id") // this option is useful in case we want to mute more warnings .arg("yes") .arg("--mute") .arg(&to_mute_s) .arg(file); let Output { status, stderr,.. } = command.output().expect("failed to run tidy command"); if status.success() { 0 } else { let stderr = String::from_utf8(stderr).expect("String::from_utf8 failed..."); if stderr.is_empty() && status.code()!= Some(2) { 0 } else { eprintln!( "=> Errors for `{}` (error code: {}) <=", file.display(), status.code().unwrap_or(-1) ); eprintln!("{}", stderr); stderr.lines().count() } } } const DOCS_TO_CHECK: &[&str] = &["alloc", "core", "proc_macro", "implementors", "src", "std", "test"]; // Returns the number of files read and the number of errors. fn find_all_html_files(dir: &Path) -> (usize, usize) { let mut files_read = 0; let mut errors = 0; for entry in walkdir::WalkDir::new(dir).into_iter().filter_entry(|e| { e.depth()!= 1 || e.file_name() .to_str() .map(|s| DOCS_TO_CHECK.into_iter().any(|d| *d == s)) .unwrap_or(false) }) { let entry = entry.expect("failed to read file"); if!entry.file_type().is_file() { continue; } let entry = entry.path(); if entry.extension().and_then(|s| s.to_str()) == Some("html") { errors += check_html_file(&entry); files_read += 1; } } (files_read, errors) } fn
() -> Result<(), String> { let args = env::args().collect::<Vec<_>>(); if args.len()!= 2 { return Err(format!("Usage: {} <doc folder>", args[0])); } println!("Running HTML checker..."); let (files_read, errors) = find_all_html_files(&Path::new(&args[1])); println!("Done! Read {} files...", files_read); if errors > 0 { Err(format!("HTML check failed: {} errors", errors)) } else { println!("No error found!"); Ok(()) } }
main
identifier_name
main.rs
use std::env; use std::path::Path; use std::process::{Command, Output}; fn check_html_file(file: &Path) -> usize { let to_mute = &[ // "disabled" on <link> or "autocomplete" on <select> emit this warning "PROPRIETARY_ATTRIBUTE", // It complains when multiple in the same page link to the same anchor for some reason... "ANCHOR_NOT_UNIQUE", // If a <span> contains only HTML elements and no text, it complains about it. "TRIM_EMPTY_ELEMENT", // FIXME: the three next warnings are about <pre> elements which are not supposed to // contain HTML. The solution here would be to replace them with a <div> "MISSING_ENDTAG_BEFORE", "INSERTING_TAG", "DISCARDING_UNEXPECTED", // This error is caused by nesting the Notable Traits tooltip within an <h4> tag. // The solution is to avoid doing that, but we need to have the <h4> tags for accessibility // reasons, and we need the Notable Traits tooltip to help everyone understand the Iterator // combinators "TAG_NOT_ALLOWED_IN", ]; let to_mute_s = to_mute.join(","); let mut command = Command::new("tidy"); command .arg("-errors") .arg("-quiet") .arg("--mute-id") // this option is useful in case we want to mute more warnings .arg("yes") .arg("--mute") .arg(&to_mute_s) .arg(file); let Output { status, stderr,.. } = command.output().expect("failed to run tidy command"); if status.success() { 0 } else { let stderr = String::from_utf8(stderr).expect("String::from_utf8 failed..."); if stderr.is_empty() && status.code()!= Some(2) { 0 } else { eprintln!( "=> Errors for `{}` (error code: {}) <=", file.display(), status.code().unwrap_or(-1) ); eprintln!("{}", stderr); stderr.lines().count() } } } const DOCS_TO_CHECK: &[&str] = &["alloc", "core", "proc_macro", "implementors", "src", "std", "test"]; // Returns the number of files read and the number of errors. fn find_all_html_files(dir: &Path) -> (usize, usize) { let mut files_read = 0;
.to_str() .map(|s| DOCS_TO_CHECK.into_iter().any(|d| *d == s)) .unwrap_or(false) }) { let entry = entry.expect("failed to read file"); if!entry.file_type().is_file() { continue; } let entry = entry.path(); if entry.extension().and_then(|s| s.to_str()) == Some("html") { errors += check_html_file(&entry); files_read += 1; } } (files_read, errors) } fn main() -> Result<(), String> { let args = env::args().collect::<Vec<_>>(); if args.len()!= 2 { return Err(format!("Usage: {} <doc folder>", args[0])); } println!("Running HTML checker..."); let (files_read, errors) = find_all_html_files(&Path::new(&args[1])); println!("Done! Read {} files...", files_read); if errors > 0 { Err(format!("HTML check failed: {} errors", errors)) } else { println!("No error found!"); Ok(()) } }
let mut errors = 0; for entry in walkdir::WalkDir::new(dir).into_iter().filter_entry(|e| { e.depth() != 1 || e.file_name()
random_line_split
main.rs
use std::env; use std::path::Path; use std::process::{Command, Output}; fn check_html_file(file: &Path) -> usize { let to_mute = &[ // "disabled" on <link> or "autocomplete" on <select> emit this warning "PROPRIETARY_ATTRIBUTE", // It complains when multiple in the same page link to the same anchor for some reason... "ANCHOR_NOT_UNIQUE", // If a <span> contains only HTML elements and no text, it complains about it. "TRIM_EMPTY_ELEMENT", // FIXME: the three next warnings are about <pre> elements which are not supposed to // contain HTML. The solution here would be to replace them with a <div> "MISSING_ENDTAG_BEFORE", "INSERTING_TAG", "DISCARDING_UNEXPECTED", // This error is caused by nesting the Notable Traits tooltip within an <h4> tag. // The solution is to avoid doing that, but we need to have the <h4> tags for accessibility // reasons, and we need the Notable Traits tooltip to help everyone understand the Iterator // combinators "TAG_NOT_ALLOWED_IN", ]; let to_mute_s = to_mute.join(","); let mut command = Command::new("tidy"); command .arg("-errors") .arg("-quiet") .arg("--mute-id") // this option is useful in case we want to mute more warnings .arg("yes") .arg("--mute") .arg(&to_mute_s) .arg(file); let Output { status, stderr,.. } = command.output().expect("failed to run tidy command"); if status.success() { 0 } else { let stderr = String::from_utf8(stderr).expect("String::from_utf8 failed..."); if stderr.is_empty() && status.code()!= Some(2) { 0 } else { eprintln!( "=> Errors for `{}` (error code: {}) <=", file.display(), status.code().unwrap_or(-1) ); eprintln!("{}", stderr); stderr.lines().count() } } } const DOCS_TO_CHECK: &[&str] = &["alloc", "core", "proc_macro", "implementors", "src", "std", "test"]; // Returns the number of files read and the number of errors. fn find_all_html_files(dir: &Path) -> (usize, usize)
} (files_read, errors) } fn main() -> Result<(), String> { let args = env::args().collect::<Vec<_>>(); if args.len()!= 2 { return Err(format!("Usage: {} <doc folder>", args[0])); } println!("Running HTML checker..."); let (files_read, errors) = find_all_html_files(&Path::new(&args[1])); println!("Done! Read {} files...", files_read); if errors > 0 { Err(format!("HTML check failed: {} errors", errors)) } else { println!("No error found!"); Ok(()) } }
{ let mut files_read = 0; let mut errors = 0; for entry in walkdir::WalkDir::new(dir).into_iter().filter_entry(|e| { e.depth() != 1 || e.file_name() .to_str() .map(|s| DOCS_TO_CHECK.into_iter().any(|d| *d == s)) .unwrap_or(false) }) { let entry = entry.expect("failed to read file"); if !entry.file_type().is_file() { continue; } let entry = entry.path(); if entry.extension().and_then(|s| s.to_str()) == Some("html") { errors += check_html_file(&entry); files_read += 1; }
identifier_body
main.rs
use std::env; use std::path::Path; use std::process::{Command, Output}; fn check_html_file(file: &Path) -> usize { let to_mute = &[ // "disabled" on <link> or "autocomplete" on <select> emit this warning "PROPRIETARY_ATTRIBUTE", // It complains when multiple in the same page link to the same anchor for some reason... "ANCHOR_NOT_UNIQUE", // If a <span> contains only HTML elements and no text, it complains about it. "TRIM_EMPTY_ELEMENT", // FIXME: the three next warnings are about <pre> elements which are not supposed to // contain HTML. The solution here would be to replace them with a <div> "MISSING_ENDTAG_BEFORE", "INSERTING_TAG", "DISCARDING_UNEXPECTED", // This error is caused by nesting the Notable Traits tooltip within an <h4> tag. // The solution is to avoid doing that, but we need to have the <h4> tags for accessibility // reasons, and we need the Notable Traits tooltip to help everyone understand the Iterator // combinators "TAG_NOT_ALLOWED_IN", ]; let to_mute_s = to_mute.join(","); let mut command = Command::new("tidy"); command .arg("-errors") .arg("-quiet") .arg("--mute-id") // this option is useful in case we want to mute more warnings .arg("yes") .arg("--mute") .arg(&to_mute_s) .arg(file); let Output { status, stderr,.. } = command.output().expect("failed to run tidy command"); if status.success() { 0 } else { let stderr = String::from_utf8(stderr).expect("String::from_utf8 failed..."); if stderr.is_empty() && status.code()!= Some(2) { 0 } else { eprintln!( "=> Errors for `{}` (error code: {}) <=", file.display(), status.code().unwrap_or(-1) ); eprintln!("{}", stderr); stderr.lines().count() } } } const DOCS_TO_CHECK: &[&str] = &["alloc", "core", "proc_macro", "implementors", "src", "std", "test"]; // Returns the number of files read and the number of errors. fn find_all_html_files(dir: &Path) -> (usize, usize) { let mut files_read = 0; let mut errors = 0; for entry in walkdir::WalkDir::new(dir).into_iter().filter_entry(|e| { e.depth()!= 1 || e.file_name() .to_str() .map(|s| DOCS_TO_CHECK.into_iter().any(|d| *d == s)) .unwrap_or(false) }) { let entry = entry.expect("failed to read file"); if!entry.file_type().is_file() { continue; } let entry = entry.path(); if entry.extension().and_then(|s| s.to_str()) == Some("html")
} (files_read, errors) } fn main() -> Result<(), String> { let args = env::args().collect::<Vec<_>>(); if args.len()!= 2 { return Err(format!("Usage: {} <doc folder>", args[0])); } println!("Running HTML checker..."); let (files_read, errors) = find_all_html_files(&Path::new(&args[1])); println!("Done! Read {} files...", files_read); if errors > 0 { Err(format!("HTML check failed: {} errors", errors)) } else { println!("No error found!"); Ok(()) } }
{ errors += check_html_file(&entry); files_read += 1; }
conditional_block
sorting.rs
#![feature(test)] extern crate test; extern crate rand; extern crate algs4; use test::Bencher; use rand::{thread_rng, Rng}; use algs4::sorting::*; use algs4::sorting::quicksort::{quick_sort_3way, quick_sort_orig};
// for small array // static SIZE: usize = 10; macro_rules! defbench( ($name:ident, $func:ident) => ( defbench!($name, $func, f64, SIZE); ); ($name:ident, $func:ident, $typ:ty) => ( defbench!($name, $func, $typ, SIZE); ); ($name:ident, $func:ident, $typ:ty, $size:expr) => ( #[bench] fn $name(b: &mut Bencher) { let array = thread_rng().gen_iter().take($size).collect::<Vec<$typ>>(); b.iter(|| { let mut array = array.clone(); $func(&mut array); }); } ) ); defbench!(bench_selection_sort, selection_sort); defbench!(bench_insertion_sort, insertion_sort); defbench!(bench_shell_sort, shell_sort); defbench!(bench_merge_sort, merge_sort); defbench!(bench_merge_bu_sort, merge_bu_sort); defbench!(bench_quick_sort, quick_sort); defbench!(bench_quick_sort_orig, quick_sort_orig); defbench!(bench_quick_sort_3way, quick_sort_3way); // :( 3way sort does not exceed defbench!(bench_quick_sort_orig_on_dup_keys, quick_sort_orig, u8); defbench!(bench_quick_sort_3way_on_dup_keys, quick_sort_3way, u8); defbench!(bench_heap_sort, heap_sort); #[bench] fn bench_knuth_shuffle(b: &mut Bencher) { let array = thread_rng().gen_iter().take(SIZE).collect::<Vec<f64>>(); b.iter(|| { let mut array = array.clone(); knuth_shuffle(&mut array); }); }
use algs4::fundamentals::knuth_shuffle; static SIZE: usize = 1000;
random_line_split
sorting.rs
#![feature(test)] extern crate test; extern crate rand; extern crate algs4; use test::Bencher; use rand::{thread_rng, Rng}; use algs4::sorting::*; use algs4::sorting::quicksort::{quick_sort_3way, quick_sort_orig}; use algs4::fundamentals::knuth_shuffle; static SIZE: usize = 1000; // for small array // static SIZE: usize = 10; macro_rules! defbench( ($name:ident, $func:ident) => ( defbench!($name, $func, f64, SIZE); ); ($name:ident, $func:ident, $typ:ty) => ( defbench!($name, $func, $typ, SIZE); ); ($name:ident, $func:ident, $typ:ty, $size:expr) => ( #[bench] fn $name(b: &mut Bencher) { let array = thread_rng().gen_iter().take($size).collect::<Vec<$typ>>(); b.iter(|| { let mut array = array.clone(); $func(&mut array); }); } ) ); defbench!(bench_selection_sort, selection_sort); defbench!(bench_insertion_sort, insertion_sort); defbench!(bench_shell_sort, shell_sort); defbench!(bench_merge_sort, merge_sort); defbench!(bench_merge_bu_sort, merge_bu_sort); defbench!(bench_quick_sort, quick_sort); defbench!(bench_quick_sort_orig, quick_sort_orig); defbench!(bench_quick_sort_3way, quick_sort_3way); // :( 3way sort does not exceed defbench!(bench_quick_sort_orig_on_dup_keys, quick_sort_orig, u8); defbench!(bench_quick_sort_3way_on_dup_keys, quick_sort_3way, u8); defbench!(bench_heap_sort, heap_sort); #[bench] fn bench_knuth_shuffle(b: &mut Bencher)
{ let array = thread_rng().gen_iter().take(SIZE).collect::<Vec<f64>>(); b.iter(|| { let mut array = array.clone(); knuth_shuffle(&mut array); }); }
identifier_body
sorting.rs
#![feature(test)] extern crate test; extern crate rand; extern crate algs4; use test::Bencher; use rand::{thread_rng, Rng}; use algs4::sorting::*; use algs4::sorting::quicksort::{quick_sort_3way, quick_sort_orig}; use algs4::fundamentals::knuth_shuffle; static SIZE: usize = 1000; // for small array // static SIZE: usize = 10; macro_rules! defbench( ($name:ident, $func:ident) => ( defbench!($name, $func, f64, SIZE); ); ($name:ident, $func:ident, $typ:ty) => ( defbench!($name, $func, $typ, SIZE); ); ($name:ident, $func:ident, $typ:ty, $size:expr) => ( #[bench] fn $name(b: &mut Bencher) { let array = thread_rng().gen_iter().take($size).collect::<Vec<$typ>>(); b.iter(|| { let mut array = array.clone(); $func(&mut array); }); } ) ); defbench!(bench_selection_sort, selection_sort); defbench!(bench_insertion_sort, insertion_sort); defbench!(bench_shell_sort, shell_sort); defbench!(bench_merge_sort, merge_sort); defbench!(bench_merge_bu_sort, merge_bu_sort); defbench!(bench_quick_sort, quick_sort); defbench!(bench_quick_sort_orig, quick_sort_orig); defbench!(bench_quick_sort_3way, quick_sort_3way); // :( 3way sort does not exceed defbench!(bench_quick_sort_orig_on_dup_keys, quick_sort_orig, u8); defbench!(bench_quick_sort_3way_on_dup_keys, quick_sort_3way, u8); defbench!(bench_heap_sort, heap_sort); #[bench] fn
(b: &mut Bencher) { let array = thread_rng().gen_iter().take(SIZE).collect::<Vec<f64>>(); b.iter(|| { let mut array = array.clone(); knuth_shuffle(&mut array); }); }
bench_knuth_shuffle
identifier_name
errors.rs
#[cfg(not(target_os = "macos"))] use std::env; use std::io; use std::num; use std::path; use app_dirs; use reqwest; use serde_json; #[cfg(target_os = "macos")] use walkdir; #[derive(Debug, ErrorChain)] #[error_chain(backtrace = "false")] pub enum
{ Msg(String), #[error_chain(foreign)] AppDirs(app_dirs::AppDirsError), #[cfg(not(target_os = "macos"))] #[error_chain(foreign)] EnvVar(env::VarError), #[error_chain(foreign)] Io(io::Error), #[error_chain(foreign)] Parse(num::ParseIntError), #[error_chain(foreign)] Prefix(path::StripPrefixError), #[error_chain(foreign)] Reqwest(reqwest::Error), #[error_chain(foreign)] SerdeJSON(serde_json::Error), #[cfg(target_os = "macos")] #[error_chain(foreign)] WalkDir(walkdir::Error), }
ErrorKind
identifier_name
errors.rs
#[cfg(not(target_os = "macos"))] use std::env; use std::io; use std::num; use std::path; use app_dirs; use reqwest; use serde_json; #[cfg(target_os = "macos")] use walkdir; #[derive(Debug, ErrorChain)] #[error_chain(backtrace = "false")] pub enum ErrorKind { Msg(String), #[error_chain(foreign)] AppDirs(app_dirs::AppDirsError),
#[error_chain(foreign)] Io(io::Error), #[error_chain(foreign)] Parse(num::ParseIntError), #[error_chain(foreign)] Prefix(path::StripPrefixError), #[error_chain(foreign)] Reqwest(reqwest::Error), #[error_chain(foreign)] SerdeJSON(serde_json::Error), #[cfg(target_os = "macos")] #[error_chain(foreign)] WalkDir(walkdir::Error), }
#[cfg(not(target_os = "macos"))] #[error_chain(foreign)] EnvVar(env::VarError),
random_line_split
reference.rs
use serde::{ser}; use std::mem::transmute; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use std::fmt::{Display,Debug}; use std::fmt; use serialize::{ serialize_u64 }; // Option to display references as nested pub static mut NESTED_REFERENCE: bool = false; #[derive(Serialize, Debug)] pub struct MftEnumReference{ #[serde(serialize_with = "serialize_u64")] reference: u64, entry: u64, sequence: u16 } // Represents a MFT Reference struct // https://msdn.microsoft.com/en-us/library/bb470211(v=vs.85).aspx // https://jmharkness.wordpress.com/2011/01/27/mft-file-reference-number/ #[derive(Hash, Eq, PartialEq, Copy, Clone)] pub struct MftReference(pub u64); impl MftReference{ pub fn from_entry_and_seq(&mut self, entry: u64, sequence: u16){ let entry_buffer: [u8; 8] = unsafe { transmute(entry.to_le()) }; let seq_buffer: [u8; 2] = unsafe { transmute(sequence.to_le()) }; let mut ref_buffer = vec![]; ref_buffer.extend_from_slice(&entry_buffer[0..6]); ref_buffer.extend_from_slice(&seq_buffer); self.0 = LittleEndian::read_u64(&ref_buffer[0..8]); } pub fn get_from_entry_and_seq(entry: u64, sequence: u16) -> MftReference{ let entry_buffer: [u8; 8] = unsafe { transmute(entry.to_le()) }; let seq_buffer: [u8; 2] = unsafe { transmute(sequence.to_le()) }; let mut ref_buffer = vec![]; ref_buffer.extend_from_slice(&entry_buffer[0..6]); ref_buffer.extend_from_slice(&seq_buffer); MftReference(LittleEndian::read_u64(&ref_buffer[0..8])) } pub fn get_enum_ref(&self)->MftEnumReference{ let mut raw_buffer = vec![]; raw_buffer.write_u64::<LittleEndian>(self.0).unwrap(); MftEnumReference{ reference: LittleEndian::read_u64(&raw_buffer[0..8]), entry: LittleEndian::read_u64( &[&raw_buffer[0..6], &[0,0]].concat() ), sequence: LittleEndian::read_u16(&raw_buffer[6..8]) } } pub fn get_entry_number(&self)->u64{ let mut raw_buffer = vec![]; raw_buffer.write_u64::<LittleEndian>(self.0).unwrap(); LittleEndian::read_u64( &[&raw_buffer[0..6], &[0,0]].concat() ) } } impl Display for MftReference { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"{}",self.0) } } impl Debug for MftReference { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"{}",self.0) } } impl ser::Serialize for MftReference { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer { // If NESTED_REFERENCE we need to serialize the enumerated structure if unsafe{NESTED_REFERENCE}
else { // Just serialize the u64 version serialize_u64(&self.0,serializer) } } } #[test] fn test_mft_reference() { use std::mem; let raw_reference: &[u8] = &[0x73,0x00,0x00,0x00,0x00,0x00,0x68,0x91]; let mft_reference = MftReference( LittleEndian::read_u64(&raw_reference[0..8]) ); assert_eq!(mft_reference.0,10477624533077459059); assert_eq!(format!("{}", mft_reference),"10477624533077459059"); // assert_eq!(mft_reference.sequence,37224); let mft_reference_01 = MftReference::get_from_entry_and_seq( 115, 37224 ); assert_eq!(mft_reference_01.0,10477624533077459059); let mut mft_reference_02: MftReference = unsafe { mem::zeroed() }; assert_eq!(mft_reference_02.0,0); mft_reference_02.from_entry_and_seq( 115, 37224 ); assert_eq!(mft_reference_02.0,10477624533077459059); }
{ serializer.serialize_newtype_struct("mft_reference",&self.get_enum_ref()) }
conditional_block
reference.rs
use serde::{ser}; use std::mem::transmute; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use std::fmt::{Display,Debug}; use std::fmt; use serialize::{ serialize_u64 }; // Option to display references as nested pub static mut NESTED_REFERENCE: bool = false; #[derive(Serialize, Debug)] pub struct MftEnumReference{ #[serde(serialize_with = "serialize_u64")] reference: u64, entry: u64, sequence: u16 } // Represents a MFT Reference struct // https://msdn.microsoft.com/en-us/library/bb470211(v=vs.85).aspx // https://jmharkness.wordpress.com/2011/01/27/mft-file-reference-number/ #[derive(Hash, Eq, PartialEq, Copy, Clone)] pub struct MftReference(pub u64); impl MftReference{ pub fn from_entry_and_seq(&mut self, entry: u64, sequence: u16){ let entry_buffer: [u8; 8] = unsafe { transmute(entry.to_le()) }; let seq_buffer: [u8; 2] = unsafe { transmute(sequence.to_le()) }; let mut ref_buffer = vec![]; ref_buffer.extend_from_slice(&entry_buffer[0..6]); ref_buffer.extend_from_slice(&seq_buffer); self.0 = LittleEndian::read_u64(&ref_buffer[0..8]); } pub fn get_from_entry_and_seq(entry: u64, sequence: u16) -> MftReference{ let entry_buffer: [u8; 8] = unsafe { transmute(entry.to_le()) }; let seq_buffer: [u8; 2] = unsafe { transmute(sequence.to_le()) }; let mut ref_buffer = vec![]; ref_buffer.extend_from_slice(&entry_buffer[0..6]); ref_buffer.extend_from_slice(&seq_buffer); MftReference(LittleEndian::read_u64(&ref_buffer[0..8])) } pub fn get_enum_ref(&self)->MftEnumReference{ let mut raw_buffer = vec![]; raw_buffer.write_u64::<LittleEndian>(self.0).unwrap(); MftEnumReference{ reference: LittleEndian::read_u64(&raw_buffer[0..8]), entry: LittleEndian::read_u64( &[&raw_buffer[0..6], &[0,0]].concat() ), sequence: LittleEndian::read_u16(&raw_buffer[6..8]) } } pub fn get_entry_number(&self)->u64
} impl Display for MftReference { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"{}",self.0) } } impl Debug for MftReference { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"{}",self.0) } } impl ser::Serialize for MftReference { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer { // If NESTED_REFERENCE we need to serialize the enumerated structure if unsafe{NESTED_REFERENCE} { serializer.serialize_newtype_struct("mft_reference",&self.get_enum_ref()) } else { // Just serialize the u64 version serialize_u64(&self.0,serializer) } } } #[test] fn test_mft_reference() { use std::mem; let raw_reference: &[u8] = &[0x73,0x00,0x00,0x00,0x00,0x00,0x68,0x91]; let mft_reference = MftReference( LittleEndian::read_u64(&raw_reference[0..8]) ); assert_eq!(mft_reference.0,10477624533077459059); assert_eq!(format!("{}", mft_reference),"10477624533077459059"); // assert_eq!(mft_reference.sequence,37224); let mft_reference_01 = MftReference::get_from_entry_and_seq( 115, 37224 ); assert_eq!(mft_reference_01.0,10477624533077459059); let mut mft_reference_02: MftReference = unsafe { mem::zeroed() }; assert_eq!(mft_reference_02.0,0); mft_reference_02.from_entry_and_seq( 115, 37224 ); assert_eq!(mft_reference_02.0,10477624533077459059); }
{ let mut raw_buffer = vec![]; raw_buffer.write_u64::<LittleEndian>(self.0).unwrap(); LittleEndian::read_u64( &[&raw_buffer[0..6], &[0,0]].concat() ) }
identifier_body
reference.rs
use serde::{ser}; use std::mem::transmute; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use std::fmt::{Display,Debug}; use std::fmt; use serialize::{ serialize_u64 }; // Option to display references as nested pub static mut NESTED_REFERENCE: bool = false; #[derive(Serialize, Debug)] pub struct MftEnumReference{ #[serde(serialize_with = "serialize_u64")] reference: u64, entry: u64, sequence: u16 } // Represents a MFT Reference struct // https://msdn.microsoft.com/en-us/library/bb470211(v=vs.85).aspx // https://jmharkness.wordpress.com/2011/01/27/mft-file-reference-number/ #[derive(Hash, Eq, PartialEq, Copy, Clone)] pub struct
(pub u64); impl MftReference{ pub fn from_entry_and_seq(&mut self, entry: u64, sequence: u16){ let entry_buffer: [u8; 8] = unsafe { transmute(entry.to_le()) }; let seq_buffer: [u8; 2] = unsafe { transmute(sequence.to_le()) }; let mut ref_buffer = vec![]; ref_buffer.extend_from_slice(&entry_buffer[0..6]); ref_buffer.extend_from_slice(&seq_buffer); self.0 = LittleEndian::read_u64(&ref_buffer[0..8]); } pub fn get_from_entry_and_seq(entry: u64, sequence: u16) -> MftReference{ let entry_buffer: [u8; 8] = unsafe { transmute(entry.to_le()) }; let seq_buffer: [u8; 2] = unsafe { transmute(sequence.to_le()) }; let mut ref_buffer = vec![]; ref_buffer.extend_from_slice(&entry_buffer[0..6]); ref_buffer.extend_from_slice(&seq_buffer); MftReference(LittleEndian::read_u64(&ref_buffer[0..8])) } pub fn get_enum_ref(&self)->MftEnumReference{ let mut raw_buffer = vec![]; raw_buffer.write_u64::<LittleEndian>(self.0).unwrap(); MftEnumReference{ reference: LittleEndian::read_u64(&raw_buffer[0..8]), entry: LittleEndian::read_u64( &[&raw_buffer[0..6], &[0,0]].concat() ), sequence: LittleEndian::read_u16(&raw_buffer[6..8]) } } pub fn get_entry_number(&self)->u64{ let mut raw_buffer = vec![]; raw_buffer.write_u64::<LittleEndian>(self.0).unwrap(); LittleEndian::read_u64( &[&raw_buffer[0..6], &[0,0]].concat() ) } } impl Display for MftReference { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"{}",self.0) } } impl Debug for MftReference { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"{}",self.0) } } impl ser::Serialize for MftReference { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer { // If NESTED_REFERENCE we need to serialize the enumerated structure if unsafe{NESTED_REFERENCE} { serializer.serialize_newtype_struct("mft_reference",&self.get_enum_ref()) } else { // Just serialize the u64 version serialize_u64(&self.0,serializer) } } } #[test] fn test_mft_reference() { use std::mem; let raw_reference: &[u8] = &[0x73,0x00,0x00,0x00,0x00,0x00,0x68,0x91]; let mft_reference = MftReference( LittleEndian::read_u64(&raw_reference[0..8]) ); assert_eq!(mft_reference.0,10477624533077459059); assert_eq!(format!("{}", mft_reference),"10477624533077459059"); // assert_eq!(mft_reference.sequence,37224); let mft_reference_01 = MftReference::get_from_entry_and_seq( 115, 37224 ); assert_eq!(mft_reference_01.0,10477624533077459059); let mut mft_reference_02: MftReference = unsafe { mem::zeroed() }; assert_eq!(mft_reference_02.0,0); mft_reference_02.from_entry_and_seq( 115, 37224 ); assert_eq!(mft_reference_02.0,10477624533077459059); }
MftReference
identifier_name
reference.rs
use serde::{ser}; use std::mem::transmute; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use std::fmt::{Display,Debug}; use std::fmt; use serialize::{ serialize_u64 }; // Option to display references as nested pub static mut NESTED_REFERENCE: bool = false; #[derive(Serialize, Debug)] pub struct MftEnumReference{ #[serde(serialize_with = "serialize_u64")] reference: u64, entry: u64, sequence: u16 } // Represents a MFT Reference struct // https://msdn.microsoft.com/en-us/library/bb470211(v=vs.85).aspx // https://jmharkness.wordpress.com/2011/01/27/mft-file-reference-number/ #[derive(Hash, Eq, PartialEq, Copy, Clone)] pub struct MftReference(pub u64); impl MftReference{ pub fn from_entry_and_seq(&mut self, entry: u64, sequence: u16){ let entry_buffer: [u8; 8] = unsafe { transmute(entry.to_le()) }; let seq_buffer: [u8; 2] = unsafe { transmute(sequence.to_le()) }; let mut ref_buffer = vec![]; ref_buffer.extend_from_slice(&entry_buffer[0..6]); ref_buffer.extend_from_slice(&seq_buffer); self.0 = LittleEndian::read_u64(&ref_buffer[0..8]); } pub fn get_from_entry_and_seq(entry: u64, sequence: u16) -> MftReference{ let entry_buffer: [u8; 8] = unsafe { transmute(entry.to_le()) }; let seq_buffer: [u8; 2] = unsafe { transmute(sequence.to_le()) }; let mut ref_buffer = vec![]; ref_buffer.extend_from_slice(&entry_buffer[0..6]); ref_buffer.extend_from_slice(&seq_buffer); MftReference(LittleEndian::read_u64(&ref_buffer[0..8])) } pub fn get_enum_ref(&self)->MftEnumReference{ let mut raw_buffer = vec![]; raw_buffer.write_u64::<LittleEndian>(self.0).unwrap();
reference: LittleEndian::read_u64(&raw_buffer[0..8]), entry: LittleEndian::read_u64( &[&raw_buffer[0..6], &[0,0]].concat() ), sequence: LittleEndian::read_u16(&raw_buffer[6..8]) } } pub fn get_entry_number(&self)->u64{ let mut raw_buffer = vec![]; raw_buffer.write_u64::<LittleEndian>(self.0).unwrap(); LittleEndian::read_u64( &[&raw_buffer[0..6], &[0,0]].concat() ) } } impl Display for MftReference { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"{}",self.0) } } impl Debug for MftReference { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"{}",self.0) } } impl ser::Serialize for MftReference { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer { // If NESTED_REFERENCE we need to serialize the enumerated structure if unsafe{NESTED_REFERENCE} { serializer.serialize_newtype_struct("mft_reference",&self.get_enum_ref()) } else { // Just serialize the u64 version serialize_u64(&self.0,serializer) } } } #[test] fn test_mft_reference() { use std::mem; let raw_reference: &[u8] = &[0x73,0x00,0x00,0x00,0x00,0x00,0x68,0x91]; let mft_reference = MftReference( LittleEndian::read_u64(&raw_reference[0..8]) ); assert_eq!(mft_reference.0,10477624533077459059); assert_eq!(format!("{}", mft_reference),"10477624533077459059"); // assert_eq!(mft_reference.sequence,37224); let mft_reference_01 = MftReference::get_from_entry_and_seq( 115, 37224 ); assert_eq!(mft_reference_01.0,10477624533077459059); let mut mft_reference_02: MftReference = unsafe { mem::zeroed() }; assert_eq!(mft_reference_02.0,0); mft_reference_02.from_entry_and_seq( 115, 37224 ); assert_eq!(mft_reference_02.0,10477624533077459059); }
MftEnumReference{
random_line_split
cp.rs
#![crate_name = "cp"] /* * This file is part of the uutils coreutils package. * * (c) Jordy Dickinson <[email protected]> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; use getopts::Options; use std::fs; use std::io::{ErrorKind, Result, Write}; use std::path::Path; #[path = "../common/util.rs"] #[macro_use] mod util; #[path = "../common/filesystem.rs"] mod filesystem; use filesystem::{canonicalize, CanonicalizeMode, UUPathExt}; #[derive(Clone, Eq, PartialEq)] pub enum Mode { Copy, Help, Version, } static NAME: &'static str = "cp"; static VERSION: &'static str = "1.0.0"; pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(e) => { show_error!("{}", e); panic!() }, }; let usage = opts.usage("Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY."); let mode = if matches.opt_present("version") { Mode::Version } else if matches.opt_present("help") { Mode::Help } else { Mode::Copy }; match mode { Mode::Copy => copy(matches), Mode::Help => help(&usage), Mode::Version => version(), } 0 } fn version() { println!("{} {}", NAME, VERSION); } fn help(usage: &String) { let msg = format!("{0} {1}\n\n\ Usage: {0} SOURCE DEST\n \ or: {0} SOURCE... DIRECTORY\n \ or: {0} -t DIRECTORY SOURCE\n\ \n\ {2}", NAME, VERSION, usage); println!("{}", msg); } fn copy(matches: getopts::Matches) { let sources: Vec<String> = if matches.free.is_empty() { show_error!("Missing SOURCE argument. Try --help."); panic!() } else { // All but the last argument: matches.free[..matches.free.len() - 1].iter().map(|arg| arg.clone()).collect() }; let dest = if matches.free.len() < 2 { show_error!("Missing DEST argument. Try --help."); panic!() } else { // Only the last argument: Path::new(&matches.free[matches.free.len() - 1]) }; assert!(sources.len() >= 1); if sources.len() == 1 { let source = Path::new(&sources[0]); let same_file = paths_refer_to_same_file(source, dest).unwrap_or_else(|err| { match err.kind() { ErrorKind::NotFound => false, _ => { show_error!("{}", err); panic!() } } }); if same_file { show_error!("\"{}\" and \"{}\" are the same file", source.display(), dest.display()); panic!(); } if let Err(err) = fs::copy(source, dest)
} else { if!dest.uu_is_dir() { show_error!("TARGET must be a directory"); panic!(); } for src in sources.iter() { let source = Path::new(&src); if!source.uu_is_file() { show_error!("\"{}\" is not a file", source.display()); continue; } let mut full_dest = dest.to_path_buf(); full_dest.push(source.to_str().unwrap()); println!("{}", full_dest.display()); let io_result = fs::copy(source, full_dest); if let Err(err) = io_result { show_error!("{}", err); panic!() } } } } pub fn paths_refer_to_same_file(p1: &Path, p2: &Path) -> Result<bool> { // We have to take symlinks and relative paths into account. let pathbuf1 = try!(canonicalize(p1, CanonicalizeMode::Normal)); let pathbuf2 = try!(canonicalize(p2, CanonicalizeMode::Normal)); Ok(pathbuf1 == pathbuf2) }
{ show_error!("{}", err); panic!(); }
conditional_block
cp.rs
#![crate_name = "cp"] /* * This file is part of the uutils coreutils package. * * (c) Jordy Dickinson <[email protected]> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; use getopts::Options; use std::fs; use std::io::{ErrorKind, Result, Write}; use std::path::Path; #[path = "../common/util.rs"] #[macro_use] mod util; #[path = "../common/filesystem.rs"] mod filesystem; use filesystem::{canonicalize, CanonicalizeMode, UUPathExt}; #[derive(Clone, Eq, PartialEq)] pub enum Mode { Copy, Help, Version, } static NAME: &'static str = "cp"; static VERSION: &'static str = "1.0.0"; pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(e) => { show_error!("{}", e); panic!() }, }; let usage = opts.usage("Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY."); let mode = if matches.opt_present("version") { Mode::Version } else if matches.opt_present("help") { Mode::Help } else { Mode::Copy }; match mode { Mode::Copy => copy(matches), Mode::Help => help(&usage), Mode::Version => version(), } 0 } fn version() { println!("{} {}", NAME, VERSION); } fn help(usage: &String) { let msg = format!("{0} {1}\n\n\ Usage: {0} SOURCE DEST\n \ or: {0} SOURCE... DIRECTORY\n \ or: {0} -t DIRECTORY SOURCE\n\
} fn copy(matches: getopts::Matches) { let sources: Vec<String> = if matches.free.is_empty() { show_error!("Missing SOURCE argument. Try --help."); panic!() } else { // All but the last argument: matches.free[..matches.free.len() - 1].iter().map(|arg| arg.clone()).collect() }; let dest = if matches.free.len() < 2 { show_error!("Missing DEST argument. Try --help."); panic!() } else { // Only the last argument: Path::new(&matches.free[matches.free.len() - 1]) }; assert!(sources.len() >= 1); if sources.len() == 1 { let source = Path::new(&sources[0]); let same_file = paths_refer_to_same_file(source, dest).unwrap_or_else(|err| { match err.kind() { ErrorKind::NotFound => false, _ => { show_error!("{}", err); panic!() } } }); if same_file { show_error!("\"{}\" and \"{}\" are the same file", source.display(), dest.display()); panic!(); } if let Err(err) = fs::copy(source, dest) { show_error!("{}", err); panic!(); } } else { if!dest.uu_is_dir() { show_error!("TARGET must be a directory"); panic!(); } for src in sources.iter() { let source = Path::new(&src); if!source.uu_is_file() { show_error!("\"{}\" is not a file", source.display()); continue; } let mut full_dest = dest.to_path_buf(); full_dest.push(source.to_str().unwrap()); println!("{}", full_dest.display()); let io_result = fs::copy(source, full_dest); if let Err(err) = io_result { show_error!("{}", err); panic!() } } } } pub fn paths_refer_to_same_file(p1: &Path, p2: &Path) -> Result<bool> { // We have to take symlinks and relative paths into account. let pathbuf1 = try!(canonicalize(p1, CanonicalizeMode::Normal)); let pathbuf2 = try!(canonicalize(p2, CanonicalizeMode::Normal)); Ok(pathbuf1 == pathbuf2) }
\n\ {2}", NAME, VERSION, usage); println!("{}", msg);
random_line_split
cp.rs
#![crate_name = "cp"] /* * This file is part of the uutils coreutils package. * * (c) Jordy Dickinson <[email protected]> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; use getopts::Options; use std::fs; use std::io::{ErrorKind, Result, Write}; use std::path::Path; #[path = "../common/util.rs"] #[macro_use] mod util; #[path = "../common/filesystem.rs"] mod filesystem; use filesystem::{canonicalize, CanonicalizeMode, UUPathExt}; #[derive(Clone, Eq, PartialEq)] pub enum Mode { Copy, Help, Version, } static NAME: &'static str = "cp"; static VERSION: &'static str = "1.0.0"; pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(e) => { show_error!("{}", e); panic!() }, }; let usage = opts.usage("Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY."); let mode = if matches.opt_present("version") { Mode::Version } else if matches.opt_present("help") { Mode::Help } else { Mode::Copy }; match mode { Mode::Copy => copy(matches), Mode::Help => help(&usage), Mode::Version => version(), } 0 } fn version() { println!("{} {}", NAME, VERSION); } fn
(usage: &String) { let msg = format!("{0} {1}\n\n\ Usage: {0} SOURCE DEST\n \ or: {0} SOURCE... DIRECTORY\n \ or: {0} -t DIRECTORY SOURCE\n\ \n\ {2}", NAME, VERSION, usage); println!("{}", msg); } fn copy(matches: getopts::Matches) { let sources: Vec<String> = if matches.free.is_empty() { show_error!("Missing SOURCE argument. Try --help."); panic!() } else { // All but the last argument: matches.free[..matches.free.len() - 1].iter().map(|arg| arg.clone()).collect() }; let dest = if matches.free.len() < 2 { show_error!("Missing DEST argument. Try --help."); panic!() } else { // Only the last argument: Path::new(&matches.free[matches.free.len() - 1]) }; assert!(sources.len() >= 1); if sources.len() == 1 { let source = Path::new(&sources[0]); let same_file = paths_refer_to_same_file(source, dest).unwrap_or_else(|err| { match err.kind() { ErrorKind::NotFound => false, _ => { show_error!("{}", err); panic!() } } }); if same_file { show_error!("\"{}\" and \"{}\" are the same file", source.display(), dest.display()); panic!(); } if let Err(err) = fs::copy(source, dest) { show_error!("{}", err); panic!(); } } else { if!dest.uu_is_dir() { show_error!("TARGET must be a directory"); panic!(); } for src in sources.iter() { let source = Path::new(&src); if!source.uu_is_file() { show_error!("\"{}\" is not a file", source.display()); continue; } let mut full_dest = dest.to_path_buf(); full_dest.push(source.to_str().unwrap()); println!("{}", full_dest.display()); let io_result = fs::copy(source, full_dest); if let Err(err) = io_result { show_error!("{}", err); panic!() } } } } pub fn paths_refer_to_same_file(p1: &Path, p2: &Path) -> Result<bool> { // We have to take symlinks and relative paths into account. let pathbuf1 = try!(canonicalize(p1, CanonicalizeMode::Normal)); let pathbuf2 = try!(canonicalize(p2, CanonicalizeMode::Normal)); Ok(pathbuf1 == pathbuf2) }
help
identifier_name
cp.rs
#![crate_name = "cp"] /* * This file is part of the uutils coreutils package. * * (c) Jordy Dickinson <[email protected]> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; use getopts::Options; use std::fs; use std::io::{ErrorKind, Result, Write}; use std::path::Path; #[path = "../common/util.rs"] #[macro_use] mod util; #[path = "../common/filesystem.rs"] mod filesystem; use filesystem::{canonicalize, CanonicalizeMode, UUPathExt}; #[derive(Clone, Eq, PartialEq)] pub enum Mode { Copy, Help, Version, } static NAME: &'static str = "cp"; static VERSION: &'static str = "1.0.0"; pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(e) => { show_error!("{}", e); panic!() }, }; let usage = opts.usage("Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY."); let mode = if matches.opt_present("version") { Mode::Version } else if matches.opt_present("help") { Mode::Help } else { Mode::Copy }; match mode { Mode::Copy => copy(matches), Mode::Help => help(&usage), Mode::Version => version(), } 0 } fn version() { println!("{} {}", NAME, VERSION); } fn help(usage: &String)
fn copy(matches: getopts::Matches) { let sources: Vec<String> = if matches.free.is_empty() { show_error!("Missing SOURCE argument. Try --help."); panic!() } else { // All but the last argument: matches.free[..matches.free.len() - 1].iter().map(|arg| arg.clone()).collect() }; let dest = if matches.free.len() < 2 { show_error!("Missing DEST argument. Try --help."); panic!() } else { // Only the last argument: Path::new(&matches.free[matches.free.len() - 1]) }; assert!(sources.len() >= 1); if sources.len() == 1 { let source = Path::new(&sources[0]); let same_file = paths_refer_to_same_file(source, dest).unwrap_or_else(|err| { match err.kind() { ErrorKind::NotFound => false, _ => { show_error!("{}", err); panic!() } } }); if same_file { show_error!("\"{}\" and \"{}\" are the same file", source.display(), dest.display()); panic!(); } if let Err(err) = fs::copy(source, dest) { show_error!("{}", err); panic!(); } } else { if!dest.uu_is_dir() { show_error!("TARGET must be a directory"); panic!(); } for src in sources.iter() { let source = Path::new(&src); if!source.uu_is_file() { show_error!("\"{}\" is not a file", source.display()); continue; } let mut full_dest = dest.to_path_buf(); full_dest.push(source.to_str().unwrap()); println!("{}", full_dest.display()); let io_result = fs::copy(source, full_dest); if let Err(err) = io_result { show_error!("{}", err); panic!() } } } } pub fn paths_refer_to_same_file(p1: &Path, p2: &Path) -> Result<bool> { // We have to take symlinks and relative paths into account. let pathbuf1 = try!(canonicalize(p1, CanonicalizeMode::Normal)); let pathbuf2 = try!(canonicalize(p2, CanonicalizeMode::Normal)); Ok(pathbuf1 == pathbuf2) }
{ let msg = format!("{0} {1}\n\n\ Usage: {0} SOURCE DEST\n \ or: {0} SOURCE... DIRECTORY\n \ or: {0} -t DIRECTORY SOURCE\n\ \n\ {2}", NAME, VERSION, usage); println!("{}", msg); }
identifier_body
scancode_linux.rs
use super::Key; use super::Key::*; /// Keyboard scancode map for Linux. pub static MAP: [Option<Key>; 97] = [ None, None, None, None, None, None, None, None, None, Some(Escape), Some(Num1), Some(Num2), Some(Num3), Some(Num4), Some(Num5), Some(Num6), Some(Num7), Some(Num8), Some(Num9), Some(Num0), Some(Minus), Some(Equals), Some(Backspace), Some(Tab), Some(Q), Some(W), Some(E), Some(R), Some(T), Some(Y), Some(U), Some(I), Some(O), Some(P), Some(LeftBracket), Some(RightBracket), Some(Enter), Some(LeftControl), Some(A), Some(S), Some(D), Some(F), Some(G), Some(H), Some(J), Some(K), Some(L),
Some(Z), Some(X), Some(C), Some(V), Some(B), Some(N), Some(M), Some(Comma), Some(Period), Some(Slash), Some(RightShift), Some(PadMultiply), Some(LeftAlt), Some(Space), Some(CapsLock), Some(F1), Some(F2), Some(F3), Some(F4), Some(F5), Some(F6), Some(F7), Some(F8), Some(F9), Some(F10), Some(NumLock), Some(ScrollLock), Some(Pad7), Some(Pad8), Some(Pad9), Some(PadMinus), Some(Pad4), Some(Pad5), Some(Pad6), Some(PadPlus), Some(Pad1), Some(Pad2), Some(Pad3), Some(Pad0), Some(PadDecimal), None, None, None, // This is the 102th key in intl keyboards. Some(F11), Some(F12), ];
Some(Semicolon), Some(Apostrophe), Some(Grave), Some(LeftShift), Some(Backslash),
random_line_split
inherent_impl.rs
// run-pass // compile-flags: -Z chalk trait Foo { } impl Foo for i32 { } struct S<T: Foo> { x: T, } fn only_foo<T: Foo>(_x: &T) { } impl<T> S<T> { // Test that we have the correct environment inside an inherent method. fn dummy_foo(&self) { only_foo(&self.x) } } trait Bar { } impl Bar for u32 { } fn only_bar<T: Bar>() { } impl<T> S<T> { // Test that the environment of `dummy_bar` adds up with the environment // of the inherent impl. fn
<U: Bar>(&self) { only_foo(&self.x); only_bar::<U>(); } } fn main() { let s = S { x: 5, }; s.dummy_bar::<u32>(); s.dummy_foo(); }
dummy_bar
identifier_name
inherent_impl.rs
// run-pass // compile-flags: -Z chalk trait Foo { } impl Foo for i32 { } struct S<T: Foo> { x: T, } fn only_foo<T: Foo>(_x: &T) { } impl<T> S<T> { // Test that we have the correct environment inside an inherent method. fn dummy_foo(&self) { only_foo(&self.x) } } trait Bar { } impl Bar for u32 { } fn only_bar<T: Bar>() { } impl<T> S<T> { // Test that the environment of `dummy_bar` adds up with the environment // of the inherent impl. fn dummy_bar<U: Bar>(&self) { only_foo(&self.x); only_bar::<U>(); } } fn main() { let s = S { x: 5,
}; s.dummy_bar::<u32>(); s.dummy_foo(); }
random_line_split
inherent_impl.rs
// run-pass // compile-flags: -Z chalk trait Foo { } impl Foo for i32 { } struct S<T: Foo> { x: T, } fn only_foo<T: Foo>(_x: &T) { } impl<T> S<T> { // Test that we have the correct environment inside an inherent method. fn dummy_foo(&self) { only_foo(&self.x) } } trait Bar { } impl Bar for u32 { } fn only_bar<T: Bar>() { } impl<T> S<T> { // Test that the environment of `dummy_bar` adds up with the environment // of the inherent impl. fn dummy_bar<U: Bar>(&self)
} fn main() { let s = S { x: 5, }; s.dummy_bar::<u32>(); s.dummy_foo(); }
{ only_foo(&self.x); only_bar::<U>(); }
identifier_body
elo.rs
// This file was taken from the rust-elo project since it's not a published // Cargo crate. Check out https://github.com/CarlColglazier/rust-elo :] // disregard dead code since this is an API #![allow(dead_code)] /// Elo. pub trait Elo { /// Get the rating. fn get_rating(&self) -> f32; /// Set the rating. fn change_rating(&mut self, rating: f32); } fn expected_rating<T: Elo>(player_one: &T, player_two: &T) -> f32 { return 1.0f32 / (1.0f32 + 10f32.powf( (player_two.get_rating() - player_one.get_rating()) / 400f32 )); } /// EloRanking. pub struct EloRanking { k_factor: usize, } impl EloRanking { /// Create a new Elo ranking system. /// /// # Example /// /// ``` /// # use elo::EloRanking; /// let k_factor: usize = 32; /// let elo_ranking = EloRanking::new(k_factor); /// ``` pub fn new(k: usize) -> EloRanking { return EloRanking { k_factor: k, } } /// Change the K factor. /// /// # Example /// /// ``` /// # use elo::EloRanking; /// # let mut elo_ranking = EloRanking::new(32); /// elo_ranking.set_k_factor(25); /// ``` pub fn set_k_factor(&mut self, k: usize)
/// Returns the K factor. /// /// # Example /// /// ``` /// # use elo::EloRanking; /// # let elo_ranking = EloRanking::new(32); /// assert_eq!(32, elo_ranking.get_k_factor()); /// ``` pub fn get_k_factor(&self) -> usize { return self.k_factor; } /// Internal method for generic calculations. fn calculate_rating<T: Elo>(&self, player_one: &mut T, player_two: &mut T, score: f32) { let change = self.k_factor as f32 * (score - expected_rating::<T>(player_one, player_two)); player_one.change_rating(change); player_two.change_rating(-change); } pub fn win<T: Elo>(&self, winner: &mut T, loser: &mut T) { self.calculate_rating(winner, loser, 1.0); } pub fn tie<T: Elo>(&self, player_one: &mut T, player_two: &mut T) { self.calculate_rating(player_one, player_two, 0.5); } pub fn loss<T: Elo>(&self, loser: &mut T, winner: &mut T) { self.win::<T>(winner, loser); } } #[cfg(test)] mod tests { use super::*; struct RatingObject { rating: f32, } impl RatingObject { pub fn new() -> RatingObject { return RatingObject { rating: 1400f32, }; } } impl Elo for RatingObject { fn get_rating(&self) -> f32 { return self.rating; } fn change_rating(&mut self, rating: f32) { self.rating += rating; } } #[test] fn rating() { let mut player_one = RatingObject::new(); let mut player_two = RatingObject::new(); let rating_system = EloRanking::new(32); assert_eq!(1400f32, player_one.get_rating()); assert_eq!(1400f32, player_two.get_rating()); player_one.change_rating(100f32); assert_eq!(1500f32, player_one.get_rating()); player_one.change_rating(-100f32); assert_eq!(1400f32, player_one.get_rating()); // In a tie, the ratings should stay the same. rating_system.tie::<RatingObject>(&mut player_one, &mut player_two); assert_eq!(1400f32, player_one.get_rating()); assert_eq!(1400f32, player_two.get_rating()); // With a win, player_one should gain an advantage. rating_system.win::<RatingObject>(&mut player_one, &mut player_two); assert_eq!(1416f32, player_one.get_rating()); assert_eq!(1384f32, player_two.get_rating()); // With a loss, this should reset to normal. rating_system.loss::<RatingObject>(&mut player_one, &mut player_two); assert_eq!(1398.5305f32, player_one.get_rating()); assert_eq!(1401.4695f32, player_two.get_rating()); } }
{ self.k_factor = k; }
identifier_body
elo.rs
// This file was taken from the rust-elo project since it's not a published // Cargo crate. Check out https://github.com/CarlColglazier/rust-elo :] // disregard dead code since this is an API #![allow(dead_code)] /// Elo. pub trait Elo { /// Get the rating. fn get_rating(&self) -> f32; /// Set the rating. fn change_rating(&mut self, rating: f32); } fn expected_rating<T: Elo>(player_one: &T, player_two: &T) -> f32 { return 1.0f32 / (1.0f32 + 10f32.powf( (player_two.get_rating() - player_one.get_rating()) / 400f32 )); } /// EloRanking. pub struct EloRanking { k_factor: usize, } impl EloRanking { /// Create a new Elo ranking system. /// /// # Example /// /// ``` /// # use elo::EloRanking; /// let k_factor: usize = 32; /// let elo_ranking = EloRanking::new(k_factor);
return EloRanking { k_factor: k, } } /// Change the K factor. /// /// # Example /// /// ``` /// # use elo::EloRanking; /// # let mut elo_ranking = EloRanking::new(32); /// elo_ranking.set_k_factor(25); /// ``` pub fn set_k_factor(&mut self, k: usize) { self.k_factor = k; } /// Returns the K factor. /// /// # Example /// /// ``` /// # use elo::EloRanking; /// # let elo_ranking = EloRanking::new(32); /// assert_eq!(32, elo_ranking.get_k_factor()); /// ``` pub fn get_k_factor(&self) -> usize { return self.k_factor; } /// Internal method for generic calculations. fn calculate_rating<T: Elo>(&self, player_one: &mut T, player_two: &mut T, score: f32) { let change = self.k_factor as f32 * (score - expected_rating::<T>(player_one, player_two)); player_one.change_rating(change); player_two.change_rating(-change); } pub fn win<T: Elo>(&self, winner: &mut T, loser: &mut T) { self.calculate_rating(winner, loser, 1.0); } pub fn tie<T: Elo>(&self, player_one: &mut T, player_two: &mut T) { self.calculate_rating(player_one, player_two, 0.5); } pub fn loss<T: Elo>(&self, loser: &mut T, winner: &mut T) { self.win::<T>(winner, loser); } } #[cfg(test)] mod tests { use super::*; struct RatingObject { rating: f32, } impl RatingObject { pub fn new() -> RatingObject { return RatingObject { rating: 1400f32, }; } } impl Elo for RatingObject { fn get_rating(&self) -> f32 { return self.rating; } fn change_rating(&mut self, rating: f32) { self.rating += rating; } } #[test] fn rating() { let mut player_one = RatingObject::new(); let mut player_two = RatingObject::new(); let rating_system = EloRanking::new(32); assert_eq!(1400f32, player_one.get_rating()); assert_eq!(1400f32, player_two.get_rating()); player_one.change_rating(100f32); assert_eq!(1500f32, player_one.get_rating()); player_one.change_rating(-100f32); assert_eq!(1400f32, player_one.get_rating()); // In a tie, the ratings should stay the same. rating_system.tie::<RatingObject>(&mut player_one, &mut player_two); assert_eq!(1400f32, player_one.get_rating()); assert_eq!(1400f32, player_two.get_rating()); // With a win, player_one should gain an advantage. rating_system.win::<RatingObject>(&mut player_one, &mut player_two); assert_eq!(1416f32, player_one.get_rating()); assert_eq!(1384f32, player_two.get_rating()); // With a loss, this should reset to normal. rating_system.loss::<RatingObject>(&mut player_one, &mut player_two); assert_eq!(1398.5305f32, player_one.get_rating()); assert_eq!(1401.4695f32, player_two.get_rating()); } }
/// ``` pub fn new(k: usize) -> EloRanking {
random_line_split
elo.rs
// This file was taken from the rust-elo project since it's not a published // Cargo crate. Check out https://github.com/CarlColglazier/rust-elo :] // disregard dead code since this is an API #![allow(dead_code)] /// Elo. pub trait Elo { /// Get the rating. fn get_rating(&self) -> f32; /// Set the rating. fn change_rating(&mut self, rating: f32); } fn
<T: Elo>(player_one: &T, player_two: &T) -> f32 { return 1.0f32 / (1.0f32 + 10f32.powf( (player_two.get_rating() - player_one.get_rating()) / 400f32 )); } /// EloRanking. pub struct EloRanking { k_factor: usize, } impl EloRanking { /// Create a new Elo ranking system. /// /// # Example /// /// ``` /// # use elo::EloRanking; /// let k_factor: usize = 32; /// let elo_ranking = EloRanking::new(k_factor); /// ``` pub fn new(k: usize) -> EloRanking { return EloRanking { k_factor: k, } } /// Change the K factor. /// /// # Example /// /// ``` /// # use elo::EloRanking; /// # let mut elo_ranking = EloRanking::new(32); /// elo_ranking.set_k_factor(25); /// ``` pub fn set_k_factor(&mut self, k: usize) { self.k_factor = k; } /// Returns the K factor. /// /// # Example /// /// ``` /// # use elo::EloRanking; /// # let elo_ranking = EloRanking::new(32); /// assert_eq!(32, elo_ranking.get_k_factor()); /// ``` pub fn get_k_factor(&self) -> usize { return self.k_factor; } /// Internal method for generic calculations. fn calculate_rating<T: Elo>(&self, player_one: &mut T, player_two: &mut T, score: f32) { let change = self.k_factor as f32 * (score - expected_rating::<T>(player_one, player_two)); player_one.change_rating(change); player_two.change_rating(-change); } pub fn win<T: Elo>(&self, winner: &mut T, loser: &mut T) { self.calculate_rating(winner, loser, 1.0); } pub fn tie<T: Elo>(&self, player_one: &mut T, player_two: &mut T) { self.calculate_rating(player_one, player_two, 0.5); } pub fn loss<T: Elo>(&self, loser: &mut T, winner: &mut T) { self.win::<T>(winner, loser); } } #[cfg(test)] mod tests { use super::*; struct RatingObject { rating: f32, } impl RatingObject { pub fn new() -> RatingObject { return RatingObject { rating: 1400f32, }; } } impl Elo for RatingObject { fn get_rating(&self) -> f32 { return self.rating; } fn change_rating(&mut self, rating: f32) { self.rating += rating; } } #[test] fn rating() { let mut player_one = RatingObject::new(); let mut player_two = RatingObject::new(); let rating_system = EloRanking::new(32); assert_eq!(1400f32, player_one.get_rating()); assert_eq!(1400f32, player_two.get_rating()); player_one.change_rating(100f32); assert_eq!(1500f32, player_one.get_rating()); player_one.change_rating(-100f32); assert_eq!(1400f32, player_one.get_rating()); // In a tie, the ratings should stay the same. rating_system.tie::<RatingObject>(&mut player_one, &mut player_two); assert_eq!(1400f32, player_one.get_rating()); assert_eq!(1400f32, player_two.get_rating()); // With a win, player_one should gain an advantage. rating_system.win::<RatingObject>(&mut player_one, &mut player_two); assert_eq!(1416f32, player_one.get_rating()); assert_eq!(1384f32, player_two.get_rating()); // With a loss, this should reset to normal. rating_system.loss::<RatingObject>(&mut player_one, &mut player_two); assert_eq!(1398.5305f32, player_one.get_rating()); assert_eq!(1401.4695f32, player_two.get_rating()); } }
expected_rating
identifier_name
borrowck-pat-reassign-binding.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. fn
() { let mut x: Option<isize> = None; match x { None => { // Note: on this branch, no borrow has occurred. x = Some(0); } Some(ref i) => { // But on this branch, `i` is an outstanding borrow x = Some(*i+1); //~ ERROR cannot assign to `x` } } x.clone(); // just to prevent liveness warnings }
main
identifier_name
borrowck-pat-reassign-binding.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. fn main()
{ let mut x: Option<isize> = None; match x { None => { // Note: on this branch, no borrow has occurred. x = Some(0); } Some(ref i) => { // But on this branch, `i` is an outstanding borrow x = Some(*i+1); //~ ERROR cannot assign to `x` } } x.clone(); // just to prevent liveness warnings }
identifier_body
borrowck-pat-reassign-binding.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. fn main() {
x = Some(0); } Some(ref i) => { // But on this branch, `i` is an outstanding borrow x = Some(*i+1); //~ ERROR cannot assign to `x` } } x.clone(); // just to prevent liveness warnings }
let mut x: Option<isize> = None; match x { None => { // Note: on this branch, no borrow has occurred.
random_line_split
borrowck-pat-reassign-binding.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. fn main() { let mut x: Option<isize> = None; match x { None =>
Some(ref i) => { // But on this branch, `i` is an outstanding borrow x = Some(*i+1); //~ ERROR cannot assign to `x` } } x.clone(); // just to prevent liveness warnings }
{ // Note: on this branch, no borrow has occurred. x = Some(0); }
conditional_block
lexical-scope-in-while.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags:-Z extra-debug-info // debugger:rbreak zzz // debugger:run // FIRST ITERATION // debugger:finish // debugger:print x // check:$1 = 0 // debugger:continue // debugger:finish // debugger:print x // check:$2 = 1 // debugger:continue // debugger:finish // debugger:print x // check:$3 = 101 // debugger:continue // debugger:finish // debugger:print x // check:$4 = 101 // debugger:continue // debugger:finish // debugger:print x // check:$5 = -987 // debugger:continue // debugger:finish // debugger:print x // check:$6 = 101 // debugger:continue // SECOND ITERATION // debugger:finish // debugger:print x // check:$7 = 1 // debugger:continue // debugger:finish // debugger:print x // check:$8 = 2 // debugger:continue // debugger:finish // debugger:print x // check:$9 = 102 // debugger:continue // debugger:finish // debugger:print x // check:$10 = 102 // debugger:continue // debugger:finish // debugger:print x // check:$11 = -987 // debugger:continue // debugger:finish // debugger:print x
// debugger:finish // debugger:print x // check:$13 = 2 // debugger:continue fn main() { let mut x = 0; while x < 2 { zzz(); sentinel(); x += 1; zzz(); sentinel(); // Shadow x let x = x + 100; zzz(); sentinel(); // open scope within loop's top level scope { zzz(); sentinel(); let x = -987; zzz(); sentinel(); } // Check that we get the x before the inner scope again zzz(); sentinel(); } zzz(); sentinel(); } fn zzz() {()} fn sentinel() {()}
// check:$12 = 102 // debugger:continue
random_line_split
lexical-scope-in-while.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags:-Z extra-debug-info // debugger:rbreak zzz // debugger:run // FIRST ITERATION // debugger:finish // debugger:print x // check:$1 = 0 // debugger:continue // debugger:finish // debugger:print x // check:$2 = 1 // debugger:continue // debugger:finish // debugger:print x // check:$3 = 101 // debugger:continue // debugger:finish // debugger:print x // check:$4 = 101 // debugger:continue // debugger:finish // debugger:print x // check:$5 = -987 // debugger:continue // debugger:finish // debugger:print x // check:$6 = 101 // debugger:continue // SECOND ITERATION // debugger:finish // debugger:print x // check:$7 = 1 // debugger:continue // debugger:finish // debugger:print x // check:$8 = 2 // debugger:continue // debugger:finish // debugger:print x // check:$9 = 102 // debugger:continue // debugger:finish // debugger:print x // check:$10 = 102 // debugger:continue // debugger:finish // debugger:print x // check:$11 = -987 // debugger:continue // debugger:finish // debugger:print x // check:$12 = 102 // debugger:continue // debugger:finish // debugger:print x // check:$13 = 2 // debugger:continue fn
() { let mut x = 0; while x < 2 { zzz(); sentinel(); x += 1; zzz(); sentinel(); // Shadow x let x = x + 100; zzz(); sentinel(); // open scope within loop's top level scope { zzz(); sentinel(); let x = -987; zzz(); sentinel(); } // Check that we get the x before the inner scope again zzz(); sentinel(); } zzz(); sentinel(); } fn zzz() {()} fn sentinel() {()}
main
identifier_name
lexical-scope-in-while.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags:-Z extra-debug-info // debugger:rbreak zzz // debugger:run // FIRST ITERATION // debugger:finish // debugger:print x // check:$1 = 0 // debugger:continue // debugger:finish // debugger:print x // check:$2 = 1 // debugger:continue // debugger:finish // debugger:print x // check:$3 = 101 // debugger:continue // debugger:finish // debugger:print x // check:$4 = 101 // debugger:continue // debugger:finish // debugger:print x // check:$5 = -987 // debugger:continue // debugger:finish // debugger:print x // check:$6 = 101 // debugger:continue // SECOND ITERATION // debugger:finish // debugger:print x // check:$7 = 1 // debugger:continue // debugger:finish // debugger:print x // check:$8 = 2 // debugger:continue // debugger:finish // debugger:print x // check:$9 = 102 // debugger:continue // debugger:finish // debugger:print x // check:$10 = 102 // debugger:continue // debugger:finish // debugger:print x // check:$11 = -987 // debugger:continue // debugger:finish // debugger:print x // check:$12 = 102 // debugger:continue // debugger:finish // debugger:print x // check:$13 = 2 // debugger:continue fn main()
sentinel(); let x = -987; zzz(); sentinel(); } // Check that we get the x before the inner scope again zzz(); sentinel(); } zzz(); sentinel(); } fn zzz() {()} fn sentinel() {()}
{ let mut x = 0; while x < 2 { zzz(); sentinel(); x += 1; zzz(); sentinel(); // Shadow x let x = x + 100; zzz(); sentinel(); // open scope within loop's top level scope { zzz();
identifier_body
mod.rs
use sfml::graphics; use engine::resource_loader::{ResourceLoader, Resource}; use engine::state::StateMachine; use engine::rendering::RenderContext; use engine::settings::Settings; use self::State::*; pub mod colors; pub mod main_menu; pub mod game_state; pub mod slot_select_menu; pub mod level; pub mod ui; pub mod savefile; pub fn load_resources(loader: &mut ResourceLoader) { let obelix_font = graphics::Font::new_from_file("res/font/AlegreyaSansSC-Light.ttf").unwrap(); loader.add_resource("MenuFont".to_string(), Resource::Font(obelix_font)); } pub enum
{ MainMenuStateID, GameStateID, SlotSelectStateID, OptionsStateID, } pub static NUM_SLOTS : isize = 6; pub fn init_states(state_machine: &mut StateMachine, loader: &ResourceLoader, ctx: &RenderContext, settings: &Settings) { state_machine.add_state(MainMenuStateID as isize, Box::new(main_menu::MainMenu::new(loader, ctx))); state_machine.set_default_state(MainMenuStateID as isize); state_machine.add_state(SlotSelectStateID as isize, Box::new(slot_select_menu::SlotSelectMenu::new(loader, ctx))); state_machine.add_state(GameStateID as isize, Box::new(game_state::GameState::new(loader, ctx, settings))); }
State
identifier_name
mod.rs
use sfml::graphics; use engine::resource_loader::{ResourceLoader, Resource}; use engine::state::StateMachine; use engine::rendering::RenderContext; use engine::settings::Settings; use self::State::*; pub mod colors; pub mod main_menu; pub mod game_state; pub mod slot_select_menu; pub mod level; pub mod ui; pub mod savefile; pub fn load_resources(loader: &mut ResourceLoader) { let obelix_font = graphics::Font::new_from_file("res/font/AlegreyaSansSC-Light.ttf").unwrap(); loader.add_resource("MenuFont".to_string(), Resource::Font(obelix_font)); } pub enum State { MainMenuStateID, GameStateID, SlotSelectStateID, OptionsStateID, } pub static NUM_SLOTS : isize = 6; pub fn init_states(state_machine: &mut StateMachine, loader: &ResourceLoader, ctx: &RenderContext, settings: &Settings) {
state_machine.add_state(MainMenuStateID as isize, Box::new(main_menu::MainMenu::new(loader, ctx))); state_machine.set_default_state(MainMenuStateID as isize); state_machine.add_state(SlotSelectStateID as isize, Box::new(slot_select_menu::SlotSelectMenu::new(loader, ctx))); state_machine.add_state(GameStateID as isize, Box::new(game_state::GameState::new(loader, ctx, settings))); }
random_line_split
mod.rs
use sfml::graphics; use engine::resource_loader::{ResourceLoader, Resource}; use engine::state::StateMachine; use engine::rendering::RenderContext; use engine::settings::Settings; use self::State::*; pub mod colors; pub mod main_menu; pub mod game_state; pub mod slot_select_menu; pub mod level; pub mod ui; pub mod savefile; pub fn load_resources(loader: &mut ResourceLoader)
pub enum State { MainMenuStateID, GameStateID, SlotSelectStateID, OptionsStateID, } pub static NUM_SLOTS : isize = 6; pub fn init_states(state_machine: &mut StateMachine, loader: &ResourceLoader, ctx: &RenderContext, settings: &Settings) { state_machine.add_state(MainMenuStateID as isize, Box::new(main_menu::MainMenu::new(loader, ctx))); state_machine.set_default_state(MainMenuStateID as isize); state_machine.add_state(SlotSelectStateID as isize, Box::new(slot_select_menu::SlotSelectMenu::new(loader, ctx))); state_machine.add_state(GameStateID as isize, Box::new(game_state::GameState::new(loader, ctx, settings))); }
{ let obelix_font = graphics::Font::new_from_file("res/font/AlegreyaSansSC-Light.ttf").unwrap(); loader.add_resource("MenuFont".to_string(), Resource::Font(obelix_font)); }
identifier_body
capture2.rs
//! Input capture using TIM2 #![deny(warnings)] #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; #[macro_use] extern crate cortex_m; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; extern crate nb; use blue_pill::stm32f103xx; use blue_pill::time::Milliseconds; use blue_pill::{Capture, Channel}; use hal::prelude::*; use rtfm::{P0, T0, TMax}; // CONFIGURATION const RESOLUTION: Milliseconds = Milliseconds(1); // RESOURCES peripherals!(stm32f103xx, { AFIO: Peripheral { ceiling: C0, }, GPIOA: Peripheral { ceiling: C0, }, ITM: Peripheral { ceiling: C0, }, RCC: Peripheral { ceiling: C0, }, TIM2: Peripheral { ceiling: C0, }, }); // INITIALIZATION PHASE fn init(ref prio: P0, thr: &TMax) { let afio = &AFIO.access(prio, thr); let gpioa = &GPIOA.access(prio, thr); let rcc = &RCC.access(prio, thr); let tim2 = TIM2.access(prio, thr); let capture = Capture(&*tim2); capture.init(RESOLUTION, afio, gpioa, rcc); } // IDLE LOOP fn idle(ref prio: P0, ref thr: T0) ->! { const CHANNELS: [Channel; 4] = [Channel::_1, Channel::_2, Channel::_3, Channel::_4]; let itm = ITM.access(prio, thr);
let capture = Capture(&*tim2); for c in &CHANNELS { capture.enable(*c); } loop { for c in &CHANNELS { match capture.capture(*c) { Ok(snapshot) => { iprintln!(&itm.stim[0], "{:?}: {:?} ms", c, snapshot); } Err(nb::Error::WouldBlock) => {} Err(nb::Error::Other(e)) => panic!("{:?}", e), } } } } // TASKS tasks!(stm32f103xx, {});
let tim2 = TIM2.access(prio, thr);
random_line_split
capture2.rs
//! Input capture using TIM2 #![deny(warnings)] #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; #[macro_use] extern crate cortex_m; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; extern crate nb; use blue_pill::stm32f103xx; use blue_pill::time::Milliseconds; use blue_pill::{Capture, Channel}; use hal::prelude::*; use rtfm::{P0, T0, TMax}; // CONFIGURATION const RESOLUTION: Milliseconds = Milliseconds(1); // RESOURCES peripherals!(stm32f103xx, { AFIO: Peripheral { ceiling: C0, }, GPIOA: Peripheral { ceiling: C0, }, ITM: Peripheral { ceiling: C0, }, RCC: Peripheral { ceiling: C0, }, TIM2: Peripheral { ceiling: C0, }, }); // INITIALIZATION PHASE fn init(ref prio: P0, thr: &TMax)
// IDLE LOOP fn idle(ref prio: P0, ref thr: T0) ->! { const CHANNELS: [Channel; 4] = [Channel::_1, Channel::_2, Channel::_3, Channel::_4]; let itm = ITM.access(prio, thr); let tim2 = TIM2.access(prio, thr); let capture = Capture(&*tim2); for c in &CHANNELS { capture.enable(*c); } loop { for c in &CHANNELS { match capture.capture(*c) { Ok(snapshot) => { iprintln!(&itm.stim[0], "{:?}: {:?} ms", c, snapshot); } Err(nb::Error::WouldBlock) => {} Err(nb::Error::Other(e)) => panic!("{:?}", e), } } } } // TASKS tasks!(stm32f103xx, {});
{ let afio = &AFIO.access(prio, thr); let gpioa = &GPIOA.access(prio, thr); let rcc = &RCC.access(prio, thr); let tim2 = TIM2.access(prio, thr); let capture = Capture(&*tim2); capture.init(RESOLUTION, afio, gpioa, rcc); }
identifier_body
capture2.rs
//! Input capture using TIM2 #![deny(warnings)] #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; #[macro_use] extern crate cortex_m; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; extern crate nb; use blue_pill::stm32f103xx; use blue_pill::time::Milliseconds; use blue_pill::{Capture, Channel}; use hal::prelude::*; use rtfm::{P0, T0, TMax}; // CONFIGURATION const RESOLUTION: Milliseconds = Milliseconds(1); // RESOURCES peripherals!(stm32f103xx, { AFIO: Peripheral { ceiling: C0, }, GPIOA: Peripheral { ceiling: C0, }, ITM: Peripheral { ceiling: C0, }, RCC: Peripheral { ceiling: C0, }, TIM2: Peripheral { ceiling: C0, }, }); // INITIALIZATION PHASE fn
(ref prio: P0, thr: &TMax) { let afio = &AFIO.access(prio, thr); let gpioa = &GPIOA.access(prio, thr); let rcc = &RCC.access(prio, thr); let tim2 = TIM2.access(prio, thr); let capture = Capture(&*tim2); capture.init(RESOLUTION, afio, gpioa, rcc); } // IDLE LOOP fn idle(ref prio: P0, ref thr: T0) ->! { const CHANNELS: [Channel; 4] = [Channel::_1, Channel::_2, Channel::_3, Channel::_4]; let itm = ITM.access(prio, thr); let tim2 = TIM2.access(prio, thr); let capture = Capture(&*tim2); for c in &CHANNELS { capture.enable(*c); } loop { for c in &CHANNELS { match capture.capture(*c) { Ok(snapshot) => { iprintln!(&itm.stim[0], "{:?}: {:?} ms", c, snapshot); } Err(nb::Error::WouldBlock) => {} Err(nb::Error::Other(e)) => panic!("{:?}", e), } } } } // TASKS tasks!(stm32f103xx, {});
init
identifier_name
capture2.rs
//! Input capture using TIM2 #![deny(warnings)] #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; #[macro_use] extern crate cortex_m; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; extern crate nb; use blue_pill::stm32f103xx; use blue_pill::time::Milliseconds; use blue_pill::{Capture, Channel}; use hal::prelude::*; use rtfm::{P0, T0, TMax}; // CONFIGURATION const RESOLUTION: Milliseconds = Milliseconds(1); // RESOURCES peripherals!(stm32f103xx, { AFIO: Peripheral { ceiling: C0, }, GPIOA: Peripheral { ceiling: C0, }, ITM: Peripheral { ceiling: C0, }, RCC: Peripheral { ceiling: C0, }, TIM2: Peripheral { ceiling: C0, }, }); // INITIALIZATION PHASE fn init(ref prio: P0, thr: &TMax) { let afio = &AFIO.access(prio, thr); let gpioa = &GPIOA.access(prio, thr); let rcc = &RCC.access(prio, thr); let tim2 = TIM2.access(prio, thr); let capture = Capture(&*tim2); capture.init(RESOLUTION, afio, gpioa, rcc); } // IDLE LOOP fn idle(ref prio: P0, ref thr: T0) ->! { const CHANNELS: [Channel; 4] = [Channel::_1, Channel::_2, Channel::_3, Channel::_4]; let itm = ITM.access(prio, thr); let tim2 = TIM2.access(prio, thr); let capture = Capture(&*tim2); for c in &CHANNELS { capture.enable(*c); } loop { for c in &CHANNELS { match capture.capture(*c) { Ok(snapshot) =>
Err(nb::Error::WouldBlock) => {} Err(nb::Error::Other(e)) => panic!("{:?}", e), } } } } // TASKS tasks!(stm32f103xx, {});
{ iprintln!(&itm.stim[0], "{:?}: {:?} ms", c, snapshot); }
conditional_block
schema.rs
diesel::table! { comments (id) { id -> Int4,
body -> Text, created_at -> Timestamp, updated_at -> Timestamp, } } diesel::table! { posts (id) { id -> Int4, user_id -> Int4, title -> Text, body -> Text, created_at -> Timestamp, updated_at -> Timestamp, published_at -> Nullable<Timestamp>, } } diesel::table! { users (id) { id -> Int4, username -> Text, hashed_password -> Text, created_at -> Timestamp, updated_at -> Timestamp, } } diesel::joinable!(comments -> posts (post_id)); diesel::joinable!(comments -> users (user_id)); diesel::joinable!(posts -> users (user_id)); diesel::allow_tables_to_appear_in_same_query!(comments, posts, users,);
user_id -> Int4, post_id -> Int4,
random_line_split
flush.rs
use crate::io::AsyncWrite; use pin_project_lite::pin_project; use std::future::Future; use std::io; use std::marker::PhantomPinned; use std::pin::Pin; use std::task::{Context, Poll}; pin_project! { /// A future used to fully flush an I/O object. /// /// Created by the [`AsyncWriteExt::flush`][flush] function. /// [flush]: crate::io::AsyncWriteExt::flush #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Flush<'a, A:?Sized> { a: &'a mut A, // Make this future `!Unpin` for compatibility with async trait methods. #[pin] _pin: PhantomPinned, } } /// Creates a future which will entirely flush an I/O object. pub(super) fn flush<A>(a: &mut A) -> Flush<'_, A> where A: AsyncWrite + Unpin +?Sized, { Flush { a, _pin: PhantomPinned, } } impl<A> Future for Flush<'_, A> where A: AsyncWrite + Unpin +?Sized, { type Output = io::Result<()>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>
}
{ let me = self.project(); Pin::new(&mut *me.a).poll_flush(cx) }
identifier_body
flush.rs
use crate::io::AsyncWrite; use pin_project_lite::pin_project; use std::future::Future; use std::io; use std::marker::PhantomPinned; use std::pin::Pin; use std::task::{Context, Poll}; pin_project! { /// A future used to fully flush an I/O object. /// /// Created by the [`AsyncWriteExt::flush`][flush] function. /// [flush]: crate::io::AsyncWriteExt::flush #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Flush<'a, A:?Sized> { a: &'a mut A, // Make this future `!Unpin` for compatibility with async trait methods. #[pin] _pin: PhantomPinned, } } /// Creates a future which will entirely flush an I/O object. pub(super) fn flush<A>(a: &mut A) -> Flush<'_, A> where A: AsyncWrite + Unpin +?Sized, { Flush { a, _pin: PhantomPinned, } }
A: AsyncWrite + Unpin +?Sized, { type Output = io::Result<()>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let me = self.project(); Pin::new(&mut *me.a).poll_flush(cx) } }
impl<A> Future for Flush<'_, A> where
random_line_split
flush.rs
use crate::io::AsyncWrite; use pin_project_lite::pin_project; use std::future::Future; use std::io; use std::marker::PhantomPinned; use std::pin::Pin; use std::task::{Context, Poll}; pin_project! { /// A future used to fully flush an I/O object. /// /// Created by the [`AsyncWriteExt::flush`][flush] function. /// [flush]: crate::io::AsyncWriteExt::flush #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Flush<'a, A:?Sized> { a: &'a mut A, // Make this future `!Unpin` for compatibility with async trait methods. #[pin] _pin: PhantomPinned, } } /// Creates a future which will entirely flush an I/O object. pub(super) fn
<A>(a: &mut A) -> Flush<'_, A> where A: AsyncWrite + Unpin +?Sized, { Flush { a, _pin: PhantomPinned, } } impl<A> Future for Flush<'_, A> where A: AsyncWrite + Unpin +?Sized, { type Output = io::Result<()>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let me = self.project(); Pin::new(&mut *me.a).poll_flush(cx) } }
flush
identifier_name
exactly_one_err.rs
#[cfg(feature = "use_std")] use std::error::Error; use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::iter::ExactSizeIterator; use either::Either; use crate::size_hint;
/// effectively "restores" the state of the input iterator when it's handed back. /// /// This is very similar to PutBackN except this iterator only supports 0-2 elements and does not /// use a `Vec`. #[derive(Clone)] pub struct ExactlyOneError<I> where I: Iterator, { first_two: Option<Either<[I::Item; 2], I::Item>>, inner: I, } impl<I> ExactlyOneError<I> where I: Iterator, { /// Creates a new `ExactlyOneErr` iterator. pub(crate) fn new(first_two: Option<Either<[I::Item; 2], I::Item>>, inner: I) -> Self { Self { first_two, inner } } fn additional_len(&self) -> usize { match self.first_two { Some(Either::Left(_)) => 2, Some(Either::Right(_)) => 1, None => 0, } } } impl<I> Iterator for ExactlyOneError<I> where I: Iterator, { type Item = I::Item; fn next(&mut self) -> Option<Self::Item> { match self.first_two.take() { Some(Either::Left([first, second])) => { self.first_two = Some(Either::Right(second)); Some(first) }, Some(Either::Right(second)) => { Some(second) } None => { self.inner.next() } } } fn size_hint(&self) -> (usize, Option<usize>) { size_hint::add_scalar(self.inner.size_hint(), self.additional_len()) } } impl<I> ExactSizeIterator for ExactlyOneError<I> where I: ExactSizeIterator {} impl<I> Display for ExactlyOneError<I> where I: Iterator, { fn fmt(&self, f: &mut Formatter) -> FmtResult { let additional = self.additional_len(); if additional > 0 { write!(f, "got at least 2 elements when exactly one was expected") } else { write!(f, "got zero elements when exactly one was expected") } } } impl<I> Debug for ExactlyOneError<I> where I: Iterator + Debug, I::Item: Debug, { fn fmt(&self, f: &mut Formatter) -> FmtResult { match &self.first_two { Some(Either::Left([first, second])) => { write!(f, "ExactlyOneError[First: {:?}, Second: {:?}, RemainingIter: {:?}]", first, second, self.inner) }, Some(Either::Right(second)) => { write!(f, "ExactlyOneError[Second: {:?}, RemainingIter: {:?}]", second, self.inner) } None => { write!(f, "ExactlyOneError[RemainingIter: {:?}]", self.inner) } } } } #[cfg(feature = "use_std")] impl<I> Error for ExactlyOneError<I> where I: Iterator + Debug, I::Item: Debug, {}
/// Iterator returned for the error case of `IterTools::exactly_one()` /// This iterator yields exactly the same elements as the input iterator. /// /// During the execution of exactly_one the iterator must be mutated. This wrapper
random_line_split
exactly_one_err.rs
#[cfg(feature = "use_std")] use std::error::Error; use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::iter::ExactSizeIterator; use either::Either; use crate::size_hint; /// Iterator returned for the error case of `IterTools::exactly_one()` /// This iterator yields exactly the same elements as the input iterator. /// /// During the execution of exactly_one the iterator must be mutated. This wrapper /// effectively "restores" the state of the input iterator when it's handed back. /// /// This is very similar to PutBackN except this iterator only supports 0-2 elements and does not /// use a `Vec`. #[derive(Clone)] pub struct ExactlyOneError<I> where I: Iterator, { first_two: Option<Either<[I::Item; 2], I::Item>>, inner: I, } impl<I> ExactlyOneError<I> where I: Iterator, { /// Creates a new `ExactlyOneErr` iterator. pub(crate) fn new(first_two: Option<Either<[I::Item; 2], I::Item>>, inner: I) -> Self { Self { first_two, inner } } fn additional_len(&self) -> usize { match self.first_two { Some(Either::Left(_)) => 2, Some(Either::Right(_)) => 1, None => 0, } } } impl<I> Iterator for ExactlyOneError<I> where I: Iterator, { type Item = I::Item; fn next(&mut self) -> Option<Self::Item> { match self.first_two.take() { Some(Either::Left([first, second])) => { self.first_two = Some(Either::Right(second)); Some(first) }, Some(Either::Right(second)) => { Some(second) } None => { self.inner.next() } } } fn size_hint(&self) -> (usize, Option<usize>) { size_hint::add_scalar(self.inner.size_hint(), self.additional_len()) } } impl<I> ExactSizeIterator for ExactlyOneError<I> where I: ExactSizeIterator {} impl<I> Display for ExactlyOneError<I> where I: Iterator, { fn fmt(&self, f: &mut Formatter) -> FmtResult { let additional = self.additional_len(); if additional > 0 { write!(f, "got at least 2 elements when exactly one was expected") } else { write!(f, "got zero elements when exactly one was expected") } } } impl<I> Debug for ExactlyOneError<I> where I: Iterator + Debug, I::Item: Debug, { fn fmt(&self, f: &mut Formatter) -> FmtResult { match &self.first_two { Some(Either::Left([first, second])) =>
, Some(Either::Right(second)) => { write!(f, "ExactlyOneError[Second: {:?}, RemainingIter: {:?}]", second, self.inner) } None => { write!(f, "ExactlyOneError[RemainingIter: {:?}]", self.inner) } } } } #[cfg(feature = "use_std")] impl<I> Error for ExactlyOneError<I> where I: Iterator + Debug, I::Item: Debug, {}
{ write!(f, "ExactlyOneError[First: {:?}, Second: {:?}, RemainingIter: {:?}]", first, second, self.inner) }
conditional_block
exactly_one_err.rs
#[cfg(feature = "use_std")] use std::error::Error; use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::iter::ExactSizeIterator; use either::Either; use crate::size_hint; /// Iterator returned for the error case of `IterTools::exactly_one()` /// This iterator yields exactly the same elements as the input iterator. /// /// During the execution of exactly_one the iterator must be mutated. This wrapper /// effectively "restores" the state of the input iterator when it's handed back. /// /// This is very similar to PutBackN except this iterator only supports 0-2 elements and does not /// use a `Vec`. #[derive(Clone)] pub struct ExactlyOneError<I> where I: Iterator, { first_two: Option<Either<[I::Item; 2], I::Item>>, inner: I, } impl<I> ExactlyOneError<I> where I: Iterator, { /// Creates a new `ExactlyOneErr` iterator. pub(crate) fn new(first_two: Option<Either<[I::Item; 2], I::Item>>, inner: I) -> Self { Self { first_two, inner } } fn additional_len(&self) -> usize { match self.first_two { Some(Either::Left(_)) => 2, Some(Either::Right(_)) => 1, None => 0, } } } impl<I> Iterator for ExactlyOneError<I> where I: Iterator, { type Item = I::Item; fn next(&mut self) -> Option<Self::Item> { match self.first_two.take() { Some(Either::Left([first, second])) => { self.first_two = Some(Either::Right(second)); Some(first) }, Some(Either::Right(second)) => { Some(second) } None => { self.inner.next() } } } fn size_hint(&self) -> (usize, Option<usize>)
} impl<I> ExactSizeIterator for ExactlyOneError<I> where I: ExactSizeIterator {} impl<I> Display for ExactlyOneError<I> where I: Iterator, { fn fmt(&self, f: &mut Formatter) -> FmtResult { let additional = self.additional_len(); if additional > 0 { write!(f, "got at least 2 elements when exactly one was expected") } else { write!(f, "got zero elements when exactly one was expected") } } } impl<I> Debug for ExactlyOneError<I> where I: Iterator + Debug, I::Item: Debug, { fn fmt(&self, f: &mut Formatter) -> FmtResult { match &self.first_two { Some(Either::Left([first, second])) => { write!(f, "ExactlyOneError[First: {:?}, Second: {:?}, RemainingIter: {:?}]", first, second, self.inner) }, Some(Either::Right(second)) => { write!(f, "ExactlyOneError[Second: {:?}, RemainingIter: {:?}]", second, self.inner) } None => { write!(f, "ExactlyOneError[RemainingIter: {:?}]", self.inner) } } } } #[cfg(feature = "use_std")] impl<I> Error for ExactlyOneError<I> where I: Iterator + Debug, I::Item: Debug, {}
{ size_hint::add_scalar(self.inner.size_hint(), self.additional_len()) }
identifier_body
exactly_one_err.rs
#[cfg(feature = "use_std")] use std::error::Error; use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::iter::ExactSizeIterator; use either::Either; use crate::size_hint; /// Iterator returned for the error case of `IterTools::exactly_one()` /// This iterator yields exactly the same elements as the input iterator. /// /// During the execution of exactly_one the iterator must be mutated. This wrapper /// effectively "restores" the state of the input iterator when it's handed back. /// /// This is very similar to PutBackN except this iterator only supports 0-2 elements and does not /// use a `Vec`. #[derive(Clone)] pub struct ExactlyOneError<I> where I: Iterator, { first_two: Option<Either<[I::Item; 2], I::Item>>, inner: I, } impl<I> ExactlyOneError<I> where I: Iterator, { /// Creates a new `ExactlyOneErr` iterator. pub(crate) fn new(first_two: Option<Either<[I::Item; 2], I::Item>>, inner: I) -> Self { Self { first_two, inner } } fn additional_len(&self) -> usize { match self.first_two { Some(Either::Left(_)) => 2, Some(Either::Right(_)) => 1, None => 0, } } } impl<I> Iterator for ExactlyOneError<I> where I: Iterator, { type Item = I::Item; fn next(&mut self) -> Option<Self::Item> { match self.first_two.take() { Some(Either::Left([first, second])) => { self.first_two = Some(Either::Right(second)); Some(first) }, Some(Either::Right(second)) => { Some(second) } None => { self.inner.next() } } } fn
(&self) -> (usize, Option<usize>) { size_hint::add_scalar(self.inner.size_hint(), self.additional_len()) } } impl<I> ExactSizeIterator for ExactlyOneError<I> where I: ExactSizeIterator {} impl<I> Display for ExactlyOneError<I> where I: Iterator, { fn fmt(&self, f: &mut Formatter) -> FmtResult { let additional = self.additional_len(); if additional > 0 { write!(f, "got at least 2 elements when exactly one was expected") } else { write!(f, "got zero elements when exactly one was expected") } } } impl<I> Debug for ExactlyOneError<I> where I: Iterator + Debug, I::Item: Debug, { fn fmt(&self, f: &mut Formatter) -> FmtResult { match &self.first_two { Some(Either::Left([first, second])) => { write!(f, "ExactlyOneError[First: {:?}, Second: {:?}, RemainingIter: {:?}]", first, second, self.inner) }, Some(Either::Right(second)) => { write!(f, "ExactlyOneError[Second: {:?}, RemainingIter: {:?}]", second, self.inner) } None => { write!(f, "ExactlyOneError[RemainingIter: {:?}]", self.inner) } } } } #[cfg(feature = "use_std")] impl<I> Error for ExactlyOneError<I> where I: Iterator + Debug, I::Item: Debug, {}
size_hint
identifier_name
text_run.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; use font::{Font, FontHandleMethods, FontMetrics, IS_WHITESPACE_SHAPING_FLAG, RunMetrics}; use font::{ShapingOptions}; use platform::font_template::FontTemplateData; use std::cell::Cell; use std::cmp::{Ordering, max}; use std::slice::Iter; use std::sync::Arc; use text::glyph::{CharIndex, GlyphStore}; use util::range::Range; use util::vec::{Comparator, FullBinarySearchMethods}; thread_local! { static INDEX_OF_FIRST_GLYPH_RUN_CACHE: Cell<Option<(*const TextRun, CharIndex, usize)>> = Cell::new(None) } /// A single "paragraph" of text in one font size and style. #[derive(Clone, Deserialize, Serialize)] pub struct TextRun { /// The UTF-8 string represented by this text run. pub text: Arc<String>, pub font_template: Arc<FontTemplateData>, pub actual_pt_size: Au, pub font_metrics: FontMetrics, /// The glyph runs that make up this text run. pub glyphs: Arc<Vec<GlyphRun>>, pub bidi_level: u8, } impl Drop for TextRun { fn drop(&mut self) { // Invalidate the glyph run cache if it was our text run that got freed. INDEX_OF_FIRST_GLYPH_RUN_CACHE.with(|index_of_first_glyph_run_cache| { if let Some((text_run_ptr, _, _)) = index_of_first_glyph_run_cache.get() { if text_run_ptr == (self as *const TextRun) { index_of_first_glyph_run_cache.set(None); } } }) } } /// A single series of glyphs within a text run. #[derive(Clone, Deserialize, Serialize)] pub struct GlyphRun { /// The glyphs. pub glyph_store: Arc<GlyphStore>, /// The range of characters in the containing run. pub range: Range<CharIndex>, } pub struct NaturalWordSliceIterator<'a> { glyphs: &'a [GlyphRun], index: usize, range: Range<CharIndex>, reverse: bool, } struct
; impl Comparator<CharIndex, GlyphRun> for CharIndexComparator { fn compare(&self, key: &CharIndex, value: &GlyphRun) -> Ordering { if *key < value.range.begin() { Ordering::Less } else if *key >= value.range.end() { Ordering::Greater } else { Ordering::Equal } } } /// A "slice" of a text run is a series of contiguous glyphs that all belong to the same glyph /// store. Line breaking strategies yield these. pub struct TextRunSlice<'a> { /// The glyph store that the glyphs in this slice belong to. pub glyphs: &'a GlyphStore, /// The character index that this slice begins at, relative to the start of the *text run*. pub offset: CharIndex, /// The range that these glyphs encompass, relative to the start of the *glyph store*. pub range: Range<CharIndex>, } impl<'a> TextRunSlice<'a> { /// Returns the range that these glyphs encompass, relative to the start of the *text run*. #[inline] pub fn text_run_range(&self) -> Range<CharIndex> { let mut range = self.range; range.shift_by(self.offset); range } } impl<'a> Iterator for NaturalWordSliceIterator<'a> { type Item = TextRunSlice<'a>; // inline(always) due to the inefficient rt failures messing up inline heuristics, I think. #[inline(always)] fn next(&mut self) -> Option<TextRunSlice<'a>> { let slice_glyphs; if self.reverse { if self.index == 0 { return None; } self.index -= 1; slice_glyphs = &self.glyphs[self.index]; } else { if self.index >= self.glyphs.len() { return None; } slice_glyphs = &self.glyphs[self.index]; self.index += 1; } let mut char_range = self.range.intersect(&slice_glyphs.range); let slice_range_begin = slice_glyphs.range.begin(); char_range.shift_by(-slice_range_begin); if!char_range.is_empty() { Some(TextRunSlice { glyphs: &*slice_glyphs.glyph_store, offset: slice_range_begin, range: char_range, }) } else { None } } } pub struct CharacterSliceIterator<'a> { glyph_run: Option<&'a GlyphRun>, glyph_run_iter: Iter<'a, GlyphRun>, range: Range<CharIndex>, } impl<'a> Iterator for CharacterSliceIterator<'a> { type Item = TextRunSlice<'a>; // inline(always) due to the inefficient rt failures messing up inline heuristics, I think. #[inline(always)] fn next(&mut self) -> Option<TextRunSlice<'a>> { let glyph_run = match self.glyph_run { None => return None, Some(glyph_run) => glyph_run, }; debug_assert!(!self.range.is_empty()); let index_to_return = self.range.begin(); self.range.adjust_by(CharIndex(1), CharIndex(-1)); if self.range.is_empty() { // We're done. self.glyph_run = None } else if self.range.intersect(&glyph_run.range).is_empty() { // Move on to the next glyph run. self.glyph_run = self.glyph_run_iter.next(); } let index_within_glyph_run = index_to_return - glyph_run.range.begin(); Some(TextRunSlice { glyphs: &*glyph_run.glyph_store, offset: glyph_run.range.begin(), range: Range::new(index_within_glyph_run, CharIndex(1)), }) } } impl<'a> TextRun { pub fn new(font: &mut Font, text: String, options: &ShapingOptions, bidi_level: u8) -> TextRun { let glyphs = TextRun::break_and_shape(font, &text, options); TextRun { text: Arc::new(text), font_metrics: font.metrics.clone(), font_template: font.handle.template(), actual_pt_size: font.actual_pt_size, glyphs: Arc::new(glyphs), bidi_level: bidi_level, } } pub fn break_and_shape(font: &mut Font, text: &str, options: &ShapingOptions) -> Vec<GlyphRun> { // TODO(Issue #230): do a better job. See Gecko's LineBreaker. let mut glyphs = vec!(); let (mut byte_i, mut char_i) = (0, CharIndex(0)); let mut cur_slice_is_whitespace = false; let (mut byte_last_boundary, mut char_last_boundary) = (0, CharIndex(0)); while byte_i < text.len() { let range = text.char_range_at(byte_i); let ch = range.ch; let next = range.next; // Slices alternate between whitespace and non-whitespace, // representing line break opportunities. let can_break_before = if cur_slice_is_whitespace { match ch { '' | '\t' | '\n' => false, _ => { cur_slice_is_whitespace = false; true } } } else { match ch { '' | '\t' | '\n' => { cur_slice_is_whitespace = true; true }, _ => false } }; // Create a glyph store for this slice if it's nonempty. if can_break_before && byte_i > byte_last_boundary { let slice = &text[byte_last_boundary.. byte_i]; debug!("creating glyph store for slice {} (ws? {}), {} - {} in run {}", slice,!cur_slice_is_whitespace, byte_last_boundary, byte_i, text); let mut options = *options; if!cur_slice_is_whitespace { options.flags.insert(IS_WHITESPACE_SHAPING_FLAG); } glyphs.push(GlyphRun { glyph_store: font.shape_text(slice, &options), range: Range::new(char_last_boundary, char_i - char_last_boundary), }); byte_last_boundary = byte_i; char_last_boundary = char_i; } byte_i = next; char_i = char_i + CharIndex(1); } // Create a glyph store for the final slice if it's nonempty. if byte_i > byte_last_boundary { let slice = &text[byte_last_boundary..]; debug!("creating glyph store for final slice {} (ws? {}), {} - {} in run {}", slice, cur_slice_is_whitespace, byte_last_boundary, text.len(), text); let mut options = *options; if cur_slice_is_whitespace { options.flags.insert(IS_WHITESPACE_SHAPING_FLAG); } glyphs.push(GlyphRun { glyph_store: font.shape_text(slice, &options), range: Range::new(char_last_boundary, char_i - char_last_boundary), }); } glyphs } pub fn ascent(&self) -> Au { self.font_metrics.ascent } pub fn descent(&self) -> Au { self.font_metrics.descent } pub fn advance_for_range(&self, range: &Range<CharIndex>) -> Au { if range.is_empty() { return Au(0) } // TODO(Issue #199): alter advance direction for RTL // TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text self.natural_word_slices_in_range(range) .fold(Au(0), |advance, slice| { advance + slice.glyphs.advance_for_char_range(&slice.range) }) } pub fn metrics_for_range(&self, range: &Range<CharIndex>) -> RunMetrics { RunMetrics::new(self.advance_for_range(range), self.font_metrics.ascent, self.font_metrics.descent) } pub fn metrics_for_slice(&self, glyphs: &GlyphStore, slice_range: &Range<CharIndex>) -> RunMetrics { RunMetrics::new(glyphs.advance_for_char_range(slice_range), self.font_metrics.ascent, self.font_metrics.descent) } pub fn min_width_for_range(&self, range: &Range<CharIndex>) -> Au { debug!("iterating outer range {:?}", range); self.natural_word_slices_in_range(range).fold(Au(0), |max_piece_width, slice| { debug!("iterated on {:?}[{:?}]", slice.offset, slice.range); max(max_piece_width, self.advance_for_range(&slice.range)) }) } /// Returns the index of the first glyph run containing the given character index. fn index_of_first_glyph_run_containing(&self, index: CharIndex) -> Option<usize> { let self_ptr = self as *const TextRun; INDEX_OF_FIRST_GLYPH_RUN_CACHE.with(|index_of_first_glyph_run_cache| { if let Some((last_text_run, last_index, last_result)) = index_of_first_glyph_run_cache.get() { if last_text_run == self_ptr && last_index == index { return Some(last_result) } } let result = (&**self.glyphs).binary_search_index_by(&index, CharIndexComparator); if let Some(result) = result { index_of_first_glyph_run_cache.set(Some((self_ptr, index, result))); } result }) } /// Returns an iterator that will iterate over all slices of glyphs that represent natural /// words in the given range. pub fn natural_word_slices_in_range(&'a self, range: &Range<CharIndex>) -> NaturalWordSliceIterator<'a> { let index = match self.index_of_first_glyph_run_containing(range.begin()) { None => self.glyphs.len(), Some(index) => index, }; NaturalWordSliceIterator { glyphs: &self.glyphs[..], index: index, range: *range, reverse: false, } } /// Returns an iterator that over natural word slices in visual order (left to right or /// right to left, depending on the bidirectional embedding level). pub fn natural_word_slices_in_visual_order(&'a self, range: &Range<CharIndex>) -> NaturalWordSliceIterator<'a> { // Iterate in reverse order if bidi level is RTL. let reverse = self.bidi_level % 2 == 1; let index = if reverse { match self.index_of_first_glyph_run_containing(range.end() - CharIndex(1)) { Some(i) => i + 1, // In reverse mode, index points one past the next element. None => 0 } } else { match self.index_of_first_glyph_run_containing(range.begin()) { Some(i) => i, None => self.glyphs.len() } }; NaturalWordSliceIterator { glyphs: &self.glyphs[..], index: index, range: *range, reverse: reverse, } } /// Returns an iterator that will iterate over all slices of glyphs that represent individual /// characters in the given range. pub fn character_slices_in_range(&'a self, range: &Range<CharIndex>) -> CharacterSliceIterator<'a> { let index = match self.index_of_first_glyph_run_containing(range.begin()) { None => self.glyphs.len(), Some(index) => index, }; let mut glyph_run_iter = self.glyphs[index..].iter(); let first_glyph_run = glyph_run_iter.next(); CharacterSliceIterator { glyph_run: first_glyph_run, glyph_run_iter: glyph_run_iter, range: *range, } } }
CharIndexComparator
identifier_name
text_run.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; use font::{Font, FontHandleMethods, FontMetrics, IS_WHITESPACE_SHAPING_FLAG, RunMetrics}; use font::{ShapingOptions}; use platform::font_template::FontTemplateData; use std::cell::Cell; use std::cmp::{Ordering, max}; use std::slice::Iter; use std::sync::Arc; use text::glyph::{CharIndex, GlyphStore}; use util::range::Range; use util::vec::{Comparator, FullBinarySearchMethods}; thread_local! { static INDEX_OF_FIRST_GLYPH_RUN_CACHE: Cell<Option<(*const TextRun, CharIndex, usize)>> = Cell::new(None) } /// A single "paragraph" of text in one font size and style. #[derive(Clone, Deserialize, Serialize)] pub struct TextRun { /// The UTF-8 string represented by this text run. pub text: Arc<String>, pub font_template: Arc<FontTemplateData>, pub actual_pt_size: Au, pub font_metrics: FontMetrics, /// The glyph runs that make up this text run. pub glyphs: Arc<Vec<GlyphRun>>, pub bidi_level: u8, } impl Drop for TextRun { fn drop(&mut self) { // Invalidate the glyph run cache if it was our text run that got freed. INDEX_OF_FIRST_GLYPH_RUN_CACHE.with(|index_of_first_glyph_run_cache| { if let Some((text_run_ptr, _, _)) = index_of_first_glyph_run_cache.get() { if text_run_ptr == (self as *const TextRun) { index_of_first_glyph_run_cache.set(None); } } }) } } /// A single series of glyphs within a text run. #[derive(Clone, Deserialize, Serialize)] pub struct GlyphRun { /// The glyphs. pub glyph_store: Arc<GlyphStore>, /// The range of characters in the containing run. pub range: Range<CharIndex>, } pub struct NaturalWordSliceIterator<'a> { glyphs: &'a [GlyphRun], index: usize, range: Range<CharIndex>, reverse: bool, } struct CharIndexComparator; impl Comparator<CharIndex, GlyphRun> for CharIndexComparator { fn compare(&self, key: &CharIndex, value: &GlyphRun) -> Ordering { if *key < value.range.begin() { Ordering::Less } else if *key >= value.range.end() { Ordering::Greater } else { Ordering::Equal } } } /// A "slice" of a text run is a series of contiguous glyphs that all belong to the same glyph /// store. Line breaking strategies yield these. pub struct TextRunSlice<'a> { /// The glyph store that the glyphs in this slice belong to. pub glyphs: &'a GlyphStore, /// The character index that this slice begins at, relative to the start of the *text run*. pub offset: CharIndex, /// The range that these glyphs encompass, relative to the start of the *glyph store*. pub range: Range<CharIndex>, } impl<'a> TextRunSlice<'a> { /// Returns the range that these glyphs encompass, relative to the start of the *text run*. #[inline] pub fn text_run_range(&self) -> Range<CharIndex> { let mut range = self.range; range.shift_by(self.offset); range } } impl<'a> Iterator for NaturalWordSliceIterator<'a> { type Item = TextRunSlice<'a>; // inline(always) due to the inefficient rt failures messing up inline heuristics, I think. #[inline(always)] fn next(&mut self) -> Option<TextRunSlice<'a>> { let slice_glyphs; if self.reverse { if self.index == 0 { return None; } self.index -= 1; slice_glyphs = &self.glyphs[self.index]; } else { if self.index >= self.glyphs.len() { return None; } slice_glyphs = &self.glyphs[self.index]; self.index += 1; } let mut char_range = self.range.intersect(&slice_glyphs.range); let slice_range_begin = slice_glyphs.range.begin(); char_range.shift_by(-slice_range_begin); if!char_range.is_empty() { Some(TextRunSlice { glyphs: &*slice_glyphs.glyph_store, offset: slice_range_begin, range: char_range, }) } else { None } } } pub struct CharacterSliceIterator<'a> { glyph_run: Option<&'a GlyphRun>, glyph_run_iter: Iter<'a, GlyphRun>, range: Range<CharIndex>, } impl<'a> Iterator for CharacterSliceIterator<'a> { type Item = TextRunSlice<'a>; // inline(always) due to the inefficient rt failures messing up inline heuristics, I think. #[inline(always)] fn next(&mut self) -> Option<TextRunSlice<'a>> { let glyph_run = match self.glyph_run { None => return None, Some(glyph_run) => glyph_run, }; debug_assert!(!self.range.is_empty()); let index_to_return = self.range.begin(); self.range.adjust_by(CharIndex(1), CharIndex(-1)); if self.range.is_empty() { // We're done. self.glyph_run = None } else if self.range.intersect(&glyph_run.range).is_empty() { // Move on to the next glyph run. self.glyph_run = self.glyph_run_iter.next(); } let index_within_glyph_run = index_to_return - glyph_run.range.begin(); Some(TextRunSlice { glyphs: &*glyph_run.glyph_store, offset: glyph_run.range.begin(), range: Range::new(index_within_glyph_run, CharIndex(1)), }) } } impl<'a> TextRun { pub fn new(font: &mut Font, text: String, options: &ShapingOptions, bidi_level: u8) -> TextRun { let glyphs = TextRun::break_and_shape(font, &text, options); TextRun { text: Arc::new(text), font_metrics: font.metrics.clone(), font_template: font.handle.template(), actual_pt_size: font.actual_pt_size, glyphs: Arc::new(glyphs), bidi_level: bidi_level, } } pub fn break_and_shape(font: &mut Font, text: &str, options: &ShapingOptions) -> Vec<GlyphRun> { // TODO(Issue #230): do a better job. See Gecko's LineBreaker. let mut glyphs = vec!(); let (mut byte_i, mut char_i) = (0, CharIndex(0)); let mut cur_slice_is_whitespace = false; let (mut byte_last_boundary, mut char_last_boundary) = (0, CharIndex(0)); while byte_i < text.len() { let range = text.char_range_at(byte_i); let ch = range.ch; let next = range.next; // Slices alternate between whitespace and non-whitespace, // representing line break opportunities. let can_break_before = if cur_slice_is_whitespace { match ch { '' | '\t' | '\n' => false, _ => { cur_slice_is_whitespace = false; true } } } else { match ch { '' | '\t' | '\n' => { cur_slice_is_whitespace = true; true }, _ => false } }; // Create a glyph store for this slice if it's nonempty. if can_break_before && byte_i > byte_last_boundary { let slice = &text[byte_last_boundary.. byte_i]; debug!("creating glyph store for slice {} (ws? {}), {} - {} in run {}", slice,!cur_slice_is_whitespace, byte_last_boundary, byte_i, text); let mut options = *options; if!cur_slice_is_whitespace { options.flags.insert(IS_WHITESPACE_SHAPING_FLAG); } glyphs.push(GlyphRun { glyph_store: font.shape_text(slice, &options), range: Range::new(char_last_boundary, char_i - char_last_boundary), }); byte_last_boundary = byte_i; char_last_boundary = char_i; } byte_i = next; char_i = char_i + CharIndex(1); } // Create a glyph store for the final slice if it's nonempty. if byte_i > byte_last_boundary { let slice = &text[byte_last_boundary..]; debug!("creating glyph store for final slice {} (ws? {}), {} - {} in run {}", slice, cur_slice_is_whitespace, byte_last_boundary, text.len(), text); let mut options = *options; if cur_slice_is_whitespace { options.flags.insert(IS_WHITESPACE_SHAPING_FLAG); } glyphs.push(GlyphRun { glyph_store: font.shape_text(slice, &options), range: Range::new(char_last_boundary, char_i - char_last_boundary), }); } glyphs } pub fn ascent(&self) -> Au { self.font_metrics.ascent } pub fn descent(&self) -> Au { self.font_metrics.descent } pub fn advance_for_range(&self, range: &Range<CharIndex>) -> Au { if range.is_empty() { return Au(0) } // TODO(Issue #199): alter advance direction for RTL // TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text self.natural_word_slices_in_range(range) .fold(Au(0), |advance, slice| { advance + slice.glyphs.advance_for_char_range(&slice.range) }) } pub fn metrics_for_range(&self, range: &Range<CharIndex>) -> RunMetrics { RunMetrics::new(self.advance_for_range(range), self.font_metrics.ascent, self.font_metrics.descent) } pub fn metrics_for_slice(&self, glyphs: &GlyphStore, slice_range: &Range<CharIndex>) -> RunMetrics { RunMetrics::new(glyphs.advance_for_char_range(slice_range), self.font_metrics.ascent, self.font_metrics.descent) } pub fn min_width_for_range(&self, range: &Range<CharIndex>) -> Au { debug!("iterating outer range {:?}", range); self.natural_word_slices_in_range(range).fold(Au(0), |max_piece_width, slice| { debug!("iterated on {:?}[{:?}]", slice.offset, slice.range); max(max_piece_width, self.advance_for_range(&slice.range)) }) } /// Returns the index of the first glyph run containing the given character index. fn index_of_first_glyph_run_containing(&self, index: CharIndex) -> Option<usize> { let self_ptr = self as *const TextRun; INDEX_OF_FIRST_GLYPH_RUN_CACHE.with(|index_of_first_glyph_run_cache| { if let Some((last_text_run, last_index, last_result)) = index_of_first_glyph_run_cache.get() { if last_text_run == self_ptr && last_index == index { return Some(last_result) } } let result = (&**self.glyphs).binary_search_index_by(&index, CharIndexComparator); if let Some(result) = result { index_of_first_glyph_run_cache.set(Some((self_ptr, index, result))); } result }) } /// Returns an iterator that will iterate over all slices of glyphs that represent natural /// words in the given range. pub fn natural_word_slices_in_range(&'a self, range: &Range<CharIndex>) -> NaturalWordSliceIterator<'a> { let index = match self.index_of_first_glyph_run_containing(range.begin()) { None => self.glyphs.len(), Some(index) => index, }; NaturalWordSliceIterator { glyphs: &self.glyphs[..], index: index, range: *range, reverse: false, }
/// right to left, depending on the bidirectional embedding level). pub fn natural_word_slices_in_visual_order(&'a self, range: &Range<CharIndex>) -> NaturalWordSliceIterator<'a> { // Iterate in reverse order if bidi level is RTL. let reverse = self.bidi_level % 2 == 1; let index = if reverse { match self.index_of_first_glyph_run_containing(range.end() - CharIndex(1)) { Some(i) => i + 1, // In reverse mode, index points one past the next element. None => 0 } } else { match self.index_of_first_glyph_run_containing(range.begin()) { Some(i) => i, None => self.glyphs.len() } }; NaturalWordSliceIterator { glyphs: &self.glyphs[..], index: index, range: *range, reverse: reverse, } } /// Returns an iterator that will iterate over all slices of glyphs that represent individual /// characters in the given range. pub fn character_slices_in_range(&'a self, range: &Range<CharIndex>) -> CharacterSliceIterator<'a> { let index = match self.index_of_first_glyph_run_containing(range.begin()) { None => self.glyphs.len(), Some(index) => index, }; let mut glyph_run_iter = self.glyphs[index..].iter(); let first_glyph_run = glyph_run_iter.next(); CharacterSliceIterator { glyph_run: first_glyph_run, glyph_run_iter: glyph_run_iter, range: *range, } } }
} /// Returns an iterator that over natural word slices in visual order (left to right or
random_line_split
match-vec-unreachable.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(slice_patterns)] #![deny(unreachable_patterns)] fn
() { let x: Vec<(isize, isize)> = Vec::new(); let x: &[(isize, isize)] = &x; match *x { [a, (2, 3), _] => (), [(1, 2), (2, 3), b] => (), //~ ERROR unreachable pattern _ => () } let x: Vec<String> = vec!["foo".to_string(), "bar".to_string(), "baz".to_string()]; let x: &[String] = &x; match *x { [ref a, _, _,..] => { println!("{}", a); } [_, _, _, _, _] => { } //~ ERROR unreachable pattern _ => { } } let x: Vec<char> = vec!['a', 'b', 'c']; let x: &[char] = &x; match *x { ['a', 'b', 'c', ref _tail..] => {} ['a', 'b', 'c'] => {} //~ ERROR unreachable pattern _ => {} } }
main
identifier_name
match-vec-unreachable.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
// except according to those terms. #![feature(slice_patterns)] #![deny(unreachable_patterns)] fn main() { let x: Vec<(isize, isize)> = Vec::new(); let x: &[(isize, isize)] = &x; match *x { [a, (2, 3), _] => (), [(1, 2), (2, 3), b] => (), //~ ERROR unreachable pattern _ => () } let x: Vec<String> = vec!["foo".to_string(), "bar".to_string(), "baz".to_string()]; let x: &[String] = &x; match *x { [ref a, _, _,..] => { println!("{}", a); } [_, _, _, _, _] => { } //~ ERROR unreachable pattern _ => { } } let x: Vec<char> = vec!['a', 'b', 'c']; let x: &[char] = &x; match *x { ['a', 'b', 'c', ref _tail..] => {} ['a', 'b', 'c'] => {} //~ ERROR unreachable pattern _ => {} } }
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
match-vec-unreachable.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(slice_patterns)] #![deny(unreachable_patterns)] fn main()
let x: &[char] = &x; match *x { ['a', 'b', 'c', ref _tail..] => {} ['a', 'b', 'c'] => {} //~ ERROR unreachable pattern _ => {} } }
{ let x: Vec<(isize, isize)> = Vec::new(); let x: &[(isize, isize)] = &x; match *x { [a, (2, 3), _] => (), [(1, 2), (2, 3), b] => (), //~ ERROR unreachable pattern _ => () } let x: Vec<String> = vec!["foo".to_string(), "bar".to_string(), "baz".to_string()]; let x: &[String] = &x; match *x { [ref a, _, _, ..] => { println!("{}", a); } [_, _, _, _, _] => { } //~ ERROR unreachable pattern _ => { } } let x: Vec<char> = vec!['a', 'b', 'c'];
identifier_body
hashset.rs
use std::collections::HashSet; fn main() { let mut a: HashSet<i32> = vec!(1i32, 2, 3).into_iter().collect(); let mut b: HashSet<i32> = vec!(2i32, 3, 4).into_iter().collect(); assert!(a.insert(4)); assert!(a.contains(&4)); // `HashSet::insert()` returns false if // there was a value already present.
// If a collection's element type implements `Show`, // then the collection implements `Show`. // It usually prints its elements in the format `[elem1, elem2,...]` println!("A: {:?}", a); println!("B: {:?}", b); // Print [1, 2, 3, 4, 5] in arbitrary order println!("Union: {:?}", a.union(&b).collect::<Vec<&i32>>()); // This should print [1] println!("Difference: {:?}", a.difference(&b).collect::<Vec<&i32>>()); // Print [2, 3, 4] in arbitrary order. println!("Intersection: {:?}", a.intersection(&b).collect::<Vec<&i32>>()); // Print [1, 5] println!("Symmetric Difference: {:?}", a.symmetric_difference(&b).collect::<Vec<&i32>>()); }
assert!(b.insert(4), "Value 4 is already in set B!"); // FIXME ^ Comment out this line b.insert(5);
random_line_split
hashset.rs
use std::collections::HashSet; fn main()
// Print [1, 2, 3, 4, 5] in arbitrary order println!("Union: {:?}", a.union(&b).collect::<Vec<&i32>>()); // This should print [1] println!("Difference: {:?}", a.difference(&b).collect::<Vec<&i32>>()); // Print [2, 3, 4] in arbitrary order. println!("Intersection: {:?}", a.intersection(&b).collect::<Vec<&i32>>()); // Print [1, 5] println!("Symmetric Difference: {:?}", a.symmetric_difference(&b).collect::<Vec<&i32>>()); }
{ let mut a: HashSet<i32> = vec!(1i32, 2, 3).into_iter().collect(); let mut b: HashSet<i32> = vec!(2i32, 3, 4).into_iter().collect(); assert!(a.insert(4)); assert!(a.contains(&4)); // `HashSet::insert()` returns false if // there was a value already present. assert!(b.insert(4), "Value 4 is already in set B!"); // FIXME ^ Comment out this line b.insert(5); // If a collection's element type implements `Show`, // then the collection implements `Show`. // It usually prints its elements in the format `[elem1, elem2, ...]` println!("A: {:?}", a); println!("B: {:?}", b);
identifier_body
hashset.rs
use std::collections::HashSet; fn
() { let mut a: HashSet<i32> = vec!(1i32, 2, 3).into_iter().collect(); let mut b: HashSet<i32> = vec!(2i32, 3, 4).into_iter().collect(); assert!(a.insert(4)); assert!(a.contains(&4)); // `HashSet::insert()` returns false if // there was a value already present. assert!(b.insert(4), "Value 4 is already in set B!"); // FIXME ^ Comment out this line b.insert(5); // If a collection's element type implements `Show`, // then the collection implements `Show`. // It usually prints its elements in the format `[elem1, elem2,...]` println!("A: {:?}", a); println!("B: {:?}", b); // Print [1, 2, 3, 4, 5] in arbitrary order println!("Union: {:?}", a.union(&b).collect::<Vec<&i32>>()); // This should print [1] println!("Difference: {:?}", a.difference(&b).collect::<Vec<&i32>>()); // Print [2, 3, 4] in arbitrary order. println!("Intersection: {:?}", a.intersection(&b).collect::<Vec<&i32>>()); // Print [1, 5] println!("Symmetric Difference: {:?}", a.symmetric_difference(&b).collect::<Vec<&i32>>()); }
main
identifier_name
optional.rs
use crate::reflect::value::value_ref::ReflectValueMut; use crate::reflect::ReflectValueBox; use crate::reflect::ReflectValueRef; use crate::reflect::RuntimeTypeBox; #[derive(Debug, Clone)] pub(crate) struct DynamicOptional { elem: RuntimeTypeBox, value: Option<ReflectValueBox>, }
impl DynamicOptional { pub fn none(elem: RuntimeTypeBox) -> DynamicOptional { DynamicOptional { elem, value: None } } pub fn mut_or_default(&mut self) -> ReflectValueMut { if let None = self.value { self.value = Some(self.elem.default_value_ref().to_box()); } self.value.as_mut().unwrap().as_value_mut() } pub fn clear(&mut self) { self.value = None; } pub fn get(&self) -> Option<ReflectValueRef> { self.value.as_ref().map(ReflectValueBox::as_value_ref) } pub fn set(&mut self, value: ReflectValueBox) { assert_eq!(value.get_type(), self.elem); self.value = Some(value); } }
random_line_split
optional.rs
use crate::reflect::value::value_ref::ReflectValueMut; use crate::reflect::ReflectValueBox; use crate::reflect::ReflectValueRef; use crate::reflect::RuntimeTypeBox; #[derive(Debug, Clone)] pub(crate) struct DynamicOptional { elem: RuntimeTypeBox, value: Option<ReflectValueBox>, } impl DynamicOptional { pub fn none(elem: RuntimeTypeBox) -> DynamicOptional { DynamicOptional { elem, value: None } } pub fn mut_or_default(&mut self) -> ReflectValueMut { if let None = self.value { self.value = Some(self.elem.default_value_ref().to_box()); } self.value.as_mut().unwrap().as_value_mut() } pub fn clear(&mut self) { self.value = None; } pub fn
(&self) -> Option<ReflectValueRef> { self.value.as_ref().map(ReflectValueBox::as_value_ref) } pub fn set(&mut self, value: ReflectValueBox) { assert_eq!(value.get_type(), self.elem); self.value = Some(value); } }
get
identifier_name
optional.rs
use crate::reflect::value::value_ref::ReflectValueMut; use crate::reflect::ReflectValueBox; use crate::reflect::ReflectValueRef; use crate::reflect::RuntimeTypeBox; #[derive(Debug, Clone)] pub(crate) struct DynamicOptional { elem: RuntimeTypeBox, value: Option<ReflectValueBox>, } impl DynamicOptional { pub fn none(elem: RuntimeTypeBox) -> DynamicOptional
pub fn mut_or_default(&mut self) -> ReflectValueMut { if let None = self.value { self.value = Some(self.elem.default_value_ref().to_box()); } self.value.as_mut().unwrap().as_value_mut() } pub fn clear(&mut self) { self.value = None; } pub fn get(&self) -> Option<ReflectValueRef> { self.value.as_ref().map(ReflectValueBox::as_value_ref) } pub fn set(&mut self, value: ReflectValueBox) { assert_eq!(value.get_type(), self.elem); self.value = Some(value); } }
{ DynamicOptional { elem, value: None } }
identifier_body
optional.rs
use crate::reflect::value::value_ref::ReflectValueMut; use crate::reflect::ReflectValueBox; use crate::reflect::ReflectValueRef; use crate::reflect::RuntimeTypeBox; #[derive(Debug, Clone)] pub(crate) struct DynamicOptional { elem: RuntimeTypeBox, value: Option<ReflectValueBox>, } impl DynamicOptional { pub fn none(elem: RuntimeTypeBox) -> DynamicOptional { DynamicOptional { elem, value: None } } pub fn mut_or_default(&mut self) -> ReflectValueMut { if let None = self.value
self.value.as_mut().unwrap().as_value_mut() } pub fn clear(&mut self) { self.value = None; } pub fn get(&self) -> Option<ReflectValueRef> { self.value.as_ref().map(ReflectValueBox::as_value_ref) } pub fn set(&mut self, value: ReflectValueBox) { assert_eq!(value.get_type(), self.elem); self.value = Some(value); } }
{ self.value = Some(self.elem.default_value_ref().to_box()); }
conditional_block
color.rs
Value}; use crate::values::generics::color::{Color as GenericColor, ColorOrAuto as GenericColorOrAuto}; use crate::values::specified::calc::CalcNode; use cssparser::{AngleOrNumber, Color as CSSParserColor, Parser, Token, RGBA}; use cssparser::{BasicParseErrorKind, NumberOrPercentage, ParseErrorKind}; use itoa; use std::fmt::{self, Write}; use std::io::Write as IoWrite; use style_traits::{CssType, CssWriter, KeywordsCollectFn, ParseError, StyleParseErrorKind}; use style_traits::{SpecifiedValueInfo, ToCss, ValueParseErrorKind}; /// Specified color value #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToShmem)] pub enum Color { /// The 'currentColor' keyword CurrentColor, /// A specific RGBA color Numeric { /// Parsed RGBA color parsed: RGBA, /// Authored representation authored: Option<Box<str>>, }, /// A complex color value from computed value Complex(ComputedColor), /// A system color #[cfg(feature = "gecko")] System(SystemColor), /// Quirksmode-only rule for inheriting color from the body #[cfg(feature = "gecko")] InheritFromBodyQuirk, } /// System colors. #[allow(missing_docs)] #[cfg(feature = "gecko")] #[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, ToCss, ToShmem)] #[repr(u8)] pub enum SystemColor { #[css(skip)] WindowBackground, #[css(skip)] WindowForeground, #[css(skip)] WidgetBackground, #[css(skip)] WidgetForeground, #[css(skip)] WidgetSelectBackground, #[css(skip)] WidgetSelectForeground, #[css(skip)] Widget3DHighlight, #[css(skip)] Widget3DShadow, #[css(skip)] TextBackground, #[css(skip)] TextForeground, #[css(skip)] TextSelectBackground, #[css(skip)] TextSelectForeground, #[css(skip)] TextSelectForegroundCustom, #[css(skip)] TextSelectBackgroundDisabled, #[css(skip)] TextSelectBackgroundAttention, #[css(skip)] TextHighlightBackground, #[css(skip)] TextHighlightForeground, #[css(skip)] IMERawInputBackground, #[css(skip)] IMERawInputForeground, #[css(skip)] IMERawInputUnderline, #[css(skip)] IMESelectedRawTextBackground, #[css(skip)] IMESelectedRawTextForeground, #[css(skip)] IMESelectedRawTextUnderline, #[css(skip)] IMEConvertedTextBackground, #[css(skip)] IMEConvertedTextForeground, #[css(skip)] IMEConvertedTextUnderline, #[css(skip)] IMESelectedConvertedTextBackground, #[css(skip)] IMESelectedConvertedTextForeground, #[css(skip)] IMESelectedConvertedTextUnderline, #[css(skip)] SpellCheckerUnderline, Activeborder, Activecaption, Appworkspace, Background, Buttonface, Buttonhighlight, Buttonshadow, Buttontext, Captiontext, #[parse(aliases = "-moz-field")] Field, #[parse(aliases = "-moz-fieldtext")] Fieldtext, Graytext, Highlight, Highlighttext, Inactiveborder, Inactivecaption, Inactivecaptiontext, Infobackground, Infotext, Menu, Menutext, Scrollbar, Threeddarkshadow, Threedface, Threedhighlight, Threedlightshadow, Threedshadow, Window, Windowframe, Windowtext, MozButtondefault, MozDefaultColor, MozDefaultBackgroundColor, MozDialog, MozDialogtext, /// Used to highlight valid regions to drop something onto. MozDragtargetzone, /// Used for selected but not focused cell backgrounds. MozCellhighlight, /// Used for selected but not focused cell text. MozCellhighlighttext, /// Used for selected but not focused html cell backgrounds. MozHtmlCellhighlight, /// Used for selected but not focused html cell text. MozHtmlCellhighlighttext, /// Used to button text background when hovered. MozButtonhoverface, /// Used to button text color when hovered. MozButtonhovertext, /// Used for menu item backgrounds when hovered. MozMenuhover, /// Used for menu item text when hovered. MozMenuhovertext, /// Used for menubar item text. MozMenubartext, /// Used for menubar item text when hovered. MozMenubarhovertext, /// On platforms where these colors are the same as -moz-field, use /// -moz-fieldtext as foreground color MozEventreerow, MozOddtreerow, /// Used for button text when pressed. #[parse(condition = "ParserContext::in_ua_or_chrome_sheet")] MozGtkButtonactivetext, /// Used for button text when pressed. MozMacButtonactivetext, /// Background color of chrome toolbars in active windows. MozMacChromeActive, /// Background color of chrome toolbars in inactive windows. MozMacChromeInactive, /// Foreground color of default buttons. MozMacDefaultbuttontext, /// Ring color around text fields and lists. MozMacFocusring, /// Color used when mouse is over a menu item. MozMacMenuselect, /// Color used to do shadows on menu items. MozMacMenushadow, /// Color used to display text for disabled menu items. MozMacMenutextdisable, /// Color used to display text while mouse is over a menu item. MozMacMenutextselect, /// Text color of disabled text on toolbars. MozMacDisabledtoolbartext, /// Inactive light hightlight MozMacSecondaryhighlight, /// Font smoothing background colors needed by the Mac OS X theme, based on /// -moz-appearance names. MozMacVibrancyLight, MozMacVibrancyDark, MozMacVibrantTitlebarLight, MozMacVibrantTitlebarDark, MozMacMenupopup, MozMacMenuitem, MozMacActiveMenuitem, MozMacSourceList, MozMacSourceListSelection, MozMacActiveSourceListSelection, MozMacTooltip, /// Accent color for title bar. MozWinAccentcolor, /// Color from drawing text over the accent color. MozWinAccentcolortext, /// Media rebar text. MozWinMediatext, /// Communications rebar text. MozWinCommunicationstext, /// Hyperlink color extracted from the system, not affected by the /// browser.anchor_color user pref. /// /// There is no OS-specified safe background color for this text, but it is /// used regularly within Windows and the Gnome DE on Dialog and Window /// colors. MozNativehyperlinktext, MozHyperlinktext, MozActivehyperlinktext, MozVisitedhyperlinktext, /// Combobox widgets MozComboboxtext, MozCombobox, MozGtkInfoBarText, #[css(skip)] End, // Just for array-indexing purposes. } #[cfg(feature = "gecko")] impl SystemColor { #[inline] fn compute(&self, cx: &Context) -> ComputedColor { use crate::gecko_bindings::bindings; let prefs = cx.device().pref_sheet_prefs(); convert_nscolor_to_computedcolor(match *self { SystemColor::MozDefaultColor => prefs.mDefaultColor, SystemColor::MozDefaultBackgroundColor => prefs.mDefaultBackgroundColor, SystemColor::MozHyperlinktext => prefs.mLinkColor, SystemColor::MozActivehyperlinktext => prefs.mActiveLinkColor, SystemColor::MozVisitedhyperlinktext => prefs.mVisitedLinkColor, _ => unsafe { bindings::Gecko_GetLookAndFeelSystemColor(*self as i32, cx.device().document()) }, }) } } impl From<RGBA> for Color { fn from(value: RGBA) -> Self { Color::rgba(value) } } struct ColorComponentParser<'a, 'b: 'a>(&'a ParserContext<'b>); impl<'a, 'b: 'a, 'i: 'a> ::cssparser::ColorComponentParser<'i> for ColorComponentParser<'a, 'b> { type Error = StyleParseErrorKind<'i>; fn parse_angle_or_number<'t>( &self, input: &mut Parser<'i, 't>, ) -> Result<AngleOrNumber, ParseError<'i>> { use crate::values::specified::Angle; let location = input.current_source_location(); let token = input.next()?.clone(); match token { Token::Dimension { value, ref unit,.. } => { let angle = Angle::parse_dimension(value, unit, /* from_calc = */ false); let degrees = match angle { Ok(angle) => angle.degrees(), Err(()) => return Err(location.new_unexpected_token_error(token.clone())), }; Ok(AngleOrNumber::Angle { degrees }) }, Token::Number { value,.. } => Ok(AngleOrNumber::Number { value }), Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { input.parse_nested_block(|i| CalcNode::parse_angle_or_number(self.0, i)) }, t => return Err(location.new_unexpected_token_error(t)), } } fn parse_percentage<'t>(&self, input: &mut Parser<'i, 't>) -> Result<f32, ParseError<'i>> { use crate::values::specified::Percentage; Ok(Percentage::parse(self.0, input)?.get()) } fn parse_number<'t>(&self, input: &mut Parser<'i, 't>) -> Result<f32, ParseError<'i>> { use crate::values::specified::Number; Ok(Number::parse(self.0, input)?.get()) } fn parse_number_or_percentage<'t>( &self, input: &mut Parser<'i, 't>, ) -> Result<NumberOrPercentage, ParseError<'i>> { let location = input.current_source_location(); match input.next()?.clone() { Token::Number { value,.. } => Ok(NumberOrPercentage::Number { value }), Token::Percentage { unit_value,.. } => { Ok(NumberOrPercentage::Percentage { unit_value }) }, Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { input.parse_nested_block(|i| CalcNode::parse_number_or_percentage(self.0, i)) }, t => return Err(location.new_unexpected_token_error(t)), } } } impl Parse for Color { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { // Currently we only store authored value for color keywords, // because all browsers serialize those values as keywords for // specified value. let start = input.state(); let authored = input.expect_ident_cloned().ok(); input.reset(&start); let compontent_parser = ColorComponentParser(&*context); match input.try(|i| CSSParserColor::parse_with(&compontent_parser, i)) { Ok(value) => Ok(match value { CSSParserColor::CurrentColor => Color::CurrentColor, CSSParserColor::RGBA(rgba) => Color::Numeric { parsed: rgba, authored: authored.map(|s| s.to_ascii_lowercase().into_boxed_str()), }, }), Err(e) => { #[cfg(feature = "gecko")] { if let Ok(system) = input.try(|i| SystemColor::parse(context, i)) { return Ok(Color::System(system)); } } match e.kind { ParseErrorKind::Basic(BasicParseErrorKind::UnexpectedToken(t)) => { Err(e.location.new_custom_error(StyleParseErrorKind::ValueError( ValueParseErrorKind::InvalidColor(t), ))) }, _ => Err(e), } }, } } } impl ToCss for Color { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { match *self { Color::CurrentColor => CSSParserColor::CurrentColor.to_css(dest), Color::Numeric { authored: Some(ref authored), .. } => dest.write_str(authored), Color::Numeric { parsed: ref rgba,.. } => rgba.to_css(dest), Color::Complex(_) => Ok(()), #[cfg(feature = "gecko")] Color::System(system) => system.to_css(dest), #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => Ok(()), } } } /// A wrapper of cssparser::Color::parse_hash. /// /// That function should never return CurrentColor, so it makes no sense to /// handle a cssparser::Color here. This should really be done in cssparser /// directly rather than here. fn parse_hash_color(value: &[u8]) -> Result<RGBA, ()> { CSSParserColor::parse_hash(value).map(|color| match color { CSSParserColor::RGBA(rgba) => rgba, CSSParserColor::CurrentColor => unreachable!("parse_hash should never return currentcolor"), }) } impl Color { /// Returns currentcolor value. #[inline] pub fn currentcolor() -> Color { Color::CurrentColor } /// Returns transparent value. #[inline] pub fn transparent() -> Color { // We should probably set authored to "transparent", but maybe it doesn't matter. Color::rgba(RGBA::transparent()) } /// Returns a numeric RGBA color value. #[inline] pub fn rgba(rgba: RGBA) -> Self { Color::Numeric { parsed: rgba, authored: None, } } /// Parse a color, with quirks. /// /// <https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk> pub fn parse_quirky<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, allow_quirks: AllowQuirks, ) -> Result<Self, ParseError<'i>> { input.try(|i| Self::parse(context, i)).or_else(|e| { if!allow_quirks.allowed(context.quirks_mode) { return Err(e); } Color::parse_quirky_color(input) .map(Color::rgba) .map_err(|_| e) }) } /// Parse a <quirky-color> value. /// /// <https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk> fn parse_quirky_color<'i, 't>(input: &mut Parser<'i, 't>) -> Result<RGBA, ParseError<'i>> { let location = input.current_source_location(); let (value, unit) = match *input.next()? { Token::Number { int_value: Some(integer), .. } => (integer, None), Token::Dimension { int_value: Some(integer), ref unit, .. } => (integer, Some(unit)), Token::Ident(ref ident) => { if ident.len()!= 3 && ident.len()!= 6 { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } return parse_hash_color(ident.as_bytes()).map_err(|()| { location.new_custom_error(StyleParseErrorKind::UnspecifiedError) }); }, ref t => { return Err(location.new_unexpected_token_error(t.clone())); }, }; if value < 0 { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } let length = if value <= 9 { 1 } else if value <= 99 { 2 } else if value <= 999 { 3 } else if value <= 9999 { 4 } else if value <= 99999 { 5 } else if value <= 999999 { 6 } else { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); }; let total = length + unit.as_ref().map_or(0, |d| d.len()); if total > 6 { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } let mut serialization = [b'0'; 6]; let space_padding = 6 - total; let mut written = space_padding; written += itoa::write(&mut serialization[written..], value).unwrap(); if let Some(unit) = unit { written += (&mut serialization[written..]) .write(unit.as_bytes()) .unwrap(); } debug_assert_eq!(written, 6); parse_hash_color(&serialization) .map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } /// Returns true if the color is completely transparent, and false /// otherwise. pub fn is_transparent(&self) -> bool { match *self { Color::Numeric { ref parsed,.. } => parsed.alpha == 0, _ => false, } } } #[cfg(feature = "gecko")] fn convert_nscolor_to_computedcolor(color: nscolor) -> ComputedColor { use crate::gecko::values::convert_nscolor_to_rgba; ComputedColor::rgba(convert_nscolor_to_rgba(color)) } impl Color { /// Converts this Color into a ComputedColor. /// /// If `context` is `None`, and the specified color requires data from /// the context to resolve, then `None` is returned. pub fn to_computed_color(&self, _context: Option<&Context>) -> Option<ComputedColor> { Some(match *self { Color::CurrentColor => ComputedColor::currentcolor(), Color::Numeric { ref parsed,.. } => ComputedColor::rgba(*parsed), Color::Complex(ref complex) => *complex, #[cfg(feature = "gecko")] Color::System(system) => system.compute(_context?), #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => { ComputedColor::rgba(_context?.device().body_text_color()) }, }) } } impl ToComputedValue for Color { type ComputedValue = ComputedColor; fn to_computed_value(&self, context: &Context) -> ComputedColor { self.to_computed_color(Some(context)).unwrap() } fn from_computed_value(computed: &ComputedColor) -> Self { match *computed { GenericColor::Numeric(color) => Color::rgba(color), GenericColor::CurrentColor => Color::currentcolor(), GenericColor::Complex {.. } => Color::Complex(*computed), } } } /// Specified color value for `-moz-font-smoothing-background-color`. /// /// This property does not support `currentcolor`. We could drop it at /// parse-time, but it's not exposed to the web so it doesn't really matter. /// /// We resolve it to `transparent` instead. #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] pub struct MozFontSmoothingBackgroundColor(pub Color); impl Parse for MozFontSmoothingBackgroundColor { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>>
} impl ToComputedValue for MozFontSmoothingBackgroundColor { type ComputedValue = RGBA; fn to_computed_value(&self, context: &Context) -> RGBA { self.0 .to_computed_value(context) .to_rgba(RGBA::transparent()) } fn from_computed_value(computed: &RGBA) -> Self { MozFontSmoothingBackgroundColor(Color::rgba(*computed)) } } impl SpecifiedValueInfo for Color { const SUPPORTED_TYPES: u8 = CssType::COLOR; fn collect_completion_keywords(f: KeywordsCollectFn) { // We are not going to insert all the color names here. Caller and // devtools should take care of them. XXX Actually, transparent // should probably be handled that way as well. // XXX `currentColor` should really be `currentcolor`. But let's // keep it consistent with the old system for now. f(&["rgb", "rgba", "hsl", "hsla", "currentColor", "transparent"]); } } /// Specified value for the "color" property, which resolves the `currentcolor` /// keyword to the parent color instead of self's color. #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[derive(Clone, Debug, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] pub struct ColorPropertyValue(pub Color); impl ToComputedValue
{ Color::parse(context, input).map(MozFontSmoothingBackgroundColor) }
identifier_body
color.rs
Value}; use crate::values::generics::color::{Color as GenericColor, ColorOrAuto as GenericColorOrAuto}; use crate::values::specified::calc::CalcNode; use cssparser::{AngleOrNumber, Color as CSSParserColor, Parser, Token, RGBA}; use cssparser::{BasicParseErrorKind, NumberOrPercentage, ParseErrorKind}; use itoa; use std::fmt::{self, Write}; use std::io::Write as IoWrite; use style_traits::{CssType, CssWriter, KeywordsCollectFn, ParseError, StyleParseErrorKind}; use style_traits::{SpecifiedValueInfo, ToCss, ValueParseErrorKind}; /// Specified color value #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToShmem)] pub enum Color { /// The 'currentColor' keyword CurrentColor, /// A specific RGBA color Numeric { /// Parsed RGBA color parsed: RGBA, /// Authored representation authored: Option<Box<str>>, }, /// A complex color value from computed value Complex(ComputedColor), /// A system color #[cfg(feature = "gecko")] System(SystemColor), /// Quirksmode-only rule for inheriting color from the body #[cfg(feature = "gecko")] InheritFromBodyQuirk, } /// System colors. #[allow(missing_docs)] #[cfg(feature = "gecko")] #[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, ToCss, ToShmem)] #[repr(u8)] pub enum SystemColor { #[css(skip)] WindowBackground, #[css(skip)] WindowForeground, #[css(skip)] WidgetBackground, #[css(skip)] WidgetForeground, #[css(skip)] WidgetSelectBackground, #[css(skip)] WidgetSelectForeground, #[css(skip)] Widget3DHighlight, #[css(skip)] Widget3DShadow, #[css(skip)] TextBackground, #[css(skip)] TextForeground, #[css(skip)] TextSelectBackground, #[css(skip)] TextSelectForeground, #[css(skip)] TextSelectForegroundCustom, #[css(skip)] TextSelectBackgroundDisabled, #[css(skip)] TextSelectBackgroundAttention, #[css(skip)] TextHighlightBackground, #[css(skip)] TextHighlightForeground, #[css(skip)] IMERawInputBackground, #[css(skip)] IMERawInputForeground, #[css(skip)] IMERawInputUnderline, #[css(skip)] IMESelectedRawTextBackground, #[css(skip)] IMESelectedRawTextForeground, #[css(skip)] IMESelectedRawTextUnderline, #[css(skip)] IMEConvertedTextBackground, #[css(skip)] IMEConvertedTextForeground, #[css(skip)] IMEConvertedTextUnderline, #[css(skip)] IMESelectedConvertedTextBackground, #[css(skip)] IMESelectedConvertedTextForeground, #[css(skip)] IMESelectedConvertedTextUnderline, #[css(skip)] SpellCheckerUnderline, Activeborder, Activecaption, Appworkspace, Background, Buttonface, Buttonhighlight, Buttonshadow, Buttontext, Captiontext, #[parse(aliases = "-moz-field")] Field, #[parse(aliases = "-moz-fieldtext")] Fieldtext, Graytext, Highlight, Highlighttext, Inactiveborder, Inactivecaption, Inactivecaptiontext, Infobackground, Infotext, Menu, Menutext, Scrollbar, Threeddarkshadow, Threedface, Threedhighlight, Threedlightshadow, Threedshadow, Window, Windowframe, Windowtext, MozButtondefault, MozDefaultColor, MozDefaultBackgroundColor, MozDialog, MozDialogtext, /// Used to highlight valid regions to drop something onto. MozDragtargetzone, /// Used for selected but not focused cell backgrounds. MozCellhighlight, /// Used for selected but not focused cell text. MozCellhighlighttext, /// Used for selected but not focused html cell backgrounds. MozHtmlCellhighlight, /// Used for selected but not focused html cell text. MozHtmlCellhighlighttext, /// Used to button text background when hovered. MozButtonhoverface, /// Used to button text color when hovered. MozButtonhovertext, /// Used for menu item backgrounds when hovered. MozMenuhover, /// Used for menu item text when hovered. MozMenuhovertext, /// Used for menubar item text. MozMenubartext, /// Used for menubar item text when hovered. MozMenubarhovertext, /// On platforms where these colors are the same as -moz-field, use /// -moz-fieldtext as foreground color MozEventreerow, MozOddtreerow, /// Used for button text when pressed. #[parse(condition = "ParserContext::in_ua_or_chrome_sheet")] MozGtkButtonactivetext, /// Used for button text when pressed. MozMacButtonactivetext, /// Background color of chrome toolbars in active windows. MozMacChromeActive, /// Background color of chrome toolbars in inactive windows. MozMacChromeInactive, /// Foreground color of default buttons. MozMacDefaultbuttontext, /// Ring color around text fields and lists. MozMacFocusring, /// Color used when mouse is over a menu item. MozMacMenuselect, /// Color used to do shadows on menu items. MozMacMenushadow, /// Color used to display text for disabled menu items. MozMacMenutextdisable, /// Color used to display text while mouse is over a menu item. MozMacMenutextselect, /// Text color of disabled text on toolbars. MozMacDisabledtoolbartext, /// Inactive light hightlight MozMacSecondaryhighlight, /// Font smoothing background colors needed by the Mac OS X theme, based on /// -moz-appearance names. MozMacVibrancyLight, MozMacVibrancyDark, MozMacVibrantTitlebarLight, MozMacVibrantTitlebarDark, MozMacMenupopup, MozMacMenuitem, MozMacActiveMenuitem, MozMacSourceList, MozMacSourceListSelection, MozMacActiveSourceListSelection, MozMacTooltip, /// Accent color for title bar. MozWinAccentcolor, /// Color from drawing text over the accent color. MozWinAccentcolortext, /// Media rebar text. MozWinMediatext, /// Communications rebar text. MozWinCommunicationstext, /// Hyperlink color extracted from the system, not affected by the /// browser.anchor_color user pref. /// /// There is no OS-specified safe background color for this text, but it is /// used regularly within Windows and the Gnome DE on Dialog and Window /// colors. MozNativehyperlinktext, MozHyperlinktext, MozActivehyperlinktext, MozVisitedhyperlinktext, /// Combobox widgets MozComboboxtext, MozCombobox, MozGtkInfoBarText, #[css(skip)] End, // Just for array-indexing purposes. } #[cfg(feature = "gecko")] impl SystemColor { #[inline] fn compute(&self, cx: &Context) -> ComputedColor { use crate::gecko_bindings::bindings; let prefs = cx.device().pref_sheet_prefs(); convert_nscolor_to_computedcolor(match *self { SystemColor::MozDefaultColor => prefs.mDefaultColor, SystemColor::MozDefaultBackgroundColor => prefs.mDefaultBackgroundColor, SystemColor::MozHyperlinktext => prefs.mLinkColor, SystemColor::MozActivehyperlinktext => prefs.mActiveLinkColor, SystemColor::MozVisitedhyperlinktext => prefs.mVisitedLinkColor, _ => unsafe { bindings::Gecko_GetLookAndFeelSystemColor(*self as i32, cx.device().document()) }, }) } } impl From<RGBA> for Color { fn from(value: RGBA) -> Self { Color::rgba(value) } } struct ColorComponentParser<'a, 'b: 'a>(&'a ParserContext<'b>); impl<'a, 'b: 'a, 'i: 'a> ::cssparser::ColorComponentParser<'i> for ColorComponentParser<'a, 'b> { type Error = StyleParseErrorKind<'i>; fn parse_angle_or_number<'t>( &self, input: &mut Parser<'i, 't>, ) -> Result<AngleOrNumber, ParseError<'i>> { use crate::values::specified::Angle; let location = input.current_source_location(); let token = input.next()?.clone(); match token { Token::Dimension { value, ref unit,.. } => { let angle = Angle::parse_dimension(value, unit, /* from_calc = */ false); let degrees = match angle { Ok(angle) => angle.degrees(), Err(()) => return Err(location.new_unexpected_token_error(token.clone())), }; Ok(AngleOrNumber::Angle { degrees }) }, Token::Number { value,.. } => Ok(AngleOrNumber::Number { value }), Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { input.parse_nested_block(|i| CalcNode::parse_angle_or_number(self.0, i)) }, t => return Err(location.new_unexpected_token_error(t)), } } fn parse_percentage<'t>(&self, input: &mut Parser<'i, 't>) -> Result<f32, ParseError<'i>> { use crate::values::specified::Percentage; Ok(Percentage::parse(self.0, input)?.get()) } fn parse_number<'t>(&self, input: &mut Parser<'i, 't>) -> Result<f32, ParseError<'i>> { use crate::values::specified::Number; Ok(Number::parse(self.0, input)?.get()) } fn parse_number_or_percentage<'t>( &self, input: &mut Parser<'i, 't>, ) -> Result<NumberOrPercentage, ParseError<'i>> { let location = input.current_source_location(); match input.next()?.clone() { Token::Number { value,.. } => Ok(NumberOrPercentage::Number { value }), Token::Percentage { unit_value,.. } => { Ok(NumberOrPercentage::Percentage { unit_value }) }, Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { input.parse_nested_block(|i| CalcNode::parse_number_or_percentage(self.0, i)) }, t => return Err(location.new_unexpected_token_error(t)), } } } impl Parse for Color { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { // Currently we only store authored value for color keywords, // because all browsers serialize those values as keywords for // specified value. let start = input.state(); let authored = input.expect_ident_cloned().ok(); input.reset(&start); let compontent_parser = ColorComponentParser(&*context); match input.try(|i| CSSParserColor::parse_with(&compontent_parser, i)) { Ok(value) => Ok(match value { CSSParserColor::CurrentColor => Color::CurrentColor, CSSParserColor::RGBA(rgba) => Color::Numeric { parsed: rgba, authored: authored.map(|s| s.to_ascii_lowercase().into_boxed_str()), }, }), Err(e) => { #[cfg(feature = "gecko")] { if let Ok(system) = input.try(|i| SystemColor::parse(context, i)) { return Ok(Color::System(system)); } } match e.kind { ParseErrorKind::Basic(BasicParseErrorKind::UnexpectedToken(t)) => { Err(e.location.new_custom_error(StyleParseErrorKind::ValueError( ValueParseErrorKind::InvalidColor(t), ))) }, _ => Err(e), } }, } } } impl ToCss for Color { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { match *self { Color::CurrentColor => CSSParserColor::CurrentColor.to_css(dest), Color::Numeric { authored: Some(ref authored), .. } => dest.write_str(authored), Color::Numeric { parsed: ref rgba,.. } => rgba.to_css(dest), Color::Complex(_) => Ok(()), #[cfg(feature = "gecko")] Color::System(system) => system.to_css(dest), #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => Ok(()), } } } /// A wrapper of cssparser::Color::parse_hash. /// /// That function should never return CurrentColor, so it makes no sense to /// handle a cssparser::Color here. This should really be done in cssparser /// directly rather than here. fn parse_hash_color(value: &[u8]) -> Result<RGBA, ()> { CSSParserColor::parse_hash(value).map(|color| match color { CSSParserColor::RGBA(rgba) => rgba, CSSParserColor::CurrentColor => unreachable!("parse_hash should never return currentcolor"), }) } impl Color { /// Returns currentcolor value. #[inline] pub fn
() -> Color { Color::CurrentColor } /// Returns transparent value. #[inline] pub fn transparent() -> Color { // We should probably set authored to "transparent", but maybe it doesn't matter. Color::rgba(RGBA::transparent()) } /// Returns a numeric RGBA color value. #[inline] pub fn rgba(rgba: RGBA) -> Self { Color::Numeric { parsed: rgba, authored: None, } } /// Parse a color, with quirks. /// /// <https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk> pub fn parse_quirky<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, allow_quirks: AllowQuirks, ) -> Result<Self, ParseError<'i>> { input.try(|i| Self::parse(context, i)).or_else(|e| { if!allow_quirks.allowed(context.quirks_mode) { return Err(e); } Color::parse_quirky_color(input) .map(Color::rgba) .map_err(|_| e) }) } /// Parse a <quirky-color> value. /// /// <https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk> fn parse_quirky_color<'i, 't>(input: &mut Parser<'i, 't>) -> Result<RGBA, ParseError<'i>> { let location = input.current_source_location(); let (value, unit) = match *input.next()? { Token::Number { int_value: Some(integer), .. } => (integer, None), Token::Dimension { int_value: Some(integer), ref unit, .. } => (integer, Some(unit)), Token::Ident(ref ident) => { if ident.len()!= 3 && ident.len()!= 6 { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } return parse_hash_color(ident.as_bytes()).map_err(|()| { location.new_custom_error(StyleParseErrorKind::UnspecifiedError) }); }, ref t => { return Err(location.new_unexpected_token_error(t.clone())); }, }; if value < 0 { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } let length = if value <= 9 { 1 } else if value <= 99 { 2 } else if value <= 999 { 3 } else if value <= 9999 { 4 } else if value <= 99999 { 5 } else if value <= 999999 { 6 } else { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); }; let total = length + unit.as_ref().map_or(0, |d| d.len()); if total > 6 { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } let mut serialization = [b'0'; 6]; let space_padding = 6 - total; let mut written = space_padding; written += itoa::write(&mut serialization[written..], value).unwrap(); if let Some(unit) = unit { written += (&mut serialization[written..]) .write(unit.as_bytes()) .unwrap(); } debug_assert_eq!(written, 6); parse_hash_color(&serialization) .map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } /// Returns true if the color is completely transparent, and false /// otherwise. pub fn is_transparent(&self) -> bool { match *self { Color::Numeric { ref parsed,.. } => parsed.alpha == 0, _ => false, } } } #[cfg(feature = "gecko")] fn convert_nscolor_to_computedcolor(color: nscolor) -> ComputedColor { use crate::gecko::values::convert_nscolor_to_rgba; ComputedColor::rgba(convert_nscolor_to_rgba(color)) } impl Color { /// Converts this Color into a ComputedColor. /// /// If `context` is `None`, and the specified color requires data from /// the context to resolve, then `None` is returned. pub fn to_computed_color(&self, _context: Option<&Context>) -> Option<ComputedColor> { Some(match *self { Color::CurrentColor => ComputedColor::currentcolor(), Color::Numeric { ref parsed,.. } => ComputedColor::rgba(*parsed), Color::Complex(ref complex) => *complex, #[cfg(feature = "gecko")] Color::System(system) => system.compute(_context?), #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => { ComputedColor::rgba(_context?.device().body_text_color()) }, }) } } impl ToComputedValue for Color { type ComputedValue = ComputedColor; fn to_computed_value(&self, context: &Context) -> ComputedColor { self.to_computed_color(Some(context)).unwrap() } fn from_computed_value(computed: &ComputedColor) -> Self { match *computed { GenericColor::Numeric(color) => Color::rgba(color), GenericColor::CurrentColor => Color::currentcolor(), GenericColor::Complex {.. } => Color::Complex(*computed), } } } /// Specified color value for `-moz-font-smoothing-background-color`. /// /// This property does not support `currentcolor`. We could drop it at /// parse-time, but it's not exposed to the web so it doesn't really matter. /// /// We resolve it to `transparent` instead. #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] pub struct MozFontSmoothingBackgroundColor(pub Color); impl Parse for MozFontSmoothingBackgroundColor { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { Color::parse(context, input).map(MozFontSmoothingBackgroundColor) } } impl ToComputedValue for MozFontSmoothingBackgroundColor { type ComputedValue = RGBA; fn to_computed_value(&self, context: &Context) -> RGBA { self.0 .to_computed_value(context) .to_rgba(RGBA::transparent()) } fn from_computed_value(computed: &RGBA) -> Self { MozFontSmoothingBackgroundColor(Color::rgba(*computed)) } } impl SpecifiedValueInfo for Color { const SUPPORTED_TYPES: u8 = CssType::COLOR; fn collect_completion_keywords(f: KeywordsCollectFn) { // We are not going to insert all the color names here. Caller and // devtools should take care of them. XXX Actually, transparent // should probably be handled that way as well. // XXX `currentColor` should really be `currentcolor`. But let's // keep it consistent with the old system for now. f(&["rgb", "rgba", "hsl", "hsla", "currentColor", "transparent"]); } } /// Specified value for the "color" property, which resolves the `currentcolor` /// keyword to the parent color instead of self's color. #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[derive(Clone, Debug, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] pub struct ColorPropertyValue(pub Color); impl ToComputedValue
currentcolor
identifier_name
color.rs
ComputedValue}; use crate::values::generics::color::{Color as GenericColor, ColorOrAuto as GenericColorOrAuto}; use crate::values::specified::calc::CalcNode; use cssparser::{AngleOrNumber, Color as CSSParserColor, Parser, Token, RGBA}; use cssparser::{BasicParseErrorKind, NumberOrPercentage, ParseErrorKind}; use itoa; use std::fmt::{self, Write}; use std::io::Write as IoWrite; use style_traits::{CssType, CssWriter, KeywordsCollectFn, ParseError, StyleParseErrorKind}; use style_traits::{SpecifiedValueInfo, ToCss, ValueParseErrorKind}; /// Specified color value #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToShmem)] pub enum Color { /// The 'currentColor' keyword CurrentColor, /// A specific RGBA color Numeric { /// Parsed RGBA color parsed: RGBA, /// Authored representation authored: Option<Box<str>>, }, /// A complex color value from computed value Complex(ComputedColor), /// A system color #[cfg(feature = "gecko")] System(SystemColor), /// Quirksmode-only rule for inheriting color from the body #[cfg(feature = "gecko")] InheritFromBodyQuirk, } /// System colors. #[allow(missing_docs)] #[cfg(feature = "gecko")] #[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, ToCss, ToShmem)] #[repr(u8)] pub enum SystemColor { #[css(skip)] WindowBackground, #[css(skip)] WindowForeground, #[css(skip)] WidgetBackground, #[css(skip)] WidgetForeground, #[css(skip)] WidgetSelectBackground, #[css(skip)] WidgetSelectForeground, #[css(skip)] Widget3DHighlight, #[css(skip)] Widget3DShadow, #[css(skip)] TextBackground, #[css(skip)] TextForeground, #[css(skip)] TextSelectBackground, #[css(skip)] TextSelectForeground,
TextSelectBackgroundAttention, #[css(skip)] TextHighlightBackground, #[css(skip)] TextHighlightForeground, #[css(skip)] IMERawInputBackground, #[css(skip)] IMERawInputForeground, #[css(skip)] IMERawInputUnderline, #[css(skip)] IMESelectedRawTextBackground, #[css(skip)] IMESelectedRawTextForeground, #[css(skip)] IMESelectedRawTextUnderline, #[css(skip)] IMEConvertedTextBackground, #[css(skip)] IMEConvertedTextForeground, #[css(skip)] IMEConvertedTextUnderline, #[css(skip)] IMESelectedConvertedTextBackground, #[css(skip)] IMESelectedConvertedTextForeground, #[css(skip)] IMESelectedConvertedTextUnderline, #[css(skip)] SpellCheckerUnderline, Activeborder, Activecaption, Appworkspace, Background, Buttonface, Buttonhighlight, Buttonshadow, Buttontext, Captiontext, #[parse(aliases = "-moz-field")] Field, #[parse(aliases = "-moz-fieldtext")] Fieldtext, Graytext, Highlight, Highlighttext, Inactiveborder, Inactivecaption, Inactivecaptiontext, Infobackground, Infotext, Menu, Menutext, Scrollbar, Threeddarkshadow, Threedface, Threedhighlight, Threedlightshadow, Threedshadow, Window, Windowframe, Windowtext, MozButtondefault, MozDefaultColor, MozDefaultBackgroundColor, MozDialog, MozDialogtext, /// Used to highlight valid regions to drop something onto. MozDragtargetzone, /// Used for selected but not focused cell backgrounds. MozCellhighlight, /// Used for selected but not focused cell text. MozCellhighlighttext, /// Used for selected but not focused html cell backgrounds. MozHtmlCellhighlight, /// Used for selected but not focused html cell text. MozHtmlCellhighlighttext, /// Used to button text background when hovered. MozButtonhoverface, /// Used to button text color when hovered. MozButtonhovertext, /// Used for menu item backgrounds when hovered. MozMenuhover, /// Used for menu item text when hovered. MozMenuhovertext, /// Used for menubar item text. MozMenubartext, /// Used for menubar item text when hovered. MozMenubarhovertext, /// On platforms where these colors are the same as -moz-field, use /// -moz-fieldtext as foreground color MozEventreerow, MozOddtreerow, /// Used for button text when pressed. #[parse(condition = "ParserContext::in_ua_or_chrome_sheet")] MozGtkButtonactivetext, /// Used for button text when pressed. MozMacButtonactivetext, /// Background color of chrome toolbars in active windows. MozMacChromeActive, /// Background color of chrome toolbars in inactive windows. MozMacChromeInactive, /// Foreground color of default buttons. MozMacDefaultbuttontext, /// Ring color around text fields and lists. MozMacFocusring, /// Color used when mouse is over a menu item. MozMacMenuselect, /// Color used to do shadows on menu items. MozMacMenushadow, /// Color used to display text for disabled menu items. MozMacMenutextdisable, /// Color used to display text while mouse is over a menu item. MozMacMenutextselect, /// Text color of disabled text on toolbars. MozMacDisabledtoolbartext, /// Inactive light hightlight MozMacSecondaryhighlight, /// Font smoothing background colors needed by the Mac OS X theme, based on /// -moz-appearance names. MozMacVibrancyLight, MozMacVibrancyDark, MozMacVibrantTitlebarLight, MozMacVibrantTitlebarDark, MozMacMenupopup, MozMacMenuitem, MozMacActiveMenuitem, MozMacSourceList, MozMacSourceListSelection, MozMacActiveSourceListSelection, MozMacTooltip, /// Accent color for title bar. MozWinAccentcolor, /// Color from drawing text over the accent color. MozWinAccentcolortext, /// Media rebar text. MozWinMediatext, /// Communications rebar text. MozWinCommunicationstext, /// Hyperlink color extracted from the system, not affected by the /// browser.anchor_color user pref. /// /// There is no OS-specified safe background color for this text, but it is /// used regularly within Windows and the Gnome DE on Dialog and Window /// colors. MozNativehyperlinktext, MozHyperlinktext, MozActivehyperlinktext, MozVisitedhyperlinktext, /// Combobox widgets MozComboboxtext, MozCombobox, MozGtkInfoBarText, #[css(skip)] End, // Just for array-indexing purposes. } #[cfg(feature = "gecko")] impl SystemColor { #[inline] fn compute(&self, cx: &Context) -> ComputedColor { use crate::gecko_bindings::bindings; let prefs = cx.device().pref_sheet_prefs(); convert_nscolor_to_computedcolor(match *self { SystemColor::MozDefaultColor => prefs.mDefaultColor, SystemColor::MozDefaultBackgroundColor => prefs.mDefaultBackgroundColor, SystemColor::MozHyperlinktext => prefs.mLinkColor, SystemColor::MozActivehyperlinktext => prefs.mActiveLinkColor, SystemColor::MozVisitedhyperlinktext => prefs.mVisitedLinkColor, _ => unsafe { bindings::Gecko_GetLookAndFeelSystemColor(*self as i32, cx.device().document()) }, }) } } impl From<RGBA> for Color { fn from(value: RGBA) -> Self { Color::rgba(value) } } struct ColorComponentParser<'a, 'b: 'a>(&'a ParserContext<'b>); impl<'a, 'b: 'a, 'i: 'a> ::cssparser::ColorComponentParser<'i> for ColorComponentParser<'a, 'b> { type Error = StyleParseErrorKind<'i>; fn parse_angle_or_number<'t>( &self, input: &mut Parser<'i, 't>, ) -> Result<AngleOrNumber, ParseError<'i>> { use crate::values::specified::Angle; let location = input.current_source_location(); let token = input.next()?.clone(); match token { Token::Dimension { value, ref unit,.. } => { let angle = Angle::parse_dimension(value, unit, /* from_calc = */ false); let degrees = match angle { Ok(angle) => angle.degrees(), Err(()) => return Err(location.new_unexpected_token_error(token.clone())), }; Ok(AngleOrNumber::Angle { degrees }) }, Token::Number { value,.. } => Ok(AngleOrNumber::Number { value }), Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { input.parse_nested_block(|i| CalcNode::parse_angle_or_number(self.0, i)) }, t => return Err(location.new_unexpected_token_error(t)), } } fn parse_percentage<'t>(&self, input: &mut Parser<'i, 't>) -> Result<f32, ParseError<'i>> { use crate::values::specified::Percentage; Ok(Percentage::parse(self.0, input)?.get()) } fn parse_number<'t>(&self, input: &mut Parser<'i, 't>) -> Result<f32, ParseError<'i>> { use crate::values::specified::Number; Ok(Number::parse(self.0, input)?.get()) } fn parse_number_or_percentage<'t>( &self, input: &mut Parser<'i, 't>, ) -> Result<NumberOrPercentage, ParseError<'i>> { let location = input.current_source_location(); match input.next()?.clone() { Token::Number { value,.. } => Ok(NumberOrPercentage::Number { value }), Token::Percentage { unit_value,.. } => { Ok(NumberOrPercentage::Percentage { unit_value }) }, Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { input.parse_nested_block(|i| CalcNode::parse_number_or_percentage(self.0, i)) }, t => return Err(location.new_unexpected_token_error(t)), } } } impl Parse for Color { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { // Currently we only store authored value for color keywords, // because all browsers serialize those values as keywords for // specified value. let start = input.state(); let authored = input.expect_ident_cloned().ok(); input.reset(&start); let compontent_parser = ColorComponentParser(&*context); match input.try(|i| CSSParserColor::parse_with(&compontent_parser, i)) { Ok(value) => Ok(match value { CSSParserColor::CurrentColor => Color::CurrentColor, CSSParserColor::RGBA(rgba) => Color::Numeric { parsed: rgba, authored: authored.map(|s| s.to_ascii_lowercase().into_boxed_str()), }, }), Err(e) => { #[cfg(feature = "gecko")] { if let Ok(system) = input.try(|i| SystemColor::parse(context, i)) { return Ok(Color::System(system)); } } match e.kind { ParseErrorKind::Basic(BasicParseErrorKind::UnexpectedToken(t)) => { Err(e.location.new_custom_error(StyleParseErrorKind::ValueError( ValueParseErrorKind::InvalidColor(t), ))) }, _ => Err(e), } }, } } } impl ToCss for Color { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { match *self { Color::CurrentColor => CSSParserColor::CurrentColor.to_css(dest), Color::Numeric { authored: Some(ref authored), .. } => dest.write_str(authored), Color::Numeric { parsed: ref rgba,.. } => rgba.to_css(dest), Color::Complex(_) => Ok(()), #[cfg(feature = "gecko")] Color::System(system) => system.to_css(dest), #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => Ok(()), } } } /// A wrapper of cssparser::Color::parse_hash. /// /// That function should never return CurrentColor, so it makes no sense to /// handle a cssparser::Color here. This should really be done in cssparser /// directly rather than here. fn parse_hash_color(value: &[u8]) -> Result<RGBA, ()> { CSSParserColor::parse_hash(value).map(|color| match color { CSSParserColor::RGBA(rgba) => rgba, CSSParserColor::CurrentColor => unreachable!("parse_hash should never return currentcolor"), }) } impl Color { /// Returns currentcolor value. #[inline] pub fn currentcolor() -> Color { Color::CurrentColor } /// Returns transparent value. #[inline] pub fn transparent() -> Color { // We should probably set authored to "transparent", but maybe it doesn't matter. Color::rgba(RGBA::transparent()) } /// Returns a numeric RGBA color value. #[inline] pub fn rgba(rgba: RGBA) -> Self { Color::Numeric { parsed: rgba, authored: None, } } /// Parse a color, with quirks. /// /// <https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk> pub fn parse_quirky<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, allow_quirks: AllowQuirks, ) -> Result<Self, ParseError<'i>> { input.try(|i| Self::parse(context, i)).or_else(|e| { if!allow_quirks.allowed(context.quirks_mode) { return Err(e); } Color::parse_quirky_color(input) .map(Color::rgba) .map_err(|_| e) }) } /// Parse a <quirky-color> value. /// /// <https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk> fn parse_quirky_color<'i, 't>(input: &mut Parser<'i, 't>) -> Result<RGBA, ParseError<'i>> { let location = input.current_source_location(); let (value, unit) = match *input.next()? { Token::Number { int_value: Some(integer), .. } => (integer, None), Token::Dimension { int_value: Some(integer), ref unit, .. } => (integer, Some(unit)), Token::Ident(ref ident) => { if ident.len()!= 3 && ident.len()!= 6 { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } return parse_hash_color(ident.as_bytes()).map_err(|()| { location.new_custom_error(StyleParseErrorKind::UnspecifiedError) }); }, ref t => { return Err(location.new_unexpected_token_error(t.clone())); }, }; if value < 0 { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } let length = if value <= 9 { 1 } else if value <= 99 { 2 } else if value <= 999 { 3 } else if value <= 9999 { 4 } else if value <= 99999 { 5 } else if value <= 999999 { 6 } else { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); }; let total = length + unit.as_ref().map_or(0, |d| d.len()); if total > 6 { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } let mut serialization = [b'0'; 6]; let space_padding = 6 - total; let mut written = space_padding; written += itoa::write(&mut serialization[written..], value).unwrap(); if let Some(unit) = unit { written += (&mut serialization[written..]) .write(unit.as_bytes()) .unwrap(); } debug_assert_eq!(written, 6); parse_hash_color(&serialization) .map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } /// Returns true if the color is completely transparent, and false /// otherwise. pub fn is_transparent(&self) -> bool { match *self { Color::Numeric { ref parsed,.. } => parsed.alpha == 0, _ => false, } } } #[cfg(feature = "gecko")] fn convert_nscolor_to_computedcolor(color: nscolor) -> ComputedColor { use crate::gecko::values::convert_nscolor_to_rgba; ComputedColor::rgba(convert_nscolor_to_rgba(color)) } impl Color { /// Converts this Color into a ComputedColor. /// /// If `context` is `None`, and the specified color requires data from /// the context to resolve, then `None` is returned. pub fn to_computed_color(&self, _context: Option<&Context>) -> Option<ComputedColor> { Some(match *self { Color::CurrentColor => ComputedColor::currentcolor(), Color::Numeric { ref parsed,.. } => ComputedColor::rgba(*parsed), Color::Complex(ref complex) => *complex, #[cfg(feature = "gecko")] Color::System(system) => system.compute(_context?), #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => { ComputedColor::rgba(_context?.device().body_text_color()) }, }) } } impl ToComputedValue for Color { type ComputedValue = ComputedColor; fn to_computed_value(&self, context: &Context) -> ComputedColor { self.to_computed_color(Some(context)).unwrap() } fn from_computed_value(computed: &ComputedColor) -> Self { match *computed { GenericColor::Numeric(color) => Color::rgba(color), GenericColor::CurrentColor => Color::currentcolor(), GenericColor::Complex {.. } => Color::Complex(*computed), } } } /// Specified color value for `-moz-font-smoothing-background-color`. /// /// This property does not support `currentcolor`. We could drop it at /// parse-time, but it's not exposed to the web so it doesn't really matter. /// /// We resolve it to `transparent` instead. #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] pub struct MozFontSmoothingBackgroundColor(pub Color); impl Parse for MozFontSmoothingBackgroundColor { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { Color::parse(context, input).map(MozFontSmoothingBackgroundColor) } } impl ToComputedValue for MozFontSmoothingBackgroundColor { type ComputedValue = RGBA; fn to_computed_value(&self, context: &Context) -> RGBA { self.0 .to_computed_value(context) .to_rgba(RGBA::transparent()) } fn from_computed_value(computed: &RGBA) -> Self { MozFontSmoothingBackgroundColor(Color::rgba(*computed)) } } impl SpecifiedValueInfo for Color { const SUPPORTED_TYPES: u8 = CssType::COLOR; fn collect_completion_keywords(f: KeywordsCollectFn) { // We are not going to insert all the color names here. Caller and // devtools should take care of them. XXX Actually, transparent // should probably be handled that way as well. // XXX `currentColor` should really be `currentcolor`. But let's // keep it consistent with the old system for now. f(&["rgb", "rgba", "hsl", "hsla", "currentColor", "transparent"]); } } /// Specified value for the "color" property, which resolves the `currentcolor` /// keyword to the parent color instead of self's color. #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[derive(Clone, Debug, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] pub struct ColorPropertyValue(pub Color); impl ToComputedValue for Color
#[css(skip)] TextSelectForegroundCustom, #[css(skip)] TextSelectBackgroundDisabled, #[css(skip)]
random_line_split
num.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. //! Integer and floating-point number formatting // FIXME: #6220 Implement floating point formatting #![allow(unsigned_negate)] use collections::Collection; use fmt; use iter::DoubleEndedIterator; use num::{Int, cast, zero}; use slice::{ImmutableSlice, MutableSlice}; /// A type that represents a specific radix #[doc(hidden)] trait GenericRadix { /// The number of digits. fn base(&self) -> u8; /// A radix-specific prefix string. fn prefix(&self) -> &'static str { "" } /// Converts an integer to corresponding radix digit. fn digit(&self, x: u8) -> u8; /// Format an integer using the radix using a formatter. fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result { // The radix can be as low as 2, so we need a buffer of at least 64 // characters for a base 2 number. let mut buf = [0u8,..64]; let base = cast(self.base()).unwrap(); let mut curr = buf.len(); let is_positive = x >= zero(); if is_positive { // Accumulate each digit of the number from the least significant // to the most significant figure. for byte in buf.iter_mut().rev() { let n = x % base; // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero() { break; } // No more digits left to accumulate. } } else { // Do the same as above, but accounting for two's complement. for byte in buf.iter_mut().rev() { let n = -(x % base); // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero() { break; } // No more digits left to accumulate. } } f.pad_integral(is_positive, self.prefix(), buf.slice_from(curr)) } } /// A binary (base 2) radix #[deriving(Clone, PartialEq)] struct Binary; /// An octal (base 8) radix #[deriving(Clone, PartialEq)] struct Octal; /// A decimal (base 10) radix #[deriving(Clone, PartialEq)] struct Decimal; /// A hexadecimal (base 16) radix, formatted with lower-case characters #[deriving(Clone, PartialEq)] struct LowerHex; /// A hexadecimal (base 16) radix, formatted with upper-case characters #[deriving(Clone, PartialEq)] pub struct UpperHex; macro_rules! radix { ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => { impl GenericRadix for $T { fn base(&self) -> u8 { $base } fn prefix(&self) -> &'static str { $prefix } fn digit(&self, x: u8) -> u8 { match x { $($x => $conv,)+ x => fail!("number not in the range 0..{}: {}", self.base() - 1, x), } } } } } radix!(Binary, 2, "0b", x @ 0.. 2 => b'0' + x) radix!(Octal, 8, "0o", x @ 0.. 7 => b'0' + x) radix!(Decimal, 10, "", x @ 0.. 9 => b'0' + x) radix!(LowerHex, 16, "0x", x @ 0.. 9 => b'0' + x, x @ 10..15 => b'a' + (x - 10)) radix!(UpperHex, 16, "0x", x @ 0.. 9 => b'0' + x, x @ 10..15 => b'A' + (x - 10)) /// A radix with in the range of `2..36`. #[deriving(Clone, PartialEq)] pub struct Radix { base: u8, } impl Radix { fn new(base: u8) -> Radix { assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base); Radix { base: base } } } impl GenericRadix for Radix { fn base(&self) -> u8 { self.base } fn digit(&self, x: u8) -> u8 { match x { x @ 0..9 => b'0' + x, x if x < self.base() => b'a' + (x - 10), x => fail!("number not in the range 0..{}: {}", self.base() - 1, x), } } } /// A helper type for formatting radixes. pub struct RadixFmt<T, R>(T, R); /// Constructs a radix formatter in the range of `2..36`. /// /// # Example /// /// ``` /// use std::fmt::radix; /// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string()); /// ``` pub fn
<T>(x: T, base: u8) -> RadixFmt<T, Radix> { RadixFmt(x, Radix::new(base)) } macro_rules! radix_fmt { ($T:ty as $U:ty, $fmt:ident) => { impl fmt::Show for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) } } } } } macro_rules! int_base { ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => { impl fmt::$Trait for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { $Radix.fmt_int(*self as $U, f) } } } } macro_rules! integer { ($Int:ident, $Uint:ident) => { int_base!(Show for $Int as $Int -> Decimal) int_base!(Signed for $Int as $Int -> Decimal) int_base!(Binary for $Int as $Uint -> Binary) int_base!(Octal for $Int as $Uint -> Octal) int_base!(LowerHex for $Int as $Uint -> LowerHex) int_base!(UpperHex for $Int as $Uint -> UpperHex) radix_fmt!($Int as $Int, fmt_int) int_base!(Show for $Uint as $Uint -> Decimal) int_base!(Unsigned for $Uint as $Uint -> Decimal) int_base!(Binary for $Uint as $Uint -> Binary) int_base!(Octal for $Uint as $Uint -> Octal) int_base!(LowerHex for $Uint as $Uint -> LowerHex) int_base!(UpperHex for $Uint as $Uint -> UpperHex) radix_fmt!($Uint as $Uint, fmt_int) } } integer!(int, uint) integer!(i8, u8) integer!(i16, u16) integer!(i32, u32) integer!(i64, u64)
radix
identifier_name
num.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. //! Integer and floating-point number formatting // FIXME: #6220 Implement floating point formatting #![allow(unsigned_negate)] use collections::Collection; use fmt; use iter::DoubleEndedIterator; use num::{Int, cast, zero}; use slice::{ImmutableSlice, MutableSlice}; /// A type that represents a specific radix #[doc(hidden)] trait GenericRadix { /// The number of digits. fn base(&self) -> u8; /// A radix-specific prefix string. fn prefix(&self) -> &'static str { "" } /// Converts an integer to corresponding radix digit. fn digit(&self, x: u8) -> u8; /// Format an integer using the radix using a formatter. fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result { // The radix can be as low as 2, so we need a buffer of at least 64 // characters for a base 2 number. let mut buf = [0u8,..64]; let base = cast(self.base()).unwrap(); let mut curr = buf.len(); let is_positive = x >= zero(); if is_positive { // Accumulate each digit of the number from the least significant // to the most significant figure. for byte in buf.iter_mut().rev() { let n = x % base; // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero() { break; } // No more digits left to accumulate. } } else
f.pad_integral(is_positive, self.prefix(), buf.slice_from(curr)) } } /// A binary (base 2) radix #[deriving(Clone, PartialEq)] struct Binary; /// An octal (base 8) radix #[deriving(Clone, PartialEq)] struct Octal; /// A decimal (base 10) radix #[deriving(Clone, PartialEq)] struct Decimal; /// A hexadecimal (base 16) radix, formatted with lower-case characters #[deriving(Clone, PartialEq)] struct LowerHex; /// A hexadecimal (base 16) radix, formatted with upper-case characters #[deriving(Clone, PartialEq)] pub struct UpperHex; macro_rules! radix { ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => { impl GenericRadix for $T { fn base(&self) -> u8 { $base } fn prefix(&self) -> &'static str { $prefix } fn digit(&self, x: u8) -> u8 { match x { $($x => $conv,)+ x => fail!("number not in the range 0..{}: {}", self.base() - 1, x), } } } } } radix!(Binary, 2, "0b", x @ 0.. 2 => b'0' + x) radix!(Octal, 8, "0o", x @ 0.. 7 => b'0' + x) radix!(Decimal, 10, "", x @ 0.. 9 => b'0' + x) radix!(LowerHex, 16, "0x", x @ 0.. 9 => b'0' + x, x @ 10..15 => b'a' + (x - 10)) radix!(UpperHex, 16, "0x", x @ 0.. 9 => b'0' + x, x @ 10..15 => b'A' + (x - 10)) /// A radix with in the range of `2..36`. #[deriving(Clone, PartialEq)] pub struct Radix { base: u8, } impl Radix { fn new(base: u8) -> Radix { assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base); Radix { base: base } } } impl GenericRadix for Radix { fn base(&self) -> u8 { self.base } fn digit(&self, x: u8) -> u8 { match x { x @ 0..9 => b'0' + x, x if x < self.base() => b'a' + (x - 10), x => fail!("number not in the range 0..{}: {}", self.base() - 1, x), } } } /// A helper type for formatting radixes. pub struct RadixFmt<T, R>(T, R); /// Constructs a radix formatter in the range of `2..36`. /// /// # Example /// /// ``` /// use std::fmt::radix; /// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string()); /// ``` pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> { RadixFmt(x, Radix::new(base)) } macro_rules! radix_fmt { ($T:ty as $U:ty, $fmt:ident) => { impl fmt::Show for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) } } } } } macro_rules! int_base { ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => { impl fmt::$Trait for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { $Radix.fmt_int(*self as $U, f) } } } } macro_rules! integer { ($Int:ident, $Uint:ident) => { int_base!(Show for $Int as $Int -> Decimal) int_base!(Signed for $Int as $Int -> Decimal) int_base!(Binary for $Int as $Uint -> Binary) int_base!(Octal for $Int as $Uint -> Octal) int_base!(LowerHex for $Int as $Uint -> LowerHex) int_base!(UpperHex for $Int as $Uint -> UpperHex) radix_fmt!($Int as $Int, fmt_int) int_base!(Show for $Uint as $Uint -> Decimal) int_base!(Unsigned for $Uint as $Uint -> Decimal) int_base!(Binary for $Uint as $Uint -> Binary) int_base!(Octal for $Uint as $Uint -> Octal) int_base!(LowerHex for $Uint as $Uint -> LowerHex) int_base!(UpperHex for $Uint as $Uint -> UpperHex) radix_fmt!($Uint as $Uint, fmt_int) } } integer!(int, uint) integer!(i8, u8) integer!(i16, u16) integer!(i32, u32) integer!(i64, u64)
{ // Do the same as above, but accounting for two's complement. for byte in buf.iter_mut().rev() { let n = -(x % base); // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero() { break; } // No more digits left to accumulate. } }
conditional_block
num.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. //! Integer and floating-point number formatting // FIXME: #6220 Implement floating point formatting #![allow(unsigned_negate)] use collections::Collection; use fmt; use iter::DoubleEndedIterator; use num::{Int, cast, zero}; use slice::{ImmutableSlice, MutableSlice}; /// A type that represents a specific radix #[doc(hidden)] trait GenericRadix { /// The number of digits. fn base(&self) -> u8; /// A radix-specific prefix string. fn prefix(&self) -> &'static str { "" } /// Converts an integer to corresponding radix digit. fn digit(&self, x: u8) -> u8; /// Format an integer using the radix using a formatter. fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result { // The radix can be as low as 2, so we need a buffer of at least 64 // characters for a base 2 number. let mut buf = [0u8,..64]; let base = cast(self.base()).unwrap(); let mut curr = buf.len(); let is_positive = x >= zero(); if is_positive { // Accumulate each digit of the number from the least significant // to the most significant figure. for byte in buf.iter_mut().rev() { let n = x % base; // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero() { break; } // No more digits left to accumulate. } } else { // Do the same as above, but accounting for two's complement. for byte in buf.iter_mut().rev() { let n = -(x % base); // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero() { break; } // No more digits left to accumulate. } } f.pad_integral(is_positive, self.prefix(), buf.slice_from(curr))
} } /// A binary (base 2) radix #[deriving(Clone, PartialEq)] struct Binary; /// An octal (base 8) radix #[deriving(Clone, PartialEq)] struct Octal; /// A decimal (base 10) radix #[deriving(Clone, PartialEq)] struct Decimal; /// A hexadecimal (base 16) radix, formatted with lower-case characters #[deriving(Clone, PartialEq)] struct LowerHex; /// A hexadecimal (base 16) radix, formatted with upper-case characters #[deriving(Clone, PartialEq)] pub struct UpperHex; macro_rules! radix { ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => { impl GenericRadix for $T { fn base(&self) -> u8 { $base } fn prefix(&self) -> &'static str { $prefix } fn digit(&self, x: u8) -> u8 { match x { $($x => $conv,)+ x => fail!("number not in the range 0..{}: {}", self.base() - 1, x), } } } } } radix!(Binary, 2, "0b", x @ 0.. 2 => b'0' + x) radix!(Octal, 8, "0o", x @ 0.. 7 => b'0' + x) radix!(Decimal, 10, "", x @ 0.. 9 => b'0' + x) radix!(LowerHex, 16, "0x", x @ 0.. 9 => b'0' + x, x @ 10..15 => b'a' + (x - 10)) radix!(UpperHex, 16, "0x", x @ 0.. 9 => b'0' + x, x @ 10..15 => b'A' + (x - 10)) /// A radix with in the range of `2..36`. #[deriving(Clone, PartialEq)] pub struct Radix { base: u8, } impl Radix { fn new(base: u8) -> Radix { assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base); Radix { base: base } } } impl GenericRadix for Radix { fn base(&self) -> u8 { self.base } fn digit(&self, x: u8) -> u8 { match x { x @ 0..9 => b'0' + x, x if x < self.base() => b'a' + (x - 10), x => fail!("number not in the range 0..{}: {}", self.base() - 1, x), } } } /// A helper type for formatting radixes. pub struct RadixFmt<T, R>(T, R); /// Constructs a radix formatter in the range of `2..36`. /// /// # Example /// /// ``` /// use std::fmt::radix; /// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string()); /// ``` pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> { RadixFmt(x, Radix::new(base)) } macro_rules! radix_fmt { ($T:ty as $U:ty, $fmt:ident) => { impl fmt::Show for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) } } } } } macro_rules! int_base { ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => { impl fmt::$Trait for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { $Radix.fmt_int(*self as $U, f) } } } } macro_rules! integer { ($Int:ident, $Uint:ident) => { int_base!(Show for $Int as $Int -> Decimal) int_base!(Signed for $Int as $Int -> Decimal) int_base!(Binary for $Int as $Uint -> Binary) int_base!(Octal for $Int as $Uint -> Octal) int_base!(LowerHex for $Int as $Uint -> LowerHex) int_base!(UpperHex for $Int as $Uint -> UpperHex) radix_fmt!($Int as $Int, fmt_int) int_base!(Show for $Uint as $Uint -> Decimal) int_base!(Unsigned for $Uint as $Uint -> Decimal) int_base!(Binary for $Uint as $Uint -> Binary) int_base!(Octal for $Uint as $Uint -> Octal) int_base!(LowerHex for $Uint as $Uint -> LowerHex) int_base!(UpperHex for $Uint as $Uint -> UpperHex) radix_fmt!($Uint as $Uint, fmt_int) } } integer!(int, uint) integer!(i8, u8) integer!(i16, u16) integer!(i32, u32) integer!(i64, u64)
random_line_split
stats.rs
use std::default::Default; use std::ops::{Add}; /// Stats specifies static bonuses for an entity. Stats values can be added /// together to build composites. The Default value for Stats must be an /// algebraic zero element, adding it to any Stats value must leave that value
/// Attack bonus pub attack: i32, /// Damage reduction pub protection: i32, /// Mana pool / mana drain pub mana: i32, /// Ranged attack range. Zero means no ranged capability. pub ranged_range: u32, /// Ranged attack power pub ranged_power: i32, /// Bit flags for intrinsics pub intrinsics: u32, } impl Stats { pub fn new(power: i32, intrinsics: &[Intrinsic]) -> Stats { let mut intr = 0u32; for &i in intrinsics.iter() { intr = intr | (i as u32); } Stats { power: power, intrinsics: intr, .. Default::default() } } pub fn mana(self, mana: i32) -> Stats { Stats { mana: mana,.. self } } pub fn protection(self, protection: i32) -> Stats { Stats { protection: protection,.. self } } pub fn attack(self, attack: i32) -> Stats { Stats { attack: attack,.. self } } pub fn ranged_range(self, ranged_range: u32) -> Stats { Stats { ranged_range: ranged_range,.. self } } pub fn ranged_power(self, ranged_power: i32) -> Stats { Stats { ranged_power: ranged_power,.. self } } } impl Add<Stats> for Stats { type Output = Stats; fn add(self, other: Stats) -> Stats { Stats { power: self.power + other.power, attack: self.attack + other.attack, protection: self.protection + other.protection, mana: self.mana + other.mana, // XXX: Must be careful to have exactly one "ranged weapon" item // in the mix. A mob with a natural ranged attack equipping a // ranged weapon should *not* have the ranges added together. // On the other hand a "sniper scope" trinket could be a +2 range // type dealie. ranged_range: self.ranged_range + other.ranged_range, ranged_power: self.ranged_power + other.ranged_power, intrinsics: self.intrinsics | other.intrinsics, } } } #[derive(Copy, Eq, PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)] pub enum Intrinsic { /// Moves 1/3 slower than usual. Slow = 0b1, /// Moves 1/3 faster than usual, stacks with Quick status. Fast = 0b10, /// Moves 1/3 faster than usual, stacks with Fast status. Quick = 0b100, /// Can manipulate objects and doors. Hands = 0b1000, /// Is dead Dead = 0b10000, /// Inorganic, phage can't use corpse Robotic = 0b100000, }
/// unchanged. #[derive(Copy, Clone, Debug, Default, RustcEncodable, RustcDecodable)] pub struct Stats { /// Generic power level pub power: i32,
random_line_split
stats.rs
use std::default::Default; use std::ops::{Add}; /// Stats specifies static bonuses for an entity. Stats values can be added /// together to build composites. The Default value for Stats must be an /// algebraic zero element, adding it to any Stats value must leave that value /// unchanged. #[derive(Copy, Clone, Debug, Default, RustcEncodable, RustcDecodable)] pub struct
{ /// Generic power level pub power: i32, /// Attack bonus pub attack: i32, /// Damage reduction pub protection: i32, /// Mana pool / mana drain pub mana: i32, /// Ranged attack range. Zero means no ranged capability. pub ranged_range: u32, /// Ranged attack power pub ranged_power: i32, /// Bit flags for intrinsics pub intrinsics: u32, } impl Stats { pub fn new(power: i32, intrinsics: &[Intrinsic]) -> Stats { let mut intr = 0u32; for &i in intrinsics.iter() { intr = intr | (i as u32); } Stats { power: power, intrinsics: intr, .. Default::default() } } pub fn mana(self, mana: i32) -> Stats { Stats { mana: mana,.. self } } pub fn protection(self, protection: i32) -> Stats { Stats { protection: protection,.. self } } pub fn attack(self, attack: i32) -> Stats { Stats { attack: attack,.. self } } pub fn ranged_range(self, ranged_range: u32) -> Stats { Stats { ranged_range: ranged_range,.. self } } pub fn ranged_power(self, ranged_power: i32) -> Stats { Stats { ranged_power: ranged_power,.. self } } } impl Add<Stats> for Stats { type Output = Stats; fn add(self, other: Stats) -> Stats { Stats { power: self.power + other.power, attack: self.attack + other.attack, protection: self.protection + other.protection, mana: self.mana + other.mana, // XXX: Must be careful to have exactly one "ranged weapon" item // in the mix. A mob with a natural ranged attack equipping a // ranged weapon should *not* have the ranges added together. // On the other hand a "sniper scope" trinket could be a +2 range // type dealie. ranged_range: self.ranged_range + other.ranged_range, ranged_power: self.ranged_power + other.ranged_power, intrinsics: self.intrinsics | other.intrinsics, } } } #[derive(Copy, Eq, PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)] pub enum Intrinsic { /// Moves 1/3 slower than usual. Slow = 0b1, /// Moves 1/3 faster than usual, stacks with Quick status. Fast = 0b10, /// Moves 1/3 faster than usual, stacks with Fast status. Quick = 0b100, /// Can manipulate objects and doors. Hands = 0b1000, /// Is dead Dead = 0b10000, /// Inorganic, phage can't use corpse Robotic = 0b100000, }
Stats
identifier_name
stats.rs
use std::default::Default; use std::ops::{Add}; /// Stats specifies static bonuses for an entity. Stats values can be added /// together to build composites. The Default value for Stats must be an /// algebraic zero element, adding it to any Stats value must leave that value /// unchanged. #[derive(Copy, Clone, Debug, Default, RustcEncodable, RustcDecodable)] pub struct Stats { /// Generic power level pub power: i32, /// Attack bonus pub attack: i32, /// Damage reduction pub protection: i32, /// Mana pool / mana drain pub mana: i32, /// Ranged attack range. Zero means no ranged capability. pub ranged_range: u32, /// Ranged attack power pub ranged_power: i32, /// Bit flags for intrinsics pub intrinsics: u32, } impl Stats { pub fn new(power: i32, intrinsics: &[Intrinsic]) -> Stats { let mut intr = 0u32; for &i in intrinsics.iter() { intr = intr | (i as u32); } Stats { power: power, intrinsics: intr, .. Default::default() } } pub fn mana(self, mana: i32) -> Stats { Stats { mana: mana,.. self } } pub fn protection(self, protection: i32) -> Stats { Stats { protection: protection,.. self } } pub fn attack(self, attack: i32) -> Stats
pub fn ranged_range(self, ranged_range: u32) -> Stats { Stats { ranged_range: ranged_range,.. self } } pub fn ranged_power(self, ranged_power: i32) -> Stats { Stats { ranged_power: ranged_power,.. self } } } impl Add<Stats> for Stats { type Output = Stats; fn add(self, other: Stats) -> Stats { Stats { power: self.power + other.power, attack: self.attack + other.attack, protection: self.protection + other.protection, mana: self.mana + other.mana, // XXX: Must be careful to have exactly one "ranged weapon" item // in the mix. A mob with a natural ranged attack equipping a // ranged weapon should *not* have the ranges added together. // On the other hand a "sniper scope" trinket could be a +2 range // type dealie. ranged_range: self.ranged_range + other.ranged_range, ranged_power: self.ranged_power + other.ranged_power, intrinsics: self.intrinsics | other.intrinsics, } } } #[derive(Copy, Eq, PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)] pub enum Intrinsic { /// Moves 1/3 slower than usual. Slow = 0b1, /// Moves 1/3 faster than usual, stacks with Quick status. Fast = 0b10, /// Moves 1/3 faster than usual, stacks with Fast status. Quick = 0b100, /// Can manipulate objects and doors. Hands = 0b1000, /// Is dead Dead = 0b10000, /// Inorganic, phage can't use corpse Robotic = 0b100000, }
{ Stats { attack: attack, .. self } }
identifier_body
test.rs
extern crate immeta; use immeta::Dimensions; use immeta::formats::{png, gif, jpeg}; use immeta::markers::{Png, Gif, Jpeg, Webp}; const OWLET_DIM: Dimensions = Dimensions { width: 1280, height: 857 }; const DROP_DIM: Dimensions = Dimensions { width: 238, height: 212 }; const CHERRY_DIM: Dimensions = Dimensions { width: 1024, height: 772 }; #[test] fn test_jpeg() { let md = immeta::load_from_file("tests/images/owlet.jpg").unwrap(); assert_eq!(md.mime_type(), "image/jpeg"); assert_eq!(md.dimensions(), OWLET_DIM); // let md = Jpeg::from(md).ok() let md = md.into::<Jpeg>().ok().expect("not JPEG metadata"); assert_eq!(md.dimensions, OWLET_DIM); assert_eq!(md.sample_precision, 8); assert_eq!(md.coding_process, jpeg::CodingProcess::DctSequential); assert_eq!(md.entropy_coding, jpeg::EntropyCoding::Huffman); assert!(md.baseline); assert!(!md.differential); } #[test] fn test_png() { let md = immeta::load_from_file("tests/images/owlet.png").unwrap(); assert_eq!(md.mime_type(), "image/png"); assert_eq!(md.dimensions(), OWLET_DIM); let md = md.into::<Png>().ok().expect("not PNG metadata"); assert_eq!(md.dimensions, OWLET_DIM); assert_eq!(md.color_type, png::ColorType::Rgb); assert_eq!(md.color_depth, 24); assert_eq!(md.compression_method, png::CompressionMethod::DeflateInflate); assert_eq!(md.filter_method, png::FilterMethod::AdaptiveFiltering); assert_eq!(md.interlace_method, png::InterlaceMethod::Disabled); } #[test] fn test_gif_plain() { let md = immeta::load_from_file("tests/images/owlet.gif").unwrap(); assert_eq!(md.mime_type(), "image/gif"); assert_eq!(md.dimensions(), OWLET_DIM); let md = md.into::<Gif>().ok().expect("not GIF metadata"); assert_eq!(md.version, gif::Version::V89a); assert_eq!(md.dimensions, OWLET_DIM); assert_eq!(md.global_color_table, Some(gif::ColorTable { size: 256, sorted: false })); assert_eq!(md.color_resolution, 256); assert_eq!(md.background_color_index, 0); assert_eq!(md.pixel_aspect_ratio, 0); assert_eq!(md.frames_number(), 1); assert_eq!(md.is_animated(), false); assert_eq!(md.blocks, vec![ gif::Block::GraphicControlExtension(gif::GraphicControlExtension { disposal_method: gif::DisposalMethod::None, user_input: false, transparent_color_index: None, delay_time: 0 }), gif::Block::ApplicationExtension(gif::ApplicationExtension { application_identifier: *b"ImageMag", authentication_code: *b"ick" }), gif::Block::ImageDescriptor(gif::ImageDescriptor { left: 0, top: 0, width: 1280, height: 857, local_color_table: None, interlace: false }) ]) } #[test] fn test_gif_animated()
assert_eq!( blocks.next().unwrap(), &gif::Block::ApplicationExtension(gif::ApplicationExtension { application_identifier: *b"NETSCAPE", authentication_code: *b"2.0" }) ); assert_eq!( blocks.next().unwrap(), &gif::Block::CommentExtension(gif::CommentExtension) ); for i in 0..30 { match blocks.next() { Some(&gif::Block::GraphicControlExtension(ref gce)) => { assert_eq!( gce, &gif::GraphicControlExtension { disposal_method: if i == 29 { gif::DisposalMethod::None } else { gif::DisposalMethod::DoNotDispose }, user_input: false, transparent_color_index: Some(255), delay_time: 7 } ); assert_eq!(gce.delay_time_ms(), 70); } _ => panic!("Invalid block") } assert_eq!( blocks.next().unwrap(), &gif::Block::ImageDescriptor(gif::ImageDescriptor { left: 0, top: 0, width: 238, height: 212, local_color_table: None, interlace: false }) ); } assert!(blocks.next().is_none()); } #[test] fn test_webp() { let md = immeta::load_from_file("tests/images/cherry.webp").unwrap(); assert_eq!(md.mime_type(), "image/webp"); assert_eq!(md.dimensions(), CHERRY_DIM); let md = md.into::<Webp>().ok().expect("not WEBP metadata"); println!("{:?}", md); }
{ let md = immeta::load_from_file("tests/images/drop.gif").unwrap(); assert_eq!(md.mime_type(), "image/gif"); assert_eq!(md.dimensions(), DROP_DIM); let md = md.into::<Gif>().ok().expect("not GIF metadata"); assert_eq!(md.version, gif::Version::V89a); assert_eq!(md.dimensions, DROP_DIM); assert_eq!(md.global_color_table, Some(gif::ColorTable { size: 256, sorted: false })); assert_eq!(md.color_resolution, 128); assert_eq!(md.background_color_index, 255); assert_eq!(md.pixel_aspect_ratio, 0); assert_eq!(md.frames_number(), 30); assert_eq!(md.is_animated(), true); let mut blocks = md.blocks.iter();
identifier_body
test.rs
extern crate immeta; use immeta::Dimensions; use immeta::formats::{png, gif, jpeg}; use immeta::markers::{Png, Gif, Jpeg, Webp}; const OWLET_DIM: Dimensions = Dimensions { width: 1280, height: 857 }; const DROP_DIM: Dimensions = Dimensions { width: 238, height: 212 }; const CHERRY_DIM: Dimensions = Dimensions { width: 1024, height: 772 }; #[test] fn test_jpeg() { let md = immeta::load_from_file("tests/images/owlet.jpg").unwrap(); assert_eq!(md.mime_type(), "image/jpeg"); assert_eq!(md.dimensions(), OWLET_DIM); // let md = Jpeg::from(md).ok() let md = md.into::<Jpeg>().ok().expect("not JPEG metadata"); assert_eq!(md.dimensions, OWLET_DIM); assert_eq!(md.sample_precision, 8); assert_eq!(md.coding_process, jpeg::CodingProcess::DctSequential); assert_eq!(md.entropy_coding, jpeg::EntropyCoding::Huffman); assert!(md.baseline); assert!(!md.differential); } #[test] fn test_png() { let md = immeta::load_from_file("tests/images/owlet.png").unwrap(); assert_eq!(md.mime_type(), "image/png"); assert_eq!(md.dimensions(), OWLET_DIM); let md = md.into::<Png>().ok().expect("not PNG metadata"); assert_eq!(md.dimensions, OWLET_DIM); assert_eq!(md.color_type, png::ColorType::Rgb); assert_eq!(md.color_depth, 24); assert_eq!(md.compression_method, png::CompressionMethod::DeflateInflate); assert_eq!(md.filter_method, png::FilterMethod::AdaptiveFiltering); assert_eq!(md.interlace_method, png::InterlaceMethod::Disabled); } #[test] fn test_gif_plain() { let md = immeta::load_from_file("tests/images/owlet.gif").unwrap();
assert_eq!(md.mime_type(), "image/gif"); assert_eq!(md.dimensions(), OWLET_DIM); let md = md.into::<Gif>().ok().expect("not GIF metadata"); assert_eq!(md.version, gif::Version::V89a); assert_eq!(md.dimensions, OWLET_DIM); assert_eq!(md.global_color_table, Some(gif::ColorTable { size: 256, sorted: false })); assert_eq!(md.color_resolution, 256); assert_eq!(md.background_color_index, 0); assert_eq!(md.pixel_aspect_ratio, 0); assert_eq!(md.frames_number(), 1); assert_eq!(md.is_animated(), false); assert_eq!(md.blocks, vec![ gif::Block::GraphicControlExtension(gif::GraphicControlExtension { disposal_method: gif::DisposalMethod::None, user_input: false, transparent_color_index: None, delay_time: 0 }), gif::Block::ApplicationExtension(gif::ApplicationExtension { application_identifier: *b"ImageMag", authentication_code: *b"ick" }), gif::Block::ImageDescriptor(gif::ImageDescriptor { left: 0, top: 0, width: 1280, height: 857, local_color_table: None, interlace: false }) ]) } #[test] fn test_gif_animated() { let md = immeta::load_from_file("tests/images/drop.gif").unwrap(); assert_eq!(md.mime_type(), "image/gif"); assert_eq!(md.dimensions(), DROP_DIM); let md = md.into::<Gif>().ok().expect("not GIF metadata"); assert_eq!(md.version, gif::Version::V89a); assert_eq!(md.dimensions, DROP_DIM); assert_eq!(md.global_color_table, Some(gif::ColorTable { size: 256, sorted: false })); assert_eq!(md.color_resolution, 128); assert_eq!(md.background_color_index, 255); assert_eq!(md.pixel_aspect_ratio, 0); assert_eq!(md.frames_number(), 30); assert_eq!(md.is_animated(), true); let mut blocks = md.blocks.iter(); assert_eq!( blocks.next().unwrap(), &gif::Block::ApplicationExtension(gif::ApplicationExtension { application_identifier: *b"NETSCAPE", authentication_code: *b"2.0" }) ); assert_eq!( blocks.next().unwrap(), &gif::Block::CommentExtension(gif::CommentExtension) ); for i in 0..30 { match blocks.next() { Some(&gif::Block::GraphicControlExtension(ref gce)) => { assert_eq!( gce, &gif::GraphicControlExtension { disposal_method: if i == 29 { gif::DisposalMethod::None } else { gif::DisposalMethod::DoNotDispose }, user_input: false, transparent_color_index: Some(255), delay_time: 7 } ); assert_eq!(gce.delay_time_ms(), 70); } _ => panic!("Invalid block") } assert_eq!( blocks.next().unwrap(), &gif::Block::ImageDescriptor(gif::ImageDescriptor { left: 0, top: 0, width: 238, height: 212, local_color_table: None, interlace: false }) ); } assert!(blocks.next().is_none()); } #[test] fn test_webp() { let md = immeta::load_from_file("tests/images/cherry.webp").unwrap(); assert_eq!(md.mime_type(), "image/webp"); assert_eq!(md.dimensions(), CHERRY_DIM); let md = md.into::<Webp>().ok().expect("not WEBP metadata"); println!("{:?}", md); }
random_line_split
test.rs
extern crate immeta; use immeta::Dimensions; use immeta::formats::{png, gif, jpeg}; use immeta::markers::{Png, Gif, Jpeg, Webp}; const OWLET_DIM: Dimensions = Dimensions { width: 1280, height: 857 }; const DROP_DIM: Dimensions = Dimensions { width: 238, height: 212 }; const CHERRY_DIM: Dimensions = Dimensions { width: 1024, height: 772 }; #[test] fn test_jpeg() { let md = immeta::load_from_file("tests/images/owlet.jpg").unwrap(); assert_eq!(md.mime_type(), "image/jpeg"); assert_eq!(md.dimensions(), OWLET_DIM); // let md = Jpeg::from(md).ok() let md = md.into::<Jpeg>().ok().expect("not JPEG metadata"); assert_eq!(md.dimensions, OWLET_DIM); assert_eq!(md.sample_precision, 8); assert_eq!(md.coding_process, jpeg::CodingProcess::DctSequential); assert_eq!(md.entropy_coding, jpeg::EntropyCoding::Huffman); assert!(md.baseline); assert!(!md.differential); } #[test] fn test_png() { let md = immeta::load_from_file("tests/images/owlet.png").unwrap(); assert_eq!(md.mime_type(), "image/png"); assert_eq!(md.dimensions(), OWLET_DIM); let md = md.into::<Png>().ok().expect("not PNG metadata"); assert_eq!(md.dimensions, OWLET_DIM); assert_eq!(md.color_type, png::ColorType::Rgb); assert_eq!(md.color_depth, 24); assert_eq!(md.compression_method, png::CompressionMethod::DeflateInflate); assert_eq!(md.filter_method, png::FilterMethod::AdaptiveFiltering); assert_eq!(md.interlace_method, png::InterlaceMethod::Disabled); } #[test] fn
() { let md = immeta::load_from_file("tests/images/owlet.gif").unwrap(); assert_eq!(md.mime_type(), "image/gif"); assert_eq!(md.dimensions(), OWLET_DIM); let md = md.into::<Gif>().ok().expect("not GIF metadata"); assert_eq!(md.version, gif::Version::V89a); assert_eq!(md.dimensions, OWLET_DIM); assert_eq!(md.global_color_table, Some(gif::ColorTable { size: 256, sorted: false })); assert_eq!(md.color_resolution, 256); assert_eq!(md.background_color_index, 0); assert_eq!(md.pixel_aspect_ratio, 0); assert_eq!(md.frames_number(), 1); assert_eq!(md.is_animated(), false); assert_eq!(md.blocks, vec![ gif::Block::GraphicControlExtension(gif::GraphicControlExtension { disposal_method: gif::DisposalMethod::None, user_input: false, transparent_color_index: None, delay_time: 0 }), gif::Block::ApplicationExtension(gif::ApplicationExtension { application_identifier: *b"ImageMag", authentication_code: *b"ick" }), gif::Block::ImageDescriptor(gif::ImageDescriptor { left: 0, top: 0, width: 1280, height: 857, local_color_table: None, interlace: false }) ]) } #[test] fn test_gif_animated() { let md = immeta::load_from_file("tests/images/drop.gif").unwrap(); assert_eq!(md.mime_type(), "image/gif"); assert_eq!(md.dimensions(), DROP_DIM); let md = md.into::<Gif>().ok().expect("not GIF metadata"); assert_eq!(md.version, gif::Version::V89a); assert_eq!(md.dimensions, DROP_DIM); assert_eq!(md.global_color_table, Some(gif::ColorTable { size: 256, sorted: false })); assert_eq!(md.color_resolution, 128); assert_eq!(md.background_color_index, 255); assert_eq!(md.pixel_aspect_ratio, 0); assert_eq!(md.frames_number(), 30); assert_eq!(md.is_animated(), true); let mut blocks = md.blocks.iter(); assert_eq!( blocks.next().unwrap(), &gif::Block::ApplicationExtension(gif::ApplicationExtension { application_identifier: *b"NETSCAPE", authentication_code: *b"2.0" }) ); assert_eq!( blocks.next().unwrap(), &gif::Block::CommentExtension(gif::CommentExtension) ); for i in 0..30 { match blocks.next() { Some(&gif::Block::GraphicControlExtension(ref gce)) => { assert_eq!( gce, &gif::GraphicControlExtension { disposal_method: if i == 29 { gif::DisposalMethod::None } else { gif::DisposalMethod::DoNotDispose }, user_input: false, transparent_color_index: Some(255), delay_time: 7 } ); assert_eq!(gce.delay_time_ms(), 70); } _ => panic!("Invalid block") } assert_eq!( blocks.next().unwrap(), &gif::Block::ImageDescriptor(gif::ImageDescriptor { left: 0, top: 0, width: 238, height: 212, local_color_table: None, interlace: false }) ); } assert!(blocks.next().is_none()); } #[test] fn test_webp() { let md = immeta::load_from_file("tests/images/cherry.webp").unwrap(); assert_eq!(md.mime_type(), "image/webp"); assert_eq!(md.dimensions(), CHERRY_DIM); let md = md.into::<Webp>().ok().expect("not WEBP metadata"); println!("{:?}", md); }
test_gif_plain
identifier_name
bloomfilter.rs
use std::hash::{Hash, Hasher, SipHasher}; use std::vec::Vec; pub struct Bloom{ pub vec: Vec<bool> , pub hashes: u32 } impl Bloom { pub fn new(prob: f64, capacity: i32) -> Bloom{ let size = (-(capacity as f64 * prob.ln())/(2_f64.ln().powi(2))).ceil() as u64; let hashes = ((size as f64*2_f64.ln())/capacity as f64).ceil() as u32; let mut vec = Vec::new(); for _ in 0..size{ vec.push(false); } Bloom{vec: vec, hashes: hashes} } pub fn insert(&mut self, value: String){ let mut hash_val = hash(value) % self.vec.len() as u64; for _ in 0..self.hashes{ hash_val = hash(hash_val) % self.vec.len() as u64; self.vec[hash_val as usize] = true } } pub fn
(&self, value: String) -> bool { let mut hash_val = hash(value) % self.vec.len() as u64; for _ in 0..self.hashes{ hash_val = hash(hash_val) % self.vec.len() as u64; if!self.vec[hash_val as usize]{ return false; } } true } } pub fn hash<T>(obj: T) -> u64 where T: Hash { let mut hasher = SipHasher::new(); obj.hash(&mut hasher); hasher.finish() } pub fn main(){ println!("Hello, world!"); }
contains
identifier_name
bloomfilter.rs
use std::hash::{Hash, Hasher, SipHasher}; use std::vec::Vec; pub struct Bloom{ pub vec: Vec<bool> , pub hashes: u32 } impl Bloom { pub fn new(prob: f64, capacity: i32) -> Bloom
pub fn insert(&mut self, value: String){ let mut hash_val = hash(value) % self.vec.len() as u64; for _ in 0..self.hashes{ hash_val = hash(hash_val) % self.vec.len() as u64; self.vec[hash_val as usize] = true } } pub fn contains(&self, value: String) -> bool { let mut hash_val = hash(value) % self.vec.len() as u64; for _ in 0..self.hashes{ hash_val = hash(hash_val) % self.vec.len() as u64; if!self.vec[hash_val as usize]{ return false; } } true } } pub fn hash<T>(obj: T) -> u64 where T: Hash { let mut hasher = SipHasher::new(); obj.hash(&mut hasher); hasher.finish() } pub fn main(){ println!("Hello, world!"); }
{ let size = (-(capacity as f64 * prob.ln())/(2_f64.ln().powi(2))).ceil() as u64; let hashes = ((size as f64*2_f64.ln())/capacity as f64).ceil() as u32; let mut vec = Vec::new(); for _ in 0..size{ vec.push(false); } Bloom{vec: vec, hashes: hashes} }
identifier_body
bloomfilter.rs
use std::hash::{Hash, Hasher, SipHasher}; use std::vec::Vec; pub struct Bloom{ pub vec: Vec<bool> , pub hashes: u32 } impl Bloom { pub fn new(prob: f64, capacity: i32) -> Bloom{ let size = (-(capacity as f64 * prob.ln())/(2_f64.ln().powi(2))).ceil() as u64; let hashes = ((size as f64*2_f64.ln())/capacity as f64).ceil() as u32; let mut vec = Vec::new(); for _ in 0..size{ vec.push(false); }
Bloom{vec: vec, hashes: hashes} } pub fn insert(&mut self, value: String){ let mut hash_val = hash(value) % self.vec.len() as u64; for _ in 0..self.hashes{ hash_val = hash(hash_val) % self.vec.len() as u64; self.vec[hash_val as usize] = true } } pub fn contains(&self, value: String) -> bool { let mut hash_val = hash(value) % self.vec.len() as u64; for _ in 0..self.hashes{ hash_val = hash(hash_val) % self.vec.len() as u64; if!self.vec[hash_val as usize]{ return false; } } true } } pub fn hash<T>(obj: T) -> u64 where T: Hash { let mut hasher = SipHasher::new(); obj.hash(&mut hasher); hasher.finish() } pub fn main(){ println!("Hello, world!"); }
random_line_split
bloomfilter.rs
use std::hash::{Hash, Hasher, SipHasher}; use std::vec::Vec; pub struct Bloom{ pub vec: Vec<bool> , pub hashes: u32 } impl Bloom { pub fn new(prob: f64, capacity: i32) -> Bloom{ let size = (-(capacity as f64 * prob.ln())/(2_f64.ln().powi(2))).ceil() as u64; let hashes = ((size as f64*2_f64.ln())/capacity as f64).ceil() as u32; let mut vec = Vec::new(); for _ in 0..size{ vec.push(false); } Bloom{vec: vec, hashes: hashes} } pub fn insert(&mut self, value: String){ let mut hash_val = hash(value) % self.vec.len() as u64; for _ in 0..self.hashes{ hash_val = hash(hash_val) % self.vec.len() as u64; self.vec[hash_val as usize] = true } } pub fn contains(&self, value: String) -> bool { let mut hash_val = hash(value) % self.vec.len() as u64; for _ in 0..self.hashes{ hash_val = hash(hash_val) % self.vec.len() as u64; if!self.vec[hash_val as usize]
} true } } pub fn hash<T>(obj: T) -> u64 where T: Hash { let mut hasher = SipHasher::new(); obj.hash(&mut hasher); hasher.finish() } pub fn main(){ println!("Hello, world!"); }
{ return false; }
conditional_block
paste.rs
#![crate_name = "paste"] #![feature(collections, core, old_io, old_path, rustc_private)] /* * This file is part of the uutils coreutils package. * * (c) Arcterus <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; use std::old_io as io; use std::iter::repeat; #[path = "../common/util.rs"] #[macro_use] mod util; static NAME: &'static str = "paste"; static VERSION: &'static str = "1.0.0"; pub fn uumain(args: Vec<String>) -> i32
} else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); } else { let serial = matches.opt_present("serial"); let delimiters = match matches.opt_str("delimiters") { Some(m) => m, None => "\t".to_string() }; paste(matches.free, serial, delimiters.as_slice()); } 0 } fn paste(filenames: Vec<String>, serial: bool, delimiters: &str) { let mut files: Vec<io::BufferedReader<Box<Reader>>> = filenames.into_iter().map(|name| io::BufferedReader::new( if name.as_slice() == "-" { Box::new(io::stdio::stdin_raw()) as Box<Reader> } else { let r = crash_if_err!(1, io::File::open(&Path::new(name))); Box::new(r) as Box<Reader> } ) ).collect(); let delimiters: Vec<String> = delimiters.chars().map(|x| x.to_string()).collect(); let mut delim_count = 0; if serial { for file in files.iter_mut() { let mut output = String::new(); loop { match file.read_line() { Ok(line) => { output.push_str(line.as_slice().trim_right()); output.push_str(delimiters[delim_count % delimiters.len()].as_slice()); } Err(f) => if f.kind == io::EndOfFile { break } else { crash!(1, "{}", f.to_string()) } } delim_count += 1; } println!("{}", output.as_slice().slice_to(output.len() - 1)); } } else { let mut eof : Vec<bool> = repeat(false).take(files.len()).collect(); loop { let mut output = "".to_string(); let mut eof_count = 0; for (i, file) in files.iter_mut().enumerate() { if eof[i] { eof_count += 1; } else { match file.read_line() { Ok(line) => output.push_str(&line.as_slice()[..line.len() - 1]), Err(f) => if f.kind == io::EndOfFile { eof[i] = true; eof_count += 1; } else { crash!(1, "{}", f.to_string()); } } } output.push_str(delimiters[delim_count % delimiters.len()].as_slice()); delim_count += 1; } if files.len() == eof_count { break; } println!("{}", output.as_slice().slice_to(output.len() - 1)); delim_count = 0; } } }
{ let program = args[0].clone(); let opts = [ getopts::optflag("s", "serial", "paste one file at a time instead of in parallel"), getopts::optopt("d", "delimiters", "reuse characters from LIST instead of TABs", "LIST"), getopts::optflag("h", "help", "display this help and exit"), getopts::optflag("V", "version", "output version information and exit") ]; let matches = match getopts::getopts(args.tail(), &opts) { Ok(m) => m, Err(f) => crash!(1, "{}", f) }; if matches.opt_present("help") { println!("{} {}", NAME, VERSION); println!(""); println!("Usage:"); println!(" {0} [OPTION]... [FILE]...", program); println!(""); print!("{}", getopts::usage("Write lines consisting of the sequentially corresponding lines from each FILE, separated by TABs, to standard output.", &opts));
identifier_body
paste.rs
#![crate_name = "paste"] #![feature(collections, core, old_io, old_path, rustc_private)] /* * This file is part of the uutils coreutils package. * * (c) Arcterus <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; use std::old_io as io; use std::iter::repeat; #[path = "../common/util.rs"] #[macro_use] mod util; static NAME: &'static str = "paste"; static VERSION: &'static str = "1.0.0"; pub fn uumain(args: Vec<String>) -> i32 { let program = args[0].clone(); let opts = [ getopts::optflag("s", "serial", "paste one file at a time instead of in parallel"), getopts::optopt("d", "delimiters", "reuse characters from LIST instead of TABs", "LIST"), getopts::optflag("h", "help", "display this help and exit"), getopts::optflag("V", "version", "output version information and exit") ]; let matches = match getopts::getopts(args.tail(), &opts) { Ok(m) => m, Err(f) => crash!(1, "{}", f) }; if matches.opt_present("help") { println!("{} {}", NAME, VERSION); println!(""); println!("Usage:"); println!(" {0} [OPTION]... [FILE]...", program); println!(""); print!("{}", getopts::usage("Write lines consisting of the sequentially corresponding lines from each FILE, separated by TABs, to standard output.", &opts)); } else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); } else { let serial = matches.opt_present("serial"); let delimiters = match matches.opt_str("delimiters") { Some(m) => m, None => "\t".to_string() }; paste(matches.free, serial, delimiters.as_slice()); } 0 } fn
(filenames: Vec<String>, serial: bool, delimiters: &str) { let mut files: Vec<io::BufferedReader<Box<Reader>>> = filenames.into_iter().map(|name| io::BufferedReader::new( if name.as_slice() == "-" { Box::new(io::stdio::stdin_raw()) as Box<Reader> } else { let r = crash_if_err!(1, io::File::open(&Path::new(name))); Box::new(r) as Box<Reader> } ) ).collect(); let delimiters: Vec<String> = delimiters.chars().map(|x| x.to_string()).collect(); let mut delim_count = 0; if serial { for file in files.iter_mut() { let mut output = String::new(); loop { match file.read_line() { Ok(line) => { output.push_str(line.as_slice().trim_right()); output.push_str(delimiters[delim_count % delimiters.len()].as_slice()); } Err(f) => if f.kind == io::EndOfFile { break } else { crash!(1, "{}", f.to_string()) } } delim_count += 1; } println!("{}", output.as_slice().slice_to(output.len() - 1)); } } else { let mut eof : Vec<bool> = repeat(false).take(files.len()).collect(); loop { let mut output = "".to_string(); let mut eof_count = 0; for (i, file) in files.iter_mut().enumerate() { if eof[i] { eof_count += 1; } else { match file.read_line() { Ok(line) => output.push_str(&line.as_slice()[..line.len() - 1]), Err(f) => if f.kind == io::EndOfFile { eof[i] = true; eof_count += 1; } else { crash!(1, "{}", f.to_string()); } } } output.push_str(delimiters[delim_count % delimiters.len()].as_slice()); delim_count += 1; } if files.len() == eof_count { break; } println!("{}", output.as_slice().slice_to(output.len() - 1)); delim_count = 0; } } }
paste
identifier_name
paste.rs
#![crate_name = "paste"] #![feature(collections, core, old_io, old_path, rustc_private)] /* * This file is part of the uutils coreutils package. * * (c) Arcterus <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; use std::old_io as io; use std::iter::repeat; #[path = "../common/util.rs"] #[macro_use] mod util; static NAME: &'static str = "paste"; static VERSION: &'static str = "1.0.0"; pub fn uumain(args: Vec<String>) -> i32 { let program = args[0].clone(); let opts = [ getopts::optflag("s", "serial", "paste one file at a time instead of in parallel"), getopts::optopt("d", "delimiters", "reuse characters from LIST instead of TABs", "LIST"), getopts::optflag("h", "help", "display this help and exit"), getopts::optflag("V", "version", "output version information and exit") ]; let matches = match getopts::getopts(args.tail(), &opts) { Ok(m) => m, Err(f) => crash!(1, "{}", f) }; if matches.opt_present("help") { println!("{} {}", NAME, VERSION); println!(""); println!("Usage:"); println!(" {0} [OPTION]... [FILE]...", program); println!(""); print!("{}", getopts::usage("Write lines consisting of the sequentially corresponding lines from each FILE, separated by TABs, to standard output.", &opts)); } else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); } else { let serial = matches.opt_present("serial"); let delimiters = match matches.opt_str("delimiters") { Some(m) => m, None => "\t".to_string() }; paste(matches.free, serial, delimiters.as_slice()); } 0 } fn paste(filenames: Vec<String>, serial: bool, delimiters: &str) { let mut files: Vec<io::BufferedReader<Box<Reader>>> = filenames.into_iter().map(|name| io::BufferedReader::new( if name.as_slice() == "-" { Box::new(io::stdio::stdin_raw()) as Box<Reader> } else { let r = crash_if_err!(1, io::File::open(&Path::new(name))); Box::new(r) as Box<Reader> } ) ).collect(); let delimiters: Vec<String> = delimiters.chars().map(|x| x.to_string()).collect(); let mut delim_count = 0; if serial { for file in files.iter_mut() { let mut output = String::new(); loop { match file.read_line() { Ok(line) => { output.push_str(line.as_slice().trim_right()); output.push_str(delimiters[delim_count % delimiters.len()].as_slice()); } Err(f) => if f.kind == io::EndOfFile { break } else { crash!(1, "{}", f.to_string()) } } delim_count += 1; } println!("{}", output.as_slice().slice_to(output.len() - 1)); } } else { let mut eof : Vec<bool> = repeat(false).take(files.len()).collect(); loop {
let mut output = "".to_string(); let mut eof_count = 0; for (i, file) in files.iter_mut().enumerate() { if eof[i] { eof_count += 1; } else { match file.read_line() { Ok(line) => output.push_str(&line.as_slice()[..line.len() - 1]), Err(f) => if f.kind == io::EndOfFile { eof[i] = true; eof_count += 1; } else { crash!(1, "{}", f.to_string()); } } } output.push_str(delimiters[delim_count % delimiters.len()].as_slice()); delim_count += 1; } if files.len() == eof_count { break; } println!("{}", output.as_slice().slice_to(output.len() - 1)); delim_count = 0; } } }
random_line_split
keys.rs
//! Types for the primary key space operations. use error::Error; /// Returned by key space API calls. pub type KeySpaceResult = Result<KeySpaceInfo, Error>; /// Information about the result of a successful key space operation. #[derive(Clone, Debug, RustcDecodable)] #[allow(non_snake_case)] pub struct KeySpaceInfo { /// The action that was taken, e.g. `get`, `set`. pub action: String, /// The etcd `Node` that was operated upon. pub node: Node, /// The previous state of the target node. pub prevNode: Option<Node>, } /// An etcd key-value pair or directory. #[derive(Clone, Debug, RustcDecodable)] #[allow(non_snake_case)] pub struct
{ /// The new value of the etcd creation index. pub createdIndex: Option<u64>, /// Whether or not the node is a directory. pub dir: Option<bool>, /// An ISO 8601 timestamp for when the key will expire. pub expiration: Option<String>, /// The name of the key. pub key: Option<String>, /// The new value of the etcd modification index. pub modifiedIndex: Option<u64>, /// Child nodes of a directory. pub nodes: Option<Vec<Node>>, /// The key's time to live in seconds. pub ttl: Option<i64>, /// The value of the key. pub value: Option<String>, }
Node
identifier_name
keys.rs
//! Types for the primary key space operations. use error::Error; /// Returned by key space API calls. pub type KeySpaceResult = Result<KeySpaceInfo, Error>; /// Information about the result of a successful key space operation. #[derive(Clone, Debug, RustcDecodable)] #[allow(non_snake_case)] pub struct KeySpaceInfo { /// The action that was taken, e.g. `get`, `set`.
/// The previous state of the target node. pub prevNode: Option<Node>, } /// An etcd key-value pair or directory. #[derive(Clone, Debug, RustcDecodable)] #[allow(non_snake_case)] pub struct Node { /// The new value of the etcd creation index. pub createdIndex: Option<u64>, /// Whether or not the node is a directory. pub dir: Option<bool>, /// An ISO 8601 timestamp for when the key will expire. pub expiration: Option<String>, /// The name of the key. pub key: Option<String>, /// The new value of the etcd modification index. pub modifiedIndex: Option<u64>, /// Child nodes of a directory. pub nodes: Option<Vec<Node>>, /// The key's time to live in seconds. pub ttl: Option<i64>, /// The value of the key. pub value: Option<String>, }
pub action: String, /// The etcd `Node` that was operated upon. pub node: Node,
random_line_split
main.rs
use axum::{ routing::{get, post}, Router, }; use cloudevents::Event; use http::StatusCode; use std::net::SocketAddr; use tower_http::trace::TraceLayer; fn echo_app() -> Router { Router::new() .route("/", get(|| async { "hello from cloudevents server" })) .route( "/", post(|event: Event| async move { tracing::debug!("received cloudevent {}", &event); (StatusCode::OK, event) }), ) .layer(TraceLayer::new_for_http()) } #[tokio::main] async fn main() { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "axum_example=debug,tower_http=debug") } tracing_subscriber::fmt::init(); let service = echo_app(); let addr = SocketAddr::from(([127, 0, 0, 1], 8080)); tracing::debug!("listening on {}", addr); axum::Server::bind(&addr) .serve(service.into_make_service()) .await .unwrap(); } #[cfg(test)] mod tests { use super::echo_app; use axum::{ body::Body, http::{self, Request}, }; use chrono::Utc; use hyper; use serde_json::json; use tower::ServiceExt; // for `app.oneshot()` #[tokio::test] async fn
() { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "axum_example=debug,tower_http=debug") } tracing_subscriber::fmt::init(); let app = echo_app(); let time = Utc::now(); let j = json!({"hello": "world"}); let request = Request::builder() .method(http::Method::POST) .header("ce-specversion", "1.0") .header("ce-id", "0001") .header("ce-type", "example.test") .header("ce-source", "http://localhost/") .header("ce-someint", "10") .header("ce-time", time.to_rfc3339()) .header("content-type", "application/json") .body(Body::from(serde_json::to_vec(&j).unwrap())) .unwrap(); let resp = app.oneshot(request).await.unwrap(); assert_eq!( resp.headers() .get("ce-specversion") .unwrap() .to_str() .unwrap(), "1.0" ); assert_eq!( resp.headers().get("ce-id").unwrap().to_str().unwrap(), "0001" ); assert_eq!( resp.headers().get("ce-type").unwrap().to_str().unwrap(), "example.test" ); assert_eq!( resp.headers().get("ce-source").unwrap().to_str().unwrap(), "http://localhost/" ); assert_eq!( resp.headers() .get("content-type") .unwrap() .to_str() .unwrap(), "application/json" ); assert_eq!( resp.headers().get("ce-someint").unwrap().to_str().unwrap(), "10" ); let (_, body) = resp.into_parts(); let body = hyper::body::to_bytes(body).await.unwrap(); assert_eq!(j.to_string().as_bytes(), body); } }
axum_mod_test
identifier_name
main.rs
use axum::{ routing::{get, post}, Router, }; use cloudevents::Event; use http::StatusCode; use std::net::SocketAddr; use tower_http::trace::TraceLayer; fn echo_app() -> Router { Router::new() .route("/", get(|| async { "hello from cloudevents server" })) .route( "/", post(|event: Event| async move { tracing::debug!("received cloudevent {}", &event); (StatusCode::OK, event) }), ) .layer(TraceLayer::new_for_http()) } #[tokio::main] async fn main() { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "axum_example=debug,tower_http=debug") } tracing_subscriber::fmt::init(); let service = echo_app(); let addr = SocketAddr::from(([127, 0, 0, 1], 8080)); tracing::debug!("listening on {}", addr); axum::Server::bind(&addr) .serve(service.into_make_service()) .await .unwrap(); } #[cfg(test)] mod tests { use super::echo_app; use axum::{ body::Body, http::{self, Request}, }; use chrono::Utc; use hyper; use serde_json::json; use tower::ServiceExt; // for `app.oneshot()` #[tokio::test] async fn axum_mod_test() { if std::env::var("RUST_LOG").is_err()
tracing_subscriber::fmt::init(); let app = echo_app(); let time = Utc::now(); let j = json!({"hello": "world"}); let request = Request::builder() .method(http::Method::POST) .header("ce-specversion", "1.0") .header("ce-id", "0001") .header("ce-type", "example.test") .header("ce-source", "http://localhost/") .header("ce-someint", "10") .header("ce-time", time.to_rfc3339()) .header("content-type", "application/json") .body(Body::from(serde_json::to_vec(&j).unwrap())) .unwrap(); let resp = app.oneshot(request).await.unwrap(); assert_eq!( resp.headers() .get("ce-specversion") .unwrap() .to_str() .unwrap(), "1.0" ); assert_eq!( resp.headers().get("ce-id").unwrap().to_str().unwrap(), "0001" ); assert_eq!( resp.headers().get("ce-type").unwrap().to_str().unwrap(), "example.test" ); assert_eq!( resp.headers().get("ce-source").unwrap().to_str().unwrap(), "http://localhost/" ); assert_eq!( resp.headers() .get("content-type") .unwrap() .to_str() .unwrap(), "application/json" ); assert_eq!( resp.headers().get("ce-someint").unwrap().to_str().unwrap(), "10" ); let (_, body) = resp.into_parts(); let body = hyper::body::to_bytes(body).await.unwrap(); assert_eq!(j.to_string().as_bytes(), body); } }
{ std::env::set_var("RUST_LOG", "axum_example=debug,tower_http=debug") }
conditional_block
main.rs
use axum::{ routing::{get, post}, Router, }; use cloudevents::Event; use http::StatusCode; use std::net::SocketAddr; use tower_http::trace::TraceLayer; fn echo_app() -> Router { Router::new() .route("/", get(|| async { "hello from cloudevents server" })) .route( "/", post(|event: Event| async move { tracing::debug!("received cloudevent {}", &event); (StatusCode::OK, event) }), ) .layer(TraceLayer::new_for_http()) } #[tokio::main] async fn main() { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "axum_example=debug,tower_http=debug") } tracing_subscriber::fmt::init(); let service = echo_app(); let addr = SocketAddr::from(([127, 0, 0, 1], 8080)); tracing::debug!("listening on {}", addr); axum::Server::bind(&addr) .serve(service.into_make_service()) .await .unwrap(); } #[cfg(test)] mod tests { use super::echo_app; use axum::{ body::Body, http::{self, Request}, }; use chrono::Utc; use hyper; use serde_json::json; use tower::ServiceExt; // for `app.oneshot()` #[tokio::test] async fn axum_mod_test() { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "axum_example=debug,tower_http=debug") } tracing_subscriber::fmt::init(); let app = echo_app(); let time = Utc::now(); let j = json!({"hello": "world"}); let request = Request::builder() .method(http::Method::POST) .header("ce-specversion", "1.0") .header("ce-id", "0001") .header("ce-type", "example.test") .header("ce-source", "http://localhost/") .header("ce-someint", "10") .header("ce-time", time.to_rfc3339()) .header("content-type", "application/json") .body(Body::from(serde_json::to_vec(&j).unwrap())) .unwrap(); let resp = app.oneshot(request).await.unwrap(); assert_eq!( resp.headers() .get("ce-specversion") .unwrap() .to_str() .unwrap(), "1.0" ); assert_eq!( resp.headers().get("ce-id").unwrap().to_str().unwrap(), "0001" ); assert_eq!( resp.headers().get("ce-type").unwrap().to_str().unwrap(), "example.test" ); assert_eq!( resp.headers().get("ce-source").unwrap().to_str().unwrap(), "http://localhost/" ); assert_eq!( resp.headers() .get("content-type") .unwrap() .to_str() .unwrap(), "application/json" ); assert_eq!( resp.headers().get("ce-someint").unwrap().to_str().unwrap(), "10" ); let (_, body) = resp.into_parts(); let body = hyper::body::to_bytes(body).await.unwrap();
assert_eq!(j.to_string().as_bytes(), body); } }
random_line_split
main.rs
use axum::{ routing::{get, post}, Router, }; use cloudevents::Event; use http::StatusCode; use std::net::SocketAddr; use tower_http::trace::TraceLayer; fn echo_app() -> Router { Router::new() .route("/", get(|| async { "hello from cloudevents server" })) .route( "/", post(|event: Event| async move { tracing::debug!("received cloudevent {}", &event); (StatusCode::OK, event) }), ) .layer(TraceLayer::new_for_http()) } #[tokio::main] async fn main()
#[cfg(test)] mod tests { use super::echo_app; use axum::{ body::Body, http::{self, Request}, }; use chrono::Utc; use hyper; use serde_json::json; use tower::ServiceExt; // for `app.oneshot()` #[tokio::test] async fn axum_mod_test() { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "axum_example=debug,tower_http=debug") } tracing_subscriber::fmt::init(); let app = echo_app(); let time = Utc::now(); let j = json!({"hello": "world"}); let request = Request::builder() .method(http::Method::POST) .header("ce-specversion", "1.0") .header("ce-id", "0001") .header("ce-type", "example.test") .header("ce-source", "http://localhost/") .header("ce-someint", "10") .header("ce-time", time.to_rfc3339()) .header("content-type", "application/json") .body(Body::from(serde_json::to_vec(&j).unwrap())) .unwrap(); let resp = app.oneshot(request).await.unwrap(); assert_eq!( resp.headers() .get("ce-specversion") .unwrap() .to_str() .unwrap(), "1.0" ); assert_eq!( resp.headers().get("ce-id").unwrap().to_str().unwrap(), "0001" ); assert_eq!( resp.headers().get("ce-type").unwrap().to_str().unwrap(), "example.test" ); assert_eq!( resp.headers().get("ce-source").unwrap().to_str().unwrap(), "http://localhost/" ); assert_eq!( resp.headers() .get("content-type") .unwrap() .to_str() .unwrap(), "application/json" ); assert_eq!( resp.headers().get("ce-someint").unwrap().to_str().unwrap(), "10" ); let (_, body) = resp.into_parts(); let body = hyper::body::to_bytes(body).await.unwrap(); assert_eq!(j.to_string().as_bytes(), body); } }
{ if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "axum_example=debug,tower_http=debug") } tracing_subscriber::fmt::init(); let service = echo_app(); let addr = SocketAddr::from(([127, 0, 0, 1], 8080)); tracing::debug!("listening on {}", addr); axum::Server::bind(&addr) .serve(service.into_make_service()) .await .unwrap(); }
identifier_body
monad.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. trait vec_monad<A> { fn bind<B, F>(&self, f: F ) -> Vec<B> where F: FnMut(&A) -> Vec<B> ; } impl<A> vec_monad<A> for Vec<A> { fn bind<B, F>(&self, mut f: F) -> Vec<B> where F: FnMut(&A) -> Vec<B> { let mut r = Vec::new(); for elt in self.iter() { r.extend(f(elt).into_iter()); } r } } trait option_monad<A> { fn bind<B, F>(&self, f: F) -> Option<B> where F: FnOnce(&A) -> Option<B>; } impl<A> option_monad<A> for Option<A> { fn bind<B, F>(&self, f: F) -> Option<B> where F: FnOnce(&A) -> Option<B> { match *self { Some(ref a) => { f(a) } None => { None } } } } fn transform(x: Option<int>) -> Option<String> { x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_string()) ) } pub fn
() { assert_eq!(transform(Some(10)), Some("11".to_string())); assert_eq!(transform(None), None); assert!((vec!("hi".to_string())) .bind(|x| vec!(x.clone(), format!("{}!", x)) ) .bind(|x| vec!(x.clone(), format!("{}?", x)) ) == vec!("hi".to_string(), "hi?".to_string(), "hi!".to_string(), "hi!?".to_string())); }
main
identifier_name