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
formatter.rs
use ansi_term::Colour::Green; use ansi_term::Colour::Yellow; use app::machine::Machine; fn get_empty_line() -> String { String::from("") } fn get_header() -> String { let o = format!("{0: ^10} | {1: ^10} | {2: ^10} | {3: ^10}", "Number", "Name", "State", "Path"); format!("{}", Yellow.paint(o)) } fn get_machine_line(machine: &Machine) -> String { let line = format!("{0: ^10} | {1: ^10} | {2: ^10} | {3: ^10}", machine.get_number(), machine.get_name(), machine.get_state(), machine.get_path()); format!("{}", Green.paint(line)) } fn get_separator() -> String { let s = format!("{0: ^10} | {1: ^10} | {2: ^10} | {3: ^10}", "----------", "----------", "----------", "----------"); format!("{}", Yellow.paint(s)) } pub fn
(machines: &[Machine]) -> String { let mut lines = Vec::new(); lines.push(get_empty_line()); lines.push(get_header()); lines.push(get_separator()); for machine in machines { lines.push(get_machine_line(machine)); } lines.push(get_empty_line()); lines.join("\n") }
format
identifier_name
formatter.rs
use ansi_term::Colour::Green; use ansi_term::Colour::Yellow; use app::machine::Machine; fn get_empty_line() -> String { String::from("") } fn get_header() -> String { let o = format!("{0: ^10} | {1: ^10} | {2: ^10} | {3: ^10}", "Number", "Name", "State", "Path"); format!("{}", Yellow.paint(o)) } fn get_machine_line(machine: &Machine) -> String { let line = format!("{0: ^10} | {1: ^10} | {2: ^10} | {3: ^10}", machine.get_number(),
machine.get_name(), machine.get_state(), machine.get_path()); format!("{}", Green.paint(line)) } fn get_separator() -> String { let s = format!("{0: ^10} | {1: ^10} | {2: ^10} | {3: ^10}", "----------", "----------", "----------", "----------"); format!("{}", Yellow.paint(s)) } pub fn format(machines: &[Machine]) -> String { let mut lines = Vec::new(); lines.push(get_empty_line()); lines.push(get_header()); lines.push(get_separator()); for machine in machines { lines.push(get_machine_line(machine)); } lines.push(get_empty_line()); lines.join("\n") }
random_line_split
board_naive.rs
use std::collections::VecDeque; use std::collections::BTreeSet; use std::str::FromStr; use std::fmt; use std::mem; use piece::Stone; use piece::Piece; use piece::Player; use board::Board; use board::PieceIter; use board::PieceCount; use board::board_from_str; use board::str_from_board; use point::Point; use turn::Direction; #[derive(Clone, Debug, RustcDecodable, RustcEncodable)] pub struct Square { pub pieces: Vec<Piece>, } impl Square { pub fn new() -> Square { Square { pieces: vec![] } } pub fn len(&self) -> usize { self.pieces.len() } pub fn add_piece(&mut self, piece: Piece) -> Result<(), String> { match self.pieces.last_mut() { Some(base) => try!(piece.move_onto(base)), None => {} } self.pieces.push(piece); Ok(()) } fn place_piece(&mut self, piece: Piece) -> Result<(), &str> { if self.len()!= 0 { return Err("Cannot place stone on top of existing stone."); } self.pieces.push(piece); Ok(()) } // Used for moving stones eligibility pub fn mover(&self) -> Option<Player> { self.pieces.last().map(|piece| piece.owner()) } // Used for road wins pub fn owner(&self) -> Option<Player> { self.pieces.last().and_then(|piece| if piece.stone() == Stone::Standing
else { Some(piece.owner()) }) } // Used for winning the flats pub fn scorer(&self) -> Option<Player> { self.pieces.last().and_then(|piece| if piece.stone() == Stone::Flat { Some(piece.owner()) } else { None }) } } #[derive(Clone, Debug, RustcDecodable, RustcEncodable)] pub struct NaiveBoard { grid: Vec<Vec<Square>>, count: PieceCount, } impl NaiveBoard { fn at_mut(&mut self, point: &Point) -> Result<&mut Square, &str> { let row = try!(self.grid.get_mut(point.y).ok_or("Invalid point")); row.get_mut(point.x).ok_or("Invalid point") } } impl Board for NaiveBoard { fn new(board_size: usize) -> NaiveBoard { assert!(board_size >= 4 && board_size <= 8); NaiveBoard { grid: vec![vec![Square::new(); board_size]; board_size], count: PieceCount::new(board_size), } } fn at(&self, point: &Point) -> Result<PieceIter, &str> { let row = try!(self.grid.get(point.y).ok_or("Invalid point")); let cell = try!(row.get(point.x).ok_or("Invalid point")); Ok(PieceIter::NaiveBoardIter { square: cell.pieces.clone(), index: 0, }) } fn at_reset(&mut self, point: &Point) -> Result<PieceIter, &str> { let row = try!(self.grid.get_mut(point.y).ok_or("Invalid point")); let square = try!(row.get_mut(point.x).ok_or("Invalid point")); Ok(PieceIter::NaiveBoardIter { square: mem::replace(square, Square::new()).pieces, index: 0, }) } fn size(&self) -> usize { self.grid.len() } fn place_piece(&mut self, point: &Point, piece: Piece) -> Result<(), String> { { let square = try!(self.at_mut(point)); try!(square.place_piece(piece)); } self.count.add(&piece); Ok(()) } fn add_piece(&mut self, point: &Point, piece: Piece) -> Result<(), String> { { let square = try!(self.at_mut(point)); try!(square.add_piece(piece)); } Ok(()) } fn count(&self) -> PieceCount { self.count } fn follow(&self, starts: &mut VecDeque<Point>, player: Player) -> BTreeSet<Point> { let mut connected = BTreeSet::new(); let mut visited = BTreeSet::new(); while let Some(start) = starts.pop_front() { visited.insert(start); if self.at(&start).ok().and_then(|p| p.owner()) == Some(player) { connected.insert(start); for point in Direction::neighbors(&start, self.size()) { if!visited.contains(&point) { starts.push_back(point) } } } } connected } } impl FromStr for NaiveBoard { type Err=(); fn from_str(s: &str) -> Result<Self, Self::Err> { board_from_str::<NaiveBoard>(s) } } impl fmt::Display for NaiveBoard { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { str_from_board(self, f) } }
{ None }
conditional_block
board_naive.rs
use std::collections::VecDeque; use std::collections::BTreeSet; use std::str::FromStr; use std::fmt; use std::mem; use piece::Stone; use piece::Piece; use piece::Player; use board::Board; use board::PieceIter; use board::PieceCount; use board::board_from_str; use board::str_from_board; use point::Point; use turn::Direction; #[derive(Clone, Debug, RustcDecodable, RustcEncodable)] pub struct Square { pub pieces: Vec<Piece>, } impl Square { pub fn new() -> Square { Square { pieces: vec![] } } pub fn len(&self) -> usize { self.pieces.len() } pub fn add_piece(&mut self, piece: Piece) -> Result<(), String> { match self.pieces.last_mut() { Some(base) => try!(piece.move_onto(base)), None => {} } self.pieces.push(piece); Ok(()) } fn place_piece(&mut self, piece: Piece) -> Result<(), &str> { if self.len()!= 0 { return Err("Cannot place stone on top of existing stone."); } self.pieces.push(piece); Ok(()) } // Used for moving stones eligibility pub fn mover(&self) -> Option<Player> { self.pieces.last().map(|piece| piece.owner()) } // Used for road wins pub fn owner(&self) -> Option<Player> { self.pieces.last().and_then(|piece| if piece.stone() == Stone::Standing { None } else { Some(piece.owner()) }) } // Used for winning the flats pub fn scorer(&self) -> Option<Player> { self.pieces.last().and_then(|piece| if piece.stone() == Stone::Flat { Some(piece.owner()) } else { None }) } } #[derive(Clone, Debug, RustcDecodable, RustcEncodable)] pub struct NaiveBoard { grid: Vec<Vec<Square>>, count: PieceCount, } impl NaiveBoard { fn at_mut(&mut self, point: &Point) -> Result<&mut Square, &str> { let row = try!(self.grid.get_mut(point.y).ok_or("Invalid point")); row.get_mut(point.x).ok_or("Invalid point") } } impl Board for NaiveBoard { fn new(board_size: usize) -> NaiveBoard { assert!(board_size >= 4 && board_size <= 8); NaiveBoard { grid: vec![vec![Square::new(); board_size]; board_size], count: PieceCount::new(board_size), } } fn at(&self, point: &Point) -> Result<PieceIter, &str> { let row = try!(self.grid.get(point.y).ok_or("Invalid point")); let cell = try!(row.get(point.x).ok_or("Invalid point")); Ok(PieceIter::NaiveBoardIter { square: cell.pieces.clone(), index: 0, }) } fn at_reset(&mut self, point: &Point) -> Result<PieceIter, &str> { let row = try!(self.grid.get_mut(point.y).ok_or("Invalid point")); let square = try!(row.get_mut(point.x).ok_or("Invalid point")); Ok(PieceIter::NaiveBoardIter { square: mem::replace(square, Square::new()).pieces, index: 0, }) } fn size(&self) -> usize { self.grid.len() } fn place_piece(&mut self, point: &Point, piece: Piece) -> Result<(), String> { { let square = try!(self.at_mut(point)); try!(square.place_piece(piece)); } self.count.add(&piece); Ok(()) } fn add_piece(&mut self, point: &Point, piece: Piece) -> Result<(), String> { { let square = try!(self.at_mut(point)); try!(square.add_piece(piece)); } Ok(()) } fn count(&self) -> PieceCount { self.count } fn follow(&self, starts: &mut VecDeque<Point>, player: Player) -> BTreeSet<Point> { let mut connected = BTreeSet::new(); let mut visited = BTreeSet::new(); while let Some(start) = starts.pop_front() { visited.insert(start); if self.at(&start).ok().and_then(|p| p.owner()) == Some(player) { connected.insert(start); for point in Direction::neighbors(&start, self.size()) { if!visited.contains(&point) { starts.push_back(point) } } } } connected } } impl FromStr for NaiveBoard { type Err=(); fn from_str(s: &str) -> Result<Self, Self::Err> { board_from_str::<NaiveBoard>(s) } } impl fmt::Display for NaiveBoard { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
}
{ str_from_board(self, f) }
identifier_body
board_naive.rs
use std::collections::VecDeque; use std::collections::BTreeSet; use std::str::FromStr; use std::fmt; use std::mem; use piece::Stone; use piece::Piece; use piece::Player; use board::Board; use board::PieceIter; use board::PieceCount; use board::board_from_str; use board::str_from_board; use point::Point; use turn::Direction; #[derive(Clone, Debug, RustcDecodable, RustcEncodable)] pub struct Square { pub pieces: Vec<Piece>, } impl Square { pub fn new() -> Square { Square { pieces: vec![] } } pub fn len(&self) -> usize { self.pieces.len() } pub fn add_piece(&mut self, piece: Piece) -> Result<(), String> { match self.pieces.last_mut() { Some(base) => try!(piece.move_onto(base)), None => {} } self.pieces.push(piece); Ok(()) } fn place_piece(&mut self, piece: Piece) -> Result<(), &str> { if self.len()!= 0 { return Err("Cannot place stone on top of existing stone."); } self.pieces.push(piece); Ok(()) } // Used for moving stones eligibility pub fn mover(&self) -> Option<Player> { self.pieces.last().map(|piece| piece.owner()) } // Used for road wins pub fn owner(&self) -> Option<Player> { self.pieces.last().and_then(|piece| if piece.stone() == Stone::Standing { None } else { Some(piece.owner()) }) } // Used for winning the flats pub fn
(&self) -> Option<Player> { self.pieces.last().and_then(|piece| if piece.stone() == Stone::Flat { Some(piece.owner()) } else { None }) } } #[derive(Clone, Debug, RustcDecodable, RustcEncodable)] pub struct NaiveBoard { grid: Vec<Vec<Square>>, count: PieceCount, } impl NaiveBoard { fn at_mut(&mut self, point: &Point) -> Result<&mut Square, &str> { let row = try!(self.grid.get_mut(point.y).ok_or("Invalid point")); row.get_mut(point.x).ok_or("Invalid point") } } impl Board for NaiveBoard { fn new(board_size: usize) -> NaiveBoard { assert!(board_size >= 4 && board_size <= 8); NaiveBoard { grid: vec![vec![Square::new(); board_size]; board_size], count: PieceCount::new(board_size), } } fn at(&self, point: &Point) -> Result<PieceIter, &str> { let row = try!(self.grid.get(point.y).ok_or("Invalid point")); let cell = try!(row.get(point.x).ok_or("Invalid point")); Ok(PieceIter::NaiveBoardIter { square: cell.pieces.clone(), index: 0, }) } fn at_reset(&mut self, point: &Point) -> Result<PieceIter, &str> { let row = try!(self.grid.get_mut(point.y).ok_or("Invalid point")); let square = try!(row.get_mut(point.x).ok_or("Invalid point")); Ok(PieceIter::NaiveBoardIter { square: mem::replace(square, Square::new()).pieces, index: 0, }) } fn size(&self) -> usize { self.grid.len() } fn place_piece(&mut self, point: &Point, piece: Piece) -> Result<(), String> { { let square = try!(self.at_mut(point)); try!(square.place_piece(piece)); } self.count.add(&piece); Ok(()) } fn add_piece(&mut self, point: &Point, piece: Piece) -> Result<(), String> { { let square = try!(self.at_mut(point)); try!(square.add_piece(piece)); } Ok(()) } fn count(&self) -> PieceCount { self.count } fn follow(&self, starts: &mut VecDeque<Point>, player: Player) -> BTreeSet<Point> { let mut connected = BTreeSet::new(); let mut visited = BTreeSet::new(); while let Some(start) = starts.pop_front() { visited.insert(start); if self.at(&start).ok().and_then(|p| p.owner()) == Some(player) { connected.insert(start); for point in Direction::neighbors(&start, self.size()) { if!visited.contains(&point) { starts.push_back(point) } } } } connected } } impl FromStr for NaiveBoard { type Err=(); fn from_str(s: &str) -> Result<Self, Self::Err> { board_from_str::<NaiveBoard>(s) } } impl fmt::Display for NaiveBoard { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { str_from_board(self, f) } }
scorer
identifier_name
board_naive.rs
use std::collections::VecDeque; use std::collections::BTreeSet; use std::str::FromStr; use std::fmt; use std::mem; use piece::Stone; use piece::Piece; use piece::Player; use board::Board; use board::PieceIter; use board::PieceCount; use board::board_from_str; use board::str_from_board; use point::Point; use turn::Direction; #[derive(Clone, Debug, RustcDecodable, RustcEncodable)] pub struct Square { pub pieces: Vec<Piece>, } impl Square { pub fn new() -> Square { Square { pieces: vec![] } } pub fn len(&self) -> usize { self.pieces.len() } pub fn add_piece(&mut self, piece: Piece) -> Result<(), String> { match self.pieces.last_mut() { Some(base) => try!(piece.move_onto(base)), None => {} } self.pieces.push(piece); Ok(()) } fn place_piece(&mut self, piece: Piece) -> Result<(), &str> { if self.len()!= 0 { return Err("Cannot place stone on top of existing stone."); }
// Used for moving stones eligibility pub fn mover(&self) -> Option<Player> { self.pieces.last().map(|piece| piece.owner()) } // Used for road wins pub fn owner(&self) -> Option<Player> { self.pieces.last().and_then(|piece| if piece.stone() == Stone::Standing { None } else { Some(piece.owner()) }) } // Used for winning the flats pub fn scorer(&self) -> Option<Player> { self.pieces.last().and_then(|piece| if piece.stone() == Stone::Flat { Some(piece.owner()) } else { None }) } } #[derive(Clone, Debug, RustcDecodable, RustcEncodable)] pub struct NaiveBoard { grid: Vec<Vec<Square>>, count: PieceCount, } impl NaiveBoard { fn at_mut(&mut self, point: &Point) -> Result<&mut Square, &str> { let row = try!(self.grid.get_mut(point.y).ok_or("Invalid point")); row.get_mut(point.x).ok_or("Invalid point") } } impl Board for NaiveBoard { fn new(board_size: usize) -> NaiveBoard { assert!(board_size >= 4 && board_size <= 8); NaiveBoard { grid: vec![vec![Square::new(); board_size]; board_size], count: PieceCount::new(board_size), } } fn at(&self, point: &Point) -> Result<PieceIter, &str> { let row = try!(self.grid.get(point.y).ok_or("Invalid point")); let cell = try!(row.get(point.x).ok_or("Invalid point")); Ok(PieceIter::NaiveBoardIter { square: cell.pieces.clone(), index: 0, }) } fn at_reset(&mut self, point: &Point) -> Result<PieceIter, &str> { let row = try!(self.grid.get_mut(point.y).ok_or("Invalid point")); let square = try!(row.get_mut(point.x).ok_or("Invalid point")); Ok(PieceIter::NaiveBoardIter { square: mem::replace(square, Square::new()).pieces, index: 0, }) } fn size(&self) -> usize { self.grid.len() } fn place_piece(&mut self, point: &Point, piece: Piece) -> Result<(), String> { { let square = try!(self.at_mut(point)); try!(square.place_piece(piece)); } self.count.add(&piece); Ok(()) } fn add_piece(&mut self, point: &Point, piece: Piece) -> Result<(), String> { { let square = try!(self.at_mut(point)); try!(square.add_piece(piece)); } Ok(()) } fn count(&self) -> PieceCount { self.count } fn follow(&self, starts: &mut VecDeque<Point>, player: Player) -> BTreeSet<Point> { let mut connected = BTreeSet::new(); let mut visited = BTreeSet::new(); while let Some(start) = starts.pop_front() { visited.insert(start); if self.at(&start).ok().and_then(|p| p.owner()) == Some(player) { connected.insert(start); for point in Direction::neighbors(&start, self.size()) { if!visited.contains(&point) { starts.push_back(point) } } } } connected } } impl FromStr for NaiveBoard { type Err=(); fn from_str(s: &str) -> Result<Self, Self::Err> { board_from_str::<NaiveBoard>(s) } } impl fmt::Display for NaiveBoard { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { str_from_board(self, f) } }
self.pieces.push(piece); Ok(()) }
random_line_split
lib.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. #![feature(const_fn_fn_ptr_basics)] //! This crate contains some necessary types and traits for implementing a custom coprocessor plugin //! for TiKV. //! //! Most notably, if you want to write a custom plugin, your plugin needs to implement the //! [`CoprocessorPlugin`] trait. The plugin then needs to be compiled to a `dylib`. //! //! > Note: Only `dylib` is supported, and not `cdylib` or `staticlib`, because the latter two are //! > not able to use TiKV's allocator. See also the documentation in [`std::alloc`]. //! //! In order to make your plugin callable, you need to declare a constructor with the //! [`declare_plugin`] macro. //! //! A plugin can interact with the underlying storage via the [`RawStorage`] trait. //! //! # Example //! //! ```no_run //! use coprocessor_plugin_api::*; //! //! #[derive(Default)] //! struct MyPlugin; //! //! impl CoprocessorPlugin for MyPlugin { //! fn name(&self) -> &'static str { "my-plugin" } //! //! fn on_raw_coprocessor_request( //! &self, //! region: &Region, //! request: &RawRequest, //! storage: &dyn RawStorage, //! ) -> Result<RawResponse, PluginError> { //! Ok(vec![]) //! } //! } //!
#[doc(hidden)] pub mod allocator; mod plugin_api; mod storage_api; mod util; pub use plugin_api::*; pub use storage_api::*; pub use util::*;
//! declare_plugin!(MyPlugin::default()); //! ```
random_line_split
cleanup-rvalue-temp-during-incomplete-alloc.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. // Test cleanup of rvalue temporary that occurs while `box` construction // is in progress. This scenario revealed a rather terrible bug. The // ingredients are: // // 1. Partial cleanup of `box` is in scope, // 2. cleanup of return value from `get_bar()` is in scope, // 3. do_it() fails. // // This led to a bug because `the top-most frame that was to be // cleaned (which happens to be the partial cleanup of `box`) required // multiple basic blocks, which led to us dropping part of the cleanup // from the top-most frame. // // It's unclear how likely such a bug is to recur, but it seems like a // scenario worth testing. use std::task; enum Conzabble { Bickwick(Foo) }
fn do_it(x: &[uint]) -> Foo { fail!() } fn get_bar(x: uint) -> Vec<uint> { vec!(x * 2) } pub fn fails() { let x = 2; let mut y = Vec::new(); y.push(box Bickwick(do_it(get_bar(x).as_slice()))); } pub fn main() { task::try(fails); }
struct Foo { field: Box<uint> }
random_line_split
cleanup-rvalue-temp-during-incomplete-alloc.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. // Test cleanup of rvalue temporary that occurs while `box` construction // is in progress. This scenario revealed a rather terrible bug. The // ingredients are: // // 1. Partial cleanup of `box` is in scope, // 2. cleanup of return value from `get_bar()` is in scope, // 3. do_it() fails. // // This led to a bug because `the top-most frame that was to be // cleaned (which happens to be the partial cleanup of `box`) required // multiple basic blocks, which led to us dropping part of the cleanup // from the top-most frame. // // It's unclear how likely such a bug is to recur, but it seems like a // scenario worth testing. use std::task; enum Conzabble { Bickwick(Foo) } struct Foo { field: Box<uint> } fn do_it(x: &[uint]) -> Foo { fail!() } fn
(x: uint) -> Vec<uint> { vec!(x * 2) } pub fn fails() { let x = 2; let mut y = Vec::new(); y.push(box Bickwick(do_it(get_bar(x).as_slice()))); } pub fn main() { task::try(fails); }
get_bar
identifier_name
cleanup-rvalue-temp-during-incomplete-alloc.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. // Test cleanup of rvalue temporary that occurs while `box` construction // is in progress. This scenario revealed a rather terrible bug. The // ingredients are: // // 1. Partial cleanup of `box` is in scope, // 2. cleanup of return value from `get_bar()` is in scope, // 3. do_it() fails. // // This led to a bug because `the top-most frame that was to be // cleaned (which happens to be the partial cleanup of `box`) required // multiple basic blocks, which led to us dropping part of the cleanup // from the top-most frame. // // It's unclear how likely such a bug is to recur, but it seems like a // scenario worth testing. use std::task; enum Conzabble { Bickwick(Foo) } struct Foo { field: Box<uint> } fn do_it(x: &[uint]) -> Foo { fail!() } fn get_bar(x: uint) -> Vec<uint> { vec!(x * 2) } pub fn fails()
pub fn main() { task::try(fails); }
{ let x = 2; let mut y = Vec::new(); y.push(box Bickwick(do_it(get_bar(x).as_slice()))); }
identifier_body
coroutine.rs
use ffi::Timeout; use core::{AsIoContext, IoContext, ThreadIoContext, Cancel}; use handler::{Handler}; use strand::{Strand, StrandImmutable, StrandHandler}; use SteadyTimer; use context::{Context, Transfer}; use context::stack::{ProtectedFixedSizeStack, Stack, StackError}; trait CoroutineExec: Send +'static { fn call_box(self: Box<Self>, coro: Coroutine); } impl<F> CoroutineExec for F where F: FnOnce(Coroutine) + Send +'static, { fn call_box(self: Box<Self>, coro: Coroutine) { self(coro) } } pub struct CoroutineData { context: Option<Context>, timer: SteadyTimer, } unsafe impl AsIoContext for CoroutineData { fn as_ctx(&self) -> &IoContext { self.timer.as_ctx() } } #[derive(Clone)] struct CancelRef(*const Cancel, *const Timeout); impl CancelRef { fn timeout(self, coro: &Strand<CoroutineData>) { coro.timer.expires_from_now(unsafe { &*self.1 }.get()); coro.timer.async_wait( coro.wrap(move |_, res| if let Ok(_) = res { unsafe { &*self.0 }.cancel(); }), ) } } unsafe impl Send for CancelRef {} unsafe impl Sync for CancelRef {} type Caller<R, E> = fn(Strand<CoroutineData>, Result<R, E>); pub struct
<R, E>(StrandHandler<CoroutineData, Caller<R, E>, R, E>); impl<R, E> Handler<R, E> for CoroutineHandler<R, E> where R: Send +'static, E: Send +'static, { type Output = Result<R, E>; #[doc(hidden)] type WrappedHandler = StrandHandler<CoroutineData, fn(Strand<CoroutineData>, Result<R, E>), R, E>; #[doc(hidden)] fn wrap<W>(self, ctx: &IoContext, wrapper: W) -> Self::Output where W: FnOnce(&IoContext, Self::WrappedHandler), { let mut data: Option<CancelRef> = None; let coro: &mut CoroutineData = unsafe { &mut *self.0.data.clone().cell.get() }; wrapper(ctx, self.0); let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume( &mut data as *mut _ as usize, ) }; coro.context = Some(context); coro.timer.cancel(); let res: &mut Option<Self::Output> = unsafe { &mut *(data as *mut Option<Self::Output>) }; res.take().unwrap() } #[doc(hidden)] fn wrap_timeout<W>(self, ctx: &Cancel, timeout: &Timeout, wrapper: W) -> Self::Output where W: FnOnce(&IoContext, Self::WrappedHandler), { let mut data = Some(CancelRef(ctx, timeout)); let coro: &mut CoroutineData = unsafe { &mut *self.0.data.clone().cell.get() }; wrapper(ctx.as_ctx(), self.0); let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume( &mut data as *mut _ as usize, ) }; coro.context = Some(context); coro.timer.cancel(); let res: &mut Option<Self::Output> = unsafe { &mut *(data as *mut Option<Self::Output>) }; res.take().unwrap() } } struct InitData { stack: ProtectedFixedSizeStack, ctx: IoContext, exec: Box<CoroutineExec>, } /// Context object that represents the currently executing coroutine. pub struct Coroutine<'a>(Strand<'a, CoroutineData>); impl<'a> Coroutine<'a> { extern "C" fn entry(t: Transfer) ->! { let InitData { stack, ctx, exec } = unsafe { &mut *(t.data as *mut Option<InitData>) } .take() .unwrap(); let mut coro: StrandImmutable<CoroutineData> = Strand::new( &ctx, CoroutineData { context: Some(t.context), timer: SteadyTimer::new(&ctx), }, ); let this = { let data = &coro as *const _ as usize; let mut coro: &mut CoroutineData = unsafe { coro.get() }; let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume(data) }; coro.context = Some(context); unsafe { &mut *(data as *mut ThreadIoContext) } }; exec.call_box(Coroutine(coro.make_mut(this))); let context = (&mut unsafe { coro.get() }.context).take().unwrap(); let mut stack = Some(stack); unsafe { context.resume_ontop(&mut stack as *mut _ as usize, Self::exit) }; unreachable!(); } extern "C" fn exit(mut t: Transfer) -> Transfer { { let stack = unsafe { &mut *(t.data as *mut Option<ProtectedFixedSizeStack>) }; // Drop the stack let _ = stack.take().unwrap(); } t.data = 0; t } /// Provides a `Coroutine` handler to asynchronous operation. /// /// # Examples /// /// ``` /// use asyncio::{IoContext, AsIoContext, Stream, spawn}; /// use asyncio::ip::{IpProtocol, Tcp, TcpSocket}; /// /// let ctx = &IoContext::new().unwrap(); /// spawn(ctx, |coro| { /// let ctx = coro.as_ctx(); /// let mut soc = TcpSocket::new(ctx, Tcp::v4()).unwrap(); /// let mut buf = [0; 256]; /// let size = soc.async_read_some(&mut buf, coro.wrap()).unwrap(); /// }); /// ``` pub fn wrap<R, E>(&self) -> CoroutineHandler<R, E> where R: Send +'static, E: Send +'static, { let handler: StrandHandler<CoroutineData, Caller<R, E>, R, E> = self.0.wrap(caller::<R, E>); CoroutineHandler(handler) } } fn caller<R, E>(mut coro: Strand<CoroutineData>, res: Result<R, E>) where R: Send +'static, E: Send +'static, { let mut data = Some(res); let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume( &mut data as *mut _ as usize, ) }; if data!= 0 { if let Some(ctx) = unsafe { &mut *(data as *mut Option<CancelRef>) }.take() { ctx.timeout(&coro); } coro.context = Some(context); } } unsafe impl<'a> AsIoContext for Coroutine<'a> { fn as_ctx(&self) -> &IoContext { self.0.as_ctx() } } pub fn spawn<F>(ctx: &IoContext, func: F) -> Result<(), StackError> where F: FnOnce(Coroutine) + Send +'static, { let data = InitData { stack: ProtectedFixedSizeStack::new(Stack::default_size())?, ctx: ctx.clone(), exec: Box::new(func), }; let context = unsafe { Context::new(&data.stack, Coroutine::entry) }; let data = Some(data); let Transfer { context, data } = unsafe { context.resume(&data as *const _ as usize) }; let coro = unsafe { &mut *(data as *mut StrandImmutable<CoroutineData>) }; unsafe { coro.get() }.context = Some(context); coro.post(move |mut coro| { let data = coro.this as *mut _ as usize; let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume(data) }; if data!= 0 { if let Some(ctx) = unsafe { &mut *(data as *mut Option<CancelRef>) }.take() { ctx.timeout(&coro); } coro.context = Some(context); } }); Ok(()) } #[test] fn test_spawn() { let ctx = &IoContext::new().unwrap(); spawn(ctx, |coro| {}); ctx.run(); }
CoroutineHandler
identifier_name
coroutine.rs
use ffi::Timeout; use core::{AsIoContext, IoContext, ThreadIoContext, Cancel}; use handler::{Handler}; use strand::{Strand, StrandImmutable, StrandHandler}; use SteadyTimer; use context::{Context, Transfer}; use context::stack::{ProtectedFixedSizeStack, Stack, StackError}; trait CoroutineExec: Send +'static { fn call_box(self: Box<Self>, coro: Coroutine); } impl<F> CoroutineExec for F where F: FnOnce(Coroutine) + Send +'static, { fn call_box(self: Box<Self>, coro: Coroutine) { self(coro) } } pub struct CoroutineData { context: Option<Context>, timer: SteadyTimer, } unsafe impl AsIoContext for CoroutineData { fn as_ctx(&self) -> &IoContext { self.timer.as_ctx() } } #[derive(Clone)] struct CancelRef(*const Cancel, *const Timeout); impl CancelRef { fn timeout(self, coro: &Strand<CoroutineData>) { coro.timer.expires_from_now(unsafe { &*self.1 }.get()); coro.timer.async_wait( coro.wrap(move |_, res| if let Ok(_) = res
), ) } } unsafe impl Send for CancelRef {} unsafe impl Sync for CancelRef {} type Caller<R, E> = fn(Strand<CoroutineData>, Result<R, E>); pub struct CoroutineHandler<R, E>(StrandHandler<CoroutineData, Caller<R, E>, R, E>); impl<R, E> Handler<R, E> for CoroutineHandler<R, E> where R: Send +'static, E: Send +'static, { type Output = Result<R, E>; #[doc(hidden)] type WrappedHandler = StrandHandler<CoroutineData, fn(Strand<CoroutineData>, Result<R, E>), R, E>; #[doc(hidden)] fn wrap<W>(self, ctx: &IoContext, wrapper: W) -> Self::Output where W: FnOnce(&IoContext, Self::WrappedHandler), { let mut data: Option<CancelRef> = None; let coro: &mut CoroutineData = unsafe { &mut *self.0.data.clone().cell.get() }; wrapper(ctx, self.0); let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume( &mut data as *mut _ as usize, ) }; coro.context = Some(context); coro.timer.cancel(); let res: &mut Option<Self::Output> = unsafe { &mut *(data as *mut Option<Self::Output>) }; res.take().unwrap() } #[doc(hidden)] fn wrap_timeout<W>(self, ctx: &Cancel, timeout: &Timeout, wrapper: W) -> Self::Output where W: FnOnce(&IoContext, Self::WrappedHandler), { let mut data = Some(CancelRef(ctx, timeout)); let coro: &mut CoroutineData = unsafe { &mut *self.0.data.clone().cell.get() }; wrapper(ctx.as_ctx(), self.0); let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume( &mut data as *mut _ as usize, ) }; coro.context = Some(context); coro.timer.cancel(); let res: &mut Option<Self::Output> = unsafe { &mut *(data as *mut Option<Self::Output>) }; res.take().unwrap() } } struct InitData { stack: ProtectedFixedSizeStack, ctx: IoContext, exec: Box<CoroutineExec>, } /// Context object that represents the currently executing coroutine. pub struct Coroutine<'a>(Strand<'a, CoroutineData>); impl<'a> Coroutine<'a> { extern "C" fn entry(t: Transfer) ->! { let InitData { stack, ctx, exec } = unsafe { &mut *(t.data as *mut Option<InitData>) } .take() .unwrap(); let mut coro: StrandImmutable<CoroutineData> = Strand::new( &ctx, CoroutineData { context: Some(t.context), timer: SteadyTimer::new(&ctx), }, ); let this = { let data = &coro as *const _ as usize; let mut coro: &mut CoroutineData = unsafe { coro.get() }; let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume(data) }; coro.context = Some(context); unsafe { &mut *(data as *mut ThreadIoContext) } }; exec.call_box(Coroutine(coro.make_mut(this))); let context = (&mut unsafe { coro.get() }.context).take().unwrap(); let mut stack = Some(stack); unsafe { context.resume_ontop(&mut stack as *mut _ as usize, Self::exit) }; unreachable!(); } extern "C" fn exit(mut t: Transfer) -> Transfer { { let stack = unsafe { &mut *(t.data as *mut Option<ProtectedFixedSizeStack>) }; // Drop the stack let _ = stack.take().unwrap(); } t.data = 0; t } /// Provides a `Coroutine` handler to asynchronous operation. /// /// # Examples /// /// ``` /// use asyncio::{IoContext, AsIoContext, Stream, spawn}; /// use asyncio::ip::{IpProtocol, Tcp, TcpSocket}; /// /// let ctx = &IoContext::new().unwrap(); /// spawn(ctx, |coro| { /// let ctx = coro.as_ctx(); /// let mut soc = TcpSocket::new(ctx, Tcp::v4()).unwrap(); /// let mut buf = [0; 256]; /// let size = soc.async_read_some(&mut buf, coro.wrap()).unwrap(); /// }); /// ``` pub fn wrap<R, E>(&self) -> CoroutineHandler<R, E> where R: Send +'static, E: Send +'static, { let handler: StrandHandler<CoroutineData, Caller<R, E>, R, E> = self.0.wrap(caller::<R, E>); CoroutineHandler(handler) } } fn caller<R, E>(mut coro: Strand<CoroutineData>, res: Result<R, E>) where R: Send +'static, E: Send +'static, { let mut data = Some(res); let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume( &mut data as *mut _ as usize, ) }; if data!= 0 { if let Some(ctx) = unsafe { &mut *(data as *mut Option<CancelRef>) }.take() { ctx.timeout(&coro); } coro.context = Some(context); } } unsafe impl<'a> AsIoContext for Coroutine<'a> { fn as_ctx(&self) -> &IoContext { self.0.as_ctx() } } pub fn spawn<F>(ctx: &IoContext, func: F) -> Result<(), StackError> where F: FnOnce(Coroutine) + Send +'static, { let data = InitData { stack: ProtectedFixedSizeStack::new(Stack::default_size())?, ctx: ctx.clone(), exec: Box::new(func), }; let context = unsafe { Context::new(&data.stack, Coroutine::entry) }; let data = Some(data); let Transfer { context, data } = unsafe { context.resume(&data as *const _ as usize) }; let coro = unsafe { &mut *(data as *mut StrandImmutable<CoroutineData>) }; unsafe { coro.get() }.context = Some(context); coro.post(move |mut coro| { let data = coro.this as *mut _ as usize; let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume(data) }; if data!= 0 { if let Some(ctx) = unsafe { &mut *(data as *mut Option<CancelRef>) }.take() { ctx.timeout(&coro); } coro.context = Some(context); } }); Ok(()) } #[test] fn test_spawn() { let ctx = &IoContext::new().unwrap(); spawn(ctx, |coro| {}); ctx.run(); }
{ unsafe { &*self.0 }.cancel(); }
conditional_block
coroutine.rs
use ffi::Timeout; use core::{AsIoContext, IoContext, ThreadIoContext, Cancel}; use handler::{Handler}; use strand::{Strand, StrandImmutable, StrandHandler}; use SteadyTimer; use context::{Context, Transfer}; use context::stack::{ProtectedFixedSizeStack, Stack, StackError}; trait CoroutineExec: Send +'static { fn call_box(self: Box<Self>, coro: Coroutine); } impl<F> CoroutineExec for F where F: FnOnce(Coroutine) + Send +'static, { fn call_box(self: Box<Self>, coro: Coroutine) { self(coro) } } pub struct CoroutineData { context: Option<Context>, timer: SteadyTimer, } unsafe impl AsIoContext for CoroutineData { fn as_ctx(&self) -> &IoContext { self.timer.as_ctx() } } #[derive(Clone)] struct CancelRef(*const Cancel, *const Timeout); impl CancelRef { fn timeout(self, coro: &Strand<CoroutineData>)
} unsafe impl Send for CancelRef {} unsafe impl Sync for CancelRef {} type Caller<R, E> = fn(Strand<CoroutineData>, Result<R, E>); pub struct CoroutineHandler<R, E>(StrandHandler<CoroutineData, Caller<R, E>, R, E>); impl<R, E> Handler<R, E> for CoroutineHandler<R, E> where R: Send +'static, E: Send +'static, { type Output = Result<R, E>; #[doc(hidden)] type WrappedHandler = StrandHandler<CoroutineData, fn(Strand<CoroutineData>, Result<R, E>), R, E>; #[doc(hidden)] fn wrap<W>(self, ctx: &IoContext, wrapper: W) -> Self::Output where W: FnOnce(&IoContext, Self::WrappedHandler), { let mut data: Option<CancelRef> = None; let coro: &mut CoroutineData = unsafe { &mut *self.0.data.clone().cell.get() }; wrapper(ctx, self.0); let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume( &mut data as *mut _ as usize, ) }; coro.context = Some(context); coro.timer.cancel(); let res: &mut Option<Self::Output> = unsafe { &mut *(data as *mut Option<Self::Output>) }; res.take().unwrap() } #[doc(hidden)] fn wrap_timeout<W>(self, ctx: &Cancel, timeout: &Timeout, wrapper: W) -> Self::Output where W: FnOnce(&IoContext, Self::WrappedHandler), { let mut data = Some(CancelRef(ctx, timeout)); let coro: &mut CoroutineData = unsafe { &mut *self.0.data.clone().cell.get() }; wrapper(ctx.as_ctx(), self.0); let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume( &mut data as *mut _ as usize, ) }; coro.context = Some(context); coro.timer.cancel(); let res: &mut Option<Self::Output> = unsafe { &mut *(data as *mut Option<Self::Output>) }; res.take().unwrap() } } struct InitData { stack: ProtectedFixedSizeStack, ctx: IoContext, exec: Box<CoroutineExec>, } /// Context object that represents the currently executing coroutine. pub struct Coroutine<'a>(Strand<'a, CoroutineData>); impl<'a> Coroutine<'a> { extern "C" fn entry(t: Transfer) ->! { let InitData { stack, ctx, exec } = unsafe { &mut *(t.data as *mut Option<InitData>) } .take() .unwrap(); let mut coro: StrandImmutable<CoroutineData> = Strand::new( &ctx, CoroutineData { context: Some(t.context), timer: SteadyTimer::new(&ctx), }, ); let this = { let data = &coro as *const _ as usize; let mut coro: &mut CoroutineData = unsafe { coro.get() }; let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume(data) }; coro.context = Some(context); unsafe { &mut *(data as *mut ThreadIoContext) } }; exec.call_box(Coroutine(coro.make_mut(this))); let context = (&mut unsafe { coro.get() }.context).take().unwrap(); let mut stack = Some(stack); unsafe { context.resume_ontop(&mut stack as *mut _ as usize, Self::exit) }; unreachable!(); } extern "C" fn exit(mut t: Transfer) -> Transfer { { let stack = unsafe { &mut *(t.data as *mut Option<ProtectedFixedSizeStack>) }; // Drop the stack let _ = stack.take().unwrap(); } t.data = 0; t } /// Provides a `Coroutine` handler to asynchronous operation. /// /// # Examples /// /// ``` /// use asyncio::{IoContext, AsIoContext, Stream, spawn}; /// use asyncio::ip::{IpProtocol, Tcp, TcpSocket}; /// /// let ctx = &IoContext::new().unwrap(); /// spawn(ctx, |coro| { /// let ctx = coro.as_ctx(); /// let mut soc = TcpSocket::new(ctx, Tcp::v4()).unwrap(); /// let mut buf = [0; 256]; /// let size = soc.async_read_some(&mut buf, coro.wrap()).unwrap(); /// }); /// ``` pub fn wrap<R, E>(&self) -> CoroutineHandler<R, E> where R: Send +'static, E: Send +'static, { let handler: StrandHandler<CoroutineData, Caller<R, E>, R, E> = self.0.wrap(caller::<R, E>); CoroutineHandler(handler) } } fn caller<R, E>(mut coro: Strand<CoroutineData>, res: Result<R, E>) where R: Send +'static, E: Send +'static, { let mut data = Some(res); let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume( &mut data as *mut _ as usize, ) }; if data!= 0 { if let Some(ctx) = unsafe { &mut *(data as *mut Option<CancelRef>) }.take() { ctx.timeout(&coro); } coro.context = Some(context); } } unsafe impl<'a> AsIoContext for Coroutine<'a> { fn as_ctx(&self) -> &IoContext { self.0.as_ctx() } } pub fn spawn<F>(ctx: &IoContext, func: F) -> Result<(), StackError> where F: FnOnce(Coroutine) + Send +'static, { let data = InitData { stack: ProtectedFixedSizeStack::new(Stack::default_size())?, ctx: ctx.clone(), exec: Box::new(func), }; let context = unsafe { Context::new(&data.stack, Coroutine::entry) }; let data = Some(data); let Transfer { context, data } = unsafe { context.resume(&data as *const _ as usize) }; let coro = unsafe { &mut *(data as *mut StrandImmutable<CoroutineData>) }; unsafe { coro.get() }.context = Some(context); coro.post(move |mut coro| { let data = coro.this as *mut _ as usize; let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume(data) }; if data!= 0 { if let Some(ctx) = unsafe { &mut *(data as *mut Option<CancelRef>) }.take() { ctx.timeout(&coro); } coro.context = Some(context); } }); Ok(()) } #[test] fn test_spawn() { let ctx = &IoContext::new().unwrap(); spawn(ctx, |coro| {}); ctx.run(); }
{ coro.timer.expires_from_now(unsafe { &*self.1 }.get()); coro.timer.async_wait( coro.wrap(move |_, res| if let Ok(_) = res { unsafe { &*self.0 }.cancel(); }), ) }
identifier_body
coroutine.rs
use ffi::Timeout; use core::{AsIoContext, IoContext, ThreadIoContext, Cancel}; use handler::{Handler}; use strand::{Strand, StrandImmutable, StrandHandler}; use SteadyTimer; use context::{Context, Transfer}; use context::stack::{ProtectedFixedSizeStack, Stack, StackError}; trait CoroutineExec: Send +'static { fn call_box(self: Box<Self>, coro: Coroutine); } impl<F> CoroutineExec for F where F: FnOnce(Coroutine) + Send +'static, { fn call_box(self: Box<Self>, coro: Coroutine) { self(coro) } } pub struct CoroutineData { context: Option<Context>, timer: SteadyTimer, } unsafe impl AsIoContext for CoroutineData { fn as_ctx(&self) -> &IoContext { self.timer.as_ctx() } } #[derive(Clone)] struct CancelRef(*const Cancel, *const Timeout); impl CancelRef { fn timeout(self, coro: &Strand<CoroutineData>) { coro.timer.expires_from_now(unsafe { &*self.1 }.get()); coro.timer.async_wait( coro.wrap(move |_, res| if let Ok(_) = res { unsafe { &*self.0 }.cancel(); }), ) } } unsafe impl Send for CancelRef {} unsafe impl Sync for CancelRef {} type Caller<R, E> = fn(Strand<CoroutineData>, Result<R, E>); pub struct CoroutineHandler<R, E>(StrandHandler<CoroutineData, Caller<R, E>, R, E>); impl<R, E> Handler<R, E> for CoroutineHandler<R, E> where R: Send +'static, E: Send +'static, { type Output = Result<R, E>; #[doc(hidden)] type WrappedHandler = StrandHandler<CoroutineData, fn(Strand<CoroutineData>, Result<R, E>), R, E>; #[doc(hidden)] fn wrap<W>(self, ctx: &IoContext, wrapper: W) -> Self::Output where W: FnOnce(&IoContext, Self::WrappedHandler), { let mut data: Option<CancelRef> = None; let coro: &mut CoroutineData = unsafe { &mut *self.0.data.clone().cell.get() }; wrapper(ctx, self.0); let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume( &mut data as *mut _ as usize, ) }; coro.context = Some(context); coro.timer.cancel(); let res: &mut Option<Self::Output> = unsafe { &mut *(data as *mut Option<Self::Output>) }; res.take().unwrap() } #[doc(hidden)] fn wrap_timeout<W>(self, ctx: &Cancel, timeout: &Timeout, wrapper: W) -> Self::Output where W: FnOnce(&IoContext, Self::WrappedHandler), { let mut data = Some(CancelRef(ctx, timeout)); let coro: &mut CoroutineData = unsafe { &mut *self.0.data.clone().cell.get() }; wrapper(ctx.as_ctx(), self.0); let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume( &mut data as *mut _ as usize, ) }; coro.context = Some(context); coro.timer.cancel(); let res: &mut Option<Self::Output> = unsafe { &mut *(data as *mut Option<Self::Output>) }; res.take().unwrap() } } struct InitData { stack: ProtectedFixedSizeStack, ctx: IoContext, exec: Box<CoroutineExec>, } /// Context object that represents the currently executing coroutine. pub struct Coroutine<'a>(Strand<'a, CoroutineData>); impl<'a> Coroutine<'a> { extern "C" fn entry(t: Transfer) ->! {
.take() .unwrap(); let mut coro: StrandImmutable<CoroutineData> = Strand::new( &ctx, CoroutineData { context: Some(t.context), timer: SteadyTimer::new(&ctx), }, ); let this = { let data = &coro as *const _ as usize; let mut coro: &mut CoroutineData = unsafe { coro.get() }; let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume(data) }; coro.context = Some(context); unsafe { &mut *(data as *mut ThreadIoContext) } }; exec.call_box(Coroutine(coro.make_mut(this))); let context = (&mut unsafe { coro.get() }.context).take().unwrap(); let mut stack = Some(stack); unsafe { context.resume_ontop(&mut stack as *mut _ as usize, Self::exit) }; unreachable!(); } extern "C" fn exit(mut t: Transfer) -> Transfer { { let stack = unsafe { &mut *(t.data as *mut Option<ProtectedFixedSizeStack>) }; // Drop the stack let _ = stack.take().unwrap(); } t.data = 0; t } /// Provides a `Coroutine` handler to asynchronous operation. /// /// # Examples /// /// ``` /// use asyncio::{IoContext, AsIoContext, Stream, spawn}; /// use asyncio::ip::{IpProtocol, Tcp, TcpSocket}; /// /// let ctx = &IoContext::new().unwrap(); /// spawn(ctx, |coro| { /// let ctx = coro.as_ctx(); /// let mut soc = TcpSocket::new(ctx, Tcp::v4()).unwrap(); /// let mut buf = [0; 256]; /// let size = soc.async_read_some(&mut buf, coro.wrap()).unwrap(); /// }); /// ``` pub fn wrap<R, E>(&self) -> CoroutineHandler<R, E> where R: Send +'static, E: Send +'static, { let handler: StrandHandler<CoroutineData, Caller<R, E>, R, E> = self.0.wrap(caller::<R, E>); CoroutineHandler(handler) } } fn caller<R, E>(mut coro: Strand<CoroutineData>, res: Result<R, E>) where R: Send +'static, E: Send +'static, { let mut data = Some(res); let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume( &mut data as *mut _ as usize, ) }; if data!= 0 { if let Some(ctx) = unsafe { &mut *(data as *mut Option<CancelRef>) }.take() { ctx.timeout(&coro); } coro.context = Some(context); } } unsafe impl<'a> AsIoContext for Coroutine<'a> { fn as_ctx(&self) -> &IoContext { self.0.as_ctx() } } pub fn spawn<F>(ctx: &IoContext, func: F) -> Result<(), StackError> where F: FnOnce(Coroutine) + Send +'static, { let data = InitData { stack: ProtectedFixedSizeStack::new(Stack::default_size())?, ctx: ctx.clone(), exec: Box::new(func), }; let context = unsafe { Context::new(&data.stack, Coroutine::entry) }; let data = Some(data); let Transfer { context, data } = unsafe { context.resume(&data as *const _ as usize) }; let coro = unsafe { &mut *(data as *mut StrandImmutable<CoroutineData>) }; unsafe { coro.get() }.context = Some(context); coro.post(move |mut coro| { let data = coro.this as *mut _ as usize; let Transfer { context, data } = unsafe { coro.context.take().unwrap().resume(data) }; if data!= 0 { if let Some(ctx) = unsafe { &mut *(data as *mut Option<CancelRef>) }.take() { ctx.timeout(&coro); } coro.context = Some(context); } }); Ok(()) } #[test] fn test_spawn() { let ctx = &IoContext::new().unwrap(); spawn(ctx, |coro| {}); ctx.run(); }
let InitData { stack, ctx, exec } = unsafe { &mut *(t.data as *mut Option<InitData>) }
random_line_split
fs.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Windows-specific extensions for the primitives in `std::fs` #![stable(feature = "rust1", since = "1.0.0")] use prelude::v1::*; use fs::{OpenOptions, Metadata}; use io; use path::Path; use sys; use sys_common::{AsInnerMut, AsInner}; /// Windows-specific extensions to `OpenOptions` #[unstable(feature = "fs_ext", reason = "may require more thought/methods")] pub trait OpenOptionsExt { /// Overrides the `dwDesiredAccess` argument to the call to `CreateFile` /// with the specified value. fn desired_access(&mut self, access: i32) -> &mut Self; /// Overrides the `dwCreationDisposition` argument to the call to /// `CreateFile` with the specified value. /// /// This will override any values of the standard `create` flags, for /// example. fn creation_disposition(&mut self, val: i32) -> &mut Self; /// Overrides the `dwFlagsAndAttributes` argument to the call to /// `CreateFile` with the specified value. /// /// This will override any values of the standard flags on the /// `OpenOptions` structure. fn flags_and_attributes(&mut self, val: i32) -> &mut Self; /// Overrides the `dwShareMode` argument to the call to `CreateFile` with /// the specified value. /// /// This will override any values of the standard flags on the /// `OpenOptions` structure. fn share_mode(&mut self, val: i32) -> &mut Self; } impl OpenOptionsExt for OpenOptions { fn desired_access(&mut self, access: i32) -> &mut OpenOptions { self.as_inner_mut().desired_access(access); self } fn creation_disposition(&mut self, access: i32) -> &mut OpenOptions { self.as_inner_mut().creation_disposition(access); self } fn flags_and_attributes(&mut self, access: i32) -> &mut OpenOptions { self.as_inner_mut().flags_and_attributes(access); self } fn share_mode(&mut self, access: i32) -> &mut OpenOptions { self.as_inner_mut().share_mode(access); self } } /// Extension methods for `fs::Metadata` to access the raw fields contained /// within. #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait MetadataExt { /// Returns the value of the `dwFileAttributes` field of this metadata. /// /// This field contains the file system attribute information for a file /// or directory. fn file_attributes(&self) -> u32; /// Returns the value of the `ftCreationTime` field of this metadata. /// /// The returned 64-bit value represents the number of 100-nanosecond /// intervals since January 1, 1601 (UTC). fn creation_time(&self) -> u64; /// Returns the value of the `ftLastAccessTime` field of this metadata. /// /// The returned 64-bit value represents the number of 100-nanosecond /// intervals since January 1, 1601 (UTC). fn last_access_time(&self) -> u64; /// Returns the value of the `ftLastWriteTime` field of this metadata. /// /// The returned 64-bit value represents the number of 100-nanosecond /// intervals since January 1, 1601 (UTC). fn last_write_time(&self) -> u64; /// Returns the value of the `nFileSize{High,Low}` fields of this /// metadata. /// /// The returned value does not have meaning for directories. fn file_size(&self) -> u64; } impl MetadataExt for Metadata { fn file_attributes(&self) -> u32 { self.as_inner().attrs() } fn
(&self) -> u64 { self.as_inner().created() } fn last_access_time(&self) -> u64 { self.as_inner().accessed() } fn last_write_time(&self) -> u64 { self.as_inner().modified() } fn file_size(&self) -> u64 { self.as_inner().size() } } /// Creates a new file symbolic link on the filesystem. /// /// The `dst` path will be a file symbolic link pointing to the `src` /// path. /// /// # Examples /// /// ```ignore /// use std::os::windows::fs; /// /// # fn foo() -> std::io::Result<()> { /// try!(fs::symlink_file("a.txt", "b.txt")); /// # Ok(()) /// # } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> { sys::fs::symlink_inner(src.as_ref(), dst.as_ref(), false) } /// Creates a new directory symlink on the filesystem. /// /// The `dst` path will be a directory symbolic link pointing to the `src` /// path. /// /// # Examples /// /// ```ignore /// use std::os::windows::fs; /// /// # fn foo() -> std::io::Result<()> { /// try!(fs::symlink_file("a", "b")); /// # Ok(()) /// # } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn symlink_dir<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> { sys::fs::symlink_inner(src.as_ref(), dst.as_ref(), true) }
creation_time
identifier_name
fs.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Windows-specific extensions for the primitives in `std::fs` #![stable(feature = "rust1", since = "1.0.0")] use prelude::v1::*; use fs::{OpenOptions, Metadata}; use io; use path::Path; use sys; use sys_common::{AsInnerMut, AsInner}; /// Windows-specific extensions to `OpenOptions` #[unstable(feature = "fs_ext", reason = "may require more thought/methods")] pub trait OpenOptionsExt { /// Overrides the `dwDesiredAccess` argument to the call to `CreateFile` /// with the specified value. fn desired_access(&mut self, access: i32) -> &mut Self; /// Overrides the `dwCreationDisposition` argument to the call to /// `CreateFile` with the specified value. /// /// This will override any values of the standard `create` flags, for /// example. fn creation_disposition(&mut self, val: i32) -> &mut Self; /// Overrides the `dwFlagsAndAttributes` argument to the call to /// `CreateFile` with the specified value. /// /// This will override any values of the standard flags on the /// `OpenOptions` structure. fn flags_and_attributes(&mut self, val: i32) -> &mut Self; /// Overrides the `dwShareMode` argument to the call to `CreateFile` with /// the specified value. /// /// This will override any values of the standard flags on the /// `OpenOptions` structure. fn share_mode(&mut self, val: i32) -> &mut Self; } impl OpenOptionsExt for OpenOptions { fn desired_access(&mut self, access: i32) -> &mut OpenOptions { self.as_inner_mut().desired_access(access); self } fn creation_disposition(&mut self, access: i32) -> &mut OpenOptions { self.as_inner_mut().creation_disposition(access); self } fn flags_and_attributes(&mut self, access: i32) -> &mut OpenOptions { self.as_inner_mut().flags_and_attributes(access); self } fn share_mode(&mut self, access: i32) -> &mut OpenOptions { self.as_inner_mut().share_mode(access); self } } /// Extension methods for `fs::Metadata` to access the raw fields contained /// within. #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait MetadataExt { /// Returns the value of the `dwFileAttributes` field of this metadata. /// /// This field contains the file system attribute information for a file /// or directory. fn file_attributes(&self) -> u32; /// Returns the value of the `ftCreationTime` field of this metadata. /// /// The returned 64-bit value represents the number of 100-nanosecond /// intervals since January 1, 1601 (UTC). fn creation_time(&self) -> u64; /// Returns the value of the `ftLastAccessTime` field of this metadata. /// /// The returned 64-bit value represents the number of 100-nanosecond /// intervals since January 1, 1601 (UTC). fn last_access_time(&self) -> u64; /// Returns the value of the `ftLastWriteTime` field of this metadata. /// /// The returned 64-bit value represents the number of 100-nanosecond /// intervals since January 1, 1601 (UTC). fn last_write_time(&self) -> u64; /// Returns the value of the `nFileSize{High,Low}` fields of this /// metadata. /// /// The returned value does not have meaning for directories. fn file_size(&self) -> u64; } impl MetadataExt for Metadata { fn file_attributes(&self) -> u32 { self.as_inner().attrs() } fn creation_time(&self) -> u64 { self.as_inner().created() } fn last_access_time(&self) -> u64 { self.as_inner().accessed() } fn last_write_time(&self) -> u64 { self.as_inner().modified() } fn file_size(&self) -> u64
} /// Creates a new file symbolic link on the filesystem. /// /// The `dst` path will be a file symbolic link pointing to the `src` /// path. /// /// # Examples /// /// ```ignore /// use std::os::windows::fs; /// /// # fn foo() -> std::io::Result<()> { /// try!(fs::symlink_file("a.txt", "b.txt")); /// # Ok(()) /// # } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> { sys::fs::symlink_inner(src.as_ref(), dst.as_ref(), false) } /// Creates a new directory symlink on the filesystem. /// /// The `dst` path will be a directory symbolic link pointing to the `src` /// path. /// /// # Examples /// /// ```ignore /// use std::os::windows::fs; /// /// # fn foo() -> std::io::Result<()> { /// try!(fs::symlink_file("a", "b")); /// # Ok(()) /// # } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn symlink_dir<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> { sys::fs::symlink_inner(src.as_ref(), dst.as_ref(), true) }
{ self.as_inner().size() }
identifier_body
fs.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Windows-specific extensions for the primitives in `std::fs` #![stable(feature = "rust1", since = "1.0.0")]
use prelude::v1::*; use fs::{OpenOptions, Metadata}; use io; use path::Path; use sys; use sys_common::{AsInnerMut, AsInner}; /// Windows-specific extensions to `OpenOptions` #[unstable(feature = "fs_ext", reason = "may require more thought/methods")] pub trait OpenOptionsExt { /// Overrides the `dwDesiredAccess` argument to the call to `CreateFile` /// with the specified value. fn desired_access(&mut self, access: i32) -> &mut Self; /// Overrides the `dwCreationDisposition` argument to the call to /// `CreateFile` with the specified value. /// /// This will override any values of the standard `create` flags, for /// example. fn creation_disposition(&mut self, val: i32) -> &mut Self; /// Overrides the `dwFlagsAndAttributes` argument to the call to /// `CreateFile` with the specified value. /// /// This will override any values of the standard flags on the /// `OpenOptions` structure. fn flags_and_attributes(&mut self, val: i32) -> &mut Self; /// Overrides the `dwShareMode` argument to the call to `CreateFile` with /// the specified value. /// /// This will override any values of the standard flags on the /// `OpenOptions` structure. fn share_mode(&mut self, val: i32) -> &mut Self; } impl OpenOptionsExt for OpenOptions { fn desired_access(&mut self, access: i32) -> &mut OpenOptions { self.as_inner_mut().desired_access(access); self } fn creation_disposition(&mut self, access: i32) -> &mut OpenOptions { self.as_inner_mut().creation_disposition(access); self } fn flags_and_attributes(&mut self, access: i32) -> &mut OpenOptions { self.as_inner_mut().flags_and_attributes(access); self } fn share_mode(&mut self, access: i32) -> &mut OpenOptions { self.as_inner_mut().share_mode(access); self } } /// Extension methods for `fs::Metadata` to access the raw fields contained /// within. #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait MetadataExt { /// Returns the value of the `dwFileAttributes` field of this metadata. /// /// This field contains the file system attribute information for a file /// or directory. fn file_attributes(&self) -> u32; /// Returns the value of the `ftCreationTime` field of this metadata. /// /// The returned 64-bit value represents the number of 100-nanosecond /// intervals since January 1, 1601 (UTC). fn creation_time(&self) -> u64; /// Returns the value of the `ftLastAccessTime` field of this metadata. /// /// The returned 64-bit value represents the number of 100-nanosecond /// intervals since January 1, 1601 (UTC). fn last_access_time(&self) -> u64; /// Returns the value of the `ftLastWriteTime` field of this metadata. /// /// The returned 64-bit value represents the number of 100-nanosecond /// intervals since January 1, 1601 (UTC). fn last_write_time(&self) -> u64; /// Returns the value of the `nFileSize{High,Low}` fields of this /// metadata. /// /// The returned value does not have meaning for directories. fn file_size(&self) -> u64; } impl MetadataExt for Metadata { fn file_attributes(&self) -> u32 { self.as_inner().attrs() } fn creation_time(&self) -> u64 { self.as_inner().created() } fn last_access_time(&self) -> u64 { self.as_inner().accessed() } fn last_write_time(&self) -> u64 { self.as_inner().modified() } fn file_size(&self) -> u64 { self.as_inner().size() } } /// Creates a new file symbolic link on the filesystem. /// /// The `dst` path will be a file symbolic link pointing to the `src` /// path. /// /// # Examples /// /// ```ignore /// use std::os::windows::fs; /// /// # fn foo() -> std::io::Result<()> { /// try!(fs::symlink_file("a.txt", "b.txt")); /// # Ok(()) /// # } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> { sys::fs::symlink_inner(src.as_ref(), dst.as_ref(), false) } /// Creates a new directory symlink on the filesystem. /// /// The `dst` path will be a directory symbolic link pointing to the `src` /// path. /// /// # Examples /// /// ```ignore /// use std::os::windows::fs; /// /// # fn foo() -> std::io::Result<()> { /// try!(fs::symlink_file("a", "b")); /// # Ok(()) /// # } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn symlink_dir<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> { sys::fs::symlink_inner(src.as_ref(), dst.as_ref(), true) }
random_line_split
lib.rs
//! Vector dot product #![deny(warnings, rust_2018_idioms)] #![feature(custom_inner_attributes)] pub mod scalar; pub mod simd; #[cfg(test)] #[rustfmt::skip]
(&[1_f32, 2., 3., 4.], &[1_f32, 2., 3., 4.], 30_f32), (&[1_f32, 2., 3., 4., 1., 2., 3., 4.], &[1_f32, 1., 1., 1., 1., 1., 1., 1.], 20_f32), ]; for &(a, b, output) in tests { assert_eq!(f(a, b), output); } }
fn test<F: Fn(&[f32], &[f32]) -> f32>(f: F) { let tests: &[(&[f32], &[f32], f32)] = &[ (&[0_f32, 0., 0., 0.], &[0_f32, 0., 0., 0.], 0_f32), (&[0_f32, 0., 0., 1.], &[0_f32, 0., 0., 1.], 1_f32), (&[1_f32, 2., 3., 4.], &[0_f32, 0., 0., 0.], 0_f32),
random_line_split
lib.rs
//! Vector dot product #![deny(warnings, rust_2018_idioms)] #![feature(custom_inner_attributes)] pub mod scalar; pub mod simd; #[cfg(test)] #[rustfmt::skip] fn
<F: Fn(&[f32], &[f32]) -> f32>(f: F) { let tests: &[(&[f32], &[f32], f32)] = &[ (&[0_f32, 0., 0., 0.], &[0_f32, 0., 0., 0.], 0_f32), (&[0_f32, 0., 0., 1.], &[0_f32, 0., 0., 1.], 1_f32), (&[1_f32, 2., 3., 4.], &[0_f32, 0., 0., 0.], 0_f32), (&[1_f32, 2., 3., 4.], &[1_f32, 2., 3., 4.], 30_f32), (&[1_f32, 2., 3., 4., 1., 2., 3., 4.], &[1_f32, 1., 1., 1., 1., 1., 1., 1.], 20_f32), ]; for &(a, b, output) in tests { assert_eq!(f(a, b), output); } }
test
identifier_name
lib.rs
//! Vector dot product #![deny(warnings, rust_2018_idioms)] #![feature(custom_inner_attributes)] pub mod scalar; pub mod simd; #[cfg(test)] #[rustfmt::skip] fn test<F: Fn(&[f32], &[f32]) -> f32>(f: F)
{ let tests: &[(&[f32], &[f32], f32)] = &[ (&[0_f32, 0., 0., 0.], &[0_f32, 0., 0., 0.], 0_f32), (&[0_f32, 0., 0., 1.], &[0_f32, 0., 0., 1.], 1_f32), (&[1_f32, 2., 3., 4.], &[0_f32, 0., 0., 0.], 0_f32), (&[1_f32, 2., 3., 4.], &[1_f32, 2., 3., 4.], 30_f32), (&[1_f32, 2., 3., 4., 1., 2., 3., 4.], &[1_f32, 1., 1., 1., 1., 1., 1., 1.], 20_f32), ]; for &(a, b, output) in tests { assert_eq!(f(a, b), output); } }
identifier_body
keyframes.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/. */ //! Keyframes: https://drafts.csswg.org/css-animations/#keyframes #![deny(missing_docs)] use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser}; use cssparser::{DeclarationListParser, DeclarationParser, parse_one_rule}; use error_reporting::NullReporter; use parser::{PARSING_MODE_DEFAULT, ParserContext, log_css_error}; use properties::{Importance, PropertyDeclaration, PropertyDeclarationBlock, PropertyId}; use properties::{PropertyDeclarationId, LonghandId, SourcePropertyDeclaration}; use properties::LonghandIdSet; use properties::animated_properties::TransitionProperty; use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction; use shared_lock::{SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard}; use std::fmt; use style_traits::ToCss; use stylearc::Arc; use stylesheets::{CssRuleType, Stylesheet, VendorPrefix}; /// A number from 0 to 1, indicating the percentage of the animation when this /// keyframe should run. #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframePercentage(pub f32); impl ::std::cmp::Ord for KeyframePercentage { #[inline] fn
(&self, other: &Self) -> ::std::cmp::Ordering { // We know we have a number from 0 to 1, so unwrap() here is safe. self.0.partial_cmp(&other.0).unwrap() } } impl ::std::cmp::Eq for KeyframePercentage { } impl ToCss for KeyframePercentage { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}%", self.0 * 100.0) } } impl KeyframePercentage { /// Trivially constructs a new `KeyframePercentage`. #[inline] pub fn new(value: f32) -> KeyframePercentage { debug_assert!(value >= 0. && value <= 1.); KeyframePercentage(value) } fn parse(input: &mut Parser) -> Result<KeyframePercentage, ()> { let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() { KeyframePercentage::new(0.) } else if input.try(|input| input.expect_ident_matching("to")).is_ok() { KeyframePercentage::new(1.) } else { let percentage = try!(input.expect_percentage()); if percentage >= 0. && percentage <= 1. { KeyframePercentage::new(percentage) } else { return Err(()); } }; Ok(percentage) } } /// A keyframes selector is a list of percentages or from/to symbols, which are /// converted at parse time to percentages. #[derive(Clone, Debug, PartialEq, Eq)] pub struct KeyframeSelector(Vec<KeyframePercentage>); impl ToCss for KeyframeSelector { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); iter.next().unwrap().to_css(dest)?; for percentage in iter { write!(dest, ", ")?; percentage.to_css(dest)?; } Ok(()) } } impl KeyframeSelector { /// Return the list of percentages this selector contains. #[inline] pub fn percentages(&self) -> &[KeyframePercentage] { &self.0 } /// A dummy public function so we can write a unit test for this. pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector { KeyframeSelector(percentages) } /// Parse a keyframe selector from CSS input. pub fn parse(input: &mut Parser) -> Result<Self, ()> { input.parse_comma_separated(KeyframePercentage::parse) .map(KeyframeSelector) } } /// A keyframe. #[derive(Debug)] pub struct Keyframe { /// The selector this keyframe was specified from. pub selector: KeyframeSelector, /// The declaration block that was declared inside this keyframe. /// /// Note that `!important` rules in keyframes don't apply, but we keep this /// `Arc` just for convenience. pub block: Arc<Locked<PropertyDeclarationBlock>>, } impl ToCssWithGuard for Keyframe { fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result where W: fmt::Write { self.selector.to_css(dest)?; try!(dest.write_str(" { ")); try!(self.block.read_with(guard).to_css(dest)); try!(dest.write_str(" }")); Ok(()) } } impl Keyframe { /// Parse a CSS keyframe. pub fn parse(css: &str, parent_stylesheet: &Stylesheet) -> Result<Arc<Locked<Self>>, ()> { let error_reporter = NullReporter; let context = ParserContext::new(parent_stylesheet.origin, &parent_stylesheet.url_data, &error_reporter, Some(CssRuleType::Keyframe), PARSING_MODE_DEFAULT, parent_stylesheet.quirks_mode); let mut input = Parser::new(css); let mut declarations = SourcePropertyDeclaration::new(); let mut rule_parser = KeyframeListParser { context: &context, shared_lock: &parent_stylesheet.shared_lock, declarations: &mut declarations, }; parse_one_rule(&mut input, &mut rule_parser) } /// Deep clones this Keyframe. pub fn deep_clone_with_lock(&self, lock: &SharedRwLock) -> Keyframe { let guard = lock.read(); Keyframe { selector: self.selector.clone(), block: Arc::new(lock.wrap(self.block.read_with(&guard).clone())), } } } /// A keyframes step value. This can be a synthetised keyframes animation, that /// is, one autogenerated from the current computed values, or a list of /// declarations to apply. /// /// TODO: Find a better name for this? #[derive(Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum KeyframesStepValue { /// A step formed by a declaration block specified by the CSS. Declarations { /// The declaration block per se. #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] block: Arc<Locked<PropertyDeclarationBlock>> }, /// A synthetic step computed from the current computed values at the time /// of the animation. ComputedValues, } /// A single step from a keyframe animation. #[derive(Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesStep { /// The percentage of the animation duration when this step starts. pub start_percentage: KeyframePercentage, /// Declarations that will determine the final style during the step, or /// `ComputedValues` if this is an autogenerated step. pub value: KeyframesStepValue, /// Wether a animation-timing-function declaration exists in the list of /// declarations. /// /// This is used to know when to override the keyframe animation style. pub declared_timing_function: bool, } impl KeyframesStep { #[inline] fn new(percentage: KeyframePercentage, value: KeyframesStepValue, guard: &SharedRwLockReadGuard) -> Self { let declared_timing_function = match value { KeyframesStepValue::Declarations { ref block } => { block.read_with(guard).declarations().iter().any(|&(ref prop_decl, _)| { match *prop_decl { PropertyDeclaration::AnimationTimingFunction(..) => true, _ => false, } }) } _ => false, }; KeyframesStep { start_percentage: percentage, value: value, declared_timing_function: declared_timing_function, } } /// Return specified TransitionTimingFunction if this KeyframesSteps has 'animation-timing-function'. pub fn get_animation_timing_function(&self, guard: &SharedRwLockReadGuard) -> Option<SpecifiedTimingFunction> { if!self.declared_timing_function { return None; } match self.value { KeyframesStepValue::Declarations { ref block } => { let guard = block.read_with(guard); let &(ref declaration, _) = guard.get(PropertyDeclarationId::Longhand(LonghandId::AnimationTimingFunction)).unwrap(); match *declaration { PropertyDeclaration::AnimationTimingFunction(ref value) => { // Use the first value. Some(value.0[0]) }, PropertyDeclaration::CSSWideKeyword(..) => None, PropertyDeclaration::WithVariables(..) => None, _ => panic!(), } }, KeyframesStepValue::ComputedValues => { panic!("Shouldn't happen to set animation-timing-function in missing keyframes") }, } } } /// This structure represents a list of animation steps computed from the list /// of keyframes, in order. /// /// It only takes into account animable properties. #[derive(Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesAnimation { /// The difference steps of the animation. pub steps: Vec<KeyframesStep>, /// The properties that change in this animation. pub properties_changed: Vec<TransitionProperty>, /// Vendor prefix type the @keyframes has. pub vendor_prefix: Option<VendorPrefix>, } /// Get all the animated properties in a keyframes animation. fn get_animated_properties(keyframes: &[Arc<Locked<Keyframe>>], guard: &SharedRwLockReadGuard) -> Vec<TransitionProperty> { let mut ret = vec![]; let mut seen = LonghandIdSet::new(); // NB: declarations are already deduplicated, so we don't have to check for // it here. for keyframe in keyframes { let keyframe = keyframe.read_with(&guard); let block = keyframe.block.read_with(guard); for &(ref declaration, importance) in block.declarations().iter() { assert!(!importance.important()); if let Some(property) = TransitionProperty::from_declaration(declaration) { if!seen.has_transition_property_bit(&property) { seen.set_transition_property_bit(&property); ret.push(property); } } } } ret } impl KeyframesAnimation { /// Create a keyframes animation from a given list of keyframes. /// /// This will return a keyframe animation with empty steps and /// properties_changed if the list of keyframes is empty, or there are no // animated properties obtained from the keyframes. /// /// Otherwise, this will compute and sort the steps used for the animation, /// and return the animation object. pub fn from_keyframes(keyframes: &[Arc<Locked<Keyframe>>], vendor_prefix: Option<VendorPrefix>, guard: &SharedRwLockReadGuard) -> Self { let mut result = KeyframesAnimation { steps: vec![], properties_changed: vec![], vendor_prefix: vendor_prefix, }; if keyframes.is_empty() { return result; } result.properties_changed = get_animated_properties(keyframes, guard); if result.properties_changed.is_empty() { return result; } for keyframe in keyframes { let keyframe = keyframe.read_with(&guard); for percentage in keyframe.selector.0.iter() { result.steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations { block: keyframe.block.clone(), }, guard)); } } // Sort by the start percentage, so we can easily find a frame. result.steps.sort_by_key(|step| step.start_percentage); // Prepend autogenerated keyframes if appropriate. if result.steps[0].start_percentage.0!= 0. { result.steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.), KeyframesStepValue::ComputedValues, guard)); } if result.steps.last().unwrap().start_percentage.0!= 1. { result.steps.push(KeyframesStep::new(KeyframePercentage::new(1.), KeyframesStepValue::ComputedValues, guard)); } result } } /// Parses a keyframes list, like: /// 0%, 50% { /// width: 50%; /// } /// /// 40%, 60%, 100% { /// width: 100%; /// } struct KeyframeListParser<'a> { context: &'a ParserContext<'a>, shared_lock: &'a SharedRwLock, declarations: &'a mut SourcePropertyDeclaration, } /// Parses a keyframe list from CSS input. pub fn parse_keyframe_list(context: &ParserContext, input: &mut Parser, shared_lock: &SharedRwLock) -> Vec<Arc<Locked<Keyframe>>> { let mut declarations = SourcePropertyDeclaration::new(); RuleListParser::new_for_nested_rule(input, KeyframeListParser { context: context, shared_lock: shared_lock, declarations: &mut declarations, }).filter_map(Result::ok).collect() } enum Void {} impl<'a> AtRuleParser for KeyframeListParser<'a> { type Prelude = Void; type AtRule = Arc<Locked<Keyframe>>; } impl<'a> QualifiedRuleParser for KeyframeListParser<'a> { type Prelude = KeyframeSelector; type QualifiedRule = Arc<Locked<Keyframe>>; fn parse_prelude(&mut self, input: &mut Parser) -> Result<Self::Prelude, ()> { let start = input.position(); match KeyframeSelector::parse(input) { Ok(sel) => Ok(sel), Err(()) => { let message = format!("Invalid keyframe rule: '{}'", input.slice_from(start)); log_css_error(input, start, &message, self.context); Err(()) } } } fn parse_block(&mut self, prelude: Self::Prelude, input: &mut Parser) -> Result<Self::QualifiedRule, ()> { let context = ParserContext::new_with_rule_type(self.context, Some(CssRuleType::Keyframe)); let parser = KeyframeDeclarationParser { context: &context, declarations: self.declarations, }; let mut iter = DeclarationListParser::new(input, parser); let mut block = PropertyDeclarationBlock::new(); while let Some(declaration) = iter.next() { match declaration { Ok(()) => { block.extend(iter.parser.declarations.drain(), Importance::Normal); } Err(range) => { iter.parser.declarations.clear(); let pos = range.start; let message = format!("Unsupported keyframe property declaration: '{}'", iter.input.slice(range)); log_css_error(iter.input, pos, &*message, &context); } } // `parse_important` is not called here, `!important` is not allowed in keyframe blocks. } Ok(Arc::new(self.shared_lock.wrap(Keyframe { selector: prelude, block: Arc::new(self.shared_lock.wrap(block)), }))) } } struct KeyframeDeclarationParser<'a, 'b: 'a> { context: &'a ParserContext<'b>, declarations: &'a mut SourcePropertyDeclaration, } /// Default methods reject all at rules. impl<'a, 'b> AtRuleParser for KeyframeDeclarationParser<'a, 'b> { type Prelude = (); type AtRule = (); } impl<'a, 'b> DeclarationParser for KeyframeDeclarationParser<'a, 'b> { type Declaration = (); fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<(), ()> { let id = try!(PropertyId::parse(name.into())); match PropertyDeclaration::parse_into(self.declarations, id, self.context, input) { Ok(()) => { // In case there is still unparsed text in the declaration, we should roll back. input.expect_exhausted() } Err(_) => Err(()) } } }
cmp
identifier_name
keyframes.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/. */ //! Keyframes: https://drafts.csswg.org/css-animations/#keyframes #![deny(missing_docs)] use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser}; use cssparser::{DeclarationListParser, DeclarationParser, parse_one_rule}; use error_reporting::NullReporter; use parser::{PARSING_MODE_DEFAULT, ParserContext, log_css_error}; use properties::{Importance, PropertyDeclaration, PropertyDeclarationBlock, PropertyId}; use properties::{PropertyDeclarationId, LonghandId, SourcePropertyDeclaration}; use properties::LonghandIdSet; use properties::animated_properties::TransitionProperty; use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction; use shared_lock::{SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard}; use std::fmt; use style_traits::ToCss; use stylearc::Arc; use stylesheets::{CssRuleType, Stylesheet, VendorPrefix}; /// A number from 0 to 1, indicating the percentage of the animation when this /// keyframe should run. #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframePercentage(pub f32); impl ::std::cmp::Ord for KeyframePercentage { #[inline] fn cmp(&self, other: &Self) -> ::std::cmp::Ordering { // We know we have a number from 0 to 1, so unwrap() here is safe. self.0.partial_cmp(&other.0).unwrap() } } impl ::std::cmp::Eq for KeyframePercentage { } impl ToCss for KeyframePercentage { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}%", self.0 * 100.0) } } impl KeyframePercentage { /// Trivially constructs a new `KeyframePercentage`. #[inline] pub fn new(value: f32) -> KeyframePercentage { debug_assert!(value >= 0. && value <= 1.); KeyframePercentage(value) } fn parse(input: &mut Parser) -> Result<KeyframePercentage, ()> { let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() { KeyframePercentage::new(0.) } else if input.try(|input| input.expect_ident_matching("to")).is_ok() { KeyframePercentage::new(1.) } else { let percentage = try!(input.expect_percentage()); if percentage >= 0. && percentage <= 1. { KeyframePercentage::new(percentage) } else { return Err(()); } }; Ok(percentage) } } /// A keyframes selector is a list of percentages or from/to symbols, which are /// converted at parse time to percentages. #[derive(Clone, Debug, PartialEq, Eq)] pub struct KeyframeSelector(Vec<KeyframePercentage>); impl ToCss for KeyframeSelector { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); iter.next().unwrap().to_css(dest)?; for percentage in iter { write!(dest, ", ")?; percentage.to_css(dest)?; } Ok(()) } } impl KeyframeSelector { /// Return the list of percentages this selector contains. #[inline] pub fn percentages(&self) -> &[KeyframePercentage] { &self.0 } /// A dummy public function so we can write a unit test for this. pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector { KeyframeSelector(percentages) } /// Parse a keyframe selector from CSS input. pub fn parse(input: &mut Parser) -> Result<Self, ()> { input.parse_comma_separated(KeyframePercentage::parse) .map(KeyframeSelector) } } /// A keyframe. #[derive(Debug)] pub struct Keyframe { /// The selector this keyframe was specified from. pub selector: KeyframeSelector, /// The declaration block that was declared inside this keyframe. /// /// Note that `!important` rules in keyframes don't apply, but we keep this /// `Arc` just for convenience. pub block: Arc<Locked<PropertyDeclarationBlock>>, } impl ToCssWithGuard for Keyframe { fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result where W: fmt::Write { self.selector.to_css(dest)?; try!(dest.write_str(" { ")); try!(self.block.read_with(guard).to_css(dest)); try!(dest.write_str(" }")); Ok(()) } } impl Keyframe { /// Parse a CSS keyframe. pub fn parse(css: &str, parent_stylesheet: &Stylesheet) -> Result<Arc<Locked<Self>>, ()>
/// Deep clones this Keyframe. pub fn deep_clone_with_lock(&self, lock: &SharedRwLock) -> Keyframe { let guard = lock.read(); Keyframe { selector: self.selector.clone(), block: Arc::new(lock.wrap(self.block.read_with(&guard).clone())), } } } /// A keyframes step value. This can be a synthetised keyframes animation, that /// is, one autogenerated from the current computed values, or a list of /// declarations to apply. /// /// TODO: Find a better name for this? #[derive(Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum KeyframesStepValue { /// A step formed by a declaration block specified by the CSS. Declarations { /// The declaration block per se. #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] block: Arc<Locked<PropertyDeclarationBlock>> }, /// A synthetic step computed from the current computed values at the time /// of the animation. ComputedValues, } /// A single step from a keyframe animation. #[derive(Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesStep { /// The percentage of the animation duration when this step starts. pub start_percentage: KeyframePercentage, /// Declarations that will determine the final style during the step, or /// `ComputedValues` if this is an autogenerated step. pub value: KeyframesStepValue, /// Wether a animation-timing-function declaration exists in the list of /// declarations. /// /// This is used to know when to override the keyframe animation style. pub declared_timing_function: bool, } impl KeyframesStep { #[inline] fn new(percentage: KeyframePercentage, value: KeyframesStepValue, guard: &SharedRwLockReadGuard) -> Self { let declared_timing_function = match value { KeyframesStepValue::Declarations { ref block } => { block.read_with(guard).declarations().iter().any(|&(ref prop_decl, _)| { match *prop_decl { PropertyDeclaration::AnimationTimingFunction(..) => true, _ => false, } }) } _ => false, }; KeyframesStep { start_percentage: percentage, value: value, declared_timing_function: declared_timing_function, } } /// Return specified TransitionTimingFunction if this KeyframesSteps has 'animation-timing-function'. pub fn get_animation_timing_function(&self, guard: &SharedRwLockReadGuard) -> Option<SpecifiedTimingFunction> { if!self.declared_timing_function { return None; } match self.value { KeyframesStepValue::Declarations { ref block } => { let guard = block.read_with(guard); let &(ref declaration, _) = guard.get(PropertyDeclarationId::Longhand(LonghandId::AnimationTimingFunction)).unwrap(); match *declaration { PropertyDeclaration::AnimationTimingFunction(ref value) => { // Use the first value. Some(value.0[0]) }, PropertyDeclaration::CSSWideKeyword(..) => None, PropertyDeclaration::WithVariables(..) => None, _ => panic!(), } }, KeyframesStepValue::ComputedValues => { panic!("Shouldn't happen to set animation-timing-function in missing keyframes") }, } } } /// This structure represents a list of animation steps computed from the list /// of keyframes, in order. /// /// It only takes into account animable properties. #[derive(Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesAnimation { /// The difference steps of the animation. pub steps: Vec<KeyframesStep>, /// The properties that change in this animation. pub properties_changed: Vec<TransitionProperty>, /// Vendor prefix type the @keyframes has. pub vendor_prefix: Option<VendorPrefix>, } /// Get all the animated properties in a keyframes animation. fn get_animated_properties(keyframes: &[Arc<Locked<Keyframe>>], guard: &SharedRwLockReadGuard) -> Vec<TransitionProperty> { let mut ret = vec![]; let mut seen = LonghandIdSet::new(); // NB: declarations are already deduplicated, so we don't have to check for // it here. for keyframe in keyframes { let keyframe = keyframe.read_with(&guard); let block = keyframe.block.read_with(guard); for &(ref declaration, importance) in block.declarations().iter() { assert!(!importance.important()); if let Some(property) = TransitionProperty::from_declaration(declaration) { if!seen.has_transition_property_bit(&property) { seen.set_transition_property_bit(&property); ret.push(property); } } } } ret } impl KeyframesAnimation { /// Create a keyframes animation from a given list of keyframes. /// /// This will return a keyframe animation with empty steps and /// properties_changed if the list of keyframes is empty, or there are no // animated properties obtained from the keyframes. /// /// Otherwise, this will compute and sort the steps used for the animation, /// and return the animation object. pub fn from_keyframes(keyframes: &[Arc<Locked<Keyframe>>], vendor_prefix: Option<VendorPrefix>, guard: &SharedRwLockReadGuard) -> Self { let mut result = KeyframesAnimation { steps: vec![], properties_changed: vec![], vendor_prefix: vendor_prefix, }; if keyframes.is_empty() { return result; } result.properties_changed = get_animated_properties(keyframes, guard); if result.properties_changed.is_empty() { return result; } for keyframe in keyframes { let keyframe = keyframe.read_with(&guard); for percentage in keyframe.selector.0.iter() { result.steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations { block: keyframe.block.clone(), }, guard)); } } // Sort by the start percentage, so we can easily find a frame. result.steps.sort_by_key(|step| step.start_percentage); // Prepend autogenerated keyframes if appropriate. if result.steps[0].start_percentage.0!= 0. { result.steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.), KeyframesStepValue::ComputedValues, guard)); } if result.steps.last().unwrap().start_percentage.0!= 1. { result.steps.push(KeyframesStep::new(KeyframePercentage::new(1.), KeyframesStepValue::ComputedValues, guard)); } result } } /// Parses a keyframes list, like: /// 0%, 50% { /// width: 50%; /// } /// /// 40%, 60%, 100% { /// width: 100%; /// } struct KeyframeListParser<'a> { context: &'a ParserContext<'a>, shared_lock: &'a SharedRwLock, declarations: &'a mut SourcePropertyDeclaration, } /// Parses a keyframe list from CSS input. pub fn parse_keyframe_list(context: &ParserContext, input: &mut Parser, shared_lock: &SharedRwLock) -> Vec<Arc<Locked<Keyframe>>> { let mut declarations = SourcePropertyDeclaration::new(); RuleListParser::new_for_nested_rule(input, KeyframeListParser { context: context, shared_lock: shared_lock, declarations: &mut declarations, }).filter_map(Result::ok).collect() } enum Void {} impl<'a> AtRuleParser for KeyframeListParser<'a> { type Prelude = Void; type AtRule = Arc<Locked<Keyframe>>; } impl<'a> QualifiedRuleParser for KeyframeListParser<'a> { type Prelude = KeyframeSelector; type QualifiedRule = Arc<Locked<Keyframe>>; fn parse_prelude(&mut self, input: &mut Parser) -> Result<Self::Prelude, ()> { let start = input.position(); match KeyframeSelector::parse(input) { Ok(sel) => Ok(sel), Err(()) => { let message = format!("Invalid keyframe rule: '{}'", input.slice_from(start)); log_css_error(input, start, &message, self.context); Err(()) } } } fn parse_block(&mut self, prelude: Self::Prelude, input: &mut Parser) -> Result<Self::QualifiedRule, ()> { let context = ParserContext::new_with_rule_type(self.context, Some(CssRuleType::Keyframe)); let parser = KeyframeDeclarationParser { context: &context, declarations: self.declarations, }; let mut iter = DeclarationListParser::new(input, parser); let mut block = PropertyDeclarationBlock::new(); while let Some(declaration) = iter.next() { match declaration { Ok(()) => { block.extend(iter.parser.declarations.drain(), Importance::Normal); } Err(range) => { iter.parser.declarations.clear(); let pos = range.start; let message = format!("Unsupported keyframe property declaration: '{}'", iter.input.slice(range)); log_css_error(iter.input, pos, &*message, &context); } } // `parse_important` is not called here, `!important` is not allowed in keyframe blocks. } Ok(Arc::new(self.shared_lock.wrap(Keyframe { selector: prelude, block: Arc::new(self.shared_lock.wrap(block)), }))) } } struct KeyframeDeclarationParser<'a, 'b: 'a> { context: &'a ParserContext<'b>, declarations: &'a mut SourcePropertyDeclaration, } /// Default methods reject all at rules. impl<'a, 'b> AtRuleParser for KeyframeDeclarationParser<'a, 'b> { type Prelude = (); type AtRule = (); } impl<'a, 'b> DeclarationParser for KeyframeDeclarationParser<'a, 'b> { type Declaration = (); fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<(), ()> { let id = try!(PropertyId::parse(name.into())); match PropertyDeclaration::parse_into(self.declarations, id, self.context, input) { Ok(()) => { // In case there is still unparsed text in the declaration, we should roll back. input.expect_exhausted() } Err(_) => Err(()) } } }
{ let error_reporter = NullReporter; let context = ParserContext::new(parent_stylesheet.origin, &parent_stylesheet.url_data, &error_reporter, Some(CssRuleType::Keyframe), PARSING_MODE_DEFAULT, parent_stylesheet.quirks_mode); let mut input = Parser::new(css); let mut declarations = SourcePropertyDeclaration::new(); let mut rule_parser = KeyframeListParser { context: &context, shared_lock: &parent_stylesheet.shared_lock, declarations: &mut declarations, }; parse_one_rule(&mut input, &mut rule_parser) }
identifier_body
keyframes.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/. */ //! Keyframes: https://drafts.csswg.org/css-animations/#keyframes #![deny(missing_docs)] use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser}; use cssparser::{DeclarationListParser, DeclarationParser, parse_one_rule}; use error_reporting::NullReporter; use parser::{PARSING_MODE_DEFAULT, ParserContext, log_css_error}; use properties::{Importance, PropertyDeclaration, PropertyDeclarationBlock, PropertyId}; use properties::{PropertyDeclarationId, LonghandId, SourcePropertyDeclaration}; use properties::LonghandIdSet; use properties::animated_properties::TransitionProperty; use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction; use shared_lock::{SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard}; use std::fmt; use style_traits::ToCss; use stylearc::Arc; use stylesheets::{CssRuleType, Stylesheet, VendorPrefix}; /// A number from 0 to 1, indicating the percentage of the animation when this /// keyframe should run. #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframePercentage(pub f32); impl ::std::cmp::Ord for KeyframePercentage { #[inline] fn cmp(&self, other: &Self) -> ::std::cmp::Ordering { // We know we have a number from 0 to 1, so unwrap() here is safe. self.0.partial_cmp(&other.0).unwrap() } } impl ::std::cmp::Eq for KeyframePercentage { } impl ToCss for KeyframePercentage { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}%", self.0 * 100.0) } } impl KeyframePercentage { /// Trivially constructs a new `KeyframePercentage`. #[inline] pub fn new(value: f32) -> KeyframePercentage { debug_assert!(value >= 0. && value <= 1.); KeyframePercentage(value) } fn parse(input: &mut Parser) -> Result<KeyframePercentage, ()> { let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() { KeyframePercentage::new(0.) } else if input.try(|input| input.expect_ident_matching("to")).is_ok() { KeyframePercentage::new(1.) } else { let percentage = try!(input.expect_percentage()); if percentage >= 0. && percentage <= 1. { KeyframePercentage::new(percentage) } else { return Err(()); } }; Ok(percentage) } } /// A keyframes selector is a list of percentages or from/to symbols, which are /// converted at parse time to percentages. #[derive(Clone, Debug, PartialEq, Eq)] pub struct KeyframeSelector(Vec<KeyframePercentage>); impl ToCss for KeyframeSelector { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); iter.next().unwrap().to_css(dest)?; for percentage in iter { write!(dest, ", ")?; percentage.to_css(dest)?; } Ok(()) } } impl KeyframeSelector { /// Return the list of percentages this selector contains. #[inline] pub fn percentages(&self) -> &[KeyframePercentage] { &self.0 } /// A dummy public function so we can write a unit test for this. pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector { KeyframeSelector(percentages) } /// Parse a keyframe selector from CSS input. pub fn parse(input: &mut Parser) -> Result<Self, ()> { input.parse_comma_separated(KeyframePercentage::parse) .map(KeyframeSelector) } } /// A keyframe. #[derive(Debug)] pub struct Keyframe { /// The selector this keyframe was specified from. pub selector: KeyframeSelector, /// The declaration block that was declared inside this keyframe. /// /// Note that `!important` rules in keyframes don't apply, but we keep this /// `Arc` just for convenience. pub block: Arc<Locked<PropertyDeclarationBlock>>, } impl ToCssWithGuard for Keyframe { fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result where W: fmt::Write { self.selector.to_css(dest)?; try!(dest.write_str(" { ")); try!(self.block.read_with(guard).to_css(dest)); try!(dest.write_str(" }")); Ok(()) } } impl Keyframe { /// Parse a CSS keyframe. pub fn parse(css: &str, parent_stylesheet: &Stylesheet) -> Result<Arc<Locked<Self>>, ()> { let error_reporter = NullReporter; let context = ParserContext::new(parent_stylesheet.origin, &parent_stylesheet.url_data, &error_reporter, Some(CssRuleType::Keyframe), PARSING_MODE_DEFAULT, parent_stylesheet.quirks_mode); let mut input = Parser::new(css); let mut declarations = SourcePropertyDeclaration::new(); let mut rule_parser = KeyframeListParser { context: &context, shared_lock: &parent_stylesheet.shared_lock, declarations: &mut declarations, }; parse_one_rule(&mut input, &mut rule_parser) } /// Deep clones this Keyframe. pub fn deep_clone_with_lock(&self, lock: &SharedRwLock) -> Keyframe { let guard = lock.read(); Keyframe { selector: self.selector.clone(), block: Arc::new(lock.wrap(self.block.read_with(&guard).clone())), } } } /// A keyframes step value. This can be a synthetised keyframes animation, that /// is, one autogenerated from the current computed values, or a list of /// declarations to apply. /// /// TODO: Find a better name for this? #[derive(Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum KeyframesStepValue { /// A step formed by a declaration block specified by the CSS. Declarations { /// The declaration block per se. #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] block: Arc<Locked<PropertyDeclarationBlock>> }, /// A synthetic step computed from the current computed values at the time /// of the animation. ComputedValues, } /// A single step from a keyframe animation. #[derive(Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesStep { /// The percentage of the animation duration when this step starts. pub start_percentage: KeyframePercentage, /// Declarations that will determine the final style during the step, or /// `ComputedValues` if this is an autogenerated step. pub value: KeyframesStepValue, /// Wether a animation-timing-function declaration exists in the list of /// declarations. /// /// This is used to know when to override the keyframe animation style. pub declared_timing_function: bool, } impl KeyframesStep { #[inline] fn new(percentage: KeyframePercentage, value: KeyframesStepValue, guard: &SharedRwLockReadGuard) -> Self { let declared_timing_function = match value { KeyframesStepValue::Declarations { ref block } => { block.read_with(guard).declarations().iter().any(|&(ref prop_decl, _)| { match *prop_decl { PropertyDeclaration::AnimationTimingFunction(..) => true, _ => false, } }) } _ => false, }; KeyframesStep {
} } /// Return specified TransitionTimingFunction if this KeyframesSteps has 'animation-timing-function'. pub fn get_animation_timing_function(&self, guard: &SharedRwLockReadGuard) -> Option<SpecifiedTimingFunction> { if!self.declared_timing_function { return None; } match self.value { KeyframesStepValue::Declarations { ref block } => { let guard = block.read_with(guard); let &(ref declaration, _) = guard.get(PropertyDeclarationId::Longhand(LonghandId::AnimationTimingFunction)).unwrap(); match *declaration { PropertyDeclaration::AnimationTimingFunction(ref value) => { // Use the first value. Some(value.0[0]) }, PropertyDeclaration::CSSWideKeyword(..) => None, PropertyDeclaration::WithVariables(..) => None, _ => panic!(), } }, KeyframesStepValue::ComputedValues => { panic!("Shouldn't happen to set animation-timing-function in missing keyframes") }, } } } /// This structure represents a list of animation steps computed from the list /// of keyframes, in order. /// /// It only takes into account animable properties. #[derive(Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesAnimation { /// The difference steps of the animation. pub steps: Vec<KeyframesStep>, /// The properties that change in this animation. pub properties_changed: Vec<TransitionProperty>, /// Vendor prefix type the @keyframes has. pub vendor_prefix: Option<VendorPrefix>, } /// Get all the animated properties in a keyframes animation. fn get_animated_properties(keyframes: &[Arc<Locked<Keyframe>>], guard: &SharedRwLockReadGuard) -> Vec<TransitionProperty> { let mut ret = vec![]; let mut seen = LonghandIdSet::new(); // NB: declarations are already deduplicated, so we don't have to check for // it here. for keyframe in keyframes { let keyframe = keyframe.read_with(&guard); let block = keyframe.block.read_with(guard); for &(ref declaration, importance) in block.declarations().iter() { assert!(!importance.important()); if let Some(property) = TransitionProperty::from_declaration(declaration) { if!seen.has_transition_property_bit(&property) { seen.set_transition_property_bit(&property); ret.push(property); } } } } ret } impl KeyframesAnimation { /// Create a keyframes animation from a given list of keyframes. /// /// This will return a keyframe animation with empty steps and /// properties_changed if the list of keyframes is empty, or there are no // animated properties obtained from the keyframes. /// /// Otherwise, this will compute and sort the steps used for the animation, /// and return the animation object. pub fn from_keyframes(keyframes: &[Arc<Locked<Keyframe>>], vendor_prefix: Option<VendorPrefix>, guard: &SharedRwLockReadGuard) -> Self { let mut result = KeyframesAnimation { steps: vec![], properties_changed: vec![], vendor_prefix: vendor_prefix, }; if keyframes.is_empty() { return result; } result.properties_changed = get_animated_properties(keyframes, guard); if result.properties_changed.is_empty() { return result; } for keyframe in keyframes { let keyframe = keyframe.read_with(&guard); for percentage in keyframe.selector.0.iter() { result.steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations { block: keyframe.block.clone(), }, guard)); } } // Sort by the start percentage, so we can easily find a frame. result.steps.sort_by_key(|step| step.start_percentage); // Prepend autogenerated keyframes if appropriate. if result.steps[0].start_percentage.0!= 0. { result.steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.), KeyframesStepValue::ComputedValues, guard)); } if result.steps.last().unwrap().start_percentage.0!= 1. { result.steps.push(KeyframesStep::new(KeyframePercentage::new(1.), KeyframesStepValue::ComputedValues, guard)); } result } } /// Parses a keyframes list, like: /// 0%, 50% { /// width: 50%; /// } /// /// 40%, 60%, 100% { /// width: 100%; /// } struct KeyframeListParser<'a> { context: &'a ParserContext<'a>, shared_lock: &'a SharedRwLock, declarations: &'a mut SourcePropertyDeclaration, } /// Parses a keyframe list from CSS input. pub fn parse_keyframe_list(context: &ParserContext, input: &mut Parser, shared_lock: &SharedRwLock) -> Vec<Arc<Locked<Keyframe>>> { let mut declarations = SourcePropertyDeclaration::new(); RuleListParser::new_for_nested_rule(input, KeyframeListParser { context: context, shared_lock: shared_lock, declarations: &mut declarations, }).filter_map(Result::ok).collect() } enum Void {} impl<'a> AtRuleParser for KeyframeListParser<'a> { type Prelude = Void; type AtRule = Arc<Locked<Keyframe>>; } impl<'a> QualifiedRuleParser for KeyframeListParser<'a> { type Prelude = KeyframeSelector; type QualifiedRule = Arc<Locked<Keyframe>>; fn parse_prelude(&mut self, input: &mut Parser) -> Result<Self::Prelude, ()> { let start = input.position(); match KeyframeSelector::parse(input) { Ok(sel) => Ok(sel), Err(()) => { let message = format!("Invalid keyframe rule: '{}'", input.slice_from(start)); log_css_error(input, start, &message, self.context); Err(()) } } } fn parse_block(&mut self, prelude: Self::Prelude, input: &mut Parser) -> Result<Self::QualifiedRule, ()> { let context = ParserContext::new_with_rule_type(self.context, Some(CssRuleType::Keyframe)); let parser = KeyframeDeclarationParser { context: &context, declarations: self.declarations, }; let mut iter = DeclarationListParser::new(input, parser); let mut block = PropertyDeclarationBlock::new(); while let Some(declaration) = iter.next() { match declaration { Ok(()) => { block.extend(iter.parser.declarations.drain(), Importance::Normal); } Err(range) => { iter.parser.declarations.clear(); let pos = range.start; let message = format!("Unsupported keyframe property declaration: '{}'", iter.input.slice(range)); log_css_error(iter.input, pos, &*message, &context); } } // `parse_important` is not called here, `!important` is not allowed in keyframe blocks. } Ok(Arc::new(self.shared_lock.wrap(Keyframe { selector: prelude, block: Arc::new(self.shared_lock.wrap(block)), }))) } } struct KeyframeDeclarationParser<'a, 'b: 'a> { context: &'a ParserContext<'b>, declarations: &'a mut SourcePropertyDeclaration, } /// Default methods reject all at rules. impl<'a, 'b> AtRuleParser for KeyframeDeclarationParser<'a, 'b> { type Prelude = (); type AtRule = (); } impl<'a, 'b> DeclarationParser for KeyframeDeclarationParser<'a, 'b> { type Declaration = (); fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<(), ()> { let id = try!(PropertyId::parse(name.into())); match PropertyDeclaration::parse_into(self.declarations, id, self.context, input) { Ok(()) => { // In case there is still unparsed text in the declaration, we should roll back. input.expect_exhausted() } Err(_) => Err(()) } } }
start_percentage: percentage, value: value, declared_timing_function: declared_timing_function,
random_line_split
clipboard_linux.rs
use std::process::{Stdio, Command}; use std::io::Write;
Ok(status) => if!status.success() { return Err("missing xclip program".to_string()) }, Err(e) => return Err(e.detail().unwrap_or("unknown IO error".to_string())) } let output = match Command::new("xclip").args(&["-out", "-selection", "clipboard"]).output() { Ok(output) => output, Err(e) => return Err(e.detail().unwrap_or("unknown IO error".to_string())) }; let s = match String::from_utf8(output.stdout) { Ok(s) => s, Err(_) => return Err("clipboard contains invalid utf8 characters".to_string()) }; Ok(s) } pub fn write(s: &str) -> Result<(), String> { match Command::new("which").arg("xclip").status() { Ok(status) => if!status.success() { return Err("missing xclip program".to_string()) }, Err(e) => return Err(e.detail().unwrap_or("unknown IO error".to_string())) } let mut child = match Command::new("xclip").args(&["-in", "-selection", "clipboard"]).stdin(Stdio::capture()).spawn() { Ok(child) => child, Err(e) => return Err(e.detail().unwrap_or("unknown IO error".to_string())) }; let stdin = match child.stdin { Some(ref mut stdin) => stdin, None => return Err("unable to get stdin of xclip".to_string()) }; match stdin.write(s.as_bytes()) { Ok(_) => Ok(()), Err(e) => return Err(e.detail().unwrap_or("error writing to xclip".to_string())) } }
pub fn read() -> Result<String, String> { match Command::new("which").arg("xclip").status() {
random_line_split
clipboard_linux.rs
use std::process::{Stdio, Command}; use std::io::Write; pub fn read() -> Result<String, String> { match Command::new("which").arg("xclip").status() { Ok(status) => if!status.success() { return Err("missing xclip program".to_string()) }, Err(e) => return Err(e.detail().unwrap_or("unknown IO error".to_string())) } let output = match Command::new("xclip").args(&["-out", "-selection", "clipboard"]).output() { Ok(output) => output, Err(e) => return Err(e.detail().unwrap_or("unknown IO error".to_string())) }; let s = match String::from_utf8(output.stdout) { Ok(s) => s, Err(_) => return Err("clipboard contains invalid utf8 characters".to_string()) }; Ok(s) } pub fn write(s: &str) -> Result<(), String>
}
{ match Command::new("which").arg("xclip").status() { Ok(status) => if !status.success() { return Err("missing xclip program".to_string()) }, Err(e) => return Err(e.detail().unwrap_or("unknown IO error".to_string())) } let mut child = match Command::new("xclip").args(&["-in", "-selection", "clipboard"]).stdin(Stdio::capture()).spawn() { Ok(child) => child, Err(e) => return Err(e.detail().unwrap_or("unknown IO error".to_string())) }; let stdin = match child.stdin { Some(ref mut stdin) => stdin, None => return Err("unable to get stdin of xclip".to_string()) }; match stdin.write(s.as_bytes()) { Ok(_) => Ok(()), Err(e) => return Err(e.detail().unwrap_or("error writing to xclip".to_string())) }
identifier_body
clipboard_linux.rs
use std::process::{Stdio, Command}; use std::io::Write; pub fn
() -> Result<String, String> { match Command::new("which").arg("xclip").status() { Ok(status) => if!status.success() { return Err("missing xclip program".to_string()) }, Err(e) => return Err(e.detail().unwrap_or("unknown IO error".to_string())) } let output = match Command::new("xclip").args(&["-out", "-selection", "clipboard"]).output() { Ok(output) => output, Err(e) => return Err(e.detail().unwrap_or("unknown IO error".to_string())) }; let s = match String::from_utf8(output.stdout) { Ok(s) => s, Err(_) => return Err("clipboard contains invalid utf8 characters".to_string()) }; Ok(s) } pub fn write(s: &str) -> Result<(), String> { match Command::new("which").arg("xclip").status() { Ok(status) => if!status.success() { return Err("missing xclip program".to_string()) }, Err(e) => return Err(e.detail().unwrap_or("unknown IO error".to_string())) } let mut child = match Command::new("xclip").args(&["-in", "-selection", "clipboard"]).stdin(Stdio::capture()).spawn() { Ok(child) => child, Err(e) => return Err(e.detail().unwrap_or("unknown IO error".to_string())) }; let stdin = match child.stdin { Some(ref mut stdin) => stdin, None => return Err("unable to get stdin of xclip".to_string()) }; match stdin.write(s.as_bytes()) { Ok(_) => Ok(()), Err(e) => return Err(e.detail().unwrap_or("error writing to xclip".to_string())) } }
read
identifier_name
restrictions.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * Computes the restrictions that result from a borrow. */ use std::vec; use middle::borrowck::*; use mc = middle::mem_categorization; use middle::ty; use syntax::ast::{MutImmutable, MutMutable}; use syntax::codemap::Span; pub enum RestrictionResult { Safe, SafeIf(@LoanPath, ~[Restriction]) } pub fn compute_restrictions(bccx: &BorrowckCtxt, span: Span, cmt: mc::cmt, loan_region: ty::Region, restr: RestrictionSet) -> RestrictionResult { let ctxt = RestrictionsContext { bccx: bccx, span: span, cmt_original: cmt, loan_region: loan_region, }; ctxt.restrict(cmt, restr) } /////////////////////////////////////////////////////////////////////////// // Private struct RestrictionsContext<'a> { bccx: &'a BorrowckCtxt, span: Span, cmt_original: mc::cmt, loan_region: ty::Region, } impl<'a> RestrictionsContext<'a> { fn
(&self, cmt: mc::cmt, restrictions: RestrictionSet) -> RestrictionResult { // Check for those cases where we cannot control the aliasing // and make sure that we are not being asked to. match cmt.freely_aliasable() { None => {} Some(cause) => { self.check_aliasing_permitted(cause, restrictions); } } match cmt.cat { mc::cat_rvalue(..) => { // Effectively, rvalues are stored into a // non-aliasable temporary on the stack. Since they // are inherently non-aliasable, they can only be // accessed later through the borrow itself and hence // must inherently comply with its terms. Safe } mc::cat_local(local_id) | mc::cat_arg(local_id) | mc::cat_self(local_id) => { // R-Variable let lp = @LpVar(local_id); SafeIf(lp, ~[Restriction {loan_path: lp, set: restrictions}]) } mc::cat_downcast(cmt_base) => { // When we borrow the interior of an enum, we have to // ensure the enum itself is not mutated, because that // could cause the type of the memory to change. self.restrict( cmt_base, restrictions | RESTR_MUTATE | RESTR_CLAIM) } mc::cat_interior(cmt_base, i) => { // R-Field // // Overwriting the base would not change the type of // the memory, so no additional restrictions are // needed. let result = self.restrict(cmt_base, restrictions); self.extend(result, cmt.mutbl, LpInterior(i), restrictions) } mc::cat_deref(cmt_base, _, pk @ mc::uniq_ptr) => { // R-Deref-Send-Pointer // // When we borrow the interior of an owned pointer, we // cannot permit the base to be mutated, because that // would cause the unique pointer to be freed. let result = self.restrict( cmt_base, restrictions | RESTR_MUTATE | RESTR_CLAIM); self.extend(result, cmt.mutbl, LpDeref(pk), restrictions) } mc::cat_copied_upvar(..) | // FIXME(#2152) allow mutation of upvars mc::cat_static_item(..) => { Safe } mc::cat_deref(cmt_base, _, mc::region_ptr(MutImmutable, lt)) => { // R-Deref-Imm-Borrowed if!self.bccx.is_subregion_of(self.loan_region, lt) { self.bccx.report( BckError { span: self.span, cmt: cmt_base, code: err_borrowed_pointer_too_short( self.loan_region, lt, restrictions)}); return Safe; } Safe } mc::cat_deref(_, _, mc::gc_ptr) => { // R-Deref-Imm-Managed Safe } mc::cat_deref(cmt_base, _, pk @ mc::region_ptr(MutMutable, lt)) => { // R-Deref-Mut-Borrowed if!self.bccx.is_subregion_of(self.loan_region, lt) { self.bccx.report( BckError { span: self.span, cmt: cmt_base, code: err_borrowed_pointer_too_short( self.loan_region, lt, restrictions)}); return Safe; } let result = self.restrict(cmt_base, restrictions); self.extend(result, cmt.mutbl, LpDeref(pk), restrictions) } mc::cat_deref(_, _, mc::unsafe_ptr(..)) => { // We are very trusting when working with unsafe pointers. Safe } mc::cat_stack_upvar(cmt_base) | mc::cat_discr(cmt_base, _) => { self.restrict(cmt_base, restrictions) } } } fn extend(&self, result: RestrictionResult, mc: mc::MutabilityCategory, elem: LoanPathElem, restrictions: RestrictionSet) -> RestrictionResult { match result { Safe => Safe, SafeIf(base_lp, base_vec) => { let lp = @LpExtend(base_lp, mc, elem); SafeIf(lp, vec::append_one(base_vec, Restriction {loan_path: lp, set: restrictions})) } } } fn check_aliasing_permitted(&self, cause: mc::AliasableReason, restrictions: RestrictionSet) { //! This method is invoked when the current `cmt` is something //! where aliasing cannot be controlled. It reports an error if //! the restrictions required that it not be aliased; currently //! this only occurs when re-borrowing an `&mut` pointer. //! //! NB: To be 100% consistent, we should report an error if //! RESTR_FREEZE is found, because we cannot prevent freezing, //! nor would we want to. However, we do not report such an //! error, because this restriction only occurs when the user //! is creating an `&mut` pointer to immutable or read-only //! data, and there is already another piece of code that //! checks for this condition. if restrictions.intersects(RESTR_ALIAS) { self.bccx.report_aliasability_violation( self.span, BorrowViolation, cause); } } }
restrict
identifier_name
restrictions.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * Computes the restrictions that result from a borrow. */ use std::vec; use middle::borrowck::*; use mc = middle::mem_categorization; use middle::ty; use syntax::ast::{MutImmutable, MutMutable}; use syntax::codemap::Span; pub enum RestrictionResult { Safe, SafeIf(@LoanPath, ~[Restriction]) } pub fn compute_restrictions(bccx: &BorrowckCtxt, span: Span, cmt: mc::cmt, loan_region: ty::Region, restr: RestrictionSet) -> RestrictionResult { let ctxt = RestrictionsContext { bccx: bccx, span: span, cmt_original: cmt, loan_region: loan_region, }; ctxt.restrict(cmt, restr) } /////////////////////////////////////////////////////////////////////////// // Private struct RestrictionsContext<'a> { bccx: &'a BorrowckCtxt, span: Span, cmt_original: mc::cmt, loan_region: ty::Region, } impl<'a> RestrictionsContext<'a> { fn restrict(&self, cmt: mc::cmt, restrictions: RestrictionSet) -> RestrictionResult { // Check for those cases where we cannot control the aliasing // and make sure that we are not being asked to. match cmt.freely_aliasable() { None => {} Some(cause) => { self.check_aliasing_permitted(cause, restrictions); } } match cmt.cat { mc::cat_rvalue(..) => { // Effectively, rvalues are stored into a // non-aliasable temporary on the stack. Since they // are inherently non-aliasable, they can only be // accessed later through the borrow itself and hence // must inherently comply with its terms. Safe } mc::cat_local(local_id) | mc::cat_arg(local_id) | mc::cat_self(local_id) => { // R-Variable let lp = @LpVar(local_id); SafeIf(lp, ~[Restriction {loan_path: lp, set: restrictions}]) } mc::cat_downcast(cmt_base) => { // When we borrow the interior of an enum, we have to // ensure the enum itself is not mutated, because that // could cause the type of the memory to change. self.restrict( cmt_base, restrictions | RESTR_MUTATE | RESTR_CLAIM) } mc::cat_interior(cmt_base, i) => { // R-Field // // Overwriting the base would not change the type of // the memory, so no additional restrictions are // needed. let result = self.restrict(cmt_base, restrictions); self.extend(result, cmt.mutbl, LpInterior(i), restrictions) } mc::cat_deref(cmt_base, _, pk @ mc::uniq_ptr) => { // R-Deref-Send-Pointer // // When we borrow the interior of an owned pointer, we // cannot permit the base to be mutated, because that // would cause the unique pointer to be freed. let result = self.restrict( cmt_base, restrictions | RESTR_MUTATE | RESTR_CLAIM); self.extend(result, cmt.mutbl, LpDeref(pk), restrictions) } mc::cat_copied_upvar(..) | // FIXME(#2152) allow mutation of upvars mc::cat_static_item(..) => { Safe } mc::cat_deref(cmt_base, _, mc::region_ptr(MutImmutable, lt)) => { // R-Deref-Imm-Borrowed if!self.bccx.is_subregion_of(self.loan_region, lt) { self.bccx.report( BckError { span: self.span, cmt: cmt_base, code: err_borrowed_pointer_too_short( self.loan_region, lt, restrictions)}); return Safe; } Safe } mc::cat_deref(_, _, mc::gc_ptr) =>
mc::cat_deref(cmt_base, _, pk @ mc::region_ptr(MutMutable, lt)) => { // R-Deref-Mut-Borrowed if!self.bccx.is_subregion_of(self.loan_region, lt) { self.bccx.report( BckError { span: self.span, cmt: cmt_base, code: err_borrowed_pointer_too_short( self.loan_region, lt, restrictions)}); return Safe; } let result = self.restrict(cmt_base, restrictions); self.extend(result, cmt.mutbl, LpDeref(pk), restrictions) } mc::cat_deref(_, _, mc::unsafe_ptr(..)) => { // We are very trusting when working with unsafe pointers. Safe } mc::cat_stack_upvar(cmt_base) | mc::cat_discr(cmt_base, _) => { self.restrict(cmt_base, restrictions) } } } fn extend(&self, result: RestrictionResult, mc: mc::MutabilityCategory, elem: LoanPathElem, restrictions: RestrictionSet) -> RestrictionResult { match result { Safe => Safe, SafeIf(base_lp, base_vec) => { let lp = @LpExtend(base_lp, mc, elem); SafeIf(lp, vec::append_one(base_vec, Restriction {loan_path: lp, set: restrictions})) } } } fn check_aliasing_permitted(&self, cause: mc::AliasableReason, restrictions: RestrictionSet) { //! This method is invoked when the current `cmt` is something //! where aliasing cannot be controlled. It reports an error if //! the restrictions required that it not be aliased; currently //! this only occurs when re-borrowing an `&mut` pointer. //! //! NB: To be 100% consistent, we should report an error if //! RESTR_FREEZE is found, because we cannot prevent freezing, //! nor would we want to. However, we do not report such an //! error, because this restriction only occurs when the user //! is creating an `&mut` pointer to immutable or read-only //! data, and there is already another piece of code that //! checks for this condition. if restrictions.intersects(RESTR_ALIAS) { self.bccx.report_aliasability_violation( self.span, BorrowViolation, cause); } } }
{ // R-Deref-Imm-Managed Safe }
conditional_block
restrictions.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * Computes the restrictions that result from a borrow. */ use std::vec; use middle::borrowck::*; use mc = middle::mem_categorization; use middle::ty; use syntax::ast::{MutImmutable, MutMutable}; use syntax::codemap::Span; pub enum RestrictionResult { Safe, SafeIf(@LoanPath, ~[Restriction]) } pub fn compute_restrictions(bccx: &BorrowckCtxt, span: Span, cmt: mc::cmt, loan_region: ty::Region, restr: RestrictionSet) -> RestrictionResult { let ctxt = RestrictionsContext { bccx: bccx, span: span, cmt_original: cmt, loan_region: loan_region, }; ctxt.restrict(cmt, restr) } /////////////////////////////////////////////////////////////////////////// // Private struct RestrictionsContext<'a> { bccx: &'a BorrowckCtxt, span: Span, cmt_original: mc::cmt, loan_region: ty::Region, } impl<'a> RestrictionsContext<'a> { fn restrict(&self, cmt: mc::cmt, restrictions: RestrictionSet) -> RestrictionResult { // Check for those cases where we cannot control the aliasing // and make sure that we are not being asked to. match cmt.freely_aliasable() { None => {} Some(cause) => { self.check_aliasing_permitted(cause, restrictions); } } match cmt.cat { mc::cat_rvalue(..) => { // Effectively, rvalues are stored into a // non-aliasable temporary on the stack. Since they // are inherently non-aliasable, they can only be // accessed later through the borrow itself and hence // must inherently comply with its terms. Safe } mc::cat_local(local_id) | mc::cat_arg(local_id) | mc::cat_self(local_id) => { // R-Variable let lp = @LpVar(local_id); SafeIf(lp, ~[Restriction {loan_path: lp, set: restrictions}]) } mc::cat_downcast(cmt_base) => { // When we borrow the interior of an enum, we have to // ensure the enum itself is not mutated, because that // could cause the type of the memory to change. self.restrict( cmt_base, restrictions | RESTR_MUTATE | RESTR_CLAIM) } mc::cat_interior(cmt_base, i) => { // R-Field // // Overwriting the base would not change the type of // the memory, so no additional restrictions are // needed. let result = self.restrict(cmt_base, restrictions); self.extend(result, cmt.mutbl, LpInterior(i), restrictions) } mc::cat_deref(cmt_base, _, pk @ mc::uniq_ptr) => { // R-Deref-Send-Pointer // // When we borrow the interior of an owned pointer, we // cannot permit the base to be mutated, because that // would cause the unique pointer to be freed. let result = self.restrict( cmt_base, restrictions | RESTR_MUTATE | RESTR_CLAIM); self.extend(result, cmt.mutbl, LpDeref(pk), restrictions) } mc::cat_copied_upvar(..) | // FIXME(#2152) allow mutation of upvars mc::cat_static_item(..) => { Safe } mc::cat_deref(cmt_base, _, mc::region_ptr(MutImmutable, lt)) => { // R-Deref-Imm-Borrowed if!self.bccx.is_subregion_of(self.loan_region, lt) { self.bccx.report( BckError { span: self.span, cmt: cmt_base, code: err_borrowed_pointer_too_short( self.loan_region, lt, restrictions)}); return Safe; } Safe } mc::cat_deref(_, _, mc::gc_ptr) => { // R-Deref-Imm-Managed Safe } mc::cat_deref(cmt_base, _, pk @ mc::region_ptr(MutMutable, lt)) => { // R-Deref-Mut-Borrowed
cmt: cmt_base, code: err_borrowed_pointer_too_short( self.loan_region, lt, restrictions)}); return Safe; } let result = self.restrict(cmt_base, restrictions); self.extend(result, cmt.mutbl, LpDeref(pk), restrictions) } mc::cat_deref(_, _, mc::unsafe_ptr(..)) => { // We are very trusting when working with unsafe pointers. Safe } mc::cat_stack_upvar(cmt_base) | mc::cat_discr(cmt_base, _) => { self.restrict(cmt_base, restrictions) } } } fn extend(&self, result: RestrictionResult, mc: mc::MutabilityCategory, elem: LoanPathElem, restrictions: RestrictionSet) -> RestrictionResult { match result { Safe => Safe, SafeIf(base_lp, base_vec) => { let lp = @LpExtend(base_lp, mc, elem); SafeIf(lp, vec::append_one(base_vec, Restriction {loan_path: lp, set: restrictions})) } } } fn check_aliasing_permitted(&self, cause: mc::AliasableReason, restrictions: RestrictionSet) { //! This method is invoked when the current `cmt` is something //! where aliasing cannot be controlled. It reports an error if //! the restrictions required that it not be aliased; currently //! this only occurs when re-borrowing an `&mut` pointer. //! //! NB: To be 100% consistent, we should report an error if //! RESTR_FREEZE is found, because we cannot prevent freezing, //! nor would we want to. However, we do not report such an //! error, because this restriction only occurs when the user //! is creating an `&mut` pointer to immutable or read-only //! data, and there is already another piece of code that //! checks for this condition. if restrictions.intersects(RESTR_ALIAS) { self.bccx.report_aliasability_violation( self.span, BorrowViolation, cause); } } }
if !self.bccx.is_subregion_of(self.loan_region, lt) { self.bccx.report( BckError { span: self.span,
random_line_split
config.rs
pub use errors::*; use serde::Deserialize; use std::{error, fmt}; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; use toml; const DEFAULT_GIT_CACHE_DIRECTORY: &'static str = "cache"; #[derive(Debug, Clone)] pub struct Config { pub gitlab: Gitlab, pub git: Git, pub repo: HashMap<String, Repo>, } #[derive(Debug, Clone)] pub struct Gitlab { pub host: String, pub access_token: String, pub insecure: bool, } #[derive(Debug, Clone)] pub struct Git { pub ssh_key: PathBuf, pub cache_directory: PathBuf, } #[derive(Debug, Clone)] pub struct Repo { pub name: String, } pub fn from_path<P>(path: P) -> Result<Config> where P: AsRef<Path> { let path = path.as_ref(); let file = read_file(path).chain_err(|| { format!("failed to read config file: {}", path.to_string_lossy()) })?; let toml = parse_toml(&file).chain_err(|| { format!("failed to parse config file: {}", path.to_string_lossy()) })?; let mut config = decode(toml).chain_err(|| { format!("failed to decode config file: {}", path.to_string_lossy()) })?; // Converts relative path into absolute path let basedir = path.parent().expect("invalid config file path"); config.git.ssh_key = basedir.join(config.git.ssh_key); config.git.cache_directory = basedir.join(config.git.cache_directory); Ok(config) } fn read_file<P>(path: P) -> Result<String> where P: AsRef<Path> { let mut file = File::open(path)?; let mut input = String::new(); let _ = file.read_to_string(&mut input)?; Ok(input) } fn parse_toml(input: &str) -> Result<toml::Value> { let mut parser = toml::Parser::new(input); let toml = match parser.parse() { None => return Err(TomlParserError::new(&parser).unwrap().into()), Some(v) => toml::Value::Table(v), }; Ok(toml) } fn decode(toml: toml::Value) -> Result<Config> { let raw: RawConfig = Deserialize::deserialize(&mut toml::Decoder::new(toml))?; Ok(raw.into()) } #[derive(Deserialize)] struct
{ gitlab: RawGitlab, git: RawGit, repo: HashMap<String, RawRepo>, } impl Into<Config> for RawConfig { fn into(self) -> Config { Config { gitlab: self.gitlab.into(), git: self.git.into(), repo: self.repo.into_iter().map(|(name, repo)| (name, repo.into())).collect(), } } } #[derive(Deserialize)] struct RawGitlab { host: String, access_token: String, insecure: Option<bool>, } impl Into<Gitlab> for RawGitlab { fn into(self) -> Gitlab { Gitlab { host: self.host, access_token: self.access_token, insecure: self.insecure.unwrap_or(false), } } } #[derive(Deserialize)] struct RawGit { ssh_key: PathBuf, cache_directory: Option<PathBuf>, } impl Into<Git> for RawGit { fn into(self) -> Git { Git { ssh_key: self.ssh_key, cache_directory: self.cache_directory.unwrap_or(DEFAULT_GIT_CACHE_DIRECTORY.into()), } } } #[derive(Deserialize)] struct RawRepo { name: String, } impl Into<Repo> for RawRepo { fn into(self) -> Repo { Repo { name: self.name } } } #[derive(Debug)] pub struct TomlParserError { lo_pos: (usize, usize), hi_pos: (usize, usize), raw: toml::ParserError, } impl TomlParserError { fn new(parser: &toml::Parser) -> Option<TomlParserError> { if parser.errors.is_empty() { return None; } let e = &parser.errors[0]; Some(TomlParserError { lo_pos: parser.to_linecol(e.lo), hi_pos: parser.to_linecol(e.hi), raw: e.clone(), }) } } impl fmt::Display for TomlParserError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}: {} (line={},column={})", error::Error::description(self), self.raw, self.lo_pos.0, self.lo_pos.1) } } impl error::Error for TomlParserError { fn description(&self) -> &str { self.raw.description() } fn cause(&self) -> Option<&error::Error> { self.raw.cause() } }
RawConfig
identifier_name
config.rs
pub use errors::*; use serde::Deserialize; use std::{error, fmt}; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; use toml; const DEFAULT_GIT_CACHE_DIRECTORY: &'static str = "cache"; #[derive(Debug, Clone)] pub struct Config { pub gitlab: Gitlab, pub git: Git, pub repo: HashMap<String, Repo>, } #[derive(Debug, Clone)] pub struct Gitlab { pub host: String, pub access_token: String, pub insecure: bool, } #[derive(Debug, Clone)] pub struct Git { pub ssh_key: PathBuf, pub cache_directory: PathBuf, } #[derive(Debug, Clone)] pub struct Repo { pub name: String, } pub fn from_path<P>(path: P) -> Result<Config> where P: AsRef<Path> { let path = path.as_ref(); let file = read_file(path).chain_err(|| { format!("failed to read config file: {}", path.to_string_lossy()) })?; let toml = parse_toml(&file).chain_err(|| { format!("failed to parse config file: {}", path.to_string_lossy()) })?; let mut config = decode(toml).chain_err(|| { format!("failed to decode config file: {}", path.to_string_lossy()) })?; // Converts relative path into absolute path let basedir = path.parent().expect("invalid config file path"); config.git.ssh_key = basedir.join(config.git.ssh_key); config.git.cache_directory = basedir.join(config.git.cache_directory); Ok(config) } fn read_file<P>(path: P) -> Result<String> where P: AsRef<Path> { let mut file = File::open(path)?; let mut input = String::new(); let _ = file.read_to_string(&mut input)?; Ok(input) } fn parse_toml(input: &str) -> Result<toml::Value> { let mut parser = toml::Parser::new(input); let toml = match parser.parse() { None => return Err(TomlParserError::new(&parser).unwrap().into()), Some(v) => toml::Value::Table(v), }; Ok(toml) } fn decode(toml: toml::Value) -> Result<Config> { let raw: RawConfig = Deserialize::deserialize(&mut toml::Decoder::new(toml))?; Ok(raw.into()) } #[derive(Deserialize)] struct RawConfig { gitlab: RawGitlab, git: RawGit, repo: HashMap<String, RawRepo>, } impl Into<Config> for RawConfig { fn into(self) -> Config { Config { gitlab: self.gitlab.into(), git: self.git.into(), repo: self.repo.into_iter().map(|(name, repo)| (name, repo.into())).collect(), } } } #[derive(Deserialize)] struct RawGitlab { host: String, access_token: String, insecure: Option<bool>, } impl Into<Gitlab> for RawGitlab { fn into(self) -> Gitlab { Gitlab { host: self.host, access_token: self.access_token, insecure: self.insecure.unwrap_or(false), } } } #[derive(Deserialize)] struct RawGit { ssh_key: PathBuf, cache_directory: Option<PathBuf>, } impl Into<Git> for RawGit { fn into(self) -> Git { Git { ssh_key: self.ssh_key, cache_directory: self.cache_directory.unwrap_or(DEFAULT_GIT_CACHE_DIRECTORY.into()), } } } #[derive(Deserialize)] struct RawRepo { name: String, } impl Into<Repo> for RawRepo { fn into(self) -> Repo { Repo { name: self.name } } } #[derive(Debug)] pub struct TomlParserError { lo_pos: (usize, usize), hi_pos: (usize, usize), raw: toml::ParserError, } impl TomlParserError { fn new(parser: &toml::Parser) -> Option<TomlParserError> { if parser.errors.is_empty() { return None; } let e = &parser.errors[0]; Some(TomlParserError { lo_pos: parser.to_linecol(e.lo), hi_pos: parser.to_linecol(e.hi), raw: e.clone(), }) } } impl fmt::Display for TomlParserError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}: {} (line={},column={})", error::Error::description(self), self.raw, self.lo_pos.0, self.lo_pos.1) } } impl error::Error for TomlParserError { fn description(&self) -> &str
fn cause(&self) -> Option<&error::Error> { self.raw.cause() } }
{ self.raw.description() }
identifier_body
config.rs
pub use errors::*; use serde::Deserialize; use std::{error, fmt}; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; use toml; const DEFAULT_GIT_CACHE_DIRECTORY: &'static str = "cache"; #[derive(Debug, Clone)] pub struct Config { pub gitlab: Gitlab, pub git: Git, pub repo: HashMap<String, Repo>, } #[derive(Debug, Clone)] pub struct Gitlab { pub host: String, pub access_token: String, pub insecure: bool, } #[derive(Debug, Clone)] pub struct Git { pub ssh_key: PathBuf, pub cache_directory: PathBuf, } #[derive(Debug, Clone)] pub struct Repo { pub name: String, } pub fn from_path<P>(path: P) -> Result<Config> where P: AsRef<Path> { let path = path.as_ref(); let file = read_file(path).chain_err(|| { format!("failed to read config file: {}", path.to_string_lossy()) })?; let toml = parse_toml(&file).chain_err(|| { format!("failed to parse config file: {}", path.to_string_lossy()) })?; let mut config = decode(toml).chain_err(|| { format!("failed to decode config file: {}", path.to_string_lossy()) })?; // Converts relative path into absolute path let basedir = path.parent().expect("invalid config file path"); config.git.ssh_key = basedir.join(config.git.ssh_key); config.git.cache_directory = basedir.join(config.git.cache_directory); Ok(config) } fn read_file<P>(path: P) -> Result<String> where P: AsRef<Path> { let mut file = File::open(path)?; let mut input = String::new(); let _ = file.read_to_string(&mut input)?; Ok(input) } fn parse_toml(input: &str) -> Result<toml::Value> { let mut parser = toml::Parser::new(input); let toml = match parser.parse() { None => return Err(TomlParserError::new(&parser).unwrap().into()), Some(v) => toml::Value::Table(v), }; Ok(toml) } fn decode(toml: toml::Value) -> Result<Config> { let raw: RawConfig = Deserialize::deserialize(&mut toml::Decoder::new(toml))?; Ok(raw.into()) } #[derive(Deserialize)] struct RawConfig { gitlab: RawGitlab, git: RawGit, repo: HashMap<String, RawRepo>, } impl Into<Config> for RawConfig { fn into(self) -> Config { Config { gitlab: self.gitlab.into(), git: self.git.into(), repo: self.repo.into_iter().map(|(name, repo)| (name, repo.into())).collect(), } } } #[derive(Deserialize)] struct RawGitlab { host: String, access_token: String, insecure: Option<bool>, } impl Into<Gitlab> for RawGitlab { fn into(self) -> Gitlab { Gitlab { host: self.host, access_token: self.access_token, insecure: self.insecure.unwrap_or(false), } } } #[derive(Deserialize)] struct RawGit { ssh_key: PathBuf, cache_directory: Option<PathBuf>, } impl Into<Git> for RawGit { fn into(self) -> Git { Git { ssh_key: self.ssh_key, cache_directory: self.cache_directory.unwrap_or(DEFAULT_GIT_CACHE_DIRECTORY.into()), } } } #[derive(Deserialize)] struct RawRepo { name: String, } impl Into<Repo> for RawRepo { fn into(self) -> Repo { Repo { name: self.name } } } #[derive(Debug)]
pub struct TomlParserError { lo_pos: (usize, usize), hi_pos: (usize, usize), raw: toml::ParserError, } impl TomlParserError { fn new(parser: &toml::Parser) -> Option<TomlParserError> { if parser.errors.is_empty() { return None; } let e = &parser.errors[0]; Some(TomlParserError { lo_pos: parser.to_linecol(e.lo), hi_pos: parser.to_linecol(e.hi), raw: e.clone(), }) } } impl fmt::Display for TomlParserError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}: {} (line={},column={})", error::Error::description(self), self.raw, self.lo_pos.0, self.lo_pos.1) } } impl error::Error for TomlParserError { fn description(&self) -> &str { self.raw.description() } fn cause(&self) -> Option<&error::Error> { self.raw.cause() } }
random_line_split
metadata.rs
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::{collections::HashMap, convert::TryFrom, sync::Arc}; use crate::xds::envoy::config::core::v3::Metadata as ProtoMetadata; /// Shared state between [`Filter`][crate::filters::Filter]s during processing for a single packet. pub type DynamicMetadata = HashMap<Arc<String>, Value>; pub const KEY: &str = "quilkin.dev"; #[derive( Clone, Debug, PartialOrd, serde::Serialize, serde::Deserialize, Eq, Ord, schemars::JsonSchema, )] #[serde(untagged)] pub enum Value { Bool(bool), Number(u64), List(Vec<Value>), String(String), Bytes(bytes::Bytes), } impl Value { /// Returns the inner `String` value of `self` if it /// matches [`Value::String`]. pub fn as_bytes(&self) -> Option<&bytes::Bytes> { match self { Self::Bytes(value) => Some(value), _ => None, } } /// Returns the inner `String` value of `self` if it /// matches [`Value::String`]. pub fn as_string(&self) -> Option<&str> { match self { Self::String(value) => Some(value), _ => None, } } /// Returns the inner `String` value of `self` if it /// matches [`Value::String`]. pub fn as_mut_string(&mut self) -> Option<&mut String> { match self { Self::String(value) => Some(value), _ => None, } } } /// Convenience macro for generating From<T> implementations. macro_rules! from_value { (($name:ident) { $($typ:ty => $ex:expr),+ $(,)? }) => { $( impl From<$typ> for Value { fn from($name: $typ) -> Self { $ex } } )+ } } from_value! { (value) { bool => Self::Bool(value), u64 => Self::Number(value), Vec<Self> => Self::List(value), String => Self::String(value), &str => Self::String(value.into()), bytes::Bytes => Self::Bytes(value), } } impl<const N: usize> From<[u8; N]> for Value { fn from(value: [u8; N]) -> Self { Self::Bytes(bytes::Bytes::copy_from_slice(&value)) } } impl<const N: usize> From<&[u8; N]> for Value { fn from(value: &[u8; N]) -> Self
} impl PartialEq for Value { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Bool(a), Self::Bool(b)) => a == b, (Self::Bool(_), _) => false, (Self::Number(a), Self::Number(b)) => a == b, (Self::Number(_), _) => false, (Self::List(a), Self::List(b)) => a == b, (Self::List(_), _) => false, (Self::String(a), Self::String(b)) => a == b, (Self::Bytes(a), Self::Bytes(b)) => a == b, (Self::String(a), Self::Bytes(b)) | (Self::Bytes(b), Self::String(a)) => a == b, (Self::String(_), _) => false, (Self::Bytes(_), _) => false, } } } impl TryFrom<prost_types::Value> for Value { type Error = eyre::Report; fn try_from(value: prost_types::Value) -> Result<Self, Self::Error> { use prost_types::value::Kind; let value = match value.kind { Some(value) => value, None => return Err(eyre::eyre!("unexpected missing value")), }; match value { Kind::NullValue(_) => Err(eyre::eyre!("unexpected missing value")), Kind::NumberValue(number) => Ok(Self::Number(number as u64)), Kind::StringValue(string) => Ok(Self::String(string)), Kind::BoolValue(value) => Ok(Self::Bool(value)), Kind::ListValue(list) => Ok(Self::List( list.values .into_iter() .map(prost_types::Value::try_into) .collect::<crate::Result<_>>()?, )), Kind::StructValue(_) => Err(eyre::eyre!("unexpected struct value")), } } } /// Represents a view into the metadata object attached to another object. `T` /// represents metadata known to Quilkin under `quilkin.dev` (available under /// the [`KEY`] constant.) #[derive( Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Clone, PartialOrd, Eq, )] #[non_exhaustive] pub struct MetadataView<T> { /// Known Quilkin metadata. #[serde(default, rename = "quilkin.dev")] pub known: T, /// User created metadata. #[serde(flatten)] pub unknown: serde_yaml::Mapping, } impl<T> MetadataView<T> { pub fn with_unknown(known: impl Into<T>, unknown: serde_yaml::Mapping) -> Self { Self { known: known.into(), unknown, } } } // This impl means that any `T` that we can try convert from a protobuf struct // at run-time can be constructed statically without going through // conversion first. impl<T, E> From<T> for MetadataView<T> where T: TryFrom<prost_types::Struct, Error = E> + Default, { fn from(known: T) -> Self { Self { known, unknown: <_>::default(), } } } impl<T, E> TryFrom<ProtoMetadata> for MetadataView<T> where T: TryFrom<prost_types::Struct, Error = E> + Default, { type Error = E; fn try_from(mut value: ProtoMetadata) -> Result<Self, Self::Error> { let known = value .filter_metadata .remove(KEY) .map(T::try_from) .transpose()? .unwrap_or_default(); let value = prost_types::value::Kind::StructValue(prost_types::Struct { fields: value .filter_metadata .into_iter() .map(|(k, v)| { ( k, prost_types::Value { kind: Some(prost_types::value::Kind::StructValue(v)), }, ) }) .collect(), }); Ok(Self { known, unknown: crate::prost::mapping_from_kind(value).unwrap_or_default(), }) } }
{ Self::Bytes(bytes::Bytes::copy_from_slice(value)) }
identifier_body
metadata.rs
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::{collections::HashMap, convert::TryFrom, sync::Arc}; use crate::xds::envoy::config::core::v3::Metadata as ProtoMetadata; /// Shared state between [`Filter`][crate::filters::Filter]s during processing for a single packet. pub type DynamicMetadata = HashMap<Arc<String>, Value>; pub const KEY: &str = "quilkin.dev"; #[derive( Clone, Debug, PartialOrd, serde::Serialize, serde::Deserialize, Eq, Ord, schemars::JsonSchema, )] #[serde(untagged)] pub enum Value { Bool(bool), Number(u64), List(Vec<Value>), String(String), Bytes(bytes::Bytes), } impl Value { /// Returns the inner `String` value of `self` if it /// matches [`Value::String`]. pub fn as_bytes(&self) -> Option<&bytes::Bytes> { match self { Self::Bytes(value) => Some(value), _ => None, } } /// Returns the inner `String` value of `self` if it /// matches [`Value::String`]. pub fn as_string(&self) -> Option<&str> { match self { Self::String(value) => Some(value), _ => None, } } /// Returns the inner `String` value of `self` if it /// matches [`Value::String`]. pub fn as_mut_string(&mut self) -> Option<&mut String> { match self { Self::String(value) => Some(value), _ => None, } } } /// Convenience macro for generating From<T> implementations. macro_rules! from_value { (($name:ident) { $($typ:ty => $ex:expr),+ $(,)? }) => { $( impl From<$typ> for Value { fn from($name: $typ) -> Self { $ex } } )+ } } from_value! { (value) { bool => Self::Bool(value), u64 => Self::Number(value), Vec<Self> => Self::List(value), String => Self::String(value), &str => Self::String(value.into()), bytes::Bytes => Self::Bytes(value), } } impl<const N: usize> From<[u8; N]> for Value { fn from(value: [u8; N]) -> Self { Self::Bytes(bytes::Bytes::copy_from_slice(&value)) } } impl<const N: usize> From<&[u8; N]> for Value { fn from(value: &[u8; N]) -> Self { Self::Bytes(bytes::Bytes::copy_from_slice(value)) }
} impl PartialEq for Value { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Bool(a), Self::Bool(b)) => a == b, (Self::Bool(_), _) => false, (Self::Number(a), Self::Number(b)) => a == b, (Self::Number(_), _) => false, (Self::List(a), Self::List(b)) => a == b, (Self::List(_), _) => false, (Self::String(a), Self::String(b)) => a == b, (Self::Bytes(a), Self::Bytes(b)) => a == b, (Self::String(a), Self::Bytes(b)) | (Self::Bytes(b), Self::String(a)) => a == b, (Self::String(_), _) => false, (Self::Bytes(_), _) => false, } } } impl TryFrom<prost_types::Value> for Value { type Error = eyre::Report; fn try_from(value: prost_types::Value) -> Result<Self, Self::Error> { use prost_types::value::Kind; let value = match value.kind { Some(value) => value, None => return Err(eyre::eyre!("unexpected missing value")), }; match value { Kind::NullValue(_) => Err(eyre::eyre!("unexpected missing value")), Kind::NumberValue(number) => Ok(Self::Number(number as u64)), Kind::StringValue(string) => Ok(Self::String(string)), Kind::BoolValue(value) => Ok(Self::Bool(value)), Kind::ListValue(list) => Ok(Self::List( list.values .into_iter() .map(prost_types::Value::try_into) .collect::<crate::Result<_>>()?, )), Kind::StructValue(_) => Err(eyre::eyre!("unexpected struct value")), } } } /// Represents a view into the metadata object attached to another object. `T` /// represents metadata known to Quilkin under `quilkin.dev` (available under /// the [`KEY`] constant.) #[derive( Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Clone, PartialOrd, Eq, )] #[non_exhaustive] pub struct MetadataView<T> { /// Known Quilkin metadata. #[serde(default, rename = "quilkin.dev")] pub known: T, /// User created metadata. #[serde(flatten)] pub unknown: serde_yaml::Mapping, } impl<T> MetadataView<T> { pub fn with_unknown(known: impl Into<T>, unknown: serde_yaml::Mapping) -> Self { Self { known: known.into(), unknown, } } } // This impl means that any `T` that we can try convert from a protobuf struct // at run-time can be constructed statically without going through // conversion first. impl<T, E> From<T> for MetadataView<T> where T: TryFrom<prost_types::Struct, Error = E> + Default, { fn from(known: T) -> Self { Self { known, unknown: <_>::default(), } } } impl<T, E> TryFrom<ProtoMetadata> for MetadataView<T> where T: TryFrom<prost_types::Struct, Error = E> + Default, { type Error = E; fn try_from(mut value: ProtoMetadata) -> Result<Self, Self::Error> { let known = value .filter_metadata .remove(KEY) .map(T::try_from) .transpose()? .unwrap_or_default(); let value = prost_types::value::Kind::StructValue(prost_types::Struct { fields: value .filter_metadata .into_iter() .map(|(k, v)| { ( k, prost_types::Value { kind: Some(prost_types::value::Kind::StructValue(v)), }, ) }) .collect(), }); Ok(Self { known, unknown: crate::prost::mapping_from_kind(value).unwrap_or_default(), }) } }
random_line_split
metadata.rs
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::{collections::HashMap, convert::TryFrom, sync::Arc}; use crate::xds::envoy::config::core::v3::Metadata as ProtoMetadata; /// Shared state between [`Filter`][crate::filters::Filter]s during processing for a single packet. pub type DynamicMetadata = HashMap<Arc<String>, Value>; pub const KEY: &str = "quilkin.dev"; #[derive( Clone, Debug, PartialOrd, serde::Serialize, serde::Deserialize, Eq, Ord, schemars::JsonSchema, )] #[serde(untagged)] pub enum Value { Bool(bool), Number(u64), List(Vec<Value>), String(String), Bytes(bytes::Bytes), } impl Value { /// Returns the inner `String` value of `self` if it /// matches [`Value::String`]. pub fn as_bytes(&self) -> Option<&bytes::Bytes> { match self { Self::Bytes(value) => Some(value), _ => None, } } /// Returns the inner `String` value of `self` if it /// matches [`Value::String`]. pub fn as_string(&self) -> Option<&str> { match self { Self::String(value) => Some(value), _ => None, } } /// Returns the inner `String` value of `self` if it /// matches [`Value::String`]. pub fn as_mut_string(&mut self) -> Option<&mut String> { match self { Self::String(value) => Some(value), _ => None, } } } /// Convenience macro for generating From<T> implementations. macro_rules! from_value { (($name:ident) { $($typ:ty => $ex:expr),+ $(,)? }) => { $( impl From<$typ> for Value { fn from($name: $typ) -> Self { $ex } } )+ } } from_value! { (value) { bool => Self::Bool(value), u64 => Self::Number(value), Vec<Self> => Self::List(value), String => Self::String(value), &str => Self::String(value.into()), bytes::Bytes => Self::Bytes(value), } } impl<const N: usize> From<[u8; N]> for Value { fn from(value: [u8; N]) -> Self { Self::Bytes(bytes::Bytes::copy_from_slice(&value)) } } impl<const N: usize> From<&[u8; N]> for Value { fn from(value: &[u8; N]) -> Self { Self::Bytes(bytes::Bytes::copy_from_slice(value)) } } impl PartialEq for Value { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Bool(a), Self::Bool(b)) => a == b, (Self::Bool(_), _) => false, (Self::Number(a), Self::Number(b)) => a == b, (Self::Number(_), _) => false, (Self::List(a), Self::List(b)) => a == b, (Self::List(_), _) => false, (Self::String(a), Self::String(b)) => a == b, (Self::Bytes(a), Self::Bytes(b)) => a == b, (Self::String(a), Self::Bytes(b)) | (Self::Bytes(b), Self::String(a)) => a == b, (Self::String(_), _) => false, (Self::Bytes(_), _) => false, } } } impl TryFrom<prost_types::Value> for Value { type Error = eyre::Report; fn try_from(value: prost_types::Value) -> Result<Self, Self::Error> { use prost_types::value::Kind; let value = match value.kind { Some(value) => value, None => return Err(eyre::eyre!("unexpected missing value")), }; match value { Kind::NullValue(_) => Err(eyre::eyre!("unexpected missing value")), Kind::NumberValue(number) => Ok(Self::Number(number as u64)), Kind::StringValue(string) => Ok(Self::String(string)), Kind::BoolValue(value) => Ok(Self::Bool(value)), Kind::ListValue(list) => Ok(Self::List( list.values .into_iter() .map(prost_types::Value::try_into) .collect::<crate::Result<_>>()?, )), Kind::StructValue(_) => Err(eyre::eyre!("unexpected struct value")), } } } /// Represents a view into the metadata object attached to another object. `T` /// represents metadata known to Quilkin under `quilkin.dev` (available under /// the [`KEY`] constant.) #[derive( Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Clone, PartialOrd, Eq, )] #[non_exhaustive] pub struct MetadataView<T> { /// Known Quilkin metadata. #[serde(default, rename = "quilkin.dev")] pub known: T, /// User created metadata. #[serde(flatten)] pub unknown: serde_yaml::Mapping, } impl<T> MetadataView<T> { pub fn with_unknown(known: impl Into<T>, unknown: serde_yaml::Mapping) -> Self { Self { known: known.into(), unknown, } } } // This impl means that any `T` that we can try convert from a protobuf struct // at run-time can be constructed statically without going through // conversion first. impl<T, E> From<T> for MetadataView<T> where T: TryFrom<prost_types::Struct, Error = E> + Default, { fn from(known: T) -> Self { Self { known, unknown: <_>::default(), } } } impl<T, E> TryFrom<ProtoMetadata> for MetadataView<T> where T: TryFrom<prost_types::Struct, Error = E> + Default, { type Error = E; fn
(mut value: ProtoMetadata) -> Result<Self, Self::Error> { let known = value .filter_metadata .remove(KEY) .map(T::try_from) .transpose()? .unwrap_or_default(); let value = prost_types::value::Kind::StructValue(prost_types::Struct { fields: value .filter_metadata .into_iter() .map(|(k, v)| { ( k, prost_types::Value { kind: Some(prost_types::value::Kind::StructValue(v)), }, ) }) .collect(), }); Ok(Self { known, unknown: crate::prost::mapping_from_kind(value).unwrap_or_default(), }) } }
try_from
identifier_name
inline.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use lib::llvm::{AvailableExternallyLinkage, SetLinkage}; use metadata::csearch; use middle::astencode; use middle::trans::base::{push_ctxt, trans_item, get_item_val, trans_fn}; use middle::trans::common::*; use middle::ty; use syntax::ast; use syntax::ast_util::local_def; use syntax::ast_util; pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) -> ast::DefId { let _icx = push_ctxt("maybe_instantiate_inline"); match ccx.external.borrow().find(&fn_id) { Some(&Some(node_id)) => { // Already inline debug!("maybe_instantiate_inline({}): already inline as node id {}", ty::item_path_str(ccx.tcx(), fn_id), node_id); return local_def(node_id); } Some(&None) => { return fn_id; // Not inlinable } None => { // Not seen yet } } let csearch_result = csearch::maybe_get_item_ast( ccx.tcx(), fn_id, |a,b,c,d| astencode::decode_inlined_item(a, b, c, d)); return match csearch_result { csearch::not_found => { ccx.external.borrow_mut().insert(fn_id, None); fn_id } csearch::found(ast::IIItem(item)) => { ccx.external.borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, fn_id); ccx.stats.n_inlines.set(ccx.stats.n_inlines.get() + 1); trans_item(ccx, &*item); // We're bringing an external global into this crate, but we don't // want to create two copies of the global. If we do this, then if // you take the address of the global in two separate crates you get // two different addresses. This is bad for things like conditions, // but it could possibly have other adverse side effects. We still // want to achieve the optimizations related to this global, // however, so we use the available_externally linkage which llvm // provides match item.node { ast::ItemStatic(_, mutbl, _) =>
_ => {} } local_def(item.id) } csearch::found(ast::IIForeign(item)) => { ccx.external.borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, fn_id); local_def(item.id) } csearch::found_parent(parent_id, ast::IIItem(item)) => { ccx.external.borrow_mut().insert(parent_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, parent_id); let mut my_id = 0; match item.node { ast::ItemEnum(_, _) => { let vs_here = ty::enum_variants(ccx.tcx(), local_def(item.id)); let vs_there = ty::enum_variants(ccx.tcx(), parent_id); for (here, there) in vs_here.iter().zip(vs_there.iter()) { if there.id == fn_id { my_id = here.id.node; } ccx.external.borrow_mut().insert(there.id, Some(here.id.node)); } } ast::ItemStruct(ref struct_def, _) => { match struct_def.ctor_id { None => {} Some(ctor_id) => { ccx.external.borrow_mut().insert(fn_id, Some(ctor_id)); my_id = ctor_id; } } } _ => ccx.sess().bug("maybe_instantiate_inline: item has a \ non-enum, non-struct parent") } trans_item(ccx, &*item); local_def(my_id) } csearch::found_parent(_, _) => { ccx.sess().bug("maybe_get_item_ast returned a found_parent \ with a non-item parent"); } csearch::found(ast::IIMethod(impl_did, is_provided, mth)) => { ccx.external.borrow_mut().insert(fn_id, Some(mth.id)); ccx.external_srcs.borrow_mut().insert(mth.id, fn_id); ccx.stats.n_inlines.set(ccx.stats.n_inlines.get() + 1); // If this is a default method, we can't look up the // impl type. But we aren't going to translate anyways, so don't. if is_provided { return local_def(mth.id); } let impl_tpt = ty::lookup_item_type(ccx.tcx(), impl_did); let unparameterized = impl_tpt.generics.types.is_empty() && mth.generics.ty_params.is_empty(); if unparameterized { let llfn = get_item_val(ccx, mth.id); trans_fn(ccx, &*mth.decl, &*mth.body, llfn, &param_substs::empty(), mth.id, []); } local_def(mth.id) } }; }
{ let g = get_item_val(ccx, item.id); // see the comment in get_item_val() as to why this check is // performed here. if ast_util::static_has_significant_address( mutbl, item.attrs.as_slice()) { SetLinkage(g, AvailableExternallyLinkage); } }
conditional_block
inline.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use lib::llvm::{AvailableExternallyLinkage, SetLinkage}; use metadata::csearch; use middle::astencode; use middle::trans::base::{push_ctxt, trans_item, get_item_val, trans_fn}; use middle::trans::common::*; use middle::ty; use syntax::ast; use syntax::ast_util::local_def; use syntax::ast_util; pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) -> ast::DefId
|a,b,c,d| astencode::decode_inlined_item(a, b, c, d)); return match csearch_result { csearch::not_found => { ccx.external.borrow_mut().insert(fn_id, None); fn_id } csearch::found(ast::IIItem(item)) => { ccx.external.borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, fn_id); ccx.stats.n_inlines.set(ccx.stats.n_inlines.get() + 1); trans_item(ccx, &*item); // We're bringing an external global into this crate, but we don't // want to create two copies of the global. If we do this, then if // you take the address of the global in two separate crates you get // two different addresses. This is bad for things like conditions, // but it could possibly have other adverse side effects. We still // want to achieve the optimizations related to this global, // however, so we use the available_externally linkage which llvm // provides match item.node { ast::ItemStatic(_, mutbl, _) => { let g = get_item_val(ccx, item.id); // see the comment in get_item_val() as to why this check is // performed here. if ast_util::static_has_significant_address( mutbl, item.attrs.as_slice()) { SetLinkage(g, AvailableExternallyLinkage); } } _ => {} } local_def(item.id) } csearch::found(ast::IIForeign(item)) => { ccx.external.borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, fn_id); local_def(item.id) } csearch::found_parent(parent_id, ast::IIItem(item)) => { ccx.external.borrow_mut().insert(parent_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, parent_id); let mut my_id = 0; match item.node { ast::ItemEnum(_, _) => { let vs_here = ty::enum_variants(ccx.tcx(), local_def(item.id)); let vs_there = ty::enum_variants(ccx.tcx(), parent_id); for (here, there) in vs_here.iter().zip(vs_there.iter()) { if there.id == fn_id { my_id = here.id.node; } ccx.external.borrow_mut().insert(there.id, Some(here.id.node)); } } ast::ItemStruct(ref struct_def, _) => { match struct_def.ctor_id { None => {} Some(ctor_id) => { ccx.external.borrow_mut().insert(fn_id, Some(ctor_id)); my_id = ctor_id; } } } _ => ccx.sess().bug("maybe_instantiate_inline: item has a \ non-enum, non-struct parent") } trans_item(ccx, &*item); local_def(my_id) } csearch::found_parent(_, _) => { ccx.sess().bug("maybe_get_item_ast returned a found_parent \ with a non-item parent"); } csearch::found(ast::IIMethod(impl_did, is_provided, mth)) => { ccx.external.borrow_mut().insert(fn_id, Some(mth.id)); ccx.external_srcs.borrow_mut().insert(mth.id, fn_id); ccx.stats.n_inlines.set(ccx.stats.n_inlines.get() + 1); // If this is a default method, we can't look up the // impl type. But we aren't going to translate anyways, so don't. if is_provided { return local_def(mth.id); } let impl_tpt = ty::lookup_item_type(ccx.tcx(), impl_did); let unparameterized = impl_tpt.generics.types.is_empty() && mth.generics.ty_params.is_empty(); if unparameterized { let llfn = get_item_val(ccx, mth.id); trans_fn(ccx, &*mth.decl, &*mth.body, llfn, &param_substs::empty(), mth.id, []); } local_def(mth.id) } }; }
{ let _icx = push_ctxt("maybe_instantiate_inline"); match ccx.external.borrow().find(&fn_id) { Some(&Some(node_id)) => { // Already inline debug!("maybe_instantiate_inline({}): already inline as node id {}", ty::item_path_str(ccx.tcx(), fn_id), node_id); return local_def(node_id); } Some(&None) => { return fn_id; // Not inlinable } None => { // Not seen yet } } let csearch_result = csearch::maybe_get_item_ast( ccx.tcx(), fn_id,
identifier_body
inline.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use lib::llvm::{AvailableExternallyLinkage, SetLinkage}; use metadata::csearch; use middle::astencode; use middle::trans::base::{push_ctxt, trans_item, get_item_val, trans_fn}; use middle::trans::common::*; use middle::ty; use syntax::ast; use syntax::ast_util::local_def; use syntax::ast_util; pub fn
(ccx: &CrateContext, fn_id: ast::DefId) -> ast::DefId { let _icx = push_ctxt("maybe_instantiate_inline"); match ccx.external.borrow().find(&fn_id) { Some(&Some(node_id)) => { // Already inline debug!("maybe_instantiate_inline({}): already inline as node id {}", ty::item_path_str(ccx.tcx(), fn_id), node_id); return local_def(node_id); } Some(&None) => { return fn_id; // Not inlinable } None => { // Not seen yet } } let csearch_result = csearch::maybe_get_item_ast( ccx.tcx(), fn_id, |a,b,c,d| astencode::decode_inlined_item(a, b, c, d)); return match csearch_result { csearch::not_found => { ccx.external.borrow_mut().insert(fn_id, None); fn_id } csearch::found(ast::IIItem(item)) => { ccx.external.borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, fn_id); ccx.stats.n_inlines.set(ccx.stats.n_inlines.get() + 1); trans_item(ccx, &*item); // We're bringing an external global into this crate, but we don't // want to create two copies of the global. If we do this, then if // you take the address of the global in two separate crates you get // two different addresses. This is bad for things like conditions, // but it could possibly have other adverse side effects. We still // want to achieve the optimizations related to this global, // however, so we use the available_externally linkage which llvm // provides match item.node { ast::ItemStatic(_, mutbl, _) => { let g = get_item_val(ccx, item.id); // see the comment in get_item_val() as to why this check is // performed here. if ast_util::static_has_significant_address( mutbl, item.attrs.as_slice()) { SetLinkage(g, AvailableExternallyLinkage); } } _ => {} } local_def(item.id) } csearch::found(ast::IIForeign(item)) => { ccx.external.borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, fn_id); local_def(item.id) } csearch::found_parent(parent_id, ast::IIItem(item)) => { ccx.external.borrow_mut().insert(parent_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, parent_id); let mut my_id = 0; match item.node { ast::ItemEnum(_, _) => { let vs_here = ty::enum_variants(ccx.tcx(), local_def(item.id)); let vs_there = ty::enum_variants(ccx.tcx(), parent_id); for (here, there) in vs_here.iter().zip(vs_there.iter()) { if there.id == fn_id { my_id = here.id.node; } ccx.external.borrow_mut().insert(there.id, Some(here.id.node)); } } ast::ItemStruct(ref struct_def, _) => { match struct_def.ctor_id { None => {} Some(ctor_id) => { ccx.external.borrow_mut().insert(fn_id, Some(ctor_id)); my_id = ctor_id; } } } _ => ccx.sess().bug("maybe_instantiate_inline: item has a \ non-enum, non-struct parent") } trans_item(ccx, &*item); local_def(my_id) } csearch::found_parent(_, _) => { ccx.sess().bug("maybe_get_item_ast returned a found_parent \ with a non-item parent"); } csearch::found(ast::IIMethod(impl_did, is_provided, mth)) => { ccx.external.borrow_mut().insert(fn_id, Some(mth.id)); ccx.external_srcs.borrow_mut().insert(mth.id, fn_id); ccx.stats.n_inlines.set(ccx.stats.n_inlines.get() + 1); // If this is a default method, we can't look up the // impl type. But we aren't going to translate anyways, so don't. if is_provided { return local_def(mth.id); } let impl_tpt = ty::lookup_item_type(ccx.tcx(), impl_did); let unparameterized = impl_tpt.generics.types.is_empty() && mth.generics.ty_params.is_empty(); if unparameterized { let llfn = get_item_val(ccx, mth.id); trans_fn(ccx, &*mth.decl, &*mth.body, llfn, &param_substs::empty(), mth.id, []); } local_def(mth.id) } }; }
maybe_instantiate_inline
identifier_name
inline.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use lib::llvm::{AvailableExternallyLinkage, SetLinkage}; use metadata::csearch; use middle::astencode; use middle::trans::base::{push_ctxt, trans_item, get_item_val, trans_fn}; use middle::trans::common::*; use middle::ty; use syntax::ast; use syntax::ast_util::local_def; use syntax::ast_util; pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) -> ast::DefId { let _icx = push_ctxt("maybe_instantiate_inline"); match ccx.external.borrow().find(&fn_id) { Some(&Some(node_id)) => { // Already inline debug!("maybe_instantiate_inline({}): already inline as node id {}", ty::item_path_str(ccx.tcx(), fn_id), node_id); return local_def(node_id); } Some(&None) => { return fn_id; // Not inlinable } None => { // Not seen yet } } let csearch_result = csearch::maybe_get_item_ast( ccx.tcx(), fn_id, |a,b,c,d| astencode::decode_inlined_item(a, b, c, d)); return match csearch_result { csearch::not_found => { ccx.external.borrow_mut().insert(fn_id, None); fn_id } csearch::found(ast::IIItem(item)) => { ccx.external.borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, fn_id); ccx.stats.n_inlines.set(ccx.stats.n_inlines.get() + 1); trans_item(ccx, &*item); // We're bringing an external global into this crate, but we don't // want to create two copies of the global. If we do this, then if // you take the address of the global in two separate crates you get // two different addresses. This is bad for things like conditions, // but it could possibly have other adverse side effects. We still // want to achieve the optimizations related to this global, // however, so we use the available_externally linkage which llvm // provides match item.node { ast::ItemStatic(_, mutbl, _) => { let g = get_item_val(ccx, item.id); // see the comment in get_item_val() as to why this check is // performed here. if ast_util::static_has_significant_address(
} _ => {} } local_def(item.id) } csearch::found(ast::IIForeign(item)) => { ccx.external.borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, fn_id); local_def(item.id) } csearch::found_parent(parent_id, ast::IIItem(item)) => { ccx.external.borrow_mut().insert(parent_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, parent_id); let mut my_id = 0; match item.node { ast::ItemEnum(_, _) => { let vs_here = ty::enum_variants(ccx.tcx(), local_def(item.id)); let vs_there = ty::enum_variants(ccx.tcx(), parent_id); for (here, there) in vs_here.iter().zip(vs_there.iter()) { if there.id == fn_id { my_id = here.id.node; } ccx.external.borrow_mut().insert(there.id, Some(here.id.node)); } } ast::ItemStruct(ref struct_def, _) => { match struct_def.ctor_id { None => {} Some(ctor_id) => { ccx.external.borrow_mut().insert(fn_id, Some(ctor_id)); my_id = ctor_id; } } } _ => ccx.sess().bug("maybe_instantiate_inline: item has a \ non-enum, non-struct parent") } trans_item(ccx, &*item); local_def(my_id) } csearch::found_parent(_, _) => { ccx.sess().bug("maybe_get_item_ast returned a found_parent \ with a non-item parent"); } csearch::found(ast::IIMethod(impl_did, is_provided, mth)) => { ccx.external.borrow_mut().insert(fn_id, Some(mth.id)); ccx.external_srcs.borrow_mut().insert(mth.id, fn_id); ccx.stats.n_inlines.set(ccx.stats.n_inlines.get() + 1); // If this is a default method, we can't look up the // impl type. But we aren't going to translate anyways, so don't. if is_provided { return local_def(mth.id); } let impl_tpt = ty::lookup_item_type(ccx.tcx(), impl_did); let unparameterized = impl_tpt.generics.types.is_empty() && mth.generics.ty_params.is_empty(); if unparameterized { let llfn = get_item_val(ccx, mth.id); trans_fn(ccx, &*mth.decl, &*mth.body, llfn, &param_substs::empty(), mth.id, []); } local_def(mth.id) } }; }
mutbl, item.attrs.as_slice()) { SetLinkage(g, AvailableExternallyLinkage); }
random_line_split
main.rs
#![feature(convert)] extern crate revord; use revord::RevOrd; use std::str::from_utf8; use std::collections::{HashSet, BinaryHeap}; fn calibrate(challenge: &str, productions: &Vec<(&str, &str)>) -> usize
// There is pretty much going on for part two. I should clean this mess up. fn reduce(challenge: &String, productions: &Vec<(&str, &str)>, steps: usize) -> (String, usize) { let mut queue = BinaryHeap::new(); let mut seen = HashSet::new(); let mut latest = (challenge.clone(), steps); queue.push((RevOrd(challenge.clone()), steps)); while let Some((RevOrd(string), steps)) = queue.pop() { if seen.contains(&string) { continue; } seen.insert(string.clone()); latest = (string.clone(), steps); for &(symbol, replacement) in productions { for (index, _) in string.rmatch_indices(replacement) { let (head, tail) = string.split_at(index); let result = format!("{}{}{}", head, symbol, &tail[replacement.len()..]); queue.push((RevOrd(result), steps + 1)); } } } latest } fn helper(challenge: &String, productions: &Vec<(&str, &str)>, steps: usize) -> (String, usize) { let mut sub_challenges: Vec<String> = challenge.split("Ar") .map(|x| x.to_string()) .collect(); for i in 0..(sub_challenges.len() - 1) { sub_challenges[i].push_str("Ar"); } if sub_challenges.last().unwrap().is_empty() { sub_challenges.pop(); } if sub_challenges.len() == 1 { return reduce(challenge, productions, steps); } let mut total_steps = steps; let mut result = String::with_capacity(challenge.len()); for sub in sub_challenges { let (string, steps) = helper(&sub, productions, 0); total_steps += steps; result.push_str(string.as_str()); } (result, total_steps) } fn fabricate(medicine: &str, productions: &Vec<(&str, &str)>) -> Option<usize> { let mut productions = productions.clone(); productions.sort_by(|&(_, a), &(_, b)| b.len().cmp(&a.len())); let mut challenge = medicine.to_string(); let mut steps = 0; while challenge!= "e" { let (new_challenge, total) = helper(&challenge, &productions, steps); challenge = new_challenge; steps = total; } Some(steps) } static PARSE_ERROR: &'static str = "Invalid input format."; fn main() { let input = from_utf8(include_bytes!("../input.txt")).unwrap(); let mut lines: Vec<_> = input.split('\n') .filter(|l|!l.is_empty()) .collect(); let mut productions = Vec::new(); let challenge = lines.pop().expect(PARSE_ERROR); for line in &lines { let tokens: Vec<_> = line.split(' ').collect(); if tokens.len() < 3 || tokens[0].len() > tokens[2].len() { // We do not allow productions that reduce the input length. panic!(PARSE_ERROR); } productions.push((tokens[0], tokens[2])); } let solution = calibrate(challenge, &productions); println!("{} molecules can be created.", solution); match fabricate(challenge, &productions) { Some(steps) => println!("The medicine can be created in {} steps.", steps), _ => println!("We seem to be unable to produce the medicine.") } }
{ let mut words = HashSet::new(); for &(symbol, replacement) in productions { for (index, _) in challenge.match_indices(symbol) { let (head, tail) = challenge.split_at(index); let result = format!("{}{}{}", head, replacement, &tail[symbol.len()..]); words.insert(result); } } words.len() }
identifier_body
main.rs
#![feature(convert)] extern crate revord; use revord::RevOrd; use std::str::from_utf8; use std::collections::{HashSet, BinaryHeap}; fn calibrate(challenge: &str, productions: &Vec<(&str, &str)>) -> usize { let mut words = HashSet::new(); for &(symbol, replacement) in productions { for (index, _) in challenge.match_indices(symbol) { let (head, tail) = challenge.split_at(index); let result = format!("{}{}{}", head, replacement, &tail[symbol.len()..]); words.insert(result); } } words.len() } // There is pretty much going on for part two. I should clean this mess up. fn reduce(challenge: &String, productions: &Vec<(&str, &str)>, steps: usize) -> (String, usize) { let mut queue = BinaryHeap::new(); let mut seen = HashSet::new(); let mut latest = (challenge.clone(), steps); queue.push((RevOrd(challenge.clone()), steps)); while let Some((RevOrd(string), steps)) = queue.pop() { if seen.contains(&string) { continue; } seen.insert(string.clone()); latest = (string.clone(), steps); for &(symbol, replacement) in productions { for (index, _) in string.rmatch_indices(replacement) { let (head, tail) = string.split_at(index); let result = format!("{}{}{}", head, symbol, &tail[replacement.len()..]); queue.push((RevOrd(result), steps + 1)); } } } latest } fn helper(challenge: &String, productions: &Vec<(&str, &str)>, steps: usize) -> (String, usize) { let mut sub_challenges: Vec<String> = challenge.split("Ar") .map(|x| x.to_string()) .collect(); for i in 0..(sub_challenges.len() - 1) { sub_challenges[i].push_str("Ar"); } if sub_challenges.last().unwrap().is_empty() { sub_challenges.pop(); } if sub_challenges.len() == 1 { return reduce(challenge, productions, steps); } let mut total_steps = steps; let mut result = String::with_capacity(challenge.len()); for sub in sub_challenges { let (string, steps) = helper(&sub, productions, 0); total_steps += steps; result.push_str(string.as_str()); } (result, total_steps) } fn fabricate(medicine: &str, productions: &Vec<(&str, &str)>) -> Option<usize> { let mut productions = productions.clone(); productions.sort_by(|&(_, a), &(_, b)| b.len().cmp(&a.len())); let mut challenge = medicine.to_string(); let mut steps = 0; while challenge!= "e" { let (new_challenge, total) = helper(&challenge, &productions, steps); challenge = new_challenge; steps = total; } Some(steps) } static PARSE_ERROR: &'static str = "Invalid input format."; fn main() { let input = from_utf8(include_bytes!("../input.txt")).unwrap(); let mut lines: Vec<_> = input.split('\n') .filter(|l|!l.is_empty()) .collect(); let mut productions = Vec::new(); let challenge = lines.pop().expect(PARSE_ERROR); for line in &lines { let tokens: Vec<_> = line.split(' ').collect();
if tokens.len() < 3 || tokens[0].len() > tokens[2].len() { // We do not allow productions that reduce the input length. panic!(PARSE_ERROR); } productions.push((tokens[0], tokens[2])); } let solution = calibrate(challenge, &productions); println!("{} molecules can be created.", solution); match fabricate(challenge, &productions) { Some(steps) => println!("The medicine can be created in {} steps.", steps), _ => println!("We seem to be unable to produce the medicine.") } }
random_line_split
main.rs
#![feature(convert)] extern crate revord; use revord::RevOrd; use std::str::from_utf8; use std::collections::{HashSet, BinaryHeap}; fn calibrate(challenge: &str, productions: &Vec<(&str, &str)>) -> usize { let mut words = HashSet::new(); for &(symbol, replacement) in productions { for (index, _) in challenge.match_indices(symbol) { let (head, tail) = challenge.split_at(index); let result = format!("{}{}{}", head, replacement, &tail[symbol.len()..]); words.insert(result); } } words.len() } // There is pretty much going on for part two. I should clean this mess up. fn reduce(challenge: &String, productions: &Vec<(&str, &str)>, steps: usize) -> (String, usize) { let mut queue = BinaryHeap::new(); let mut seen = HashSet::new(); let mut latest = (challenge.clone(), steps); queue.push((RevOrd(challenge.clone()), steps)); while let Some((RevOrd(string), steps)) = queue.pop() { if seen.contains(&string) { continue; } seen.insert(string.clone()); latest = (string.clone(), steps); for &(symbol, replacement) in productions { for (index, _) in string.rmatch_indices(replacement) { let (head, tail) = string.split_at(index); let result = format!("{}{}{}", head, symbol, &tail[replacement.len()..]); queue.push((RevOrd(result), steps + 1)); } } } latest } fn helper(challenge: &String, productions: &Vec<(&str, &str)>, steps: usize) -> (String, usize) { let mut sub_challenges: Vec<String> = challenge.split("Ar") .map(|x| x.to_string()) .collect(); for i in 0..(sub_challenges.len() - 1) { sub_challenges[i].push_str("Ar"); } if sub_challenges.last().unwrap().is_empty() { sub_challenges.pop(); } if sub_challenges.len() == 1 { return reduce(challenge, productions, steps); } let mut total_steps = steps; let mut result = String::with_capacity(challenge.len()); for sub in sub_challenges { let (string, steps) = helper(&sub, productions, 0); total_steps += steps; result.push_str(string.as_str()); } (result, total_steps) } fn
(medicine: &str, productions: &Vec<(&str, &str)>) -> Option<usize> { let mut productions = productions.clone(); productions.sort_by(|&(_, a), &(_, b)| b.len().cmp(&a.len())); let mut challenge = medicine.to_string(); let mut steps = 0; while challenge!= "e" { let (new_challenge, total) = helper(&challenge, &productions, steps); challenge = new_challenge; steps = total; } Some(steps) } static PARSE_ERROR: &'static str = "Invalid input format."; fn main() { let input = from_utf8(include_bytes!("../input.txt")).unwrap(); let mut lines: Vec<_> = input.split('\n') .filter(|l|!l.is_empty()) .collect(); let mut productions = Vec::new(); let challenge = lines.pop().expect(PARSE_ERROR); for line in &lines { let tokens: Vec<_> = line.split(' ').collect(); if tokens.len() < 3 || tokens[0].len() > tokens[2].len() { // We do not allow productions that reduce the input length. panic!(PARSE_ERROR); } productions.push((tokens[0], tokens[2])); } let solution = calibrate(challenge, &productions); println!("{} molecules can be created.", solution); match fabricate(challenge, &productions) { Some(steps) => println!("The medicine can be created in {} steps.", steps), _ => println!("We seem to be unable to produce the medicine.") } }
fabricate
identifier_name
builder.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::Duration; use anyhow::{Context, Error}; use url::Url; use anyhow::anyhow; use auth::AuthSection; use configparser::config::ConfigSet; use http_client::HttpVersion; use crate::client::Client; use crate::errors::{ConfigError, EdenApiError}; /// Builder for creating new EdenAPI clients. #[derive(Debug, Default)] pub struct Builder { server_url: Option<Url>, cert: Option<PathBuf>, key: Option<PathBuf>, ca_bundle: Option<PathBuf>, headers: HashMap<String, String>, max_files: Option<usize>, max_trees: Option<usize>, max_history: Option<usize>, max_location_to_hash: Option<usize>, timeout: Option<Duration>, debug: bool, correlator: Option<String>, http_version: Option<HttpVersion>, validate_certs: bool, log_dir: Option<PathBuf>, } impl Builder { pub fn new() -> Self { Default::default() } /// Build the client. pub fn build(self) -> Result<Client, EdenApiError> { self.try_into().map(Client::with_config) } /// Populate a `Builder` from a Mercurial configuration. pub fn from_config(config: &ConfigSet) -> Result<Self, EdenApiError> { let server_url = config .get_opt::<String>("edenapi", "url") .map_err(|e| ConfigError::Malformed("edenapi.url".into(), e))? .ok_or(ConfigError::MissingUrl)? .parse::<Url>() .map_err(ConfigError::InvalidUrl)?; let validate_certs = config .get_opt::<bool>("edenapi", "validate-certs") .map_err(|e| ConfigError::Malformed("edenapi.validate-certs".into(), e))? .unwrap_or_default(); let (cert, key, ca_bundle) = AuthSection::from_config(&config) .validate(validate_certs) .best_match_for(&server_url)? .map(|auth| (auth.cert, auth.key, auth.cacerts)) .unwrap_or_default(); let headers = config .get_opt::<String>("edenapi", "headers") .map_err(|e| ConfigError::Malformed("edenapi.headers".into(), e))? .map(parse_headers) .transpose() .map_err(|e| ConfigError::Malformed("edenapi.headers".into(), e))? .unwrap_or_default(); let max_files = config .get_opt("edenapi", "maxfiles") .map_err(|e| ConfigError::Malformed("edenapi.maxfiles".into(), e))?; let max_trees = config .get_opt("edenapi", "maxtrees") .map_err(|e| ConfigError::Malformed("edenapi.maxtrees".into(), e))?; let max_history = config .get_opt("edenapi", "maxhistory") .map_err(|e| ConfigError::Malformed("edenapi.maxhistory".into(), e))?; let max_location_to_hash = config .get_opt("edenapi", "maxlocationtohash") .map_err(|e| ConfigError::Malformed("edenapi.maxlocationtohash".into(), e))?; let timeout = config .get_opt("edenapi", "timeout") .map_err(|e| ConfigError::Malformed("edenapi.timeout".into(), e))? .map(Duration::from_secs); let debug = config .get_opt("edenapi", "debug") .map_err(|e| ConfigError::Malformed("edenapi.timeout".into(), e))? .unwrap_or_default(); let http_version = config .get_opt("edenapi", "http-version") .map_err(|e| ConfigError::Malformed("edenapi.http-version".into(), e))? .unwrap_or_else(|| "2".to_string()); let http_version = Some(match http_version.as_str() { "1.1" => HttpVersion::V11, "2" => HttpVersion::V2, x => { return Err(EdenApiError::BadConfig(ConfigError::Malformed( "edenapi.http-version".into(), anyhow!("invalid http version {}", x), ))); } }); let log_dir = config .get_opt::<PathBuf>("edenapi", "logdir") .map_err(|e| ConfigError::Malformed("edenapi.logdir".into(), e))?; Ok(Self { server_url: Some(server_url), cert, key, ca_bundle, headers, max_files, max_trees, max_history, max_location_to_hash, timeout, debug, correlator: None, http_version, validate_certs, log_dir, }) } /// Set the server URL. pub fn server_url(mut self, url: Url) -> Self { self.server_url = Some(url); self } /// Specify a client certificate for authenticating with the server. /// The caller should provide a path to PEM-encoded X.509 certificate file. /// The corresponding private key may either be provided in the same file /// as the certificate, or separately using the `key` method. pub fn cert(mut self, cert: impl AsRef<Path>) -> Self { self.cert = Some(cert.as_ref().into()); self } /// Specify the client's private key pub fn key(mut self, key: impl AsRef<Path>) -> Self { self.key = Some(key.as_ref().into()); self } /// Specify a CA certificate bundle to be used to validate the server's /// TLS certificate in place of the default system certificate bundle. /// Primarily used in tests. pub fn ca_bundle(mut self, ca: impl AsRef<Path>) -> Self { self.ca_bundle = Some(ca.as_ref().into()); self } /// Extra HTTP headers that should be sent with each request. pub fn headers<T, K, V>(mut self, headers: T) -> Self where T: IntoIterator<Item = (K, V)>, K: ToString, V: ToString, { let headers = headers .into_iter() .map(|(k, v)| (k.to_string(), v.to_string())); self.headers.extend(headers); self } /// Add an extra HTTP header that should be sent with each request. pub fn header(mut self, name: impl ToString, value: impl ToString) -> Self { self.headers.insert(name.to_string(), value.to_string()); self } /// Maximum number of keys per file request. Larger requests will be /// split up into concurrently-sent batches. pub fn max_files(mut self, size: Option<usize>) -> Self { self.max_files = size; self } /// Maximum number of keys per tree request. Larger requests will be /// split up into concurrently-sent batches. pub fn
(mut self, size: Option<usize>) -> Self { self.max_trees = size; self } /// Maximum number of keys per history request. Larger requests will be /// split up into concurrently-sent batches. pub fn max_history(mut self, size: Option<usize>) -> Self { self.max_history = size; self } /// Maximum number of locations per location to has request. Larger requests will be split up /// into concurrently-sent batches. pub fn max_location_to_hash(mut self, size: Option<usize>) -> Self { self.max_location_to_hash = size; self } /// Timeout for HTTP requests sent by the client. pub fn timeout(mut self, timeout: Duration) -> Self { self.timeout = Some(timeout); self } /// Unique identifier that will be logged by both the client and server for /// every request, allowing log entries on both sides to be correlated. Also /// allows correlating multiple requests that were made by the same instance /// of the client. pub fn correlator(mut self, correlator: Option<impl ToString>) -> Self { self.correlator = correlator.map(|s| s.to_string()); self } /// Set the HTTP version that the client should use. pub fn http_version(mut self, version: HttpVersion) -> Self { self.http_version = Some(version); self } /// Specify whether the client should validate the user's client certificate /// before each request. pub fn validate_certs(mut self, validate_certs: bool) -> Self { self.validate_certs = validate_certs; self } /// If specified, the client will write a JSON version of every request /// it sends to the specified directory. This is primarily useful for /// debugging. The JSON requests can be sent with the `edenapi_cli`, or /// converted to CBOR with the `make_req` tool and sent with `curl`. pub fn log_dir(mut self, dir: impl AsRef<Path>) -> Self { self.log_dir = Some(dir.as_ref().into()); self } } /// Configuration for a `Client`. Essentially has the same fields as a /// `Builder`, but required fields are not optional and values have been /// appropriately parsed and validated. #[derive(Debug)] pub(crate) struct Config { pub(crate) server_url: Url, pub(crate) cert: Option<PathBuf>, pub(crate) key: Option<PathBuf>, pub(crate) ca_bundle: Option<PathBuf>, pub(crate) headers: HashMap<String, String>, pub(crate) max_files: Option<usize>, pub(crate) max_trees: Option<usize>, pub(crate) max_history: Option<usize>, pub(crate) max_location_to_hash: Option<usize>, pub(crate) timeout: Option<Duration>, pub(crate) debug: bool, pub(crate) correlator: Option<String>, pub(crate) http_version: Option<HttpVersion>, pub(crate) validate_certs: bool, pub(crate) log_dir: Option<PathBuf>, } impl TryFrom<Builder> for Config { type Error = EdenApiError; fn try_from(builder: Builder) -> Result<Self, Self::Error> { let Builder { server_url, cert, key, ca_bundle, headers, max_files, max_trees, max_history, max_location_to_hash, timeout, debug, correlator, http_version, validate_certs, log_dir, } = builder; // Check for missing required fields. let mut server_url = server_url.ok_or(ConfigError::MissingUrl)?; // Ensure the base URL's path ends with a slash so that `Url::join` // won't strip the final path component. if!server_url.path().ends_with('/') { let path = format!("{}/", server_url.path()); server_url.set_path(&path); } // Setting these to 0 is the same as None. let max_files = max_files.filter(|n| *n > 0); let max_trees = max_trees.filter(|n| *n > 0); let max_history = max_history.filter(|n| *n > 0); Ok(Config { server_url, cert, key, ca_bundle, headers, max_files, max_trees, max_history, max_location_to_hash, timeout, debug, correlator, http_version, validate_certs, log_dir, }) } } /// Parse headers from a JSON object. fn parse_headers(headers: impl AsRef<str>) -> Result<HashMap<String, String>, Error> { Ok(serde_json::from_str(headers.as_ref()) .context(format!("Not a valid JSON object: {:?}", headers.as_ref()))?) }
max_trees
identifier_name
builder.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::Duration; use anyhow::{Context, Error}; use url::Url; use anyhow::anyhow; use auth::AuthSection; use configparser::config::ConfigSet; use http_client::HttpVersion; use crate::client::Client; use crate::errors::{ConfigError, EdenApiError}; /// Builder for creating new EdenAPI clients. #[derive(Debug, Default)] pub struct Builder { server_url: Option<Url>, cert: Option<PathBuf>, key: Option<PathBuf>, ca_bundle: Option<PathBuf>, headers: HashMap<String, String>, max_files: Option<usize>, max_trees: Option<usize>, max_history: Option<usize>, max_location_to_hash: Option<usize>, timeout: Option<Duration>, debug: bool, correlator: Option<String>, http_version: Option<HttpVersion>, validate_certs: bool, log_dir: Option<PathBuf>, } impl Builder { pub fn new() -> Self { Default::default() } /// Build the client. pub fn build(self) -> Result<Client, EdenApiError> { self.try_into().map(Client::with_config) } /// Populate a `Builder` from a Mercurial configuration. pub fn from_config(config: &ConfigSet) -> Result<Self, EdenApiError> { let server_url = config .get_opt::<String>("edenapi", "url") .map_err(|e| ConfigError::Malformed("edenapi.url".into(), e))? .ok_or(ConfigError::MissingUrl)? .parse::<Url>() .map_err(ConfigError::InvalidUrl)?; let validate_certs = config .get_opt::<bool>("edenapi", "validate-certs") .map_err(|e| ConfigError::Malformed("edenapi.validate-certs".into(), e))? .unwrap_or_default(); let (cert, key, ca_bundle) = AuthSection::from_config(&config) .validate(validate_certs) .best_match_for(&server_url)? .map(|auth| (auth.cert, auth.key, auth.cacerts)) .unwrap_or_default(); let headers = config .get_opt::<String>("edenapi", "headers") .map_err(|e| ConfigError::Malformed("edenapi.headers".into(), e))? .map(parse_headers) .transpose() .map_err(|e| ConfigError::Malformed("edenapi.headers".into(), e))? .unwrap_or_default(); let max_files = config .get_opt("edenapi", "maxfiles") .map_err(|e| ConfigError::Malformed("edenapi.maxfiles".into(), e))?; let max_trees = config .get_opt("edenapi", "maxtrees") .map_err(|e| ConfigError::Malformed("edenapi.maxtrees".into(), e))?; let max_history = config .get_opt("edenapi", "maxhistory") .map_err(|e| ConfigError::Malformed("edenapi.maxhistory".into(), e))?; let max_location_to_hash = config .get_opt("edenapi", "maxlocationtohash") .map_err(|e| ConfigError::Malformed("edenapi.maxlocationtohash".into(), e))?; let timeout = config .get_opt("edenapi", "timeout") .map_err(|e| ConfigError::Malformed("edenapi.timeout".into(), e))? .map(Duration::from_secs); let debug = config .get_opt("edenapi", "debug") .map_err(|e| ConfigError::Malformed("edenapi.timeout".into(), e))? .unwrap_or_default(); let http_version = config .get_opt("edenapi", "http-version") .map_err(|e| ConfigError::Malformed("edenapi.http-version".into(), e))? .unwrap_or_else(|| "2".to_string()); let http_version = Some(match http_version.as_str() { "1.1" => HttpVersion::V11, "2" => HttpVersion::V2, x => { return Err(EdenApiError::BadConfig(ConfigError::Malformed( "edenapi.http-version".into(), anyhow!("invalid http version {}", x), ))); } }); let log_dir = config .get_opt::<PathBuf>("edenapi", "logdir") .map_err(|e| ConfigError::Malformed("edenapi.logdir".into(), e))?; Ok(Self { server_url: Some(server_url), cert, key, ca_bundle, headers, max_files, max_trees, max_history, max_location_to_hash, timeout, debug, correlator: None, http_version, validate_certs, log_dir, }) } /// Set the server URL. pub fn server_url(mut self, url: Url) -> Self { self.server_url = Some(url); self } /// Specify a client certificate for authenticating with the server. /// The caller should provide a path to PEM-encoded X.509 certificate file. /// The corresponding private key may either be provided in the same file /// as the certificate, or separately using the `key` method. pub fn cert(mut self, cert: impl AsRef<Path>) -> Self { self.cert = Some(cert.as_ref().into()); self } /// Specify the client's private key pub fn key(mut self, key: impl AsRef<Path>) -> Self { self.key = Some(key.as_ref().into()); self } /// Specify a CA certificate bundle to be used to validate the server's /// TLS certificate in place of the default system certificate bundle. /// Primarily used in tests. pub fn ca_bundle(mut self, ca: impl AsRef<Path>) -> Self { self.ca_bundle = Some(ca.as_ref().into()); self } /// Extra HTTP headers that should be sent with each request. pub fn headers<T, K, V>(mut self, headers: T) -> Self where T: IntoIterator<Item = (K, V)>, K: ToString, V: ToString, { let headers = headers .into_iter() .map(|(k, v)| (k.to_string(), v.to_string())); self.headers.extend(headers); self } /// Add an extra HTTP header that should be sent with each request. pub fn header(mut self, name: impl ToString, value: impl ToString) -> Self { self.headers.insert(name.to_string(), value.to_string()); self } /// Maximum number of keys per file request. Larger requests will be /// split up into concurrently-sent batches. pub fn max_files(mut self, size: Option<usize>) -> Self { self.max_files = size; self } /// Maximum number of keys per tree request. Larger requests will be /// split up into concurrently-sent batches. pub fn max_trees(mut self, size: Option<usize>) -> Self { self.max_trees = size; self } /// Maximum number of keys per history request. Larger requests will be /// split up into concurrently-sent batches. pub fn max_history(mut self, size: Option<usize>) -> Self { self.max_history = size; self } /// Maximum number of locations per location to has request. Larger requests will be split up /// into concurrently-sent batches. pub fn max_location_to_hash(mut self, size: Option<usize>) -> Self { self.max_location_to_hash = size; self } /// Timeout for HTTP requests sent by the client. pub fn timeout(mut self, timeout: Duration) -> Self { self.timeout = Some(timeout); self } /// Unique identifier that will be logged by both the client and server for /// every request, allowing log entries on both sides to be correlated. Also /// allows correlating multiple requests that were made by the same instance /// of the client. pub fn correlator(mut self, correlator: Option<impl ToString>) -> Self { self.correlator = correlator.map(|s| s.to_string()); self } /// Set the HTTP version that the client should use. pub fn http_version(mut self, version: HttpVersion) -> Self { self.http_version = Some(version); self } /// Specify whether the client should validate the user's client certificate /// before each request. pub fn validate_certs(mut self, validate_certs: bool) -> Self { self.validate_certs = validate_certs; self } /// If specified, the client will write a JSON version of every request /// it sends to the specified directory. This is primarily useful for /// debugging. The JSON requests can be sent with the `edenapi_cli`, or /// converted to CBOR with the `make_req` tool and sent with `curl`. pub fn log_dir(mut self, dir: impl AsRef<Path>) -> Self { self.log_dir = Some(dir.as_ref().into()); self } } /// Configuration for a `Client`. Essentially has the same fields as a /// `Builder`, but required fields are not optional and values have been /// appropriately parsed and validated. #[derive(Debug)] pub(crate) struct Config { pub(crate) server_url: Url, pub(crate) cert: Option<PathBuf>, pub(crate) key: Option<PathBuf>, pub(crate) ca_bundle: Option<PathBuf>, pub(crate) headers: HashMap<String, String>, pub(crate) max_files: Option<usize>, pub(crate) max_trees: Option<usize>, pub(crate) max_history: Option<usize>, pub(crate) max_location_to_hash: Option<usize>, pub(crate) timeout: Option<Duration>, pub(crate) debug: bool, pub(crate) correlator: Option<String>, pub(crate) http_version: Option<HttpVersion>, pub(crate) validate_certs: bool, pub(crate) log_dir: Option<PathBuf>, } impl TryFrom<Builder> for Config { type Error = EdenApiError; fn try_from(builder: Builder) -> Result<Self, Self::Error> { let Builder { server_url, cert, key, ca_bundle, headers, max_files, max_trees, max_history, max_location_to_hash, timeout, debug, correlator, http_version, validate_certs, log_dir, } = builder; // Check for missing required fields. let mut server_url = server_url.ok_or(ConfigError::MissingUrl)?; // Ensure the base URL's path ends with a slash so that `Url::join` // won't strip the final path component. if!server_url.path().ends_with('/')
// Setting these to 0 is the same as None. let max_files = max_files.filter(|n| *n > 0); let max_trees = max_trees.filter(|n| *n > 0); let max_history = max_history.filter(|n| *n > 0); Ok(Config { server_url, cert, key, ca_bundle, headers, max_files, max_trees, max_history, max_location_to_hash, timeout, debug, correlator, http_version, validate_certs, log_dir, }) } } /// Parse headers from a JSON object. fn parse_headers(headers: impl AsRef<str>) -> Result<HashMap<String, String>, Error> { Ok(serde_json::from_str(headers.as_ref()) .context(format!("Not a valid JSON object: {:?}", headers.as_ref()))?) }
{ let path = format!("{}/", server_url.path()); server_url.set_path(&path); }
conditional_block
builder.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::Duration; use anyhow::{Context, Error}; use url::Url; use anyhow::anyhow; use auth::AuthSection; use configparser::config::ConfigSet; use http_client::HttpVersion; use crate::client::Client; use crate::errors::{ConfigError, EdenApiError}; /// Builder for creating new EdenAPI clients. #[derive(Debug, Default)] pub struct Builder { server_url: Option<Url>, cert: Option<PathBuf>, key: Option<PathBuf>, ca_bundle: Option<PathBuf>, headers: HashMap<String, String>, max_files: Option<usize>, max_trees: Option<usize>, max_history: Option<usize>, max_location_to_hash: Option<usize>, timeout: Option<Duration>, debug: bool, correlator: Option<String>, http_version: Option<HttpVersion>, validate_certs: bool, log_dir: Option<PathBuf>, } impl Builder { pub fn new() -> Self { Default::default() } /// Build the client. pub fn build(self) -> Result<Client, EdenApiError> { self.try_into().map(Client::with_config) } /// Populate a `Builder` from a Mercurial configuration. pub fn from_config(config: &ConfigSet) -> Result<Self, EdenApiError> { let server_url = config .get_opt::<String>("edenapi", "url") .map_err(|e| ConfigError::Malformed("edenapi.url".into(), e))? .ok_or(ConfigError::MissingUrl)? .parse::<Url>() .map_err(ConfigError::InvalidUrl)?; let validate_certs = config .get_opt::<bool>("edenapi", "validate-certs") .map_err(|e| ConfigError::Malformed("edenapi.validate-certs".into(), e))? .unwrap_or_default(); let (cert, key, ca_bundle) = AuthSection::from_config(&config) .validate(validate_certs) .best_match_for(&server_url)? .map(|auth| (auth.cert, auth.key, auth.cacerts)) .unwrap_or_default(); let headers = config .get_opt::<String>("edenapi", "headers") .map_err(|e| ConfigError::Malformed("edenapi.headers".into(), e))? .map(parse_headers) .transpose() .map_err(|e| ConfigError::Malformed("edenapi.headers".into(), e))? .unwrap_or_default(); let max_files = config .get_opt("edenapi", "maxfiles") .map_err(|e| ConfigError::Malformed("edenapi.maxfiles".into(), e))?; let max_trees = config .get_opt("edenapi", "maxtrees") .map_err(|e| ConfigError::Malformed("edenapi.maxtrees".into(), e))?; let max_history = config .get_opt("edenapi", "maxhistory") .map_err(|e| ConfigError::Malformed("edenapi.maxhistory".into(), e))?; let max_location_to_hash = config .get_opt("edenapi", "maxlocationtohash") .map_err(|e| ConfigError::Malformed("edenapi.maxlocationtohash".into(), e))?; let timeout = config .get_opt("edenapi", "timeout") .map_err(|e| ConfigError::Malformed("edenapi.timeout".into(), e))? .map(Duration::from_secs); let debug = config .get_opt("edenapi", "debug") .map_err(|e| ConfigError::Malformed("edenapi.timeout".into(), e))? .unwrap_or_default(); let http_version = config .get_opt("edenapi", "http-version") .map_err(|e| ConfigError::Malformed("edenapi.http-version".into(), e))? .unwrap_or_else(|| "2".to_string()); let http_version = Some(match http_version.as_str() { "1.1" => HttpVersion::V11, "2" => HttpVersion::V2, x => { return Err(EdenApiError::BadConfig(ConfigError::Malformed( "edenapi.http-version".into(), anyhow!("invalid http version {}", x), ))); } }); let log_dir = config .get_opt::<PathBuf>("edenapi", "logdir") .map_err(|e| ConfigError::Malformed("edenapi.logdir".into(), e))?; Ok(Self { server_url: Some(server_url), cert, key, ca_bundle, headers, max_files, max_trees, max_history, max_location_to_hash, timeout, debug, correlator: None, http_version, validate_certs, log_dir, }) } /// Set the server URL. pub fn server_url(mut self, url: Url) -> Self { self.server_url = Some(url); self } /// Specify a client certificate for authenticating with the server. /// The caller should provide a path to PEM-encoded X.509 certificate file.
self } /// Specify the client's private key pub fn key(mut self, key: impl AsRef<Path>) -> Self { self.key = Some(key.as_ref().into()); self } /// Specify a CA certificate bundle to be used to validate the server's /// TLS certificate in place of the default system certificate bundle. /// Primarily used in tests. pub fn ca_bundle(mut self, ca: impl AsRef<Path>) -> Self { self.ca_bundle = Some(ca.as_ref().into()); self } /// Extra HTTP headers that should be sent with each request. pub fn headers<T, K, V>(mut self, headers: T) -> Self where T: IntoIterator<Item = (K, V)>, K: ToString, V: ToString, { let headers = headers .into_iter() .map(|(k, v)| (k.to_string(), v.to_string())); self.headers.extend(headers); self } /// Add an extra HTTP header that should be sent with each request. pub fn header(mut self, name: impl ToString, value: impl ToString) -> Self { self.headers.insert(name.to_string(), value.to_string()); self } /// Maximum number of keys per file request. Larger requests will be /// split up into concurrently-sent batches. pub fn max_files(mut self, size: Option<usize>) -> Self { self.max_files = size; self } /// Maximum number of keys per tree request. Larger requests will be /// split up into concurrently-sent batches. pub fn max_trees(mut self, size: Option<usize>) -> Self { self.max_trees = size; self } /// Maximum number of keys per history request. Larger requests will be /// split up into concurrently-sent batches. pub fn max_history(mut self, size: Option<usize>) -> Self { self.max_history = size; self } /// Maximum number of locations per location to has request. Larger requests will be split up /// into concurrently-sent batches. pub fn max_location_to_hash(mut self, size: Option<usize>) -> Self { self.max_location_to_hash = size; self } /// Timeout for HTTP requests sent by the client. pub fn timeout(mut self, timeout: Duration) -> Self { self.timeout = Some(timeout); self } /// Unique identifier that will be logged by both the client and server for /// every request, allowing log entries on both sides to be correlated. Also /// allows correlating multiple requests that were made by the same instance /// of the client. pub fn correlator(mut self, correlator: Option<impl ToString>) -> Self { self.correlator = correlator.map(|s| s.to_string()); self } /// Set the HTTP version that the client should use. pub fn http_version(mut self, version: HttpVersion) -> Self { self.http_version = Some(version); self } /// Specify whether the client should validate the user's client certificate /// before each request. pub fn validate_certs(mut self, validate_certs: bool) -> Self { self.validate_certs = validate_certs; self } /// If specified, the client will write a JSON version of every request /// it sends to the specified directory. This is primarily useful for /// debugging. The JSON requests can be sent with the `edenapi_cli`, or /// converted to CBOR with the `make_req` tool and sent with `curl`. pub fn log_dir(mut self, dir: impl AsRef<Path>) -> Self { self.log_dir = Some(dir.as_ref().into()); self } } /// Configuration for a `Client`. Essentially has the same fields as a /// `Builder`, but required fields are not optional and values have been /// appropriately parsed and validated. #[derive(Debug)] pub(crate) struct Config { pub(crate) server_url: Url, pub(crate) cert: Option<PathBuf>, pub(crate) key: Option<PathBuf>, pub(crate) ca_bundle: Option<PathBuf>, pub(crate) headers: HashMap<String, String>, pub(crate) max_files: Option<usize>, pub(crate) max_trees: Option<usize>, pub(crate) max_history: Option<usize>, pub(crate) max_location_to_hash: Option<usize>, pub(crate) timeout: Option<Duration>, pub(crate) debug: bool, pub(crate) correlator: Option<String>, pub(crate) http_version: Option<HttpVersion>, pub(crate) validate_certs: bool, pub(crate) log_dir: Option<PathBuf>, } impl TryFrom<Builder> for Config { type Error = EdenApiError; fn try_from(builder: Builder) -> Result<Self, Self::Error> { let Builder { server_url, cert, key, ca_bundle, headers, max_files, max_trees, max_history, max_location_to_hash, timeout, debug, correlator, http_version, validate_certs, log_dir, } = builder; // Check for missing required fields. let mut server_url = server_url.ok_or(ConfigError::MissingUrl)?; // Ensure the base URL's path ends with a slash so that `Url::join` // won't strip the final path component. if!server_url.path().ends_with('/') { let path = format!("{}/", server_url.path()); server_url.set_path(&path); } // Setting these to 0 is the same as None. let max_files = max_files.filter(|n| *n > 0); let max_trees = max_trees.filter(|n| *n > 0); let max_history = max_history.filter(|n| *n > 0); Ok(Config { server_url, cert, key, ca_bundle, headers, max_files, max_trees, max_history, max_location_to_hash, timeout, debug, correlator, http_version, validate_certs, log_dir, }) } } /// Parse headers from a JSON object. fn parse_headers(headers: impl AsRef<str>) -> Result<HashMap<String, String>, Error> { Ok(serde_json::from_str(headers.as_ref()) .context(format!("Not a valid JSON object: {:?}", headers.as_ref()))?) }
/// The corresponding private key may either be provided in the same file /// as the certificate, or separately using the `key` method. pub fn cert(mut self, cert: impl AsRef<Path>) -> Self { self.cert = Some(cert.as_ref().into());
random_line_split
builder.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::Duration; use anyhow::{Context, Error}; use url::Url; use anyhow::anyhow; use auth::AuthSection; use configparser::config::ConfigSet; use http_client::HttpVersion; use crate::client::Client; use crate::errors::{ConfigError, EdenApiError}; /// Builder for creating new EdenAPI clients. #[derive(Debug, Default)] pub struct Builder { server_url: Option<Url>, cert: Option<PathBuf>, key: Option<PathBuf>, ca_bundle: Option<PathBuf>, headers: HashMap<String, String>, max_files: Option<usize>, max_trees: Option<usize>, max_history: Option<usize>, max_location_to_hash: Option<usize>, timeout: Option<Duration>, debug: bool, correlator: Option<String>, http_version: Option<HttpVersion>, validate_certs: bool, log_dir: Option<PathBuf>, } impl Builder { pub fn new() -> Self { Default::default() } /// Build the client. pub fn build(self) -> Result<Client, EdenApiError> { self.try_into().map(Client::with_config) } /// Populate a `Builder` from a Mercurial configuration. pub fn from_config(config: &ConfigSet) -> Result<Self, EdenApiError> { let server_url = config .get_opt::<String>("edenapi", "url") .map_err(|e| ConfigError::Malformed("edenapi.url".into(), e))? .ok_or(ConfigError::MissingUrl)? .parse::<Url>() .map_err(ConfigError::InvalidUrl)?; let validate_certs = config .get_opt::<bool>("edenapi", "validate-certs") .map_err(|e| ConfigError::Malformed("edenapi.validate-certs".into(), e))? .unwrap_or_default(); let (cert, key, ca_bundle) = AuthSection::from_config(&config) .validate(validate_certs) .best_match_for(&server_url)? .map(|auth| (auth.cert, auth.key, auth.cacerts)) .unwrap_or_default(); let headers = config .get_opt::<String>("edenapi", "headers") .map_err(|e| ConfigError::Malformed("edenapi.headers".into(), e))? .map(parse_headers) .transpose() .map_err(|e| ConfigError::Malformed("edenapi.headers".into(), e))? .unwrap_or_default(); let max_files = config .get_opt("edenapi", "maxfiles") .map_err(|e| ConfigError::Malformed("edenapi.maxfiles".into(), e))?; let max_trees = config .get_opt("edenapi", "maxtrees") .map_err(|e| ConfigError::Malformed("edenapi.maxtrees".into(), e))?; let max_history = config .get_opt("edenapi", "maxhistory") .map_err(|e| ConfigError::Malformed("edenapi.maxhistory".into(), e))?; let max_location_to_hash = config .get_opt("edenapi", "maxlocationtohash") .map_err(|e| ConfigError::Malformed("edenapi.maxlocationtohash".into(), e))?; let timeout = config .get_opt("edenapi", "timeout") .map_err(|e| ConfigError::Malformed("edenapi.timeout".into(), e))? .map(Duration::from_secs); let debug = config .get_opt("edenapi", "debug") .map_err(|e| ConfigError::Malformed("edenapi.timeout".into(), e))? .unwrap_or_default(); let http_version = config .get_opt("edenapi", "http-version") .map_err(|e| ConfigError::Malformed("edenapi.http-version".into(), e))? .unwrap_or_else(|| "2".to_string()); let http_version = Some(match http_version.as_str() { "1.1" => HttpVersion::V11, "2" => HttpVersion::V2, x => { return Err(EdenApiError::BadConfig(ConfigError::Malformed( "edenapi.http-version".into(), anyhow!("invalid http version {}", x), ))); } }); let log_dir = config .get_opt::<PathBuf>("edenapi", "logdir") .map_err(|e| ConfigError::Malformed("edenapi.logdir".into(), e))?; Ok(Self { server_url: Some(server_url), cert, key, ca_bundle, headers, max_files, max_trees, max_history, max_location_to_hash, timeout, debug, correlator: None, http_version, validate_certs, log_dir, }) } /// Set the server URL. pub fn server_url(mut self, url: Url) -> Self { self.server_url = Some(url); self } /// Specify a client certificate for authenticating with the server. /// The caller should provide a path to PEM-encoded X.509 certificate file. /// The corresponding private key may either be provided in the same file /// as the certificate, or separately using the `key` method. pub fn cert(mut self, cert: impl AsRef<Path>) -> Self { self.cert = Some(cert.as_ref().into()); self } /// Specify the client's private key pub fn key(mut self, key: impl AsRef<Path>) -> Self { self.key = Some(key.as_ref().into()); self } /// Specify a CA certificate bundle to be used to validate the server's /// TLS certificate in place of the default system certificate bundle. /// Primarily used in tests. pub fn ca_bundle(mut self, ca: impl AsRef<Path>) -> Self { self.ca_bundle = Some(ca.as_ref().into()); self } /// Extra HTTP headers that should be sent with each request. pub fn headers<T, K, V>(mut self, headers: T) -> Self where T: IntoIterator<Item = (K, V)>, K: ToString, V: ToString, { let headers = headers .into_iter() .map(|(k, v)| (k.to_string(), v.to_string())); self.headers.extend(headers); self } /// Add an extra HTTP header that should be sent with each request. pub fn header(mut self, name: impl ToString, value: impl ToString) -> Self { self.headers.insert(name.to_string(), value.to_string()); self } /// Maximum number of keys per file request. Larger requests will be /// split up into concurrently-sent batches. pub fn max_files(mut self, size: Option<usize>) -> Self { self.max_files = size; self } /// Maximum number of keys per tree request. Larger requests will be /// split up into concurrently-sent batches. pub fn max_trees(mut self, size: Option<usize>) -> Self
/// Maximum number of keys per history request. Larger requests will be /// split up into concurrently-sent batches. pub fn max_history(mut self, size: Option<usize>) -> Self { self.max_history = size; self } /// Maximum number of locations per location to has request. Larger requests will be split up /// into concurrently-sent batches. pub fn max_location_to_hash(mut self, size: Option<usize>) -> Self { self.max_location_to_hash = size; self } /// Timeout for HTTP requests sent by the client. pub fn timeout(mut self, timeout: Duration) -> Self { self.timeout = Some(timeout); self } /// Unique identifier that will be logged by both the client and server for /// every request, allowing log entries on both sides to be correlated. Also /// allows correlating multiple requests that were made by the same instance /// of the client. pub fn correlator(mut self, correlator: Option<impl ToString>) -> Self { self.correlator = correlator.map(|s| s.to_string()); self } /// Set the HTTP version that the client should use. pub fn http_version(mut self, version: HttpVersion) -> Self { self.http_version = Some(version); self } /// Specify whether the client should validate the user's client certificate /// before each request. pub fn validate_certs(mut self, validate_certs: bool) -> Self { self.validate_certs = validate_certs; self } /// If specified, the client will write a JSON version of every request /// it sends to the specified directory. This is primarily useful for /// debugging. The JSON requests can be sent with the `edenapi_cli`, or /// converted to CBOR with the `make_req` tool and sent with `curl`. pub fn log_dir(mut self, dir: impl AsRef<Path>) -> Self { self.log_dir = Some(dir.as_ref().into()); self } } /// Configuration for a `Client`. Essentially has the same fields as a /// `Builder`, but required fields are not optional and values have been /// appropriately parsed and validated. #[derive(Debug)] pub(crate) struct Config { pub(crate) server_url: Url, pub(crate) cert: Option<PathBuf>, pub(crate) key: Option<PathBuf>, pub(crate) ca_bundle: Option<PathBuf>, pub(crate) headers: HashMap<String, String>, pub(crate) max_files: Option<usize>, pub(crate) max_trees: Option<usize>, pub(crate) max_history: Option<usize>, pub(crate) max_location_to_hash: Option<usize>, pub(crate) timeout: Option<Duration>, pub(crate) debug: bool, pub(crate) correlator: Option<String>, pub(crate) http_version: Option<HttpVersion>, pub(crate) validate_certs: bool, pub(crate) log_dir: Option<PathBuf>, } impl TryFrom<Builder> for Config { type Error = EdenApiError; fn try_from(builder: Builder) -> Result<Self, Self::Error> { let Builder { server_url, cert, key, ca_bundle, headers, max_files, max_trees, max_history, max_location_to_hash, timeout, debug, correlator, http_version, validate_certs, log_dir, } = builder; // Check for missing required fields. let mut server_url = server_url.ok_or(ConfigError::MissingUrl)?; // Ensure the base URL's path ends with a slash so that `Url::join` // won't strip the final path component. if!server_url.path().ends_with('/') { let path = format!("{}/", server_url.path()); server_url.set_path(&path); } // Setting these to 0 is the same as None. let max_files = max_files.filter(|n| *n > 0); let max_trees = max_trees.filter(|n| *n > 0); let max_history = max_history.filter(|n| *n > 0); Ok(Config { server_url, cert, key, ca_bundle, headers, max_files, max_trees, max_history, max_location_to_hash, timeout, debug, correlator, http_version, validate_certs, log_dir, }) } } /// Parse headers from a JSON object. fn parse_headers(headers: impl AsRef<str>) -> Result<HashMap<String, String>, Error> { Ok(serde_json::from_str(headers.as_ref()) .context(format!("Not a valid JSON object: {:?}", headers.as_ref()))?) }
{ self.max_trees = size; self }
identifier_body
documentfragment.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::DocumentFragmentBinding; use crate::dom::bindings::codegen::Bindings::DocumentFragmentBinding::DocumentFragmentMethods; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::codegen::UnionTypes::NodeOrString; use crate::dom::bindings::error::{ErrorResult, Fallible}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::htmlcollection::HTMLCollection; use crate::dom::node::{window_from_node, Node}; use crate::dom::nodelist::NodeList; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; use std::collections::HashMap; // https://dom.spec.whatwg.org/#documentfragment #[dom_struct] pub struct DocumentFragment { node: Node, /// Caches for the getElement methods id_map: DomRefCell<HashMap<Atom, Vec<Dom<Element>>>>, } impl DocumentFragment { /// Creates a new DocumentFragment. pub fn new_inherited(document: &Document) -> DocumentFragment { DocumentFragment { node: Node::new_inherited(document), id_map: DomRefCell::new(HashMap::new()), } } pub fn new(document: &Document) -> DomRoot<DocumentFragment> { Node::reflect_node( Box::new(DocumentFragment::new_inherited(document)), document, DocumentFragmentBinding::Wrap, ) } #[allow(non_snake_case)] pub fn Constructor(window: &Window) -> Fallible<DomRoot<DocumentFragment>> { let document = window.Document(); Ok(DocumentFragment::new(&document)) } pub fn id_map(&self) -> &DomRefCell<HashMap<Atom, Vec<Dom<Element>>>> { &self.id_map } } impl DocumentFragmentMethods for DocumentFragment { // https://dom.spec.whatwg.org/#dom-parentnode-children fn Children(&self) -> DomRoot<HTMLCollection> { let window = window_from_node(self); HTMLCollection::children(&window, self.upcast()) } // https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid fn GetElementById(&self, id: DOMString) -> Option<DomRoot<Element>> { let id = Atom::from(id); self.id_map .borrow() .get(&id) .map(|ref elements| DomRoot::from_ref(&*(*elements)[0])) } // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild fn GetFirstElementChild(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>().child_elements().next() } // https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild fn GetLastElementChild(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>() .rev_children() .filter_map(DomRoot::downcast::<Element>) .next() } // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount fn ChildElementCount(&self) -> u32 { self.upcast::<Node>().child_elements().count() as u32 } // https://dom.spec.whatwg.org/#dom-parentnode-prepend fn Prepend(&self, nodes: Vec<NodeOrString>) -> ErrorResult
// https://dom.spec.whatwg.org/#dom-parentnode-append fn Append(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().append(nodes) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselector fn QuerySelector(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> { self.upcast::<Node>().query_selector(selectors) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible<DomRoot<NodeList>> { self.upcast::<Node>().query_selector_all(selectors) } }
{ self.upcast::<Node>().prepend(nodes) }
identifier_body
documentfragment.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::DocumentFragmentBinding; use crate::dom::bindings::codegen::Bindings::DocumentFragmentBinding::DocumentFragmentMethods; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::codegen::UnionTypes::NodeOrString; use crate::dom::bindings::error::{ErrorResult, Fallible}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::htmlcollection::HTMLCollection; use crate::dom::node::{window_from_node, Node}; use crate::dom::nodelist::NodeList; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; use std::collections::HashMap; // https://dom.spec.whatwg.org/#documentfragment #[dom_struct] pub struct DocumentFragment { node: Node, /// Caches for the getElement methods id_map: DomRefCell<HashMap<Atom, Vec<Dom<Element>>>>, } impl DocumentFragment { /// Creates a new DocumentFragment. pub fn new_inherited(document: &Document) -> DocumentFragment { DocumentFragment { node: Node::new_inherited(document), id_map: DomRefCell::new(HashMap::new()), } } pub fn new(document: &Document) -> DomRoot<DocumentFragment> { Node::reflect_node( Box::new(DocumentFragment::new_inherited(document)), document, DocumentFragmentBinding::Wrap, ) } #[allow(non_snake_case)] pub fn Constructor(window: &Window) -> Fallible<DomRoot<DocumentFragment>> { let document = window.Document(); Ok(DocumentFragment::new(&document)) } pub fn id_map(&self) -> &DomRefCell<HashMap<Atom, Vec<Dom<Element>>>> { &self.id_map } } impl DocumentFragmentMethods for DocumentFragment { // https://dom.spec.whatwg.org/#dom-parentnode-children fn Children(&self) -> DomRoot<HTMLCollection> { let window = window_from_node(self); HTMLCollection::children(&window, self.upcast()) } // https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid fn GetElementById(&self, id: DOMString) -> Option<DomRoot<Element>> { let id = Atom::from(id); self.id_map .borrow() .get(&id) .map(|ref elements| DomRoot::from_ref(&*(*elements)[0])) } // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild fn GetFirstElementChild(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>().child_elements().next() } // https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild fn GetLastElementChild(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>() .rev_children() .filter_map(DomRoot::downcast::<Element>) .next() } // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount fn ChildElementCount(&self) -> u32 { self.upcast::<Node>().child_elements().count() as u32 } // https://dom.spec.whatwg.org/#dom-parentnode-prepend fn Prepend(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().prepend(nodes) } // https://dom.spec.whatwg.org/#dom-parentnode-append fn Append(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().append(nodes) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselector fn QuerySelector(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> { self.upcast::<Node>().query_selector(selectors) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible<DomRoot<NodeList>> { self.upcast::<Node>().query_selector_all(selectors)
} }
random_line_split
documentfragment.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::DocumentFragmentBinding; use crate::dom::bindings::codegen::Bindings::DocumentFragmentBinding::DocumentFragmentMethods; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::codegen::UnionTypes::NodeOrString; use crate::dom::bindings::error::{ErrorResult, Fallible}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::htmlcollection::HTMLCollection; use crate::dom::node::{window_from_node, Node}; use crate::dom::nodelist::NodeList; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; use std::collections::HashMap; // https://dom.spec.whatwg.org/#documentfragment #[dom_struct] pub struct DocumentFragment { node: Node, /// Caches for the getElement methods id_map: DomRefCell<HashMap<Atom, Vec<Dom<Element>>>>, } impl DocumentFragment { /// Creates a new DocumentFragment. pub fn new_inherited(document: &Document) -> DocumentFragment { DocumentFragment { node: Node::new_inherited(document), id_map: DomRefCell::new(HashMap::new()), } } pub fn new(document: &Document) -> DomRoot<DocumentFragment> { Node::reflect_node( Box::new(DocumentFragment::new_inherited(document)), document, DocumentFragmentBinding::Wrap, ) } #[allow(non_snake_case)] pub fn Constructor(window: &Window) -> Fallible<DomRoot<DocumentFragment>> { let document = window.Document(); Ok(DocumentFragment::new(&document)) } pub fn id_map(&self) -> &DomRefCell<HashMap<Atom, Vec<Dom<Element>>>> { &self.id_map } } impl DocumentFragmentMethods for DocumentFragment { // https://dom.spec.whatwg.org/#dom-parentnode-children fn Children(&self) -> DomRoot<HTMLCollection> { let window = window_from_node(self); HTMLCollection::children(&window, self.upcast()) } // https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid fn GetElementById(&self, id: DOMString) -> Option<DomRoot<Element>> { let id = Atom::from(id); self.id_map .borrow() .get(&id) .map(|ref elements| DomRoot::from_ref(&*(*elements)[0])) } // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild fn GetFirstElementChild(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>().child_elements().next() } // https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild fn GetLastElementChild(&self) -> Option<DomRoot<Element>> { self.upcast::<Node>() .rev_children() .filter_map(DomRoot::downcast::<Element>) .next() } // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount fn ChildElementCount(&self) -> u32 { self.upcast::<Node>().child_elements().count() as u32 } // https://dom.spec.whatwg.org/#dom-parentnode-prepend fn Prepend(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().prepend(nodes) } // https://dom.spec.whatwg.org/#dom-parentnode-append fn Append(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().append(nodes) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselector fn QuerySelector(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> { self.upcast::<Node>().query_selector(selectors) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall fn
(&self, selectors: DOMString) -> Fallible<DomRoot<NodeList>> { self.upcast::<Node>().query_selector_all(selectors) } }
QuerySelectorAll
identifier_name
maybe_owned_vec.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::collections::Collection; use std::default::Default; use std::fmt; use std::iter::FromIterator; use std::path::BytesContainer; use std::slice; // Note 1: It is not clear whether the flexibility of providing both // the `Growable` and `FixedLen` variants is sufficiently useful. // Consider restricting to just a two variant enum. // Note 2: Once Dynamically Sized Types (DST) lands, it might be // reasonable to replace this with something like `enum MaybeOwned<'a, // Sized? U>{ Owned(Box<U>), Borrowed(&'a U) }`; and then `U` could be // instantiated with `[T]` or `str`, etc. Of course, that would imply // removing the `Growable` variant, which relates to note 1 above. // Alternatively, we might add `MaybeOwned` for the general case but // keep some form of `MaybeOwnedVector` to avoid unnecessary copying // of the contents of `Vec<T>`, since we anticipate that to be a // frequent way to dynamically construct a vector. /// MaybeOwnedVector<'a,T> abstracts over `Vec<T>`, `&'a [T]`. /// /// Some clients will have a pre-allocated vector ready to hand off in /// a slice; others will want to create the set on the fly and hand /// off ownership, via `Growable`. pub enum MaybeOwnedVector<'a,T> { Growable(Vec<T>), Borrowed(&'a [T]), } /// Trait for moving into a `MaybeOwnedVector` pub trait IntoMaybeOwnedVector<'a,T> { /// Moves self into a `MaybeOwnedVector` fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T>; } impl<'a,T> IntoMaybeOwnedVector<'a,T> for Vec<T> { #[inline] fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Growable(self) } } impl<'a,T> IntoMaybeOwnedVector<'a,T> for &'a [T] { #[inline] fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Borrowed(self) } } impl<'a,T> MaybeOwnedVector<'a,T> { pub fn iter(&'a self) -> slice::Items<'a,T> { match self { &Growable(ref v) => v.iter(), &Borrowed(ref v) => v.iter(), } } } impl<'a, T: PartialEq> PartialEq for MaybeOwnedVector<'a, T> { fn eq(&self, other: &MaybeOwnedVector<T>) -> bool { self.as_slice() == other.as_slice() } } impl<'a, T: Eq> Eq for MaybeOwnedVector<'a, T> {} impl<'a, T: PartialOrd> PartialOrd for MaybeOwnedVector<'a, T> { fn partial_cmp(&self, other: &MaybeOwnedVector<T>) -> Option<Ordering> { self.as_slice().partial_cmp(&other.as_slice()) } } impl<'a, T: Ord> Ord for MaybeOwnedVector<'a, T> { fn cmp(&self, other: &MaybeOwnedVector<T>) -> Ordering { self.as_slice().cmp(&other.as_slice()) } } impl<'a, T: PartialEq, V: Vector<T>> Equiv<V> for MaybeOwnedVector<'a, T> { fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() } } // The `Vector` trait is provided in the prelude and is implemented on // both `&'a [T]` and `Vec<T>`, so it makes sense to try to support it // seamlessly. The other vector related traits from the prelude do // not appear to be implemented on both `&'a [T]` and `Vec<T>`. (It // is possible that this is an oversight in some cases.) // // In any case, with `Vector` in place, the client can just use // `as_slice` if they prefer that over `match`. impl<'b,T> slice::Vector<T> for MaybeOwnedVector<'b,T> { fn as_slice<'a>(&'a self) -> &'a [T] { match self { &Growable(ref v) => v.as_slice(), &Borrowed(ref v) => v.as_slice(), } } } impl<'a,T> FromIterator<T> for MaybeOwnedVector<'a,T> { fn from_iter<I:Iterator<T>>(iterator: I) -> MaybeOwnedVector<'a,T> { // If we are building from scratch, might as well build the // most flexible variant. Growable(FromIterator::from_iter(iterator)) } } impl<'a,T:fmt::Show> fmt::Show for MaybeOwnedVector<'a,T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.as_slice().fmt(f) } } impl<'a,T:Clone> CloneableVector<T> for MaybeOwnedVector<'a,T> { /// Returns a copy of `self`. fn to_vec(&self) -> Vec<T> { self.as_slice().to_vec() } /// Convert `self` into an owned slice, not making a copy if possible. fn into_vec(self) -> Vec<T>
} impl<'a, T: Clone> Clone for MaybeOwnedVector<'a, T> { fn clone(&self) -> MaybeOwnedVector<'a, T> { match *self { Growable(ref v) => Growable(v.to_vec()), Borrowed(v) => Borrowed(v) } } } impl<'a, T> Default for MaybeOwnedVector<'a, T> { fn default() -> MaybeOwnedVector<'a, T> { Growable(Vec::new()) } } impl<'a, T> Collection for MaybeOwnedVector<'a, T> { fn len(&self) -> uint { self.as_slice().len() } } impl<'a> BytesContainer for MaybeOwnedVector<'a, u8> { fn container_as_bytes<'a>(&'a self) -> &'a [u8] { self.as_slice() } } impl<'a,T:Clone> MaybeOwnedVector<'a,T> { /// Convert `self` into a growable `Vec`, not making a copy if possible. pub fn into_vec(self) -> Vec<T> { match self { Growable(v) => v, Borrowed(v) => Vec::from_slice(v), } } }
{ match self { Growable(v) => v.as_slice().to_vec(), Borrowed(v) => v.to_vec(), } }
identifier_body
maybe_owned_vec.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::collections::Collection; use std::default::Default; use std::fmt; use std::iter::FromIterator; use std::path::BytesContainer; use std::slice; // Note 1: It is not clear whether the flexibility of providing both // the `Growable` and `FixedLen` variants is sufficiently useful. // Consider restricting to just a two variant enum. // Note 2: Once Dynamically Sized Types (DST) lands, it might be // reasonable to replace this with something like `enum MaybeOwned<'a, // Sized? U>{ Owned(Box<U>), Borrowed(&'a U) }`; and then `U` could be // instantiated with `[T]` or `str`, etc. Of course, that would imply // removing the `Growable` variant, which relates to note 1 above. // Alternatively, we might add `MaybeOwned` for the general case but // keep some form of `MaybeOwnedVector` to avoid unnecessary copying // of the contents of `Vec<T>`, since we anticipate that to be a // frequent way to dynamically construct a vector. /// MaybeOwnedVector<'a,T> abstracts over `Vec<T>`, `&'a [T]`. /// /// Some clients will have a pre-allocated vector ready to hand off in /// a slice; others will want to create the set on the fly and hand /// off ownership, via `Growable`. pub enum MaybeOwnedVector<'a,T> { Growable(Vec<T>), Borrowed(&'a [T]), } /// Trait for moving into a `MaybeOwnedVector` pub trait IntoMaybeOwnedVector<'a,T> { /// Moves self into a `MaybeOwnedVector` fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T>; } impl<'a,T> IntoMaybeOwnedVector<'a,T> for Vec<T> { #[inline] fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Growable(self) } } impl<'a,T> IntoMaybeOwnedVector<'a,T> for &'a [T] { #[inline] fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Borrowed(self) } } impl<'a,T> MaybeOwnedVector<'a,T> { pub fn iter(&'a self) -> slice::Items<'a,T> { match self { &Growable(ref v) => v.iter(), &Borrowed(ref v) => v.iter(), } } } impl<'a, T: PartialEq> PartialEq for MaybeOwnedVector<'a, T> { fn eq(&self, other: &MaybeOwnedVector<T>) -> bool { self.as_slice() == other.as_slice() } } impl<'a, T: Eq> Eq for MaybeOwnedVector<'a, T> {} impl<'a, T: PartialOrd> PartialOrd for MaybeOwnedVector<'a, T> { fn partial_cmp(&self, other: &MaybeOwnedVector<T>) -> Option<Ordering> { self.as_slice().partial_cmp(&other.as_slice()) } } impl<'a, T: Ord> Ord for MaybeOwnedVector<'a, T> { fn cmp(&self, other: &MaybeOwnedVector<T>) -> Ordering { self.as_slice().cmp(&other.as_slice()) } } impl<'a, T: PartialEq, V: Vector<T>> Equiv<V> for MaybeOwnedVector<'a, T> { fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() } } // The `Vector` trait is provided in the prelude and is implemented on // both `&'a [T]` and `Vec<T>`, so it makes sense to try to support it // seamlessly. The other vector related traits from the prelude do // not appear to be implemented on both `&'a [T]` and `Vec<T>`. (It // is possible that this is an oversight in some cases.) // // In any case, with `Vector` in place, the client can just use // `as_slice` if they prefer that over `match`. impl<'b,T> slice::Vector<T> for MaybeOwnedVector<'b,T> { fn as_slice<'a>(&'a self) -> &'a [T] { match self { &Growable(ref v) => v.as_slice(), &Borrowed(ref v) => v.as_slice(), } } } impl<'a,T> FromIterator<T> for MaybeOwnedVector<'a,T> { fn from_iter<I:Iterator<T>>(iterator: I) -> MaybeOwnedVector<'a,T> { // If we are building from scratch, might as well build the // most flexible variant. Growable(FromIterator::from_iter(iterator)) } } impl<'a,T:fmt::Show> fmt::Show for MaybeOwnedVector<'a,T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.as_slice().fmt(f) } } impl<'a,T:Clone> CloneableVector<T> for MaybeOwnedVector<'a,T> { /// Returns a copy of `self`. fn to_vec(&self) -> Vec<T> { self.as_slice().to_vec() } /// Convert `self` into an owned slice, not making a copy if possible. fn into_vec(self) -> Vec<T> { match self { Growable(v) => v.as_slice().to_vec(), Borrowed(v) => v.to_vec(), } } } impl<'a, T: Clone> Clone for MaybeOwnedVector<'a, T> {
} } impl<'a, T> Default for MaybeOwnedVector<'a, T> { fn default() -> MaybeOwnedVector<'a, T> { Growable(Vec::new()) } } impl<'a, T> Collection for MaybeOwnedVector<'a, T> { fn len(&self) -> uint { self.as_slice().len() } } impl<'a> BytesContainer for MaybeOwnedVector<'a, u8> { fn container_as_bytes<'a>(&'a self) -> &'a [u8] { self.as_slice() } } impl<'a,T:Clone> MaybeOwnedVector<'a,T> { /// Convert `self` into a growable `Vec`, not making a copy if possible. pub fn into_vec(self) -> Vec<T> { match self { Growable(v) => v, Borrowed(v) => Vec::from_slice(v), } } }
fn clone(&self) -> MaybeOwnedVector<'a, T> { match *self { Growable(ref v) => Growable(v.to_vec()), Borrowed(v) => Borrowed(v) }
random_line_split
maybe_owned_vec.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::collections::Collection; use std::default::Default; use std::fmt; use std::iter::FromIterator; use std::path::BytesContainer; use std::slice; // Note 1: It is not clear whether the flexibility of providing both // the `Growable` and `FixedLen` variants is sufficiently useful. // Consider restricting to just a two variant enum. // Note 2: Once Dynamically Sized Types (DST) lands, it might be // reasonable to replace this with something like `enum MaybeOwned<'a, // Sized? U>{ Owned(Box<U>), Borrowed(&'a U) }`; and then `U` could be // instantiated with `[T]` or `str`, etc. Of course, that would imply // removing the `Growable` variant, which relates to note 1 above. // Alternatively, we might add `MaybeOwned` for the general case but // keep some form of `MaybeOwnedVector` to avoid unnecessary copying // of the contents of `Vec<T>`, since we anticipate that to be a // frequent way to dynamically construct a vector. /// MaybeOwnedVector<'a,T> abstracts over `Vec<T>`, `&'a [T]`. /// /// Some clients will have a pre-allocated vector ready to hand off in /// a slice; others will want to create the set on the fly and hand /// off ownership, via `Growable`. pub enum MaybeOwnedVector<'a,T> { Growable(Vec<T>), Borrowed(&'a [T]), } /// Trait for moving into a `MaybeOwnedVector` pub trait IntoMaybeOwnedVector<'a,T> { /// Moves self into a `MaybeOwnedVector` fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T>; } impl<'a,T> IntoMaybeOwnedVector<'a,T> for Vec<T> { #[inline] fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Growable(self) } } impl<'a,T> IntoMaybeOwnedVector<'a,T> for &'a [T] { #[inline] fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Borrowed(self) } } impl<'a,T> MaybeOwnedVector<'a,T> { pub fn iter(&'a self) -> slice::Items<'a,T> { match self { &Growable(ref v) => v.iter(), &Borrowed(ref v) => v.iter(), } } } impl<'a, T: PartialEq> PartialEq for MaybeOwnedVector<'a, T> { fn eq(&self, other: &MaybeOwnedVector<T>) -> bool { self.as_slice() == other.as_slice() } } impl<'a, T: Eq> Eq for MaybeOwnedVector<'a, T> {} impl<'a, T: PartialOrd> PartialOrd for MaybeOwnedVector<'a, T> { fn partial_cmp(&self, other: &MaybeOwnedVector<T>) -> Option<Ordering> { self.as_slice().partial_cmp(&other.as_slice()) } } impl<'a, T: Ord> Ord for MaybeOwnedVector<'a, T> { fn cmp(&self, other: &MaybeOwnedVector<T>) -> Ordering { self.as_slice().cmp(&other.as_slice()) } } impl<'a, T: PartialEq, V: Vector<T>> Equiv<V> for MaybeOwnedVector<'a, T> { fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() } } // The `Vector` trait is provided in the prelude and is implemented on // both `&'a [T]` and `Vec<T>`, so it makes sense to try to support it // seamlessly. The other vector related traits from the prelude do // not appear to be implemented on both `&'a [T]` and `Vec<T>`. (It // is possible that this is an oversight in some cases.) // // In any case, with `Vector` in place, the client can just use // `as_slice` if they prefer that over `match`. impl<'b,T> slice::Vector<T> for MaybeOwnedVector<'b,T> { fn as_slice<'a>(&'a self) -> &'a [T] { match self { &Growable(ref v) => v.as_slice(), &Borrowed(ref v) => v.as_slice(), } } } impl<'a,T> FromIterator<T> for MaybeOwnedVector<'a,T> { fn
<I:Iterator<T>>(iterator: I) -> MaybeOwnedVector<'a,T> { // If we are building from scratch, might as well build the // most flexible variant. Growable(FromIterator::from_iter(iterator)) } } impl<'a,T:fmt::Show> fmt::Show for MaybeOwnedVector<'a,T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.as_slice().fmt(f) } } impl<'a,T:Clone> CloneableVector<T> for MaybeOwnedVector<'a,T> { /// Returns a copy of `self`. fn to_vec(&self) -> Vec<T> { self.as_slice().to_vec() } /// Convert `self` into an owned slice, not making a copy if possible. fn into_vec(self) -> Vec<T> { match self { Growable(v) => v.as_slice().to_vec(), Borrowed(v) => v.to_vec(), } } } impl<'a, T: Clone> Clone for MaybeOwnedVector<'a, T> { fn clone(&self) -> MaybeOwnedVector<'a, T> { match *self { Growable(ref v) => Growable(v.to_vec()), Borrowed(v) => Borrowed(v) } } } impl<'a, T> Default for MaybeOwnedVector<'a, T> { fn default() -> MaybeOwnedVector<'a, T> { Growable(Vec::new()) } } impl<'a, T> Collection for MaybeOwnedVector<'a, T> { fn len(&self) -> uint { self.as_slice().len() } } impl<'a> BytesContainer for MaybeOwnedVector<'a, u8> { fn container_as_bytes<'a>(&'a self) -> &'a [u8] { self.as_slice() } } impl<'a,T:Clone> MaybeOwnedVector<'a,T> { /// Convert `self` into a growable `Vec`, not making a copy if possible. pub fn into_vec(self) -> Vec<T> { match self { Growable(v) => v, Borrowed(v) => Vec::from_slice(v), } } }
from_iter
identifier_name
lib.rs
use std::collections::HashMap; use std::path::Path; use std::fs::File; use std::error::Error; use std::io::BufReader; use std::io::prelude::*; pub mod actor; mod log_entry; mod http; mod hash_utils; mod nginx; pub fn
(logfile: &str) -> Result<HashMap<String, actor::Actor>, String> { let path = Path::new(logfile); let file_handle = match File::open(&path) { Err(why) => { return Err(format!("Could not open {} : {}", path.display(), Error::description(&why))); }, Ok(file) => file, }; let reader = BufReader::new(file_handle); let mut actors = HashMap::<String, actor::Actor>::new(); for line in reader.lines() { match line { Ok(line) => nginx::process(&mut actors, &line), Err(e) => return Err(format!("ERROR {}", e)), } } return Ok(actors); }
process
identifier_name
lib.rs
use std::collections::HashMap; use std::path::Path; use std::fs::File; use std::error::Error; use std::io::BufReader; use std::io::prelude::*;
mod hash_utils; mod nginx; pub fn process(logfile: &str) -> Result<HashMap<String, actor::Actor>, String> { let path = Path::new(logfile); let file_handle = match File::open(&path) { Err(why) => { return Err(format!("Could not open {} : {}", path.display(), Error::description(&why))); }, Ok(file) => file, }; let reader = BufReader::new(file_handle); let mut actors = HashMap::<String, actor::Actor>::new(); for line in reader.lines() { match line { Ok(line) => nginx::process(&mut actors, &line), Err(e) => return Err(format!("ERROR {}", e)), } } return Ok(actors); }
pub mod actor; mod log_entry; mod http;
random_line_split
lib.rs
use std::collections::HashMap; use std::path::Path; use std::fs::File; use std::error::Error; use std::io::BufReader; use std::io::prelude::*; pub mod actor; mod log_entry; mod http; mod hash_utils; mod nginx; pub fn process(logfile: &str) -> Result<HashMap<String, actor::Actor>, String>
{ let path = Path::new(logfile); let file_handle = match File::open(&path) { Err(why) => { return Err(format!("Could not open {} : {}", path.display(), Error::description(&why))); }, Ok(file) => file, }; let reader = BufReader::new(file_handle); let mut actors = HashMap::<String, actor::Actor>::new(); for line in reader.lines() { match line { Ok(line) => nginx::process(&mut actors, &line), Err(e) => return Err(format!("ERROR {}", e)), } } return Ok(actors); }
identifier_body
recent_chooser_dialog.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use std::ptr; use glib::translate::ToGlibPtr; use ffi; use FFIWidget; use DialogButtons; use cast::{GTK_WINDOW, GTK_RECENT_MANAGER}; struct_Widget!(RecentChooserDialog); impl RecentChooserDialog { pub fn new<T: DialogButtons>(title: &str, parent: Option<&::Window>, buttons: T) -> RecentChooserDialog
pub fn new_for_manager<T: DialogButtons>(title: &str, parent: Option<&::Window>, manager: &::RecentManager, buttons: T) -> RecentChooserDialog { let parent = match parent { Some(ref p) => GTK_WINDOW(p.unwrap_widget()), None => ptr::null_mut() }; unsafe { ::FFIWidget::wrap_widget( buttons.invoke3( ffi::gtk_recent_chooser_dialog_new_for_manager, title.to_glib_none().0, parent, GTK_RECENT_MANAGER(manager.unwrap_widget()))) } } } impl_drop!(RecentChooserDialog); impl_TraitWidget!(RecentChooserDialog); impl ::ContainerTrait for RecentChooserDialog {} impl ::BinTrait for RecentChooserDialog {} impl ::WindowTrait for RecentChooserDialog {} impl ::DialogTrait for RecentChooserDialog {} impl ::RecentChooserTrait for RecentChooserDialog {}
{ let parent = match parent { Some(ref p) => GTK_WINDOW(p.unwrap_widget()), None => ptr::null_mut() }; unsafe { ::FFIWidget::wrap_widget( buttons.invoke2( ffi::gtk_recent_chooser_dialog_new, title.to_glib_none().0, parent)) } }
identifier_body
recent_chooser_dialog.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use std::ptr; use glib::translate::ToGlibPtr; use ffi; use FFIWidget; use DialogButtons; use cast::{GTK_WINDOW, GTK_RECENT_MANAGER}; struct_Widget!(RecentChooserDialog); impl RecentChooserDialog { pub fn
<T: DialogButtons>(title: &str, parent: Option<&::Window>, buttons: T) -> RecentChooserDialog { let parent = match parent { Some(ref p) => GTK_WINDOW(p.unwrap_widget()), None => ptr::null_mut() }; unsafe { ::FFIWidget::wrap_widget( buttons.invoke2( ffi::gtk_recent_chooser_dialog_new, title.to_glib_none().0, parent)) } } pub fn new_for_manager<T: DialogButtons>(title: &str, parent: Option<&::Window>, manager: &::RecentManager, buttons: T) -> RecentChooserDialog { let parent = match parent { Some(ref p) => GTK_WINDOW(p.unwrap_widget()), None => ptr::null_mut() }; unsafe { ::FFIWidget::wrap_widget( buttons.invoke3( ffi::gtk_recent_chooser_dialog_new_for_manager, title.to_glib_none().0, parent, GTK_RECENT_MANAGER(manager.unwrap_widget()))) } } } impl_drop!(RecentChooserDialog); impl_TraitWidget!(RecentChooserDialog); impl ::ContainerTrait for RecentChooserDialog {} impl ::BinTrait for RecentChooserDialog {} impl ::WindowTrait for RecentChooserDialog {} impl ::DialogTrait for RecentChooserDialog {} impl ::RecentChooserTrait for RecentChooserDialog {}
new
identifier_name
recent_chooser_dialog.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use std::ptr; use glib::translate::ToGlibPtr; use ffi; use FFIWidget;
struct_Widget!(RecentChooserDialog); impl RecentChooserDialog { pub fn new<T: DialogButtons>(title: &str, parent: Option<&::Window>, buttons: T) -> RecentChooserDialog { let parent = match parent { Some(ref p) => GTK_WINDOW(p.unwrap_widget()), None => ptr::null_mut() }; unsafe { ::FFIWidget::wrap_widget( buttons.invoke2( ffi::gtk_recent_chooser_dialog_new, title.to_glib_none().0, parent)) } } pub fn new_for_manager<T: DialogButtons>(title: &str, parent: Option<&::Window>, manager: &::RecentManager, buttons: T) -> RecentChooserDialog { let parent = match parent { Some(ref p) => GTK_WINDOW(p.unwrap_widget()), None => ptr::null_mut() }; unsafe { ::FFIWidget::wrap_widget( buttons.invoke3( ffi::gtk_recent_chooser_dialog_new_for_manager, title.to_glib_none().0, parent, GTK_RECENT_MANAGER(manager.unwrap_widget()))) } } } impl_drop!(RecentChooserDialog); impl_TraitWidget!(RecentChooserDialog); impl ::ContainerTrait for RecentChooserDialog {} impl ::BinTrait for RecentChooserDialog {} impl ::WindowTrait for RecentChooserDialog {} impl ::DialogTrait for RecentChooserDialog {} impl ::RecentChooserTrait for RecentChooserDialog {}
use DialogButtons; use cast::{GTK_WINDOW, GTK_RECENT_MANAGER};
random_line_split
fs.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::prelude::*; use io::prelude::*; use os::unix::prelude::*; use ffi::{CString, CStr, OsString, OsStr}; use fmt; use io::{self, Error, SeekFrom}; use libc::{self, c_int, size_t, off_t, c_char, mode_t}; use mem; use path::{Path, PathBuf}; use ptr; use sync::Arc; use sys::fd::FileDesc; use sys::platform::raw; use sys::{c, cvt, cvt_r}; use sys_common::{AsInner, FromInner}; use vec::Vec; pub struct File(FileDesc); pub struct FileAttr { stat: raw::stat, } pub struct ReadDir { dirp: Dir, root: Arc<PathBuf>, } struct Dir(*mut libc::DIR); unsafe impl Send for Dir {} unsafe impl Sync for Dir {} pub struct DirEntry { buf: Vec<u8>, // actually *mut libc::dirent_t root: Arc<PathBuf>, } #[derive(Clone)] pub struct OpenOptions { flags: c_int, read: bool, write: bool, mode: mode_t, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct FilePermissions { mode: mode_t } #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct FileType { mode: mode_t } pub struct DirBuilder { mode: mode_t } impl FileAttr { pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 } } pub fn accessed(&self) -> u64 { self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64) } pub fn modified(&self) -> u64 { self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64) } pub fn file_type(&self) -> FileType { FileType { mode: self.stat.st_mode as mode_t } } pub fn raw(&self) -> &raw::stat { &self.stat } // times are in milliseconds (currently) fn mktime(&self, secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 } } impl AsInner<raw::stat> for FileAttr { fn as_inner(&self) -> &raw::stat { &self.stat } } #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait MetadataExt { fn as_raw_stat(&self) -> &raw::stat; } impl MetadataExt for ::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { &self.as_inner().stat } } impl MetadataExt for ::os::unix::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { self.as_inner() } } impl FilePermissions { pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 } pub fn set_readonly(&mut self, readonly: bool) { if readonly { self.mode &=!0o222; } else { self.mode |= 0o222; } } pub fn mode(&self) -> raw::mode_t { self.mode } } impl FileType { pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) } pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) } pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) } fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode } } impl FromInner<raw::mode_t> for FilePermissions { fn from_inner(mode: raw::mode_t) -> FilePermissions { FilePermissions { mode: mode as mode_t } } } impl Iterator for ReadDir { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<io::Result<DirEntry>> { extern { fn rust_dirent_t_size() -> c_int; } let mut buf: Vec<u8> = Vec::with_capacity(unsafe { rust_dirent_t_size() as usize }); let ptr = buf.as_mut_ptr() as *mut libc::dirent_t; let mut entry_ptr = ptr::null_mut(); loop { if unsafe { libc::readdir_r(self.dirp.0, ptr, &mut entry_ptr)!= 0 } { return Some(Err(Error::last_os_error())) } if entry_ptr.is_null() { return None } let entry = DirEntry { buf: buf, root: self.root.clone() }; if entry.name_bytes() == b"." || entry.name_bytes() == b".." { buf = entry.buf; } else { return Some(Ok(entry)) } } } } impl Drop for Dir { fn drop(&mut self) { let r = unsafe { libc::closedir(self.0) }; debug_assert_eq!(r, 0); } } impl DirEntry { pub fn path(&self) -> PathBuf { self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes())) } pub fn file_name(&self) -> OsString { OsStr::from_bytes(self.name_bytes()).to_os_string() } pub fn metadata(&self) -> io::Result<FileAttr> { lstat(&self.path()) } pub fn file_type(&self) -> io::Result<FileType> { extern { fn rust_dir_get_mode(ptr: *mut libc::dirent_t) -> c_int; } unsafe { match rust_dir_get_mode(self.dirent()) { -1 => lstat(&self.path()).map(|m| m.file_type()), n => Ok(FileType { mode: n as mode_t }), } } } pub fn ino(&self) -> raw::ino_t { extern { fn rust_dir_get_ino(ptr: *mut libc::dirent_t) -> raw::ino_t; } unsafe { rust_dir_get_ino(self.dirent()) } } fn name_bytes(&self) -> &[u8] { extern { fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char; } unsafe { CStr::from_ptr(rust_list_dir_val(self.dirent())).to_bytes() } } fn dirent(&self) -> *mut libc::dirent_t { self.buf.as_ptr() as *mut _ } } impl OpenOptions { pub fn new() -> OpenOptions { OpenOptions { flags: 0, read: false, write: false, mode: 0o666, } } pub fn read(&mut self, read: bool) { self.read = read; } pub fn write(&mut self, write: bool) { self.write = write; } pub fn append(&mut self, append: bool) { self.flag(libc::O_APPEND, append); } pub fn truncate(&mut self, truncate: bool) { self.flag(libc::O_TRUNC, truncate); } pub fn create(&mut self, create: bool) { self.flag(libc::O_CREAT, create); } pub fn mode(&mut self, mode: raw::mode_t) { self.mode = mode as mode_t; } fn flag(&mut self, bit: c_int, on: bool) { if on { self.flags |= bit; } else { self.flags &=!bit; } } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let path = try!(cstr(path)); File::open_c(&path, opts) } pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> { let flags = opts.flags | match (opts.read, opts.write) { (true, true) => libc::O_RDWR, (false, true) => libc::O_WRONLY, (true, false) | (false, false) => libc::O_RDONLY, }; let fd = try!(cvt_r(|| unsafe { libc::open(path.as_ptr(), flags, opts.mode) })); let fd = FileDesc::new(fd); fd.set_cloexec(); Ok(File(fd)) } pub fn into_fd(self) -> FileDesc { self.0 } pub fn file_attr(&self) -> io::Result<FileAttr> { let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn fsync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) })); Ok(()) } pub fn datasync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) })); return Ok(()); #[cfg(any(target_os = "macos", target_os = "ios"))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(target_os = "linux")] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) } #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } } pub fn truncate(&self, size: u64) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::ftruncate(self.0.raw(), size as libc::off_t) })); Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t), SeekFrom::End(off) => (libc::SEEK_END, off as off_t), SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t), }; let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) })); Ok(n as u64) } pub fn fd(&self) -> &FileDesc
} impl DirBuilder { pub fn new() -> DirBuilder { DirBuilder { mode: 0o777 } } pub fn mkdir(&self, p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })); Ok(()) } pub fn set_mode(&mut self, mode: mode_t) { self.mode = mode; } } fn cstr(path: &Path) -> io::Result<CString> { path.as_os_str().to_cstring().ok_or( io::Error::new(io::ErrorKind::InvalidInput, "path contained a null")) } impl FromInner<c_int> for File { fn from_inner(fd: c_int) -> File { File(FileDesc::new(fd)) } } impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { #[cfg(target_os = "linux")] fn get_path(fd: c_int) -> Option<PathBuf> { use string::ToString; let mut p = PathBuf::from("/proc/self/fd"); p.push(&fd.to_string()); readlink(&p).ok() } #[cfg(not(target_os = "linux"))] fn get_path(_fd: c_int) -> Option<PathBuf> { // FIXME(#24570): implement this for other Unix platforms None } #[cfg(target_os = "linux")] fn get_mode(fd: c_int) -> Option<(bool, bool)> { let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) }; if mode == -1 { return None; } match mode & libc::O_ACCMODE { libc::O_RDONLY => Some((true, false)), libc::O_RDWR => Some((true, true)), libc::O_WRONLY => Some((false, true)), _ => None } } #[cfg(not(target_os = "linux"))] fn get_mode(_fd: c_int) -> Option<(bool, bool)> { // FIXME(#24570): implement this for other Unix platforms None } let fd = self.0.raw(); let mut b = f.debug_struct("File").field("fd", &fd); if let Some(path) = get_path(fd) { b = b.field("path", &path); } if let Some((read, write)) = get_mode(fd) { b = b.field("read", &read).field("write", &write); } b.finish() } } pub fn readdir(p: &Path) -> io::Result<ReadDir> { let root = Arc::new(p.to_path_buf()); let p = try!(cstr(p)); unsafe { let ptr = libc::opendir(p.as_ptr()); if ptr.is_null() { Err(Error::last_os_error()) } else { Ok(ReadDir { dirp: Dir(ptr), root: root }) } } } pub fn unlink(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::unlink(p.as_ptr()) })); Ok(()) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let old = try!(cstr(old)); let new = try!(cstr(new)); try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })); Ok(()) } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })); Ok(()) } pub fn rmdir(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::rmdir(p.as_ptr()) })); Ok(()) } pub fn readlink(p: &Path) -> io::Result<PathBuf> { let c_path = try!(cstr(p)); let p = c_path.as_ptr(); let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) }; if len < 0 { len = 1024; // FIXME: read PATH_MAX from C ffi? } let mut buf: Vec<u8> = Vec::with_capacity(len as usize); unsafe { let n = try!(cvt({ libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t) })); buf.set_len(n as usize); } Ok(PathBuf::from(OsString::from_vec(buf))) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn link(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn stat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn lstat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> { let p = try!(cstr(p)); let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)]; try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) })); Ok(()) } pub fn canonicalize(p: &Path) -> io::Result<PathBuf> { let path = try!(CString::new(p.as_os_str().as_bytes())); let mut buf = vec![0u8; 16 * 1024]; unsafe { let r = c::realpath(path.as_ptr(), buf.as_mut_ptr() as *mut _); if r.is_null() { return Err(io::Error::last_os_error()) } } let p = buf.iter().position(|i| *i == 0).unwrap(); buf.truncate(p); Ok(PathBuf::from(OsString::from_vec(buf))) }
{ &self.0 }
identifier_body
fs.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::prelude::*; use io::prelude::*; use os::unix::prelude::*; use ffi::{CString, CStr, OsString, OsStr}; use fmt; use io::{self, Error, SeekFrom}; use libc::{self, c_int, size_t, off_t, c_char, mode_t}; use mem; use path::{Path, PathBuf}; use ptr; use sync::Arc; use sys::fd::FileDesc; use sys::platform::raw; use sys::{c, cvt, cvt_r}; use sys_common::{AsInner, FromInner}; use vec::Vec; pub struct File(FileDesc); pub struct FileAttr { stat: raw::stat, } pub struct ReadDir { dirp: Dir, root: Arc<PathBuf>, } struct Dir(*mut libc::DIR); unsafe impl Send for Dir {} unsafe impl Sync for Dir {} pub struct DirEntry { buf: Vec<u8>, // actually *mut libc::dirent_t root: Arc<PathBuf>, } #[derive(Clone)] pub struct OpenOptions { flags: c_int, read: bool, write: bool, mode: mode_t, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct FilePermissions { mode: mode_t } #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct FileType { mode: mode_t } pub struct DirBuilder { mode: mode_t } impl FileAttr { pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 } } pub fn accessed(&self) -> u64 { self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64) } pub fn modified(&self) -> u64 { self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64) } pub fn file_type(&self) -> FileType { FileType { mode: self.stat.st_mode as mode_t } } pub fn raw(&self) -> &raw::stat { &self.stat } // times are in milliseconds (currently) fn mktime(&self, secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 } } impl AsInner<raw::stat> for FileAttr { fn as_inner(&self) -> &raw::stat { &self.stat } } #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait MetadataExt { fn as_raw_stat(&self) -> &raw::stat; } impl MetadataExt for ::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { &self.as_inner().stat } } impl MetadataExt for ::os::unix::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { self.as_inner() } } impl FilePermissions { pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 } pub fn set_readonly(&mut self, readonly: bool) { if readonly { self.mode &=!0o222; } else { self.mode |= 0o222; } } pub fn mode(&self) -> raw::mode_t { self.mode } } impl FileType { pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) } pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) } pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) } fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode } } impl FromInner<raw::mode_t> for FilePermissions { fn from_inner(mode: raw::mode_t) -> FilePermissions { FilePermissions { mode: mode as mode_t } } } impl Iterator for ReadDir { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<io::Result<DirEntry>> { extern { fn rust_dirent_t_size() -> c_int; } let mut buf: Vec<u8> = Vec::with_capacity(unsafe { rust_dirent_t_size() as usize }); let ptr = buf.as_mut_ptr() as *mut libc::dirent_t; let mut entry_ptr = ptr::null_mut(); loop { if unsafe { libc::readdir_r(self.dirp.0, ptr, &mut entry_ptr)!= 0 } { return Some(Err(Error::last_os_error())) } if entry_ptr.is_null() { return None } let entry = DirEntry { buf: buf, root: self.root.clone() }; if entry.name_bytes() == b"." || entry.name_bytes() == b".." { buf = entry.buf; } else { return Some(Ok(entry)) } } } } impl Drop for Dir { fn drop(&mut self) { let r = unsafe { libc::closedir(self.0) }; debug_assert_eq!(r, 0); } } impl DirEntry { pub fn path(&self) -> PathBuf { self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes())) } pub fn file_name(&self) -> OsString { OsStr::from_bytes(self.name_bytes()).to_os_string() } pub fn metadata(&self) -> io::Result<FileAttr> { lstat(&self.path()) } pub fn file_type(&self) -> io::Result<FileType> { extern { fn rust_dir_get_mode(ptr: *mut libc::dirent_t) -> c_int; } unsafe { match rust_dir_get_mode(self.dirent()) { -1 => lstat(&self.path()).map(|m| m.file_type()), n => Ok(FileType { mode: n as mode_t }), } } } pub fn ino(&self) -> raw::ino_t { extern { fn rust_dir_get_ino(ptr: *mut libc::dirent_t) -> raw::ino_t; } unsafe { rust_dir_get_ino(self.dirent()) } } fn
(&self) -> &[u8] { extern { fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char; } unsafe { CStr::from_ptr(rust_list_dir_val(self.dirent())).to_bytes() } } fn dirent(&self) -> *mut libc::dirent_t { self.buf.as_ptr() as *mut _ } } impl OpenOptions { pub fn new() -> OpenOptions { OpenOptions { flags: 0, read: false, write: false, mode: 0o666, } } pub fn read(&mut self, read: bool) { self.read = read; } pub fn write(&mut self, write: bool) { self.write = write; } pub fn append(&mut self, append: bool) { self.flag(libc::O_APPEND, append); } pub fn truncate(&mut self, truncate: bool) { self.flag(libc::O_TRUNC, truncate); } pub fn create(&mut self, create: bool) { self.flag(libc::O_CREAT, create); } pub fn mode(&mut self, mode: raw::mode_t) { self.mode = mode as mode_t; } fn flag(&mut self, bit: c_int, on: bool) { if on { self.flags |= bit; } else { self.flags &=!bit; } } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let path = try!(cstr(path)); File::open_c(&path, opts) } pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> { let flags = opts.flags | match (opts.read, opts.write) { (true, true) => libc::O_RDWR, (false, true) => libc::O_WRONLY, (true, false) | (false, false) => libc::O_RDONLY, }; let fd = try!(cvt_r(|| unsafe { libc::open(path.as_ptr(), flags, opts.mode) })); let fd = FileDesc::new(fd); fd.set_cloexec(); Ok(File(fd)) } pub fn into_fd(self) -> FileDesc { self.0 } pub fn file_attr(&self) -> io::Result<FileAttr> { let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn fsync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) })); Ok(()) } pub fn datasync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) })); return Ok(()); #[cfg(any(target_os = "macos", target_os = "ios"))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(target_os = "linux")] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) } #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } } pub fn truncate(&self, size: u64) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::ftruncate(self.0.raw(), size as libc::off_t) })); Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t), SeekFrom::End(off) => (libc::SEEK_END, off as off_t), SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t), }; let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) })); Ok(n as u64) } pub fn fd(&self) -> &FileDesc { &self.0 } } impl DirBuilder { pub fn new() -> DirBuilder { DirBuilder { mode: 0o777 } } pub fn mkdir(&self, p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })); Ok(()) } pub fn set_mode(&mut self, mode: mode_t) { self.mode = mode; } } fn cstr(path: &Path) -> io::Result<CString> { path.as_os_str().to_cstring().ok_or( io::Error::new(io::ErrorKind::InvalidInput, "path contained a null")) } impl FromInner<c_int> for File { fn from_inner(fd: c_int) -> File { File(FileDesc::new(fd)) } } impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { #[cfg(target_os = "linux")] fn get_path(fd: c_int) -> Option<PathBuf> { use string::ToString; let mut p = PathBuf::from("/proc/self/fd"); p.push(&fd.to_string()); readlink(&p).ok() } #[cfg(not(target_os = "linux"))] fn get_path(_fd: c_int) -> Option<PathBuf> { // FIXME(#24570): implement this for other Unix platforms None } #[cfg(target_os = "linux")] fn get_mode(fd: c_int) -> Option<(bool, bool)> { let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) }; if mode == -1 { return None; } match mode & libc::O_ACCMODE { libc::O_RDONLY => Some((true, false)), libc::O_RDWR => Some((true, true)), libc::O_WRONLY => Some((false, true)), _ => None } } #[cfg(not(target_os = "linux"))] fn get_mode(_fd: c_int) -> Option<(bool, bool)> { // FIXME(#24570): implement this for other Unix platforms None } let fd = self.0.raw(); let mut b = f.debug_struct("File").field("fd", &fd); if let Some(path) = get_path(fd) { b = b.field("path", &path); } if let Some((read, write)) = get_mode(fd) { b = b.field("read", &read).field("write", &write); } b.finish() } } pub fn readdir(p: &Path) -> io::Result<ReadDir> { let root = Arc::new(p.to_path_buf()); let p = try!(cstr(p)); unsafe { let ptr = libc::opendir(p.as_ptr()); if ptr.is_null() { Err(Error::last_os_error()) } else { Ok(ReadDir { dirp: Dir(ptr), root: root }) } } } pub fn unlink(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::unlink(p.as_ptr()) })); Ok(()) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let old = try!(cstr(old)); let new = try!(cstr(new)); try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })); Ok(()) } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })); Ok(()) } pub fn rmdir(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::rmdir(p.as_ptr()) })); Ok(()) } pub fn readlink(p: &Path) -> io::Result<PathBuf> { let c_path = try!(cstr(p)); let p = c_path.as_ptr(); let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) }; if len < 0 { len = 1024; // FIXME: read PATH_MAX from C ffi? } let mut buf: Vec<u8> = Vec::with_capacity(len as usize); unsafe { let n = try!(cvt({ libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t) })); buf.set_len(n as usize); } Ok(PathBuf::from(OsString::from_vec(buf))) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn link(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn stat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn lstat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> { let p = try!(cstr(p)); let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)]; try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) })); Ok(()) } pub fn canonicalize(p: &Path) -> io::Result<PathBuf> { let path = try!(CString::new(p.as_os_str().as_bytes())); let mut buf = vec![0u8; 16 * 1024]; unsafe { let r = c::realpath(path.as_ptr(), buf.as_mut_ptr() as *mut _); if r.is_null() { return Err(io::Error::last_os_error()) } } let p = buf.iter().position(|i| *i == 0).unwrap(); buf.truncate(p); Ok(PathBuf::from(OsString::from_vec(buf))) }
name_bytes
identifier_name
fs.rs
// Copyright 2013-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
use io::prelude::*; use os::unix::prelude::*; use ffi::{CString, CStr, OsString, OsStr}; use fmt; use io::{self, Error, SeekFrom}; use libc::{self, c_int, size_t, off_t, c_char, mode_t}; use mem; use path::{Path, PathBuf}; use ptr; use sync::Arc; use sys::fd::FileDesc; use sys::platform::raw; use sys::{c, cvt, cvt_r}; use sys_common::{AsInner, FromInner}; use vec::Vec; pub struct File(FileDesc); pub struct FileAttr { stat: raw::stat, } pub struct ReadDir { dirp: Dir, root: Arc<PathBuf>, } struct Dir(*mut libc::DIR); unsafe impl Send for Dir {} unsafe impl Sync for Dir {} pub struct DirEntry { buf: Vec<u8>, // actually *mut libc::dirent_t root: Arc<PathBuf>, } #[derive(Clone)] pub struct OpenOptions { flags: c_int, read: bool, write: bool, mode: mode_t, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct FilePermissions { mode: mode_t } #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct FileType { mode: mode_t } pub struct DirBuilder { mode: mode_t } impl FileAttr { pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 } } pub fn accessed(&self) -> u64 { self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64) } pub fn modified(&self) -> u64 { self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64) } pub fn file_type(&self) -> FileType { FileType { mode: self.stat.st_mode as mode_t } } pub fn raw(&self) -> &raw::stat { &self.stat } // times are in milliseconds (currently) fn mktime(&self, secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 } } impl AsInner<raw::stat> for FileAttr { fn as_inner(&self) -> &raw::stat { &self.stat } } #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait MetadataExt { fn as_raw_stat(&self) -> &raw::stat; } impl MetadataExt for ::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { &self.as_inner().stat } } impl MetadataExt for ::os::unix::fs::Metadata { fn as_raw_stat(&self) -> &raw::stat { self.as_inner() } } impl FilePermissions { pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 } pub fn set_readonly(&mut self, readonly: bool) { if readonly { self.mode &=!0o222; } else { self.mode |= 0o222; } } pub fn mode(&self) -> raw::mode_t { self.mode } } impl FileType { pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) } pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) } pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) } fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode } } impl FromInner<raw::mode_t> for FilePermissions { fn from_inner(mode: raw::mode_t) -> FilePermissions { FilePermissions { mode: mode as mode_t } } } impl Iterator for ReadDir { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<io::Result<DirEntry>> { extern { fn rust_dirent_t_size() -> c_int; } let mut buf: Vec<u8> = Vec::with_capacity(unsafe { rust_dirent_t_size() as usize }); let ptr = buf.as_mut_ptr() as *mut libc::dirent_t; let mut entry_ptr = ptr::null_mut(); loop { if unsafe { libc::readdir_r(self.dirp.0, ptr, &mut entry_ptr)!= 0 } { return Some(Err(Error::last_os_error())) } if entry_ptr.is_null() { return None } let entry = DirEntry { buf: buf, root: self.root.clone() }; if entry.name_bytes() == b"." || entry.name_bytes() == b".." { buf = entry.buf; } else { return Some(Ok(entry)) } } } } impl Drop for Dir { fn drop(&mut self) { let r = unsafe { libc::closedir(self.0) }; debug_assert_eq!(r, 0); } } impl DirEntry { pub fn path(&self) -> PathBuf { self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes())) } pub fn file_name(&self) -> OsString { OsStr::from_bytes(self.name_bytes()).to_os_string() } pub fn metadata(&self) -> io::Result<FileAttr> { lstat(&self.path()) } pub fn file_type(&self) -> io::Result<FileType> { extern { fn rust_dir_get_mode(ptr: *mut libc::dirent_t) -> c_int; } unsafe { match rust_dir_get_mode(self.dirent()) { -1 => lstat(&self.path()).map(|m| m.file_type()), n => Ok(FileType { mode: n as mode_t }), } } } pub fn ino(&self) -> raw::ino_t { extern { fn rust_dir_get_ino(ptr: *mut libc::dirent_t) -> raw::ino_t; } unsafe { rust_dir_get_ino(self.dirent()) } } fn name_bytes(&self) -> &[u8] { extern { fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char; } unsafe { CStr::from_ptr(rust_list_dir_val(self.dirent())).to_bytes() } } fn dirent(&self) -> *mut libc::dirent_t { self.buf.as_ptr() as *mut _ } } impl OpenOptions { pub fn new() -> OpenOptions { OpenOptions { flags: 0, read: false, write: false, mode: 0o666, } } pub fn read(&mut self, read: bool) { self.read = read; } pub fn write(&mut self, write: bool) { self.write = write; } pub fn append(&mut self, append: bool) { self.flag(libc::O_APPEND, append); } pub fn truncate(&mut self, truncate: bool) { self.flag(libc::O_TRUNC, truncate); } pub fn create(&mut self, create: bool) { self.flag(libc::O_CREAT, create); } pub fn mode(&mut self, mode: raw::mode_t) { self.mode = mode as mode_t; } fn flag(&mut self, bit: c_int, on: bool) { if on { self.flags |= bit; } else { self.flags &=!bit; } } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let path = try!(cstr(path)); File::open_c(&path, opts) } pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> { let flags = opts.flags | match (opts.read, opts.write) { (true, true) => libc::O_RDWR, (false, true) => libc::O_WRONLY, (true, false) | (false, false) => libc::O_RDONLY, }; let fd = try!(cvt_r(|| unsafe { libc::open(path.as_ptr(), flags, opts.mode) })); let fd = FileDesc::new(fd); fd.set_cloexec(); Ok(File(fd)) } pub fn into_fd(self) -> FileDesc { self.0 } pub fn file_attr(&self) -> io::Result<FileAttr> { let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn fsync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) })); Ok(()) } pub fn datasync(&self) -> io::Result<()> { try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) })); return Ok(()); #[cfg(any(target_os = "macos", target_os = "ios"))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(target_os = "linux")] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) } #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))] unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } } pub fn truncate(&self, size: u64) -> io::Result<()> { try!(cvt_r(|| unsafe { libc::ftruncate(self.0.raw(), size as libc::off_t) })); Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t), SeekFrom::End(off) => (libc::SEEK_END, off as off_t), SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t), }; let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) })); Ok(n as u64) } pub fn fd(&self) -> &FileDesc { &self.0 } } impl DirBuilder { pub fn new() -> DirBuilder { DirBuilder { mode: 0o777 } } pub fn mkdir(&self, p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })); Ok(()) } pub fn set_mode(&mut self, mode: mode_t) { self.mode = mode; } } fn cstr(path: &Path) -> io::Result<CString> { path.as_os_str().to_cstring().ok_or( io::Error::new(io::ErrorKind::InvalidInput, "path contained a null")) } impl FromInner<c_int> for File { fn from_inner(fd: c_int) -> File { File(FileDesc::new(fd)) } } impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { #[cfg(target_os = "linux")] fn get_path(fd: c_int) -> Option<PathBuf> { use string::ToString; let mut p = PathBuf::from("/proc/self/fd"); p.push(&fd.to_string()); readlink(&p).ok() } #[cfg(not(target_os = "linux"))] fn get_path(_fd: c_int) -> Option<PathBuf> { // FIXME(#24570): implement this for other Unix platforms None } #[cfg(target_os = "linux")] fn get_mode(fd: c_int) -> Option<(bool, bool)> { let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) }; if mode == -1 { return None; } match mode & libc::O_ACCMODE { libc::O_RDONLY => Some((true, false)), libc::O_RDWR => Some((true, true)), libc::O_WRONLY => Some((false, true)), _ => None } } #[cfg(not(target_os = "linux"))] fn get_mode(_fd: c_int) -> Option<(bool, bool)> { // FIXME(#24570): implement this for other Unix platforms None } let fd = self.0.raw(); let mut b = f.debug_struct("File").field("fd", &fd); if let Some(path) = get_path(fd) { b = b.field("path", &path); } if let Some((read, write)) = get_mode(fd) { b = b.field("read", &read).field("write", &write); } b.finish() } } pub fn readdir(p: &Path) -> io::Result<ReadDir> { let root = Arc::new(p.to_path_buf()); let p = try!(cstr(p)); unsafe { let ptr = libc::opendir(p.as_ptr()); if ptr.is_null() { Err(Error::last_os_error()) } else { Ok(ReadDir { dirp: Dir(ptr), root: root }) } } } pub fn unlink(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::unlink(p.as_ptr()) })); Ok(()) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let old = try!(cstr(old)); let new = try!(cstr(new)); try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })); Ok(()) } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })); Ok(()) } pub fn rmdir(p: &Path) -> io::Result<()> { let p = try!(cstr(p)); try!(cvt(unsafe { libc::rmdir(p.as_ptr()) })); Ok(()) } pub fn readlink(p: &Path) -> io::Result<PathBuf> { let c_path = try!(cstr(p)); let p = c_path.as_ptr(); let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) }; if len < 0 { len = 1024; // FIXME: read PATH_MAX from C ffi? } let mut buf: Vec<u8> = Vec::with_capacity(len as usize); unsafe { let n = try!(cvt({ libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t) })); buf.set_len(n as usize); } Ok(PathBuf::from(OsString::from_vec(buf))) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn link(src: &Path, dst: &Path) -> io::Result<()> { let src = try!(cstr(src)); let dst = try!(cstr(dst)); try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })); Ok(()) } pub fn stat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn lstat(p: &Path) -> io::Result<FileAttr> { let p = try!(cstr(p)); let mut stat: raw::stat = unsafe { mem::zeroed() }; try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _) })); Ok(FileAttr { stat: stat }) } pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> { let p = try!(cstr(p)); let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)]; try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) })); Ok(()) } pub fn canonicalize(p: &Path) -> io::Result<PathBuf> { let path = try!(CString::new(p.as_os_str().as_bytes())); let mut buf = vec![0u8; 16 * 1024]; unsafe { let r = c::realpath(path.as_ptr(), buf.as_mut_ptr() as *mut _); if r.is_null() { return Err(io::Error::last_os_error()) } } let p = buf.iter().position(|i| *i == 0).unwrap(); buf.truncate(p); Ok(PathBuf::from(OsString::from_vec(buf))) }
// except according to those terms. use core::prelude::*;
random_line_split
issue-50825-1.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // regression test for issue #50825 // Make sure that the `impl` bound (): X<T = ()> is preferred over // the (): X bound in the where clause.
trait Y<U>: X { fn foo(x: &Self::T); } impl X for () { type T = (); } impl<T> Y<Vec<T>> for () where (): Y<T> { fn foo(_x: &()) {} } fn main () {}
trait X { type T; }
random_line_split
issue-50825-1.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // regression test for issue #50825 // Make sure that the `impl` bound (): X<T = ()> is preferred over // the (): X bound in the where clause. trait X { type T; } trait Y<U>: X { fn foo(x: &Self::T); } impl X for () { type T = (); } impl<T> Y<Vec<T>> for () where (): Y<T> { fn foo(_x: &())
} fn main () {}
{}
identifier_body
issue-50825-1.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // regression test for issue #50825 // Make sure that the `impl` bound (): X<T = ()> is preferred over // the (): X bound in the where clause. trait X { type T; } trait Y<U>: X { fn foo(x: &Self::T); } impl X for () { type T = (); } impl<T> Y<Vec<T>> for () where (): Y<T> { fn foo(_x: &()) {} } fn
() {}
main
identifier_name
print_operation_preview.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use PageSetup; use PrintContext; use ffi; use glib; use glib::object::Downcast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::boxed::Box as Box_; use std::mem; use std::mem::transmute; use std::ptr; glib_wrapper! { pub struct PrintOperationPreview(Object<ffi::GtkPrintOperationPreview, ffi::GtkPrintOperationPreviewIface>); match fn { get_type => || ffi::gtk_print_operation_preview_get_type(), } } pub trait PrintOperationPreviewExt { fn end_preview(&self); fn is_selected(&self, page_nr: i32) -> bool; fn render_page(&self, page_nr: i32); fn connect_got_page_size<F: Fn(&Self, &PrintContext, &PageSetup) +'static>(&self, f: F) -> SignalHandlerId; fn connect_ready<F: Fn(&Self, &PrintContext) +'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<PrintOperationPreview> + IsA<glib::object::Object>> PrintOperationPreviewExt for O { fn end_preview(&self) { unsafe { ffi::gtk_print_operation_preview_end_preview(self.to_glib_none().0); } } fn is_selected(&self, page_nr: i32) -> bool { unsafe { from_glib(ffi::gtk_print_operation_preview_is_selected(self.to_glib_none().0, page_nr)) } } fn render_page(&self, page_nr: i32) { unsafe { ffi::gtk_print_operation_preview_render_page(self.to_glib_none().0, page_nr); } } fn connect_got_page_size<F: Fn(&Self, &PrintContext, &PageSetup) +'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self, &PrintContext, &PageSetup) +'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "got-page-size", transmute(got_page_size_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_ready<F: Fn(&Self, &PrintContext) +'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self, &PrintContext) +'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "ready", transmute(ready_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } } unsafe extern "C" fn got_page_size_trampoline<P>(this: *mut ffi::GtkPrintOperationPreview, context: *mut ffi::GtkPrintContext, page_setup: *mut ffi::GtkPageSetup, f: glib_ffi::gpointer) where P: IsA<PrintOperationPreview> { let f: &&(Fn(&P, &PrintContext, &PageSetup) +'static) = transmute(f); f(&PrintOperationPreview::from_glib_borrow(this).downcast_unchecked(), &from_glib_borrow(context), &from_glib_borrow(page_setup)) } unsafe extern "C" fn
<P>(this: *mut ffi::GtkPrintOperationPreview, context: *mut ffi::GtkPrintContext, f: glib_ffi::gpointer) where P: IsA<PrintOperationPreview> { let f: &&(Fn(&P, &PrintContext) +'static) = transmute(f); f(&PrintOperationPreview::from_glib_borrow(this).downcast_unchecked(), &from_glib_borrow(context)) }
ready_trampoline
identifier_name
print_operation_preview.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use PageSetup; use PrintContext; use ffi; use glib; use glib::object::Downcast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::boxed::Box as Box_; use std::mem; use std::mem::transmute; use std::ptr; glib_wrapper! { pub struct PrintOperationPreview(Object<ffi::GtkPrintOperationPreview, ffi::GtkPrintOperationPreviewIface>); match fn { get_type => || ffi::gtk_print_operation_preview_get_type(), } } pub trait PrintOperationPreviewExt {
fn is_selected(&self, page_nr: i32) -> bool; fn render_page(&self, page_nr: i32); fn connect_got_page_size<F: Fn(&Self, &PrintContext, &PageSetup) +'static>(&self, f: F) -> SignalHandlerId; fn connect_ready<F: Fn(&Self, &PrintContext) +'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<PrintOperationPreview> + IsA<glib::object::Object>> PrintOperationPreviewExt for O { fn end_preview(&self) { unsafe { ffi::gtk_print_operation_preview_end_preview(self.to_glib_none().0); } } fn is_selected(&self, page_nr: i32) -> bool { unsafe { from_glib(ffi::gtk_print_operation_preview_is_selected(self.to_glib_none().0, page_nr)) } } fn render_page(&self, page_nr: i32) { unsafe { ffi::gtk_print_operation_preview_render_page(self.to_glib_none().0, page_nr); } } fn connect_got_page_size<F: Fn(&Self, &PrintContext, &PageSetup) +'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self, &PrintContext, &PageSetup) +'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "got-page-size", transmute(got_page_size_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_ready<F: Fn(&Self, &PrintContext) +'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self, &PrintContext) +'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "ready", transmute(ready_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } } unsafe extern "C" fn got_page_size_trampoline<P>(this: *mut ffi::GtkPrintOperationPreview, context: *mut ffi::GtkPrintContext, page_setup: *mut ffi::GtkPageSetup, f: glib_ffi::gpointer) where P: IsA<PrintOperationPreview> { let f: &&(Fn(&P, &PrintContext, &PageSetup) +'static) = transmute(f); f(&PrintOperationPreview::from_glib_borrow(this).downcast_unchecked(), &from_glib_borrow(context), &from_glib_borrow(page_setup)) } unsafe extern "C" fn ready_trampoline<P>(this: *mut ffi::GtkPrintOperationPreview, context: *mut ffi::GtkPrintContext, f: glib_ffi::gpointer) where P: IsA<PrintOperationPreview> { let f: &&(Fn(&P, &PrintContext) +'static) = transmute(f); f(&PrintOperationPreview::from_glib_borrow(this).downcast_unchecked(), &from_glib_borrow(context)) }
fn end_preview(&self);
random_line_split
print_operation_preview.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use PageSetup; use PrintContext; use ffi; use glib; use glib::object::Downcast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::boxed::Box as Box_; use std::mem; use std::mem::transmute; use std::ptr; glib_wrapper! { pub struct PrintOperationPreview(Object<ffi::GtkPrintOperationPreview, ffi::GtkPrintOperationPreviewIface>); match fn { get_type => || ffi::gtk_print_operation_preview_get_type(), } } pub trait PrintOperationPreviewExt { fn end_preview(&self); fn is_selected(&self, page_nr: i32) -> bool; fn render_page(&self, page_nr: i32); fn connect_got_page_size<F: Fn(&Self, &PrintContext, &PageSetup) +'static>(&self, f: F) -> SignalHandlerId; fn connect_ready<F: Fn(&Self, &PrintContext) +'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<PrintOperationPreview> + IsA<glib::object::Object>> PrintOperationPreviewExt for O { fn end_preview(&self) { unsafe { ffi::gtk_print_operation_preview_end_preview(self.to_glib_none().0); } } fn is_selected(&self, page_nr: i32) -> bool { unsafe { from_glib(ffi::gtk_print_operation_preview_is_selected(self.to_glib_none().0, page_nr)) } } fn render_page(&self, page_nr: i32) { unsafe { ffi::gtk_print_operation_preview_render_page(self.to_glib_none().0, page_nr); } } fn connect_got_page_size<F: Fn(&Self, &PrintContext, &PageSetup) +'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self, &PrintContext, &PageSetup) +'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "got-page-size", transmute(got_page_size_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_ready<F: Fn(&Self, &PrintContext) +'static>(&self, f: F) -> SignalHandlerId
} unsafe extern "C" fn got_page_size_trampoline<P>(this: *mut ffi::GtkPrintOperationPreview, context: *mut ffi::GtkPrintContext, page_setup: *mut ffi::GtkPageSetup, f: glib_ffi::gpointer) where P: IsA<PrintOperationPreview> { let f: &&(Fn(&P, &PrintContext, &PageSetup) +'static) = transmute(f); f(&PrintOperationPreview::from_glib_borrow(this).downcast_unchecked(), &from_glib_borrow(context), &from_glib_borrow(page_setup)) } unsafe extern "C" fn ready_trampoline<P>(this: *mut ffi::GtkPrintOperationPreview, context: *mut ffi::GtkPrintContext, f: glib_ffi::gpointer) where P: IsA<PrintOperationPreview> { let f: &&(Fn(&P, &PrintContext) +'static) = transmute(f); f(&PrintOperationPreview::from_glib_borrow(this).downcast_unchecked(), &from_glib_borrow(context)) }
{ unsafe { let f: Box_<Box_<Fn(&Self, &PrintContext) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "ready", transmute(ready_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } }
identifier_body
lib.rs
#![allow(clippy::too_many_arguments)] #![allow(clippy::cognitive_complexity)] mod config; mod editor; mod exit_dialogue; mod input_area; mod key_map; mod line_split; mod messaging; #[doc(hidden)] pub mod msg_area; // Public to be able to use in an example mod notifier; mod tab; mod termbox; pub mod test_utils; #[doc(hidden)] pub mod trie; // Public for benchmarks pub mod tui; // Public for benchmarks mod utils; mod widget; #[cfg(test)] mod tests; use crate::tui::{CmdResult, TUIRet}; use libtiny_common::{ChanNameRef, Event, MsgSource, MsgTarget, TabStyle}; use term_input::Input; use std::cell::RefCell; use std::path::PathBuf; use std::rc::{Rc, Weak}; use time::Tm; use tokio::select; use tokio::signal::unix::{signal, SignalKind}; use tokio::sync::mpsc; use tokio::task::spawn_local; use tokio_stream::wrappers::{ReceiverStream, SignalStream}; use tokio_stream::{Stream, StreamExt}; #[macro_use] extern crate log; #[derive(Clone)] pub struct TUI { inner: Weak<RefCell<tui::TUI>>, } impl TUI { pub fn run(config_path: PathBuf) -> (TUI, mpsc::Receiver<Event>) { let tui = Rc::new(RefCell::new(tui::TUI::new(config_path))); let inner = Rc::downgrade(&tui); let (snd_ev, rcv_ev) = mpsc::channel(10); // For SIGWINCH handler let (snd_abort, rcv_abort) = mpsc::channel::<()>(1); // Spawn SIGWINCH handler spawn_local(sigwinch_handler(inner.clone(), rcv_abort)); // Spawn input handler task let input = Input::new(); spawn_local(input_handler(input, tui, snd_ev, snd_abort)); (TUI { inner }, rcv_ev) } /// Create a test instance that doesn't render to the terminal, just updates the termbox /// buffer. Useful for testing. See also [`get_front_buffer`](TUI::get_front_buffer). pub fn
<S>(width: u16, height: u16, input_stream: S) -> (TUI, mpsc::Receiver<Event>) where S: Stream<Item = std::io::Result<term_input::Event>> + Unpin +'static, { let tui = Rc::new(RefCell::new(tui::TUI::new_test(width, height))); let inner = Rc::downgrade(&tui); let (snd_ev, rcv_ev) = mpsc::channel(10); // We don't need to handle SIGWINCH in testing so the receiver end is not used let (snd_abort, _rcv_abort) = mpsc::channel::<()>(1); // Spawn input handler task spawn_local(input_handler(input_stream, tui, snd_ev, snd_abort)); (TUI { inner }, rcv_ev) } /// Get termbox front buffer. Useful for testing rendering. pub fn get_front_buffer(&self) -> termbox_simple::CellBuf { self.inner.upgrade().unwrap().borrow().get_front_buffer() } } async fn sigwinch_handler(tui: Weak<RefCell<tui::TUI>>, rcv_abort: mpsc::Receiver<()>) { let stream = match signal(SignalKind::window_change()) { Err(err) => { debug!("Can't install SIGWINCH handler: {:?}", err); return; } Ok(stream) => stream, }; let mut stream_fused = SignalStream::new(stream).fuse(); let mut rcv_abort_fused = ReceiverStream::new(rcv_abort).fuse(); loop { select! { _ = stream_fused.next() => { match tui.upgrade() { None => { return; } Some(tui) => { tui.borrow_mut().resize(); } } }, _ = rcv_abort_fused.next() => { return; } } } } async fn input_handler<S>( mut input_stream: S, tui: Rc<RefCell<tui::TUI>>, snd_ev: mpsc::Sender<Event>, snd_abort: mpsc::Sender<()>, ) where S: Stream<Item = std::io::Result<term_input::Event>> + Unpin, { // See module documentation of `editor` for how editor stuff works let mut rcv_editor_ret: Option<editor::ResultReceiver> = None; loop { if let Some(editor_ret) = rcv_editor_ret.take() { // $EDITOR running, don't read stdin, wait for $EDITOR to finish match editor_ret.await { Err(recv_error) => { debug!("RecvError while waiting editor response: {:?}", recv_error); } Ok(editor_ret) => { if let Some((lines, from)) = tui.borrow_mut().handle_editor_result(editor_ret) { debug!("editor ret: {:?}", lines); snd_ev .try_send(Event::Lines { lines, source: from, }) .unwrap(); } } } tui.borrow_mut().activate(); tui.borrow_mut().draw(); } match input_stream.next().await { None => { break; } Some(Err(io_err)) => { debug!("term_input error: {:?}", io_err); break; } Some(Ok(ev)) => { let tui_ret = tui.borrow_mut().handle_input_event(ev, &mut rcv_editor_ret); match tui_ret { TUIRet::Abort => { snd_ev.try_send(Event::Abort).unwrap(); let _ = snd_abort.try_send(()); return; } TUIRet::KeyHandled | TUIRet::KeyIgnored(_) | TUIRet::EventIgnored(_) => {} TUIRet::Input { msg, from } => { if msg[0] == '/' { // Handle TUI commands, send others to downstream let cmd: String = (&msg[1..]).iter().collect(); let result = tui.borrow_mut().try_handle_cmd(&cmd, &from); match result { CmdResult::Ok => {} CmdResult::Continue => { snd_ev.try_send(Event::Cmd { cmd, source: from }).unwrap() } CmdResult::Quit => { snd_ev.try_send(Event::Abort).unwrap(); let _ = snd_abort.try_send(()); return; } } } else { snd_ev .try_send(Event::Msg { msg: msg.into_iter().collect(), source: from, }) .unwrap(); } } } } } tui.borrow_mut().draw(); } } macro_rules! delegate { ( $name:ident ( $( $x:ident: $t:ty, )* ) ) => { pub fn $name(&self, $($x: $t,)*) { if let Some(inner) = self.inner.upgrade() { inner.borrow_mut().$name( $( $x, )* ); } } } } impl TUI { delegate!(draw()); delegate!(new_server_tab(serv_name: &str, alias: Option<String>,)); delegate!(close_server_tab(serv_name: &str,)); delegate!(new_chan_tab(serv_name: &str, chan: &ChanNameRef,)); delegate!(close_chan_tab(serv_name: &str, chan: &ChanNameRef,)); delegate!(close_user_tab(serv_name: &str, nick: &str,)); delegate!(add_client_msg(msg: &str, target: &MsgTarget,)); delegate!(add_msg(msg: &str, ts: Tm, target: &MsgTarget,)); delegate!(add_err_msg(msg: &str, ts: Tm, target: &MsgTarget,)); delegate!(add_client_err_msg(msg: &str, target: &MsgTarget,)); delegate!(clear_nicks(serv_name: &str,)); delegate!(set_nick(serv_name: &str, new_nick: &str,)); delegate!(add_privmsg( sender: &str, msg: &str, ts: Tm, target: &MsgTarget, highlight: bool, is_action: bool, )); delegate!(add_nick(nick: &str, ts: Option<Tm>, target: &MsgTarget,)); delegate!(remove_nick(nick: &str, ts: Option<Tm>, target: &MsgTarget,)); delegate!(rename_nick( old_nick: &str, new_nick: &str, ts: Tm, target: &MsgTarget, )); delegate!(set_topic( topic: &str, ts: Tm, serv_name: &str, chan_name: &ChanNameRef, )); delegate!(set_tab_style(style: TabStyle, target: &MsgTarget,)); pub fn user_tab_exists(&self, serv_name: &str, nick: &str) -> bool { match self.inner.upgrade() { Some(tui) => tui.borrow().user_tab_exists(serv_name, nick), None => false, } } pub fn current_tab(&self) -> Option<MsgSource> { self.inner .upgrade() .map(|tui| tui.borrow().current_tab().clone()) } }
run_test
identifier_name
lib.rs
#![allow(clippy::too_many_arguments)] #![allow(clippy::cognitive_complexity)] mod config; mod editor; mod exit_dialogue; mod input_area; mod key_map; mod line_split; mod messaging; #[doc(hidden)] pub mod msg_area; // Public to be able to use in an example mod notifier; mod tab; mod termbox; pub mod test_utils; #[doc(hidden)] pub mod trie; // Public for benchmarks pub mod tui; // Public for benchmarks mod utils; mod widget; #[cfg(test)] mod tests; use crate::tui::{CmdResult, TUIRet}; use libtiny_common::{ChanNameRef, Event, MsgSource, MsgTarget, TabStyle}; use term_input::Input; use std::cell::RefCell; use std::path::PathBuf; use std::rc::{Rc, Weak}; use time::Tm; use tokio::select; use tokio::signal::unix::{signal, SignalKind}; use tokio::sync::mpsc; use tokio::task::spawn_local; use tokio_stream::wrappers::{ReceiverStream, SignalStream}; use tokio_stream::{Stream, StreamExt}; #[macro_use] extern crate log; #[derive(Clone)] pub struct TUI { inner: Weak<RefCell<tui::TUI>>, } impl TUI { pub fn run(config_path: PathBuf) -> (TUI, mpsc::Receiver<Event>) { let tui = Rc::new(RefCell::new(tui::TUI::new(config_path))); let inner = Rc::downgrade(&tui); let (snd_ev, rcv_ev) = mpsc::channel(10); // For SIGWINCH handler let (snd_abort, rcv_abort) = mpsc::channel::<()>(1); // Spawn SIGWINCH handler spawn_local(sigwinch_handler(inner.clone(), rcv_abort)); // Spawn input handler task let input = Input::new(); spawn_local(input_handler(input, tui, snd_ev, snd_abort)); (TUI { inner }, rcv_ev) } /// Create a test instance that doesn't render to the terminal, just updates the termbox /// buffer. Useful for testing. See also [`get_front_buffer`](TUI::get_front_buffer). pub fn run_test<S>(width: u16, height: u16, input_stream: S) -> (TUI, mpsc::Receiver<Event>) where S: Stream<Item = std::io::Result<term_input::Event>> + Unpin +'static, { let tui = Rc::new(RefCell::new(tui::TUI::new_test(width, height))); let inner = Rc::downgrade(&tui); let (snd_ev, rcv_ev) = mpsc::channel(10); // We don't need to handle SIGWINCH in testing so the receiver end is not used let (snd_abort, _rcv_abort) = mpsc::channel::<()>(1); // Spawn input handler task spawn_local(input_handler(input_stream, tui, snd_ev, snd_abort)); (TUI { inner }, rcv_ev) } /// Get termbox front buffer. Useful for testing rendering. pub fn get_front_buffer(&self) -> termbox_simple::CellBuf { self.inner.upgrade().unwrap().borrow().get_front_buffer() } } async fn sigwinch_handler(tui: Weak<RefCell<tui::TUI>>, rcv_abort: mpsc::Receiver<()>) { let stream = match signal(SignalKind::window_change()) { Err(err) => { debug!("Can't install SIGWINCH handler: {:?}", err); return; } Ok(stream) => stream, }; let mut stream_fused = SignalStream::new(stream).fuse(); let mut rcv_abort_fused = ReceiverStream::new(rcv_abort).fuse(); loop { select! { _ = stream_fused.next() => { match tui.upgrade() { None => { return; } Some(tui) => { tui.borrow_mut().resize(); } } }, _ = rcv_abort_fused.next() => { return; } } } } async fn input_handler<S>( mut input_stream: S, tui: Rc<RefCell<tui::TUI>>, snd_ev: mpsc::Sender<Event>, snd_abort: mpsc::Sender<()>, ) where S: Stream<Item = std::io::Result<term_input::Event>> + Unpin, { // See module documentation of `editor` for how editor stuff works let mut rcv_editor_ret: Option<editor::ResultReceiver> = None; loop { if let Some(editor_ret) = rcv_editor_ret.take() { // $EDITOR running, don't read stdin, wait for $EDITOR to finish match editor_ret.await { Err(recv_error) => { debug!("RecvError while waiting editor response: {:?}", recv_error); } Ok(editor_ret) => { if let Some((lines, from)) = tui.borrow_mut().handle_editor_result(editor_ret) { debug!("editor ret: {:?}", lines); snd_ev .try_send(Event::Lines { lines, source: from, }) .unwrap(); } } } tui.borrow_mut().activate(); tui.borrow_mut().draw(); } match input_stream.next().await { None => { break; } Some(Err(io_err)) => { debug!("term_input error: {:?}", io_err); break; } Some(Ok(ev)) => { let tui_ret = tui.borrow_mut().handle_input_event(ev, &mut rcv_editor_ret); match tui_ret { TUIRet::Abort => { snd_ev.try_send(Event::Abort).unwrap(); let _ = snd_abort.try_send(()); return; } TUIRet::KeyHandled | TUIRet::KeyIgnored(_) | TUIRet::EventIgnored(_) => {} TUIRet::Input { msg, from } => { if msg[0] == '/' { // Handle TUI commands, send others to downstream let cmd: String = (&msg[1..]).iter().collect(); let result = tui.borrow_mut().try_handle_cmd(&cmd, &from); match result { CmdResult::Ok => {} CmdResult::Continue => { snd_ev.try_send(Event::Cmd { cmd, source: from }).unwrap() } CmdResult::Quit => { snd_ev.try_send(Event::Abort).unwrap(); let _ = snd_abort.try_send(()); return; } } } else { snd_ev .try_send(Event::Msg { msg: msg.into_iter().collect(), source: from, }) .unwrap(); } } } } } tui.borrow_mut().draw(); } } macro_rules! delegate { ( $name:ident ( $( $x:ident: $t:ty, )* ) ) => { pub fn $name(&self, $($x: $t,)*) { if let Some(inner) = self.inner.upgrade() { inner.borrow_mut().$name( $( $x, )* ); } } } } impl TUI { delegate!(draw()); delegate!(new_server_tab(serv_name: &str, alias: Option<String>,)); delegate!(close_server_tab(serv_name: &str,)); delegate!(new_chan_tab(serv_name: &str, chan: &ChanNameRef,)); delegate!(close_chan_tab(serv_name: &str, chan: &ChanNameRef,)); delegate!(close_user_tab(serv_name: &str, nick: &str,)); delegate!(add_client_msg(msg: &str, target: &MsgTarget,)); delegate!(add_msg(msg: &str, ts: Tm, target: &MsgTarget,)); delegate!(add_err_msg(msg: &str, ts: Tm, target: &MsgTarget,)); delegate!(add_client_err_msg(msg: &str, target: &MsgTarget,)); delegate!(clear_nicks(serv_name: &str,)); delegate!(set_nick(serv_name: &str, new_nick: &str,)); delegate!(add_privmsg( sender: &str, msg: &str, ts: Tm, target: &MsgTarget, highlight: bool, is_action: bool, )); delegate!(add_nick(nick: &str, ts: Option<Tm>, target: &MsgTarget,)); delegate!(remove_nick(nick: &str, ts: Option<Tm>, target: &MsgTarget,)); delegate!(rename_nick( old_nick: &str, new_nick: &str, ts: Tm, target: &MsgTarget, )); delegate!(set_topic( topic: &str, ts: Tm, serv_name: &str, chan_name: &ChanNameRef, )); delegate!(set_tab_style(style: TabStyle, target: &MsgTarget,)); pub fn user_tab_exists(&self, serv_name: &str, nick: &str) -> bool { match self.inner.upgrade() { Some(tui) => tui.borrow().user_tab_exists(serv_name, nick), None => false, } } pub fn current_tab(&self) -> Option<MsgSource> {
} }
self.inner .upgrade() .map(|tui| tui.borrow().current_tab().clone())
random_line_split
defaults.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate native; extern crate glfw; use glfw::Context; #[start] fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, main) } fn main() { let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::Visible(true)); let (window, _) = glfw.create_window(640, 480, "Defaults", glfw::Windowed) .expect("Failed to create GLFW window."); window.make_current(); let (width, height) = window.get_size(); println!("window size: ({}, {})", width, height); println!("Context version: {:s}", window.get_context_version().to_str()); println!("OpenGL forward compatible: {}", window.is_opengl_forward_compat()); println!("OpenGL debug context: {}", window.is_opengl_debug_context()); println!("OpenGL profile: {}", window.get_opengl_profile()); let gl_params = [ (gl::RED_BITS, None, "red bits" ), (gl::GREEN_BITS, None, "green bits" ), (gl::BLUE_BITS, None, "blue bits" ), (gl::ALPHA_BITS, None, "alpha bits" ), (gl::DEPTH_BITS, None, "depth bits" ), (gl::STENCIL_BITS, None, "stencil bits" ), (gl::ACCUM_RED_BITS, None, "accum red bits" ), (gl::ACCUM_GREEN_BITS, None, "accum green bits" ), (gl::ACCUM_BLUE_BITS, None, "accum blue bits" ), (gl::ACCUM_ALPHA_BITS, None, "accum alpha bits" ), (gl::STEREO, None, "stereo" ), (gl::SAMPLES_ARB, Some("GL_ARB_multisample"), "FSAA samples" ), ]; for &(param, ext, name) in gl_params.iter() { if ext.map_or(true, |s| { glfw.extension_supported(s) })
; } } mod gl { extern crate libc; #[cfg(target_os = "macos")] #[link(name="OpenGL", kind="framework")] extern { } #[cfg(target_os = "linux")] #[link(name="GL")] extern { } pub type GLenum = libc::c_uint; pub type GLint = libc::c_int; pub static RED_BITS : GLenum = 0x0D52; pub static GREEN_BITS : GLenum = 0x0D53; pub static BLUE_BITS : GLenum = 0x0D54; pub static ALPHA_BITS : GLenum = 0x0D55; pub static DEPTH_BITS : GLenum = 0x0D56; pub static STENCIL_BITS : GLenum = 0x0D57; pub static ACCUM_RED_BITS : GLenum = 0x0D58; pub static ACCUM_GREEN_BITS : GLenum = 0x0D59; pub static ACCUM_BLUE_BITS : GLenum = 0x0D5A; pub static ACCUM_ALPHA_BITS : GLenum = 0x0D5B; pub static STEREO : GLenum = 0x0C33; pub static SAMPLES_ARB : GLenum = 0x80A9; #[inline(never)] pub unsafe fn GetIntegerv(pname: GLenum, params: *GLint) { glGetIntegerv(pname, params) } extern "C" { fn glGetIntegerv(pname: GLenum, params: *GLint); } }
{ let value = 0; unsafe { gl::GetIntegerv(param, &value) }; println!("OpenGL {:s}: {}", name, value); }
conditional_block
defaults.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate native; extern crate glfw; use glfw::Context; #[start] fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, main) } fn main() { let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::Visible(true)); let (window, _) = glfw.create_window(640, 480, "Defaults", glfw::Windowed) .expect("Failed to create GLFW window."); window.make_current(); let (width, height) = window.get_size(); println!("window size: ({}, {})", width, height); println!("Context version: {:s}", window.get_context_version().to_str()); println!("OpenGL forward compatible: {}", window.is_opengl_forward_compat()); println!("OpenGL debug context: {}", window.is_opengl_debug_context()); println!("OpenGL profile: {}", window.get_opengl_profile()); let gl_params = [ (gl::RED_BITS, None, "red bits" ), (gl::GREEN_BITS, None, "green bits" ), (gl::BLUE_BITS, None, "blue bits" ), (gl::ALPHA_BITS, None, "alpha bits" ), (gl::DEPTH_BITS, None, "depth bits" ), (gl::STENCIL_BITS, None, "stencil bits" ), (gl::ACCUM_RED_BITS, None, "accum red bits" ), (gl::ACCUM_GREEN_BITS, None, "accum green bits" ), (gl::ACCUM_BLUE_BITS, None, "accum blue bits" ), (gl::ACCUM_ALPHA_BITS, None, "accum alpha bits" ), (gl::STEREO, None, "stereo" ), (gl::SAMPLES_ARB, Some("GL_ARB_multisample"), "FSAA samples" ), ]; for &(param, ext, name) in gl_params.iter() { if ext.map_or(true, |s| { glfw.extension_supported(s) }) { let value = 0; unsafe { gl::GetIntegerv(param, &value) }; println!("OpenGL {:s}: {}", name, value); }; } } mod gl { extern crate libc; #[cfg(target_os = "macos")] #[link(name="OpenGL", kind="framework")] extern { } #[cfg(target_os = "linux")] #[link(name="GL")] extern { } pub type GLenum = libc::c_uint; pub type GLint = libc::c_int; pub static RED_BITS : GLenum = 0x0D52; pub static GREEN_BITS : GLenum = 0x0D53; pub static BLUE_BITS : GLenum = 0x0D54; pub static ALPHA_BITS : GLenum = 0x0D55; pub static DEPTH_BITS : GLenum = 0x0D56; pub static STENCIL_BITS : GLenum = 0x0D57; pub static ACCUM_RED_BITS : GLenum = 0x0D58; pub static ACCUM_GREEN_BITS : GLenum = 0x0D59; pub static ACCUM_BLUE_BITS : GLenum = 0x0D5A; pub static ACCUM_ALPHA_BITS : GLenum = 0x0D5B; pub static STEREO : GLenum = 0x0C33; pub static SAMPLES_ARB : GLenum = 0x80A9; #[inline(never)] pub unsafe fn GetIntegerv(pname: GLenum, params: *GLint)
extern "C" { fn glGetIntegerv(pname: GLenum, params: *GLint); } }
{ glGetIntegerv(pname, params) }
identifier_body
defaults.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate native; extern crate glfw; use glfw::Context; #[start] fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, main) } fn main() { let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::Visible(true)); let (window, _) = glfw.create_window(640, 480, "Defaults", glfw::Windowed) .expect("Failed to create GLFW window."); window.make_current(); let (width, height) = window.get_size(); println!("window size: ({}, {})", width, height); println!("Context version: {:s}", window.get_context_version().to_str()); println!("OpenGL forward compatible: {}", window.is_opengl_forward_compat()); println!("OpenGL debug context: {}", window.is_opengl_debug_context()); println!("OpenGL profile: {}", window.get_opengl_profile()); let gl_params = [ (gl::RED_BITS, None, "red bits" ), (gl::GREEN_BITS, None, "green bits" ), (gl::BLUE_BITS, None, "blue bits" ), (gl::ALPHA_BITS, None, "alpha bits" ), (gl::DEPTH_BITS, None, "depth bits" ), (gl::STENCIL_BITS, None, "stencil bits" ), (gl::ACCUM_RED_BITS, None, "accum red bits" ), (gl::ACCUM_GREEN_BITS, None, "accum green bits" ),
]; for &(param, ext, name) in gl_params.iter() { if ext.map_or(true, |s| { glfw.extension_supported(s) }) { let value = 0; unsafe { gl::GetIntegerv(param, &value) }; println!("OpenGL {:s}: {}", name, value); }; } } mod gl { extern crate libc; #[cfg(target_os = "macos")] #[link(name="OpenGL", kind="framework")] extern { } #[cfg(target_os = "linux")] #[link(name="GL")] extern { } pub type GLenum = libc::c_uint; pub type GLint = libc::c_int; pub static RED_BITS : GLenum = 0x0D52; pub static GREEN_BITS : GLenum = 0x0D53; pub static BLUE_BITS : GLenum = 0x0D54; pub static ALPHA_BITS : GLenum = 0x0D55; pub static DEPTH_BITS : GLenum = 0x0D56; pub static STENCIL_BITS : GLenum = 0x0D57; pub static ACCUM_RED_BITS : GLenum = 0x0D58; pub static ACCUM_GREEN_BITS : GLenum = 0x0D59; pub static ACCUM_BLUE_BITS : GLenum = 0x0D5A; pub static ACCUM_ALPHA_BITS : GLenum = 0x0D5B; pub static STEREO : GLenum = 0x0C33; pub static SAMPLES_ARB : GLenum = 0x80A9; #[inline(never)] pub unsafe fn GetIntegerv(pname: GLenum, params: *GLint) { glGetIntegerv(pname, params) } extern "C" { fn glGetIntegerv(pname: GLenum, params: *GLint); } }
(gl::ACCUM_BLUE_BITS, None, "accum blue bits" ), (gl::ACCUM_ALPHA_BITS, None, "accum alpha bits" ), (gl::STEREO, None, "stereo" ), (gl::SAMPLES_ARB, Some("GL_ARB_multisample"), "FSAA samples" ),
random_line_split
defaults.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate native; extern crate glfw; use glfw::Context; #[start] fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, main) } fn
() { let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::Visible(true)); let (window, _) = glfw.create_window(640, 480, "Defaults", glfw::Windowed) .expect("Failed to create GLFW window."); window.make_current(); let (width, height) = window.get_size(); println!("window size: ({}, {})", width, height); println!("Context version: {:s}", window.get_context_version().to_str()); println!("OpenGL forward compatible: {}", window.is_opengl_forward_compat()); println!("OpenGL debug context: {}", window.is_opengl_debug_context()); println!("OpenGL profile: {}", window.get_opengl_profile()); let gl_params = [ (gl::RED_BITS, None, "red bits" ), (gl::GREEN_BITS, None, "green bits" ), (gl::BLUE_BITS, None, "blue bits" ), (gl::ALPHA_BITS, None, "alpha bits" ), (gl::DEPTH_BITS, None, "depth bits" ), (gl::STENCIL_BITS, None, "stencil bits" ), (gl::ACCUM_RED_BITS, None, "accum red bits" ), (gl::ACCUM_GREEN_BITS, None, "accum green bits" ), (gl::ACCUM_BLUE_BITS, None, "accum blue bits" ), (gl::ACCUM_ALPHA_BITS, None, "accum alpha bits" ), (gl::STEREO, None, "stereo" ), (gl::SAMPLES_ARB, Some("GL_ARB_multisample"), "FSAA samples" ), ]; for &(param, ext, name) in gl_params.iter() { if ext.map_or(true, |s| { glfw.extension_supported(s) }) { let value = 0; unsafe { gl::GetIntegerv(param, &value) }; println!("OpenGL {:s}: {}", name, value); }; } } mod gl { extern crate libc; #[cfg(target_os = "macos")] #[link(name="OpenGL", kind="framework")] extern { } #[cfg(target_os = "linux")] #[link(name="GL")] extern { } pub type GLenum = libc::c_uint; pub type GLint = libc::c_int; pub static RED_BITS : GLenum = 0x0D52; pub static GREEN_BITS : GLenum = 0x0D53; pub static BLUE_BITS : GLenum = 0x0D54; pub static ALPHA_BITS : GLenum = 0x0D55; pub static DEPTH_BITS : GLenum = 0x0D56; pub static STENCIL_BITS : GLenum = 0x0D57; pub static ACCUM_RED_BITS : GLenum = 0x0D58; pub static ACCUM_GREEN_BITS : GLenum = 0x0D59; pub static ACCUM_BLUE_BITS : GLenum = 0x0D5A; pub static ACCUM_ALPHA_BITS : GLenum = 0x0D5B; pub static STEREO : GLenum = 0x0C33; pub static SAMPLES_ARB : GLenum = 0x80A9; #[inline(never)] pub unsafe fn GetIntegerv(pname: GLenum, params: *GLint) { glGetIntegerv(pname, params) } extern "C" { fn glGetIntegerv(pname: GLenum, params: *GLint); } }
main
identifier_name
target.rs
// Copyright 2014 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Render target specification. // TODO: Really tighten up the terminology here. /// A depth value, specifying which plane to select out of a 3D texture. pub type Layer = u16; /// Mipmap level to select in a texture. pub type Level = u8;
/// A single depth value from a depth buffer. pub type Depth = f32; /// A single value from a stencil stencstencil buffer. pub type Stencil = u8; /// A screen space rectangle #[allow(missing_docs)] #[derive(Clone, Copy, Debug, Hash, PartialEq, PartialOrd)] #[cfg_attr(feature="serialize", derive(Serialize, Deserialize))] pub struct Rect { pub x: u16, pub y: u16, pub w: u16, pub h: u16, } /// A color with floating-point components. pub type ColorValue = [f32; 4]; bitflags!( /// Mirroring flags, used for blitting #[cfg_attr(feature="serialize", derive(Serialize, Deserialize))] pub flags Mirror: u8 { #[allow(missing_docs)] const MIRROR_X = 0x01, #[allow(missing_docs)] const MIRROR_Y = 0x02, } );
random_line_split
target.rs
// Copyright 2014 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Render target specification. // TODO: Really tighten up the terminology here. /// A depth value, specifying which plane to select out of a 3D texture. pub type Layer = u16; /// Mipmap level to select in a texture. pub type Level = u8; /// A single depth value from a depth buffer. pub type Depth = f32; /// A single value from a stencil stencstencil buffer. pub type Stencil = u8; /// A screen space rectangle #[allow(missing_docs)] #[derive(Clone, Copy, Debug, Hash, PartialEq, PartialOrd)] #[cfg_attr(feature="serialize", derive(Serialize, Deserialize))] pub struct
{ pub x: u16, pub y: u16, pub w: u16, pub h: u16, } /// A color with floating-point components. pub type ColorValue = [f32; 4]; bitflags!( /// Mirroring flags, used for blitting #[cfg_attr(feature="serialize", derive(Serialize, Deserialize))] pub flags Mirror: u8 { #[allow(missing_docs)] const MIRROR_X = 0x01, #[allow(missing_docs)] const MIRROR_Y = 0x02, } );
Rect
identifier_name
question.rs
use std::str; pub struct Question { pub name: Vec<String>, pub rrtype: u16, pub class: u16, } impl Question { pub fn unpack(buffer: &[u8], offset: usize) -> (Question, usize) { let mut name = Vec::new(); let mut offset = offset; loop { let size: usize = buffer[offset] as usize; offset += 1; if size == 0
name.push( str::from_utf8(&buffer[offset..offset + size]) .unwrap() .to_string(), ); offset += size; } let rrtype: u16 = u16::from(buffer[offset]) << 8 | u16::from(buffer[offset + 1]); offset += 2; let class: u16 = u16::from(buffer[offset]) << 8 | u16::from(buffer[offset + 1]); offset += 2; ( Question { name, rrtype, class, }, offset, ) } pub fn pack(&self, buffer: &mut [u8], offset: usize) -> usize { let mut offset: usize = offset; for part in self.name.iter() { buffer[offset] = part.len() as u8; offset += 1; for byte in part.to_owned().into_bytes().iter() { buffer[offset] = *byte; offset += 1; } } buffer[offset] = 0 as u8; offset += 1; buffer[offset] = (self.rrtype >> 8) as u8; buffer[offset + 1] = self.rrtype as u8; offset += 2; buffer[offset] = (self.class >> 8) as u8; buffer[offset + 1] = self.class as u8; offset += 2; offset } }
{ break; }
conditional_block
question.rs
use std::str; pub struct Question { pub name: Vec<String>, pub rrtype: u16, pub class: u16, } impl Question { pub fn unpack(buffer: &[u8], offset: usize) -> (Question, usize) { let mut name = Vec::new(); let mut offset = offset; loop { let size: usize = buffer[offset] as usize; offset += 1; if size == 0 { break; } name.push( str::from_utf8(&buffer[offset..offset + size]) .unwrap() .to_string(), ); offset += size; } let rrtype: u16 = u16::from(buffer[offset]) << 8 | u16::from(buffer[offset + 1]); offset += 2; let class: u16 = u16::from(buffer[offset]) << 8 | u16::from(buffer[offset + 1]); offset += 2; ( Question { name, rrtype, class, }, offset, ) } pub fn pack(&self, buffer: &mut [u8], offset: usize) -> usize { let mut offset: usize = offset; for part in self.name.iter() {
buffer[offset] = *byte; offset += 1; } } buffer[offset] = 0 as u8; offset += 1; buffer[offset] = (self.rrtype >> 8) as u8; buffer[offset + 1] = self.rrtype as u8; offset += 2; buffer[offset] = (self.class >> 8) as u8; buffer[offset + 1] = self.class as u8; offset += 2; offset } }
buffer[offset] = part.len() as u8; offset += 1; for byte in part.to_owned().into_bytes().iter() {
random_line_split
question.rs
use std::str; pub struct Question { pub name: Vec<String>, pub rrtype: u16, pub class: u16, } impl Question { pub fn unpack(buffer: &[u8], offset: usize) -> (Question, usize) { let mut name = Vec::new(); let mut offset = offset; loop { let size: usize = buffer[offset] as usize; offset += 1; if size == 0 { break; } name.push( str::from_utf8(&buffer[offset..offset + size]) .unwrap() .to_string(), ); offset += size; } let rrtype: u16 = u16::from(buffer[offset]) << 8 | u16::from(buffer[offset + 1]); offset += 2; let class: u16 = u16::from(buffer[offset]) << 8 | u16::from(buffer[offset + 1]); offset += 2; ( Question { name, rrtype, class, }, offset, ) } pub fn
(&self, buffer: &mut [u8], offset: usize) -> usize { let mut offset: usize = offset; for part in self.name.iter() { buffer[offset] = part.len() as u8; offset += 1; for byte in part.to_owned().into_bytes().iter() { buffer[offset] = *byte; offset += 1; } } buffer[offset] = 0 as u8; offset += 1; buffer[offset] = (self.rrtype >> 8) as u8; buffer[offset + 1] = self.rrtype as u8; offset += 2; buffer[offset] = (self.class >> 8) as u8; buffer[offset + 1] = self.class as u8; offset += 2; offset } }
pack
identifier_name
from_geo.rs
extern crate geos; extern crate geo_types; extern crate failure; use failure::Error; fn fun() -> Result<(), Error> { use geos::GGeom; use geo_types::{LineString, Polygon, Coordinate}; use geos::from_geo::TryInto; let exterior = LineString(vec![ Coordinate::from((0., 0.)), Coordinate::from((0., 1.)), Coordinate::from((1., 1.)), Coordinate::from((1., 0.)), Coordinate::from((0., 0.)), ]); let interiors = vec![ LineString(vec![ Coordinate::from((0.1, 0.1)), Coordinate::from((0.1, 0.9)), Coordinate::from((0.9, 0.9)), Coordinate::from((0.9, 0.1)),
assert_eq!(p.exterior(), &exterior); assert_eq!(p.interiors(), interiors.as_slice()); let geom: GGeom = (&p).try_into()?; assert!(geom.contains(&geom)?); assert!(!geom.contains(&(&exterior).try_into()?)?); assert!(geom.covers(&(&exterior).try_into()?)?); assert!(geom.touches(&(&exterior).try_into()?)?); Ok(()) } fn main() { fun().unwrap(); }
Coordinate::from((0.1, 0.1)), ]), ]; let p = Polygon::new(exterior.clone(), interiors.clone());
random_line_split
from_geo.rs
extern crate geos; extern crate geo_types; extern crate failure; use failure::Error; fn fun() -> Result<(), Error> { use geos::GGeom; use geo_types::{LineString, Polygon, Coordinate}; use geos::from_geo::TryInto; let exterior = LineString(vec![ Coordinate::from((0., 0.)), Coordinate::from((0., 1.)), Coordinate::from((1., 1.)), Coordinate::from((1., 0.)), Coordinate::from((0., 0.)), ]); let interiors = vec![ LineString(vec![ Coordinate::from((0.1, 0.1)), Coordinate::from((0.1, 0.9)), Coordinate::from((0.9, 0.9)), Coordinate::from((0.9, 0.1)), Coordinate::from((0.1, 0.1)), ]), ]; let p = Polygon::new(exterior.clone(), interiors.clone()); assert_eq!(p.exterior(), &exterior); assert_eq!(p.interiors(), interiors.as_slice()); let geom: GGeom = (&p).try_into()?; assert!(geom.contains(&geom)?); assert!(!geom.contains(&(&exterior).try_into()?)?); assert!(geom.covers(&(&exterior).try_into()?)?); assert!(geom.touches(&(&exterior).try_into()?)?); Ok(()) } fn
() { fun().unwrap(); }
main
identifier_name
from_geo.rs
extern crate geos; extern crate geo_types; extern crate failure; use failure::Error; fn fun() -> Result<(), Error> { use geos::GGeom; use geo_types::{LineString, Polygon, Coordinate}; use geos::from_geo::TryInto; let exterior = LineString(vec![ Coordinate::from((0., 0.)), Coordinate::from((0., 1.)), Coordinate::from((1., 1.)), Coordinate::from((1., 0.)), Coordinate::from((0., 0.)), ]); let interiors = vec![ LineString(vec![ Coordinate::from((0.1, 0.1)), Coordinate::from((0.1, 0.9)), Coordinate::from((0.9, 0.9)), Coordinate::from((0.9, 0.1)), Coordinate::from((0.1, 0.1)), ]), ]; let p = Polygon::new(exterior.clone(), interiors.clone()); assert_eq!(p.exterior(), &exterior); assert_eq!(p.interiors(), interiors.as_slice()); let geom: GGeom = (&p).try_into()?; assert!(geom.contains(&geom)?); assert!(!geom.contains(&(&exterior).try_into()?)?); assert!(geom.covers(&(&exterior).try_into()?)?); assert!(geom.touches(&(&exterior).try_into()?)?); Ok(()) } fn main()
{ fun().unwrap(); }
identifier_body
problem_04.rs
// Copyright 2014 Mitchell Kember. Subject to the MIT License. // Project Euler: Problem 4 // Largest palindrome product fn is_palindrome(n: int) -> bool { let size = (n as f64).log10().ceil() as int; let mut num = n; let mut digits = Vec::with_capacity((size/2) as uint); let mut i = 0; // Push the first half of the digits into the vector. while i < size/2 { digits.push(num % 10); num /= 10; i += 1; } i -= 1; // Skip the middle digit when there are an odd number of digits. if size % 2!= 0 { num /= 10; } // Verify that the second half of the digits matches the first. while i >= 0 { let d = num % 10; if d!= *digits.get(i as uint) { return false; } num /= 10; i -= 1; } true } pub fn solve() -> int { let mut largest = 0; for a in range(100, 1000) { for b in range(100, 1000) { let c = a * b; if c > largest && is_palindrome(c)
} } largest }
{ largest = c; }
conditional_block
problem_04.rs
// Copyright 2014 Mitchell Kember. Subject to the MIT License. // Project Euler: Problem 4 // Largest palindrome product fn is_palindrome(n: int) -> bool { let size = (n as f64).log10().ceil() as int; let mut num = n; let mut digits = Vec::with_capacity((size/2) as uint); let mut i = 0; // Push the first half of the digits into the vector. while i < size/2 { digits.push(num % 10);
} i -= 1; // Skip the middle digit when there are an odd number of digits. if size % 2!= 0 { num /= 10; } // Verify that the second half of the digits matches the first. while i >= 0 { let d = num % 10; if d!= *digits.get(i as uint) { return false; } num /= 10; i -= 1; } true } pub fn solve() -> int { let mut largest = 0; for a in range(100, 1000) { for b in range(100, 1000) { let c = a * b; if c > largest && is_palindrome(c) { largest = c; } } } largest }
num /= 10; i += 1;
random_line_split
problem_04.rs
// Copyright 2014 Mitchell Kember. Subject to the MIT License. // Project Euler: Problem 4 // Largest palindrome product fn
(n: int) -> bool { let size = (n as f64).log10().ceil() as int; let mut num = n; let mut digits = Vec::with_capacity((size/2) as uint); let mut i = 0; // Push the first half of the digits into the vector. while i < size/2 { digits.push(num % 10); num /= 10; i += 1; } i -= 1; // Skip the middle digit when there are an odd number of digits. if size % 2!= 0 { num /= 10; } // Verify that the second half of the digits matches the first. while i >= 0 { let d = num % 10; if d!= *digits.get(i as uint) { return false; } num /= 10; i -= 1; } true } pub fn solve() -> int { let mut largest = 0; for a in range(100, 1000) { for b in range(100, 1000) { let c = a * b; if c > largest && is_palindrome(c) { largest = c; } } } largest }
is_palindrome
identifier_name
problem_04.rs
// Copyright 2014 Mitchell Kember. Subject to the MIT License. // Project Euler: Problem 4 // Largest palindrome product fn is_palindrome(n: int) -> bool
return false; } num /= 10; i -= 1; } true } pub fn solve() -> int { let mut largest = 0; for a in range(100, 1000) { for b in range(100, 1000) { let c = a * b; if c > largest && is_palindrome(c) { largest = c; } } } largest }
{ let size = (n as f64).log10().ceil() as int; let mut num = n; let mut digits = Vec::with_capacity((size/2) as uint); let mut i = 0; // Push the first half of the digits into the vector. while i < size/2 { digits.push(num % 10); num /= 10; i += 1; } i -= 1; // Skip the middle digit when there are an odd number of digits. if size % 2 != 0 { num /= 10; } // Verify that the second half of the digits matches the first. while i >= 0 { let d = num % 10; if d != *digits.get(i as uint) {
identifier_body
enum4.rs
// enum4.rs #[derive(Debug)] enum Value { Number(f64), Str(String), Bool(bool), Arr(Vec<Value>) } use std::fmt; impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use Value::*; match *self { Number(n) => write!(f,"{} ",n), Str(ref s) => write!(f,"{} ",s), Bool(b) => write!(f,"{} ",b), Arr(ref arr) => { write!(f,"(")?; for v in arr.iter() { v.fmt(f)?; } write!(f,")") } } } } struct Builder { stack: Vec<Vec<Value>>, current: Vec<Value> } impl Builder { fn new() -> Builder { Builder { stack: Vec::new(), current: Vec::new() } } fn push(&mut self, v: Value) -> &mut Builder { self.current.push(v); self } fn s(&mut self, s: &str) -> &mut Builder
fn b(&mut self, v: bool) -> &mut Builder { self.push(Value::Bool(v)) } fn n(&mut self, v: f64) -> &mut Builder { self.push(Value::Number(v)) } fn extract_current(&mut self, arr: Vec<Value>) -> Vec<Value> { let mut current = arr; std::mem::swap(&mut current, &mut self.current); current } fn value(&mut self) -> Value { Value::Arr(self.extract_current(Vec::new())) } fn open(&mut self) -> &mut Builder { let current = self.extract_current(Vec::new()); self.stack.push(current); self } fn close(&mut self) -> &mut Builder { let last_current = self.stack.pop().expect("stack empty"); let current = self.extract_current(last_current); self.current.push(Value::Arr(current)); self } } fn main() { // building the hard way use Value::*; let s = "hello".to_string(); let v = vec![Number(1.0),Bool(false),Str(s)]; let arr = Arr(v); let res = Arr(vec![Number(2.0),arr]); //*/ println!("{:?}",res); println!("{}",res); let res = Builder::new().open() .s("one") .open() .s("two") .b(true) .open() .s("four") .n(1.0) .close() .close().close().value(); println!("{:?}",res); println!("{}",res); }
{ self.push(Value::Str(s.to_string())) }
identifier_body
enum4.rs
// enum4.rs #[derive(Debug)] enum Value { Number(f64), Str(String), Bool(bool), Arr(Vec<Value>) } use std::fmt; impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use Value::*; match *self { Number(n) => write!(f,"{} ",n), Str(ref s) => write!(f,"{} ",s), Bool(b) => write!(f,"{} ",b), Arr(ref arr) => { write!(f,"(")?; for v in arr.iter() { v.fmt(f)?; } write!(f,")") } } } } struct Builder { stack: Vec<Vec<Value>>, current: Vec<Value> } impl Builder { fn new() -> Builder { Builder { stack: Vec::new(), current: Vec::new() } } fn push(&mut self, v: Value) -> &mut Builder { self.current.push(v);
self.push(Value::Str(s.to_string())) } fn b(&mut self, v: bool) -> &mut Builder { self.push(Value::Bool(v)) } fn n(&mut self, v: f64) -> &mut Builder { self.push(Value::Number(v)) } fn extract_current(&mut self, arr: Vec<Value>) -> Vec<Value> { let mut current = arr; std::mem::swap(&mut current, &mut self.current); current } fn value(&mut self) -> Value { Value::Arr(self.extract_current(Vec::new())) } fn open(&mut self) -> &mut Builder { let current = self.extract_current(Vec::new()); self.stack.push(current); self } fn close(&mut self) -> &mut Builder { let last_current = self.stack.pop().expect("stack empty"); let current = self.extract_current(last_current); self.current.push(Value::Arr(current)); self } } fn main() { // building the hard way use Value::*; let s = "hello".to_string(); let v = vec![Number(1.0),Bool(false),Str(s)]; let arr = Arr(v); let res = Arr(vec![Number(2.0),arr]); //*/ println!("{:?}",res); println!("{}",res); let res = Builder::new().open() .s("one") .open() .s("two") .b(true) .open() .s("four") .n(1.0) .close() .close().close().value(); println!("{:?}",res); println!("{}",res); }
self } fn s(&mut self, s: &str) -> &mut Builder {
random_line_split
enum4.rs
// enum4.rs #[derive(Debug)] enum Value { Number(f64), Str(String), Bool(bool), Arr(Vec<Value>) } use std::fmt; impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use Value::*; match *self { Number(n) => write!(f,"{} ",n), Str(ref s) => write!(f,"{} ",s), Bool(b) => write!(f,"{} ",b), Arr(ref arr) => { write!(f,"(")?; for v in arr.iter() { v.fmt(f)?; } write!(f,")") } } } } struct Builder { stack: Vec<Vec<Value>>, current: Vec<Value> } impl Builder { fn new() -> Builder { Builder { stack: Vec::new(), current: Vec::new() } } fn push(&mut self, v: Value) -> &mut Builder { self.current.push(v); self } fn
(&mut self, s: &str) -> &mut Builder { self.push(Value::Str(s.to_string())) } fn b(&mut self, v: bool) -> &mut Builder { self.push(Value::Bool(v)) } fn n(&mut self, v: f64) -> &mut Builder { self.push(Value::Number(v)) } fn extract_current(&mut self, arr: Vec<Value>) -> Vec<Value> { let mut current = arr; std::mem::swap(&mut current, &mut self.current); current } fn value(&mut self) -> Value { Value::Arr(self.extract_current(Vec::new())) } fn open(&mut self) -> &mut Builder { let current = self.extract_current(Vec::new()); self.stack.push(current); self } fn close(&mut self) -> &mut Builder { let last_current = self.stack.pop().expect("stack empty"); let current = self.extract_current(last_current); self.current.push(Value::Arr(current)); self } } fn main() { // building the hard way use Value::*; let s = "hello".to_string(); let v = vec![Number(1.0),Bool(false),Str(s)]; let arr = Arr(v); let res = Arr(vec![Number(2.0),arr]); //*/ println!("{:?}",res); println!("{}",res); let res = Builder::new().open() .s("one") .open() .s("two") .b(true) .open() .s("four") .n(1.0) .close() .close().close().value(); println!("{:?}",res); println!("{}",res); }
s
identifier_name
lisp_attr.rs
use std::str::FromStr; use syn; use synom; use function::{Function, LispFnType}; /// Arguments of the lisp_fn attribute. pub struct LispFnArgs { /// Desired Lisp name of the function. /// If not given, derived as the Rust name with "_" -> "-". pub name: String, /// Desired C name of the related statics (with F and S appended). /// If not given, same as the Rust name. pub c_name: String, /// Minimum number of required arguments. /// If not given, all arguments are required for normal functions, /// and no arguments are required for MANY functions. pub min: i16, /// The interactive specification. This may be a normal prompt /// string, such as `"bBuffer: "` or an elisp form as a string. /// If the function is not interactive, this should be None. pub intspec: Option<String>, } pub fn parse(input: &str, function: &Function) -> Result<LispFnArgs, &'static str>
fn parse_kv(kv_list: Vec<(syn::Ident, syn::StrLit)>, function: &Function) -> LispFnArgs { let mut name = None; let mut c_name = None; let mut intspec = None; let mut min = match function.fntype { LispFnType::Many => 0, LispFnType::Normal(n) => n, }; for (ident, string) in kv_list { match ident.as_ref() { "name" => name = Some(string.value), "c_name" => c_name = Some(string.value), "min" => min = i16::from_str(&string.value).unwrap(), "intspec" => intspec = Some(string.value), _ => (), // TODO: throw a warning? } } LispFnArgs { name: name.unwrap_or_else(|| function.name.to_string().replace("_", "-")), c_name: c_name.unwrap_or_else(|| function.name.to_string()), min, intspec, } } named!(parse_arguments -> Vec<(syn::Ident, syn::StrLit)>, opt_vec!( do_parse!( punct!("(") >> args: separated_list!(punct!(","), key_value) >> punct!(")") >> (args) ) ) ); named!(key_value -> (syn::Ident, syn::StrLit), do_parse!( key: call!(syn::parse::ident) >> option!(alt!(punct!(" ") | punct!("\t") | punct!("\n"))) >> punct!("=") >> option!(alt!(punct!(" ") | punct!("\t") | punct!("\n"))) >> val: call!(syn::parse::string) >> (key, val) ) ); #[test] fn parse_args_str() { let args = parse_arguments(r#"(name = "foo", min = "0")"#).expect("cannot parse lisp_fn attributes"); // name = "foo" assert_eq!(format!("{}", args[0].0), "name"); assert_eq!(format!("{}", args[0].1.value), "foo"); // min = "0" assert_eq!(format!("{}", args[1].0), "min"); assert_eq!(format!("{}", args[1].1.value), "0"); }
{ let kv = match parse_arguments(input) { synom::IResult::Done(_, o) => o, synom::IResult::Error => return Err("failed to parse `lisp_fn` arguments"), }; Ok(parse_kv(kv, function)) }
identifier_body
lisp_attr.rs
use std::str::FromStr; use syn; use synom; use function::{Function, LispFnType}; /// Arguments of the lisp_fn attribute. pub struct LispFnArgs { /// Desired Lisp name of the function. /// If not given, derived as the Rust name with "_" -> "-". pub name: String, /// Desired C name of the related statics (with F and S appended). /// If not given, same as the Rust name. pub c_name: String, /// Minimum number of required arguments. /// If not given, all arguments are required for normal functions, /// and no arguments are required for MANY functions. pub min: i16, /// The interactive specification. This may be a normal prompt /// string, such as `"bBuffer: "` or an elisp form as a string. /// If the function is not interactive, this should be None. pub intspec: Option<String>, } pub fn parse(input: &str, function: &Function) -> Result<LispFnArgs, &'static str> { let kv = match parse_arguments(input) { synom::IResult::Done(_, o) => o, synom::IResult::Error => return Err("failed to parse `lisp_fn` arguments"), }; Ok(parse_kv(kv, function)) } fn parse_kv(kv_list: Vec<(syn::Ident, syn::StrLit)>, function: &Function) -> LispFnArgs { let mut name = None; let mut c_name = None; let mut intspec = None; let mut min = match function.fntype { LispFnType::Many => 0, LispFnType::Normal(n) => n, }; for (ident, string) in kv_list { match ident.as_ref() { "name" => name = Some(string.value), "c_name" => c_name = Some(string.value), "min" => min = i16::from_str(&string.value).unwrap(), "intspec" => intspec = Some(string.value), _ => (), // TODO: throw a warning? }
c_name: c_name.unwrap_or_else(|| function.name.to_string()), min, intspec, } } named!(parse_arguments -> Vec<(syn::Ident, syn::StrLit)>, opt_vec!( do_parse!( punct!("(") >> args: separated_list!(punct!(","), key_value) >> punct!(")") >> (args) ) ) ); named!(key_value -> (syn::Ident, syn::StrLit), do_parse!( key: call!(syn::parse::ident) >> option!(alt!(punct!(" ") | punct!("\t") | punct!("\n"))) >> punct!("=") >> option!(alt!(punct!(" ") | punct!("\t") | punct!("\n"))) >> val: call!(syn::parse::string) >> (key, val) ) ); #[test] fn parse_args_str() { let args = parse_arguments(r#"(name = "foo", min = "0")"#).expect("cannot parse lisp_fn attributes"); // name = "foo" assert_eq!(format!("{}", args[0].0), "name"); assert_eq!(format!("{}", args[0].1.value), "foo"); // min = "0" assert_eq!(format!("{}", args[1].0), "min"); assert_eq!(format!("{}", args[1].1.value), "0"); }
} LispFnArgs { name: name.unwrap_or_else(|| function.name.to_string().replace("_", "-")),
random_line_split
lisp_attr.rs
use std::str::FromStr; use syn; use synom; use function::{Function, LispFnType}; /// Arguments of the lisp_fn attribute. pub struct LispFnArgs { /// Desired Lisp name of the function. /// If not given, derived as the Rust name with "_" -> "-". pub name: String, /// Desired C name of the related statics (with F and S appended). /// If not given, same as the Rust name. pub c_name: String, /// Minimum number of required arguments. /// If not given, all arguments are required for normal functions, /// and no arguments are required for MANY functions. pub min: i16, /// The interactive specification. This may be a normal prompt /// string, such as `"bBuffer: "` or an elisp form as a string. /// If the function is not interactive, this should be None. pub intspec: Option<String>, } pub fn
(input: &str, function: &Function) -> Result<LispFnArgs, &'static str> { let kv = match parse_arguments(input) { synom::IResult::Done(_, o) => o, synom::IResult::Error => return Err("failed to parse `lisp_fn` arguments"), }; Ok(parse_kv(kv, function)) } fn parse_kv(kv_list: Vec<(syn::Ident, syn::StrLit)>, function: &Function) -> LispFnArgs { let mut name = None; let mut c_name = None; let mut intspec = None; let mut min = match function.fntype { LispFnType::Many => 0, LispFnType::Normal(n) => n, }; for (ident, string) in kv_list { match ident.as_ref() { "name" => name = Some(string.value), "c_name" => c_name = Some(string.value), "min" => min = i16::from_str(&string.value).unwrap(), "intspec" => intspec = Some(string.value), _ => (), // TODO: throw a warning? } } LispFnArgs { name: name.unwrap_or_else(|| function.name.to_string().replace("_", "-")), c_name: c_name.unwrap_or_else(|| function.name.to_string()), min, intspec, } } named!(parse_arguments -> Vec<(syn::Ident, syn::StrLit)>, opt_vec!( do_parse!( punct!("(") >> args: separated_list!(punct!(","), key_value) >> punct!(")") >> (args) ) ) ); named!(key_value -> (syn::Ident, syn::StrLit), do_parse!( key: call!(syn::parse::ident) >> option!(alt!(punct!(" ") | punct!("\t") | punct!("\n"))) >> punct!("=") >> option!(alt!(punct!(" ") | punct!("\t") | punct!("\n"))) >> val: call!(syn::parse::string) >> (key, val) ) ); #[test] fn parse_args_str() { let args = parse_arguments(r#"(name = "foo", min = "0")"#).expect("cannot parse lisp_fn attributes"); // name = "foo" assert_eq!(format!("{}", args[0].0), "name"); assert_eq!(format!("{}", args[0].1.value), "foo"); // min = "0" assert_eq!(format!("{}", args[1].0), "min"); assert_eq!(format!("{}", args[1].1.value), "0"); }
parse
identifier_name
mod.rs
/*! Contains everything related to vertex buffers. The main struct is the `VertexBuffer`, which represents a buffer in the video memory, containing a list of vertices. In order to create a vertex buffer, you must first create a struct that represents each vertex, and implement the `glium::vertex::Vertex` trait on it. The `implement_vertex!` macro helps you with that. ``` # #[macro_use] # extern crate glium; # extern crate glutin; # fn main() { #[derive(Copy)] struct Vertex { position: [f32; 3], texcoords: [f32; 2], } implement_vertex!(Vertex, position, texcoords); # } ``` Next, build a `Vec` of the vertices that you want to upload, and pass it to `VertexBuffer::new`. ```no_run # let display: glium::Display = unsafe { ::std::mem::uninitialized() }; # #[derive(Copy)] # struct Vertex { # position: [f32; 3], # texcoords: [f32; 2], # } # impl glium::vertex::Vertex for Vertex { # fn build_bindings() -> glium::vertex::VertexFormat { # unimplemented!() } # } let data = vec![ Vertex { position: [0.0, 0.0, 0.4], texcoords: [0.0, 1.0] }, Vertex { position: [12.0, 4.5, -1.8], texcoords: [1.0, 0.5] }, Vertex { position: [-7.124, 0.1, 0.0], texcoords: [0.0, 0.4] }, ]; let vertex_buffer = glium::vertex::VertexBuffer::new(&display, data); ``` */ use std::marker::MarkerTrait; use std::sync::mpsc::Sender; use sync::LinearSyncFence; use std::iter::Chain; use std::option::IntoIter; pub use self::buffer::{VertexBuffer, VertexBufferAny, Mapping}; pub use self::buffer::{VertexBufferSlice, VertexBufferAnySlice}; pub use self::format::{AttributeType, VertexFormat}; pub use self::per_instance::{PerInstanceAttributesBuffer, PerInstanceAttributesBufferAny}; pub use self::per_instance::Mapping as PerInstanceAttributesBufferMapping; mod buffer; mod format; mod per_instance; /// Describes the source to use for the vertices when drawing. #[derive(Clone)] pub enum
<'a> { /// A buffer uploaded in the video memory. /// /// If the second parameter is `Some`, then a fence *must* be sent with this sender for /// when the buffer stops being used. /// /// The third and fourth parameters are the offset and length of the buffer. VertexBuffer(&'a VertexBufferAny, Option<Sender<LinearSyncFence>>, usize, usize), /// A buffer uploaded in the video memory. /// /// If the second parameter is `Some`, then a fence *must* be sent with this sender for /// when the buffer stops being used. PerInstanceBuffer(&'a PerInstanceAttributesBufferAny, Option<Sender<LinearSyncFence>>), } /// Objects that can be used as vertex sources. pub trait IntoVerticesSource<'a> { /// Builds the `VerticesSource`. fn into_vertices_source(self) -> VerticesSource<'a>; } impl<'a> IntoVerticesSource<'a> for VerticesSource<'a> { fn into_vertices_source(self) -> VerticesSource<'a> { self } } /// Objects that describe multiple vertex sources. pub trait MultiVerticesSource<'a> { type Iterator: Iterator<Item = VerticesSource<'a>>; /// Iterates over the `VerticesSource`. fn iter(self) -> Self::Iterator; } impl<'a, T> MultiVerticesSource<'a> for T where T: IntoVerticesSource<'a> { type Iterator = IntoIter<VerticesSource<'a>>; fn iter(self) -> IntoIter<VerticesSource<'a>> { Some(self.into_vertices_source()).into_iter() } } macro_rules! impl_for_tuple { ($t:ident) => ( impl<'a, $t> MultiVerticesSource<'a> for ($t,) where $t: IntoVerticesSource<'a> { type Iterator = IntoIter<VerticesSource<'a>>; fn iter(self) -> IntoIter<VerticesSource<'a>> { Some(self.0.into_vertices_source()).into_iter() } } ); ($t1:ident, $t2:ident) => ( #[allow(non_snake_case)] impl<'a, $t1, $t2> MultiVerticesSource<'a> for ($t1, $t2) where $t1: IntoVerticesSource<'a>, $t2: IntoVerticesSource<'a> { type Iterator = Chain<<($t1,) as MultiVerticesSource<'a>>::Iterator, <($t2,) as MultiVerticesSource<'a>>::Iterator>; fn iter(self) -> Chain<<($t1,) as MultiVerticesSource<'a>>::Iterator, <($t2,) as MultiVerticesSource<'a>>::Iterator> { let ($t1, $t2) = self; Some($t1.into_vertices_source()).into_iter().chain(($t2,).iter()) } } impl_for_tuple!($t2); ); ($t1:ident, $($t2:ident),+) => ( #[allow(non_snake_case)] impl<'a, $t1, $($t2),+> MultiVerticesSource<'a> for ($t1, $($t2),+) where $t1: IntoVerticesSource<'a>, $($t2: IntoVerticesSource<'a>),+ { type Iterator = Chain<<($t1,) as MultiVerticesSource<'a>>::Iterator, <($($t2),+) as MultiVerticesSource<'a>>::Iterator>; fn iter(self) -> Chain<<($t1,) as MultiVerticesSource<'a>>::Iterator, <($($t2),+) as MultiVerticesSource<'a>>::Iterator> { let ($t1, $($t2),+) = self; Some($t1.into_vertices_source()).into_iter().chain(($($t2),+).iter()) } } impl_for_tuple!($($t2),+); ); } impl_for_tuple!(A, B, C, D, E, F, G); /// Trait for structures that represent a vertex. /// /// Instead of implementing this trait yourself, it is recommended to use the `implement_vertex!` /// macro instead. // TODO: this should be `unsafe`, but that would break the syntax extension pub trait Vertex: Copy + MarkerTrait { /// Builds the `VertexFormat` representing the layout of this element. fn build_bindings() -> VertexFormat; } /// Trait for types that can be used as vertex attributes. pub unsafe trait Attribute: MarkerTrait { /// Get the type of data. fn get_type() -> AttributeType; }
VerticesSource
identifier_name
mod.rs
/*! Contains everything related to vertex buffers. The main struct is the `VertexBuffer`, which represents a buffer in the video memory, containing a list of vertices. In order to create a vertex buffer, you must first create a struct that represents each vertex, and implement the `glium::vertex::Vertex` trait on it. The `implement_vertex!` macro helps you with that. ``` # #[macro_use] # extern crate glium; # extern crate glutin; # fn main() { #[derive(Copy)] struct Vertex { position: [f32; 3], texcoords: [f32; 2], } implement_vertex!(Vertex, position, texcoords); # } ``` Next, build a `Vec` of the vertices that you want to upload, and pass it to `VertexBuffer::new`. ```no_run # let display: glium::Display = unsafe { ::std::mem::uninitialized() }; # #[derive(Copy)] # struct Vertex { # position: [f32; 3], # texcoords: [f32; 2], # } # impl glium::vertex::Vertex for Vertex { # fn build_bindings() -> glium::vertex::VertexFormat { # unimplemented!() } # } let data = vec![ Vertex { position: [0.0, 0.0, 0.4], texcoords: [0.0, 1.0] }, Vertex { position: [12.0, 4.5, -1.8], texcoords: [1.0, 0.5] }, Vertex { position: [-7.124, 0.1, 0.0], texcoords: [0.0, 0.4] }, ]; let vertex_buffer = glium::vertex::VertexBuffer::new(&display, data); ``` */ use std::marker::MarkerTrait; use std::sync::mpsc::Sender; use sync::LinearSyncFence;
use std::iter::Chain; use std::option::IntoIter; pub use self::buffer::{VertexBuffer, VertexBufferAny, Mapping}; pub use self::buffer::{VertexBufferSlice, VertexBufferAnySlice}; pub use self::format::{AttributeType, VertexFormat}; pub use self::per_instance::{PerInstanceAttributesBuffer, PerInstanceAttributesBufferAny}; pub use self::per_instance::Mapping as PerInstanceAttributesBufferMapping; mod buffer; mod format; mod per_instance; /// Describes the source to use for the vertices when drawing. #[derive(Clone)] pub enum VerticesSource<'a> { /// A buffer uploaded in the video memory. /// /// If the second parameter is `Some`, then a fence *must* be sent with this sender for /// when the buffer stops being used. /// /// The third and fourth parameters are the offset and length of the buffer. VertexBuffer(&'a VertexBufferAny, Option<Sender<LinearSyncFence>>, usize, usize), /// A buffer uploaded in the video memory. /// /// If the second parameter is `Some`, then a fence *must* be sent with this sender for /// when the buffer stops being used. PerInstanceBuffer(&'a PerInstanceAttributesBufferAny, Option<Sender<LinearSyncFence>>), } /// Objects that can be used as vertex sources. pub trait IntoVerticesSource<'a> { /// Builds the `VerticesSource`. fn into_vertices_source(self) -> VerticesSource<'a>; } impl<'a> IntoVerticesSource<'a> for VerticesSource<'a> { fn into_vertices_source(self) -> VerticesSource<'a> { self } } /// Objects that describe multiple vertex sources. pub trait MultiVerticesSource<'a> { type Iterator: Iterator<Item = VerticesSource<'a>>; /// Iterates over the `VerticesSource`. fn iter(self) -> Self::Iterator; } impl<'a, T> MultiVerticesSource<'a> for T where T: IntoVerticesSource<'a> { type Iterator = IntoIter<VerticesSource<'a>>; fn iter(self) -> IntoIter<VerticesSource<'a>> { Some(self.into_vertices_source()).into_iter() } } macro_rules! impl_for_tuple { ($t:ident) => ( impl<'a, $t> MultiVerticesSource<'a> for ($t,) where $t: IntoVerticesSource<'a> { type Iterator = IntoIter<VerticesSource<'a>>; fn iter(self) -> IntoIter<VerticesSource<'a>> { Some(self.0.into_vertices_source()).into_iter() } } ); ($t1:ident, $t2:ident) => ( #[allow(non_snake_case)] impl<'a, $t1, $t2> MultiVerticesSource<'a> for ($t1, $t2) where $t1: IntoVerticesSource<'a>, $t2: IntoVerticesSource<'a> { type Iterator = Chain<<($t1,) as MultiVerticesSource<'a>>::Iterator, <($t2,) as MultiVerticesSource<'a>>::Iterator>; fn iter(self) -> Chain<<($t1,) as MultiVerticesSource<'a>>::Iterator, <($t2,) as MultiVerticesSource<'a>>::Iterator> { let ($t1, $t2) = self; Some($t1.into_vertices_source()).into_iter().chain(($t2,).iter()) } } impl_for_tuple!($t2); ); ($t1:ident, $($t2:ident),+) => ( #[allow(non_snake_case)] impl<'a, $t1, $($t2),+> MultiVerticesSource<'a> for ($t1, $($t2),+) where $t1: IntoVerticesSource<'a>, $($t2: IntoVerticesSource<'a>),+ { type Iterator = Chain<<($t1,) as MultiVerticesSource<'a>>::Iterator, <($($t2),+) as MultiVerticesSource<'a>>::Iterator>; fn iter(self) -> Chain<<($t1,) as MultiVerticesSource<'a>>::Iterator, <($($t2),+) as MultiVerticesSource<'a>>::Iterator> { let ($t1, $($t2),+) = self; Some($t1.into_vertices_source()).into_iter().chain(($($t2),+).iter()) } } impl_for_tuple!($($t2),+); ); } impl_for_tuple!(A, B, C, D, E, F, G); /// Trait for structures that represent a vertex. /// /// Instead of implementing this trait yourself, it is recommended to use the `implement_vertex!` /// macro instead. // TODO: this should be `unsafe`, but that would break the syntax extension pub trait Vertex: Copy + MarkerTrait { /// Builds the `VertexFormat` representing the layout of this element. fn build_bindings() -> VertexFormat; } /// Trait for types that can be used as vertex attributes. pub unsafe trait Attribute: MarkerTrait { /// Get the type of data. fn get_type() -> AttributeType; }
random_line_split
gpio_multithreaded_mutex.rs
// gpio_multithreaded_mutex.rs - Blinks an LED from multiple threads. // // Remember to add a resistor of an appropriate value in series, to prevent // exceeding the maximum current rating of the GPIO pin and the LED. use std::error::Error; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; use rppal::gpio::Gpio; // Gpio uses BCM pin numbering. BCM GPIO 23 is tied to physical pin 16. const GPIO_LED: u8 = 23; const NUM_THREADS: usize = 3; fn main() -> Result<(), Box<dyn Error>> { // Retrieve the GPIO pin and configure it as an output. let output_pin = Arc::new(Mutex::new(Gpio::new()?.get(GPIO_LED)?.into_output_low())); // Populate a Vec with threads so we can call join() on them later. let mut threads = Vec::with_capacity(NUM_THREADS); (0..NUM_THREADS).for_each(|thread_id| { // Clone the Arc so it can be moved to the spawned thread. let output_pin_clone = Arc::clone(&output_pin); threads.push(thread::spawn(move || { // Lock the Mutex on the spawned thread to get exclusive access to the OutputPin.
pin.set_high(); thread::sleep(Duration::from_millis(250)); pin.set_low(); thread::sleep(Duration::from_millis(250)); // The MutexGuard is automatically dropped here. })); }); // Lock the Mutex on the main thread to get exclusive access to the OutputPin. let mut pin = output_pin.lock().unwrap(); println!("Blinking the LED from the main thread."); pin.set_high(); thread::sleep(Duration::from_millis(250)); pin.set_low(); thread::sleep(Duration::from_millis(250)); // Manually drop the MutexGuard so the Mutex doesn't stay locked indefinitely. drop(pin); // Wait until all threads have finished executing. threads .into_iter() .for_each(|thread| thread.join().unwrap()); Ok(()) }
let mut pin = output_pin_clone.lock().unwrap(); println!("Blinking the LED from thread {}.", thread_id);
random_line_split
gpio_multithreaded_mutex.rs
// gpio_multithreaded_mutex.rs - Blinks an LED from multiple threads. // // Remember to add a resistor of an appropriate value in series, to prevent // exceeding the maximum current rating of the GPIO pin and the LED. use std::error::Error; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; use rppal::gpio::Gpio; // Gpio uses BCM pin numbering. BCM GPIO 23 is tied to physical pin 16. const GPIO_LED: u8 = 23; const NUM_THREADS: usize = 3; fn main() -> Result<(), Box<dyn Error>>
}); // Lock the Mutex on the main thread to get exclusive access to the OutputPin. let mut pin = output_pin.lock().unwrap(); println!("Blinking the LED from the main thread."); pin.set_high(); thread::sleep(Duration::from_millis(250)); pin.set_low(); thread::sleep(Duration::from_millis(250)); // Manually drop the MutexGuard so the Mutex doesn't stay locked indefinitely. drop(pin); // Wait until all threads have finished executing. threads .into_iter() .for_each(|thread| thread.join().unwrap()); Ok(()) }
{ // Retrieve the GPIO pin and configure it as an output. let output_pin = Arc::new(Mutex::new(Gpio::new()?.get(GPIO_LED)?.into_output_low())); // Populate a Vec with threads so we can call join() on them later. let mut threads = Vec::with_capacity(NUM_THREADS); (0..NUM_THREADS).for_each(|thread_id| { // Clone the Arc so it can be moved to the spawned thread. let output_pin_clone = Arc::clone(&output_pin); threads.push(thread::spawn(move || { // Lock the Mutex on the spawned thread to get exclusive access to the OutputPin. let mut pin = output_pin_clone.lock().unwrap(); println!("Blinking the LED from thread {}.", thread_id); pin.set_high(); thread::sleep(Duration::from_millis(250)); pin.set_low(); thread::sleep(Duration::from_millis(250)); // The MutexGuard is automatically dropped here. }));
identifier_body
gpio_multithreaded_mutex.rs
// gpio_multithreaded_mutex.rs - Blinks an LED from multiple threads. // // Remember to add a resistor of an appropriate value in series, to prevent // exceeding the maximum current rating of the GPIO pin and the LED. use std::error::Error; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; use rppal::gpio::Gpio; // Gpio uses BCM pin numbering. BCM GPIO 23 is tied to physical pin 16. const GPIO_LED: u8 = 23; const NUM_THREADS: usize = 3; fn
() -> Result<(), Box<dyn Error>> { // Retrieve the GPIO pin and configure it as an output. let output_pin = Arc::new(Mutex::new(Gpio::new()?.get(GPIO_LED)?.into_output_low())); // Populate a Vec with threads so we can call join() on them later. let mut threads = Vec::with_capacity(NUM_THREADS); (0..NUM_THREADS).for_each(|thread_id| { // Clone the Arc so it can be moved to the spawned thread. let output_pin_clone = Arc::clone(&output_pin); threads.push(thread::spawn(move || { // Lock the Mutex on the spawned thread to get exclusive access to the OutputPin. let mut pin = output_pin_clone.lock().unwrap(); println!("Blinking the LED from thread {}.", thread_id); pin.set_high(); thread::sleep(Duration::from_millis(250)); pin.set_low(); thread::sleep(Duration::from_millis(250)); // The MutexGuard is automatically dropped here. })); }); // Lock the Mutex on the main thread to get exclusive access to the OutputPin. let mut pin = output_pin.lock().unwrap(); println!("Blinking the LED from the main thread."); pin.set_high(); thread::sleep(Duration::from_millis(250)); pin.set_low(); thread::sleep(Duration::from_millis(250)); // Manually drop the MutexGuard so the Mutex doesn't stay locked indefinitely. drop(pin); // Wait until all threads have finished executing. threads .into_iter() .for_each(|thread| thread.join().unwrap()); Ok(()) }
main
identifier_name
reexports.rs
#![feature(decl_macro)] pub macro addr_of($place:expr) { &raw const $place } pub macro addr_of_crate($place:expr) { &raw const $place } pub macro addr_of_super($place:expr) { &raw const $place } pub macro addr_of_self($place:expr) { &raw const $place } pub macro addr_of_local($place:expr) { &raw const $place } pub struct
; pub struct FooCrate; pub struct FooSuper; pub struct FooSelf; pub struct FooLocal; pub enum Bar { Foo, } pub enum BarCrate { Foo, } pub enum BarSuper { Foo, } pub enum BarSelf { Foo, } pub enum BarLocal { Foo, } pub fn foo() {} pub fn foo_crate() {} pub fn foo_super() {} pub fn foo_self() {} pub fn foo_local() {} pub type Type = i32; pub type TypeCrate = i32; pub type TypeSuper = i32; pub type TypeSelf = i32; pub type TypeLocal = i32; pub union Union { a: i8, b: i8, } pub union UnionCrate { a: i8, b: i8, } pub union UnionSuper { a: i8, b: i8, } pub union UnionSelf { a: i8, b: i8, } pub union UnionLocal { a: i8, b: i8, }
Foo
identifier_name
reexports.rs
#![feature(decl_macro)] pub macro addr_of($place:expr) { &raw const $place } pub macro addr_of_crate($place:expr) { &raw const $place } pub macro addr_of_super($place:expr) { &raw const $place } pub macro addr_of_self($place:expr) { &raw const $place } pub macro addr_of_local($place:expr) { &raw const $place } pub struct Foo; pub struct FooCrate; pub struct FooSuper; pub struct FooSelf; pub struct FooLocal; pub enum Bar { Foo, } pub enum BarCrate { Foo, } pub enum BarSuper { Foo, } pub enum BarSelf { Foo, } pub enum BarLocal { Foo, } pub fn foo() {} pub fn foo_crate() {} pub fn foo_super() {} pub fn foo_self() {} pub fn foo_local() {}
pub type Type = i32; pub type TypeCrate = i32; pub type TypeSuper = i32; pub type TypeSelf = i32; pub type TypeLocal = i32; pub union Union { a: i8, b: i8, } pub union UnionCrate { a: i8, b: i8, } pub union UnionSuper { a: i8, b: i8, } pub union UnionSelf { a: i8, b: i8, } pub union UnionLocal { a: i8, b: i8, }
random_line_split
usart3.rs
//! Test the USART3 instance //! //! Connect the TX and RX pins to run this test #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; 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::{Serial, stm32f103xx}; use blue_pill::time::Hertz; use hal::prelude::*; use nb::Error; use rtfm::{P0, T0, TMax}; // CONFIGURATION pub const BAUD_RATE: Hertz = Hertz(115_200); // RESOURCES peripherals!(stm32f103xx, { AFIO: Peripheral { ceiling: C0, }, GPIOB: Peripheral { ceiling: C0, }, RCC: Peripheral { ceiling: C0, }, USART3: Peripheral { ceiling: C1, }, }); // INITIALIZATION PHASE fn init(ref prio: P0, thr: &TMax) { let afio = &AFIO.access(prio, thr); let gpiob = &GPIOB.access(prio, thr); let rcc = &RCC.access(prio, thr); let usart3 = USART3.access(prio, thr); let serial = Serial(&*usart3); serial.init(BAUD_RATE.invert(), afio, None, gpiob, rcc); const BYTE: u8 = b'A'; assert!(serial.write(BYTE).is_ok()); for _ in 0..1_000 { match serial.read() { Ok(byte) => { assert_eq!(byte, BYTE); return; } Err(Error::Other(e)) => panic!("{:?}", e), Err(Error::WouldBlock) => continue, } } panic!("Timeout") } // IDLE LOOP fn idle(_prio: P0, _thr: T0) ->!
// TASKS tasks!(stm32f103xx, {});
{ // OK rtfm::bkpt(); // Sleep loop { rtfm::wfi(); } }
identifier_body
usart3.rs
//! Test the USART3 instance //! //! Connect the TX and RX pins to run this test #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; 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::{Serial, stm32f103xx}; use blue_pill::time::Hertz; use hal::prelude::*; use nb::Error; use rtfm::{P0, T0, TMax}; // CONFIGURATION pub const BAUD_RATE: Hertz = Hertz(115_200); // RESOURCES peripherals!(stm32f103xx, { AFIO: Peripheral { ceiling: C0, }, GPIOB: Peripheral { ceiling: C0, }, RCC: Peripheral { ceiling: C0, }, USART3: Peripheral { ceiling: C1, }, }); // INITIALIZATION PHASE fn init(ref prio: P0, thr: &TMax) { let afio = &AFIO.access(prio, thr); let gpiob = &GPIOB.access(prio, thr); let rcc = &RCC.access(prio, thr); let usart3 = USART3.access(prio, thr); let serial = Serial(&*usart3); serial.init(BAUD_RATE.invert(), afio, None, gpiob, rcc); const BYTE: u8 = b'A'; assert!(serial.write(BYTE).is_ok()); for _ in 0..1_000 { match serial.read() { Ok(byte) => { assert_eq!(byte, BYTE); return; } Err(Error::Other(e)) => panic!("{:?}", e), Err(Error::WouldBlock) => continue, } } panic!("Timeout") } // IDLE LOOP fn
(_prio: P0, _thr: T0) ->! { // OK rtfm::bkpt(); // Sleep loop { rtfm::wfi(); } } // TASKS tasks!(stm32f103xx, {});
idle
identifier_name