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
ast.rs
// Copyright 2015 Pierre Talbot (IRCAM) // 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. //! AST of a PEG expression that is shared across all the compiling steps. #![macro_use] pub use identifier::*; pub use rust::Span; use rust; use std::fmt::{Formatter, Write, Display, Error}; pub type RTy = rust::P<rust::Ty>; pub type RExpr = rust::P<rust::Expr>; pub type RItem = rust::P<rust::Item>; #[derive(Clone, Debug)] pub enum Expression_<SubExpr:?Sized>{ StrLiteral(String), // "match me" AnySingleChar, //. CharacterClass(CharacterClassExpr), // [0-9] NonTerminalSymbol(Ident), // a_rule Sequence(Vec<Box<SubExpr>>), // a_rule next_rule Choice(Vec<Box<SubExpr>>), // try_this / or_try_this_one ZeroOrMore(Box<SubExpr>), // space* OneOrMore(Box<SubExpr>), // space+ Optional(Box<SubExpr>), // space? NotPredicate(Box<SubExpr>), //!space AndPredicate(Box<SubExpr>), // &space SemanticAction(Box<SubExpr>, Ident) // rule > function } #[derive(Clone, Debug)] pub struct CharacterClassExpr { pub intervals: Vec<CharacterInterval> } impl Display for CharacterClassExpr { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { try!(formatter.write_str("[\"")); for interval in &self.intervals { try!(interval.fmt(formatter)); } formatter.write_str("\"]") } } #[derive(Clone, Debug)] pub struct CharacterInterval { pub lo: char, pub hi: char } impl Display for CharacterInterval { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { if self.lo == self.hi { formatter.write_char(self.lo) } else { formatter.write_fmt(format_args!("{}-{}", self.lo, self.hi)) } } } pub trait ItemIdent { fn ident(&self) -> Ident; } pub trait ItemSpan { fn span(&self) -> Span; } pub trait ExprNode { fn expr_node<'a>(&'a self) -> &'a Expression_<Self>; } pub trait Visitor<Node: ExprNode, R> { fn visit_expr(&mut self, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_str_literal(&mut self, _parent: &Box<Node>, _lit: &String) -> R; fn visit_non_terminal_symbol(&mut self, _parent: &Box<Node>, _id: Ident) -> R; fn visit_character(&mut self, _parent: &Box<Node>) -> R; fn visit_any_single_char(&mut self, parent: &Box<Node>) -> R { self.visit_character(parent) } fn visit_character_class(&mut self, parent: &Box<Node>, _expr: &CharacterClassExpr) -> R { self.visit_character(parent) } fn visit_sequence(&mut self, _parent: &Box<Node>, exprs: &Vec<Box<Node>>) -> R; fn visit_choice(&mut self, _parent: &Box<Node>, exprs: &Vec<Box<Node>>) -> R; fn visit_repeat(&mut self, _parent: &Box<Node>, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_zero_or_more(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_repeat(parent, expr) } fn visit_one_or_more(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_repeat(parent, expr) } fn visit_optional(&mut self, _parent: &Box<Node>, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_syntactic_predicate(&mut self, _parent: &Box<Node>, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_not_predicate(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_syntactic_predicate(parent, expr) } fn visit_and_predicate(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_syntactic_predicate(parent, expr) } fn visit_semantic_action(&mut self, _parent: &Box<Node>, expr: &Box<Node>, _id: Ident) -> R { walk_expr(self, expr) } } /// We need this macro for factorizing the code since we can not specialize a trait on specific type parameter (we would need to specialize on `()` here). macro_rules! unit_visitor_impl { ($Node:ty, str_literal) => (fn visit_str_literal(&mut self, _parent: &Box<$Node>, _lit: &String) -> () {}); ($Node:ty, non_terminal) => (fn visit_non_terminal_symbol(&mut self, _parent: &Box<$Node>, _id: Ident) -> () {}); ($Node:ty, character) => (fn visit_character(&mut self, _parent: &Box<$Node>) -> () {}); ($Node:ty, sequence) => ( fn visit_sequence(&mut self, _parent: &Box<$Node>, exprs: &Vec<Box<$Node>>) -> () { walk_exprs(self, exprs); } ); ($Node:ty, choice) => ( fn visit_choice(&mut self, _parent: &Box<$Node>, exprs: &Vec<Box<$Node>>) -> () { walk_exprs(self, exprs); } ); } pub fn walk_expr<Node, R, V:?Sized>(visitor: &mut V, parent: &Box<Node>) -> R where Node: ExprNode, V: Visitor<Node, R> { use self::Expression_::*; match parent.expr_node() { &StrLiteral(ref lit) =>
&AnySingleChar => { visitor.visit_any_single_char(parent) } &NonTerminalSymbol(id) => { visitor.visit_non_terminal_symbol(parent, id) } &Sequence(ref seq) => { visitor.visit_sequence(parent, seq) } &Choice(ref choices) => { visitor.visit_choice(parent, choices) } &ZeroOrMore(ref expr) => { visitor.visit_zero_or_more(parent, expr) } &OneOrMore(ref expr) => { visitor.visit_one_or_more(parent, expr) } &Optional(ref expr) => { visitor.visit_optional(parent, expr) } &NotPredicate(ref expr) => { visitor.visit_not_predicate(parent, expr) } &AndPredicate(ref expr) => { visitor.visit_and_predicate(parent, expr) } &CharacterClass(ref char_class) => { visitor.visit_character_class(parent, char_class) } &SemanticAction(ref expr, id) => { visitor.visit_semantic_action(parent, expr, id) } } } pub fn walk_exprs<Node, R, V:?Sized>(visitor: &mut V, exprs: &Vec<Box<Node>>) -> Vec<R> where Node: ExprNode, V: Visitor<Node, R> { exprs.iter().map(|expr| visitor.visit_expr(expr)).collect() }
{ visitor.visit_str_literal(parent, lit) }
conditional_block
ast.rs
// Copyright 2015 Pierre Talbot (IRCAM) // 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. //! AST of a PEG expression that is shared across all the compiling steps. #![macro_use] pub use identifier::*; pub use rust::Span; use rust; use std::fmt::{Formatter, Write, Display, Error}; pub type RTy = rust::P<rust::Ty>; pub type RExpr = rust::P<rust::Expr>; pub type RItem = rust::P<rust::Item>; #[derive(Clone, Debug)] pub enum Expression_<SubExpr:?Sized>{ StrLiteral(String), // "match me" AnySingleChar, //. CharacterClass(CharacterClassExpr), // [0-9] NonTerminalSymbol(Ident), // a_rule Sequence(Vec<Box<SubExpr>>), // a_rule next_rule Choice(Vec<Box<SubExpr>>), // try_this / or_try_this_one ZeroOrMore(Box<SubExpr>), // space* OneOrMore(Box<SubExpr>), // space+ Optional(Box<SubExpr>), // space? NotPredicate(Box<SubExpr>), //!space AndPredicate(Box<SubExpr>), // &space SemanticAction(Box<SubExpr>, Ident) // rule > function } #[derive(Clone, Debug)] pub struct CharacterClassExpr { pub intervals: Vec<CharacterInterval> } impl Display for CharacterClassExpr { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { try!(formatter.write_str("[\"")); for interval in &self.intervals { try!(interval.fmt(formatter)); } formatter.write_str("\"]") } } #[derive(Clone, Debug)] pub struct CharacterInterval { pub lo: char, pub hi: char } impl Display for CharacterInterval { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { if self.lo == self.hi { formatter.write_char(self.lo) } else { formatter.write_fmt(format_args!("{}-{}", self.lo, self.hi)) } } } pub trait ItemIdent { fn ident(&self) -> Ident; } pub trait ItemSpan { fn span(&self) -> Span; } pub trait ExprNode { fn expr_node<'a>(&'a self) -> &'a Expression_<Self>; } pub trait Visitor<Node: ExprNode, R> { fn visit_expr(&mut self, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_str_literal(&mut self, _parent: &Box<Node>, _lit: &String) -> R; fn visit_non_terminal_symbol(&mut self, _parent: &Box<Node>, _id: Ident) -> R; fn visit_character(&mut self, _parent: &Box<Node>) -> R; fn visit_any_single_char(&mut self, parent: &Box<Node>) -> R { self.visit_character(parent) } fn visit_character_class(&mut self, parent: &Box<Node>, _expr: &CharacterClassExpr) -> R { self.visit_character(parent) } fn visit_sequence(&mut self, _parent: &Box<Node>, exprs: &Vec<Box<Node>>) -> R; fn visit_choice(&mut self, _parent: &Box<Node>, exprs: &Vec<Box<Node>>) -> R; fn visit_repeat(&mut self, _parent: &Box<Node>, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_zero_or_more(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_repeat(parent, expr) } fn visit_one_or_more(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_repeat(parent, expr) } fn visit_optional(&mut self, _parent: &Box<Node>, expr: &Box<Node>) -> R
fn visit_syntactic_predicate(&mut self, _parent: &Box<Node>, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_not_predicate(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_syntactic_predicate(parent, expr) } fn visit_and_predicate(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_syntactic_predicate(parent, expr) } fn visit_semantic_action(&mut self, _parent: &Box<Node>, expr: &Box<Node>, _id: Ident) -> R { walk_expr(self, expr) } } /// We need this macro for factorizing the code since we can not specialize a trait on specific type parameter (we would need to specialize on `()` here). macro_rules! unit_visitor_impl { ($Node:ty, str_literal) => (fn visit_str_literal(&mut self, _parent: &Box<$Node>, _lit: &String) -> () {}); ($Node:ty, non_terminal) => (fn visit_non_terminal_symbol(&mut self, _parent: &Box<$Node>, _id: Ident) -> () {}); ($Node:ty, character) => (fn visit_character(&mut self, _parent: &Box<$Node>) -> () {}); ($Node:ty, sequence) => ( fn visit_sequence(&mut self, _parent: &Box<$Node>, exprs: &Vec<Box<$Node>>) -> () { walk_exprs(self, exprs); } ); ($Node:ty, choice) => ( fn visit_choice(&mut self, _parent: &Box<$Node>, exprs: &Vec<Box<$Node>>) -> () { walk_exprs(self, exprs); } ); } pub fn walk_expr<Node, R, V:?Sized>(visitor: &mut V, parent: &Box<Node>) -> R where Node: ExprNode, V: Visitor<Node, R> { use self::Expression_::*; match parent.expr_node() { &StrLiteral(ref lit) => { visitor.visit_str_literal(parent, lit) } &AnySingleChar => { visitor.visit_any_single_char(parent) } &NonTerminalSymbol(id) => { visitor.visit_non_terminal_symbol(parent, id) } &Sequence(ref seq) => { visitor.visit_sequence(parent, seq) } &Choice(ref choices) => { visitor.visit_choice(parent, choices) } &ZeroOrMore(ref expr) => { visitor.visit_zero_or_more(parent, expr) } &OneOrMore(ref expr) => { visitor.visit_one_or_more(parent, expr) } &Optional(ref expr) => { visitor.visit_optional(parent, expr) } &NotPredicate(ref expr) => { visitor.visit_not_predicate(parent, expr) } &AndPredicate(ref expr) => { visitor.visit_and_predicate(parent, expr) } &CharacterClass(ref char_class) => { visitor.visit_character_class(parent, char_class) } &SemanticAction(ref expr, id) => { visitor.visit_semantic_action(parent, expr, id) } } } pub fn walk_exprs<Node, R, V:?Sized>(visitor: &mut V, exprs: &Vec<Box<Node>>) -> Vec<R> where Node: ExprNode, V: Visitor<Node, R> { exprs.iter().map(|expr| visitor.visit_expr(expr)).collect() }
{ walk_expr(self, expr) }
identifier_body
ast.rs
// Copyright 2015 Pierre Talbot (IRCAM) // 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. //! AST of a PEG expression that is shared across all the compiling steps. #![macro_use] pub use identifier::*; pub use rust::Span; use rust; use std::fmt::{Formatter, Write, Display, Error}; pub type RTy = rust::P<rust::Ty>; pub type RExpr = rust::P<rust::Expr>;
AnySingleChar, //. CharacterClass(CharacterClassExpr), // [0-9] NonTerminalSymbol(Ident), // a_rule Sequence(Vec<Box<SubExpr>>), // a_rule next_rule Choice(Vec<Box<SubExpr>>), // try_this / or_try_this_one ZeroOrMore(Box<SubExpr>), // space* OneOrMore(Box<SubExpr>), // space+ Optional(Box<SubExpr>), // space? NotPredicate(Box<SubExpr>), //!space AndPredicate(Box<SubExpr>), // &space SemanticAction(Box<SubExpr>, Ident) // rule > function } #[derive(Clone, Debug)] pub struct CharacterClassExpr { pub intervals: Vec<CharacterInterval> } impl Display for CharacterClassExpr { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { try!(formatter.write_str("[\"")); for interval in &self.intervals { try!(interval.fmt(formatter)); } formatter.write_str("\"]") } } #[derive(Clone, Debug)] pub struct CharacterInterval { pub lo: char, pub hi: char } impl Display for CharacterInterval { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { if self.lo == self.hi { formatter.write_char(self.lo) } else { formatter.write_fmt(format_args!("{}-{}", self.lo, self.hi)) } } } pub trait ItemIdent { fn ident(&self) -> Ident; } pub trait ItemSpan { fn span(&self) -> Span; } pub trait ExprNode { fn expr_node<'a>(&'a self) -> &'a Expression_<Self>; } pub trait Visitor<Node: ExprNode, R> { fn visit_expr(&mut self, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_str_literal(&mut self, _parent: &Box<Node>, _lit: &String) -> R; fn visit_non_terminal_symbol(&mut self, _parent: &Box<Node>, _id: Ident) -> R; fn visit_character(&mut self, _parent: &Box<Node>) -> R; fn visit_any_single_char(&mut self, parent: &Box<Node>) -> R { self.visit_character(parent) } fn visit_character_class(&mut self, parent: &Box<Node>, _expr: &CharacterClassExpr) -> R { self.visit_character(parent) } fn visit_sequence(&mut self, _parent: &Box<Node>, exprs: &Vec<Box<Node>>) -> R; fn visit_choice(&mut self, _parent: &Box<Node>, exprs: &Vec<Box<Node>>) -> R; fn visit_repeat(&mut self, _parent: &Box<Node>, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_zero_or_more(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_repeat(parent, expr) } fn visit_one_or_more(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_repeat(parent, expr) } fn visit_optional(&mut self, _parent: &Box<Node>, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_syntactic_predicate(&mut self, _parent: &Box<Node>, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_not_predicate(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_syntactic_predicate(parent, expr) } fn visit_and_predicate(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_syntactic_predicate(parent, expr) } fn visit_semantic_action(&mut self, _parent: &Box<Node>, expr: &Box<Node>, _id: Ident) -> R { walk_expr(self, expr) } } /// We need this macro for factorizing the code since we can not specialize a trait on specific type parameter (we would need to specialize on `()` here). macro_rules! unit_visitor_impl { ($Node:ty, str_literal) => (fn visit_str_literal(&mut self, _parent: &Box<$Node>, _lit: &String) -> () {}); ($Node:ty, non_terminal) => (fn visit_non_terminal_symbol(&mut self, _parent: &Box<$Node>, _id: Ident) -> () {}); ($Node:ty, character) => (fn visit_character(&mut self, _parent: &Box<$Node>) -> () {}); ($Node:ty, sequence) => ( fn visit_sequence(&mut self, _parent: &Box<$Node>, exprs: &Vec<Box<$Node>>) -> () { walk_exprs(self, exprs); } ); ($Node:ty, choice) => ( fn visit_choice(&mut self, _parent: &Box<$Node>, exprs: &Vec<Box<$Node>>) -> () { walk_exprs(self, exprs); } ); } pub fn walk_expr<Node, R, V:?Sized>(visitor: &mut V, parent: &Box<Node>) -> R where Node: ExprNode, V: Visitor<Node, R> { use self::Expression_::*; match parent.expr_node() { &StrLiteral(ref lit) => { visitor.visit_str_literal(parent, lit) } &AnySingleChar => { visitor.visit_any_single_char(parent) } &NonTerminalSymbol(id) => { visitor.visit_non_terminal_symbol(parent, id) } &Sequence(ref seq) => { visitor.visit_sequence(parent, seq) } &Choice(ref choices) => { visitor.visit_choice(parent, choices) } &ZeroOrMore(ref expr) => { visitor.visit_zero_or_more(parent, expr) } &OneOrMore(ref expr) => { visitor.visit_one_or_more(parent, expr) } &Optional(ref expr) => { visitor.visit_optional(parent, expr) } &NotPredicate(ref expr) => { visitor.visit_not_predicate(parent, expr) } &AndPredicate(ref expr) => { visitor.visit_and_predicate(parent, expr) } &CharacterClass(ref char_class) => { visitor.visit_character_class(parent, char_class) } &SemanticAction(ref expr, id) => { visitor.visit_semantic_action(parent, expr, id) } } } pub fn walk_exprs<Node, R, V:?Sized>(visitor: &mut V, exprs: &Vec<Box<Node>>) -> Vec<R> where Node: ExprNode, V: Visitor<Node, R> { exprs.iter().map(|expr| visitor.visit_expr(expr)).collect() }
pub type RItem = rust::P<rust::Item>; #[derive(Clone, Debug)] pub enum Expression_<SubExpr: ?Sized>{ StrLiteral(String), // "match me"
random_line_split
system.rs
use std::sync::{Arc, RwLock}; use crayon::application::prelude::{LifecycleListener, LifecycleListenerHandle}; use crayon::errors::Result; use crayon::math::prelude::Vector3; use crayon::res::utils::prelude::{ResourcePool, ResourceState}; use crayon::uuid::Uuid; use super::assets::prelude::{AudioClipHandle, AudioClipLoader}; use super::mixer::Mixer; use super::source::{AudioSource, AudioSourceHandle}; /// The centralized management of audio sub-system. pub struct AudioSystem { lis: LifecycleListenerHandle, clips: Arc<RwLock<ResourcePool<AudioClipHandle, AudioClipLoader>>>, mixer: Mixer, } struct AudioState { clips: Arc<RwLock<ResourcePool<AudioClipHandle, AudioClipLoader>>>, } impl LifecycleListener for AudioState { fn on_pre_update(&mut self) -> Result<()> { self.clips.write().unwrap().advance()?; Ok(()) } } impl Drop for AudioSystem { fn drop(&mut self) { crayon::application::detach(self.lis); } } impl AudioSystem { pub fn new() -> Result<Self> { let clips = Arc::new(RwLock::new(ResourcePool::new(AudioClipLoader::new()))); let mixer = if crayon::application::headless() { Mixer::headless(clips.clone())? } else { Mixer::new(clips.clone())? }; let state = AudioState { clips: clips.clone(), }; Ok(AudioSystem { lis: crayon::application::attach(state), clips: clips, mixer: mixer, }) } /// Sets the position of listener. #[inline] pub fn set_listener<T>(&self, position: T) where T: Into<Vector3<f32>>, { self.mixer.set_listener(position.into()); } /// Creates a clip object from file asynchronously. #[inline] pub fn
<T: AsRef<str>>(&self, url: T) -> Result<AudioClipHandle> { self.clips.write().unwrap().create_from(url) } /// Creates a clip object from file asynchronously. #[inline] pub fn create_clip_from_uuid(&self, uuid: Uuid) -> Result<AudioClipHandle> { self.clips.write().unwrap().create_from_uuid(uuid) } #[inline] pub fn clip_state(&self, handle: AudioClipHandle) -> ResourceState { self.clips.read().unwrap().state(handle) } /// Deletes a `AudioClip` resource from `AudioSystem`. #[inline] pub fn delete_clip(&self, handle: AudioClipHandle) { self.clips.write().unwrap().delete(handle); } /// Plays a audio source, returning a `AudioSourceHandle` for it. #[inline] pub fn play<T>(&self, params: T) -> Result<AudioSourceHandle> where T: Into<AudioSource>, { self.mixer.create_source(params.into()) } /// Stops a played audio source. #[inline] pub fn stop(&self, handle: AudioSourceHandle) { self.mixer.delete_source(handle); } /// Sets the emiiter position of playing sound. #[inline] pub fn set_position<T>(&self, handle: AudioSourceHandle, position: T) where T: Into<Vector3<f32>>, { self.mixer.set_position(handle, position.into()); } /// Sets the volume of a playing sound. #[inline] pub fn set_volume(&self, handle: AudioSourceHandle, volume: f32) { self.mixer.set_volume(handle, volume); } /// Sets the frequency-shift of a playing sound. #[inline] pub fn set_pitch(&self, handle: AudioSourceHandle, pitch: f32) { self.mixer.set_pitch(handle, pitch); } }
create_clip_from
identifier_name
system.rs
use std::sync::{Arc, RwLock}; use crayon::application::prelude::{LifecycleListener, LifecycleListenerHandle}; use crayon::errors::Result; use crayon::math::prelude::Vector3; use crayon::res::utils::prelude::{ResourcePool, ResourceState}; use crayon::uuid::Uuid; use super::assets::prelude::{AudioClipHandle, AudioClipLoader}; use super::mixer::Mixer; use super::source::{AudioSource, AudioSourceHandle}; /// The centralized management of audio sub-system. pub struct AudioSystem { lis: LifecycleListenerHandle, clips: Arc<RwLock<ResourcePool<AudioClipHandle, AudioClipLoader>>>, mixer: Mixer, } struct AudioState { clips: Arc<RwLock<ResourcePool<AudioClipHandle, AudioClipLoader>>>, } impl LifecycleListener for AudioState { fn on_pre_update(&mut self) -> Result<()> { self.clips.write().unwrap().advance()?; Ok(()) } } impl Drop for AudioSystem { fn drop(&mut self) { crayon::application::detach(self.lis); } } impl AudioSystem { pub fn new() -> Result<Self> { let clips = Arc::new(RwLock::new(ResourcePool::new(AudioClipLoader::new()))); let mixer = if crayon::application::headless() { Mixer::headless(clips.clone())? } else { Mixer::new(clips.clone())? }; let state = AudioState { clips: clips.clone(), }; Ok(AudioSystem { lis: crayon::application::attach(state), clips: clips, mixer: mixer, }) } /// Sets the position of listener. #[inline] pub fn set_listener<T>(&self, position: T) where T: Into<Vector3<f32>>, { self.mixer.set_listener(position.into()); } /// Creates a clip object from file asynchronously. #[inline] pub fn create_clip_from<T: AsRef<str>>(&self, url: T) -> Result<AudioClipHandle> { self.clips.write().unwrap().create_from(url) } /// Creates a clip object from file asynchronously. #[inline] pub fn create_clip_from_uuid(&self, uuid: Uuid) -> Result<AudioClipHandle> { self.clips.write().unwrap().create_from_uuid(uuid) } #[inline] pub fn clip_state(&self, handle: AudioClipHandle) -> ResourceState { self.clips.read().unwrap().state(handle) } /// Deletes a `AudioClip` resource from `AudioSystem`. #[inline] pub fn delete_clip(&self, handle: AudioClipHandle) { self.clips.write().unwrap().delete(handle); } /// Plays a audio source, returning a `AudioSourceHandle` for it. #[inline]
self.mixer.create_source(params.into()) } /// Stops a played audio source. #[inline] pub fn stop(&self, handle: AudioSourceHandle) { self.mixer.delete_source(handle); } /// Sets the emiiter position of playing sound. #[inline] pub fn set_position<T>(&self, handle: AudioSourceHandle, position: T) where T: Into<Vector3<f32>>, { self.mixer.set_position(handle, position.into()); } /// Sets the volume of a playing sound. #[inline] pub fn set_volume(&self, handle: AudioSourceHandle, volume: f32) { self.mixer.set_volume(handle, volume); } /// Sets the frequency-shift of a playing sound. #[inline] pub fn set_pitch(&self, handle: AudioSourceHandle, pitch: f32) { self.mixer.set_pitch(handle, pitch); } }
pub fn play<T>(&self, params: T) -> Result<AudioSourceHandle> where T: Into<AudioSource>, {
random_line_split
system.rs
use std::sync::{Arc, RwLock}; use crayon::application::prelude::{LifecycleListener, LifecycleListenerHandle}; use crayon::errors::Result; use crayon::math::prelude::Vector3; use crayon::res::utils::prelude::{ResourcePool, ResourceState}; use crayon::uuid::Uuid; use super::assets::prelude::{AudioClipHandle, AudioClipLoader}; use super::mixer::Mixer; use super::source::{AudioSource, AudioSourceHandle}; /// The centralized management of audio sub-system. pub struct AudioSystem { lis: LifecycleListenerHandle, clips: Arc<RwLock<ResourcePool<AudioClipHandle, AudioClipLoader>>>, mixer: Mixer, } struct AudioState { clips: Arc<RwLock<ResourcePool<AudioClipHandle, AudioClipLoader>>>, } impl LifecycleListener for AudioState { fn on_pre_update(&mut self) -> Result<()> { self.clips.write().unwrap().advance()?; Ok(()) } } impl Drop for AudioSystem { fn drop(&mut self) { crayon::application::detach(self.lis); } } impl AudioSystem { pub fn new() -> Result<Self> { let clips = Arc::new(RwLock::new(ResourcePool::new(AudioClipLoader::new()))); let mixer = if crayon::application::headless()
else { Mixer::new(clips.clone())? }; let state = AudioState { clips: clips.clone(), }; Ok(AudioSystem { lis: crayon::application::attach(state), clips: clips, mixer: mixer, }) } /// Sets the position of listener. #[inline] pub fn set_listener<T>(&self, position: T) where T: Into<Vector3<f32>>, { self.mixer.set_listener(position.into()); } /// Creates a clip object from file asynchronously. #[inline] pub fn create_clip_from<T: AsRef<str>>(&self, url: T) -> Result<AudioClipHandle> { self.clips.write().unwrap().create_from(url) } /// Creates a clip object from file asynchronously. #[inline] pub fn create_clip_from_uuid(&self, uuid: Uuid) -> Result<AudioClipHandle> { self.clips.write().unwrap().create_from_uuid(uuid) } #[inline] pub fn clip_state(&self, handle: AudioClipHandle) -> ResourceState { self.clips.read().unwrap().state(handle) } /// Deletes a `AudioClip` resource from `AudioSystem`. #[inline] pub fn delete_clip(&self, handle: AudioClipHandle) { self.clips.write().unwrap().delete(handle); } /// Plays a audio source, returning a `AudioSourceHandle` for it. #[inline] pub fn play<T>(&self, params: T) -> Result<AudioSourceHandle> where T: Into<AudioSource>, { self.mixer.create_source(params.into()) } /// Stops a played audio source. #[inline] pub fn stop(&self, handle: AudioSourceHandle) { self.mixer.delete_source(handle); } /// Sets the emiiter position of playing sound. #[inline] pub fn set_position<T>(&self, handle: AudioSourceHandle, position: T) where T: Into<Vector3<f32>>, { self.mixer.set_position(handle, position.into()); } /// Sets the volume of a playing sound. #[inline] pub fn set_volume(&self, handle: AudioSourceHandle, volume: f32) { self.mixer.set_volume(handle, volume); } /// Sets the frequency-shift of a playing sound. #[inline] pub fn set_pitch(&self, handle: AudioSourceHandle, pitch: f32) { self.mixer.set_pitch(handle, pitch); } }
{ Mixer::headless(clips.clone())? }
conditional_block
system.rs
use std::sync::{Arc, RwLock}; use crayon::application::prelude::{LifecycleListener, LifecycleListenerHandle}; use crayon::errors::Result; use crayon::math::prelude::Vector3; use crayon::res::utils::prelude::{ResourcePool, ResourceState}; use crayon::uuid::Uuid; use super::assets::prelude::{AudioClipHandle, AudioClipLoader}; use super::mixer::Mixer; use super::source::{AudioSource, AudioSourceHandle}; /// The centralized management of audio sub-system. pub struct AudioSystem { lis: LifecycleListenerHandle, clips: Arc<RwLock<ResourcePool<AudioClipHandle, AudioClipLoader>>>, mixer: Mixer, } struct AudioState { clips: Arc<RwLock<ResourcePool<AudioClipHandle, AudioClipLoader>>>, } impl LifecycleListener for AudioState { fn on_pre_update(&mut self) -> Result<()> { self.clips.write().unwrap().advance()?; Ok(()) } } impl Drop for AudioSystem { fn drop(&mut self) { crayon::application::detach(self.lis); } } impl AudioSystem { pub fn new() -> Result<Self>
/// Sets the position of listener. #[inline] pub fn set_listener<T>(&self, position: T) where T: Into<Vector3<f32>>, { self.mixer.set_listener(position.into()); } /// Creates a clip object from file asynchronously. #[inline] pub fn create_clip_from<T: AsRef<str>>(&self, url: T) -> Result<AudioClipHandle> { self.clips.write().unwrap().create_from(url) } /// Creates a clip object from file asynchronously. #[inline] pub fn create_clip_from_uuid(&self, uuid: Uuid) -> Result<AudioClipHandle> { self.clips.write().unwrap().create_from_uuid(uuid) } #[inline] pub fn clip_state(&self, handle: AudioClipHandle) -> ResourceState { self.clips.read().unwrap().state(handle) } /// Deletes a `AudioClip` resource from `AudioSystem`. #[inline] pub fn delete_clip(&self, handle: AudioClipHandle) { self.clips.write().unwrap().delete(handle); } /// Plays a audio source, returning a `AudioSourceHandle` for it. #[inline] pub fn play<T>(&self, params: T) -> Result<AudioSourceHandle> where T: Into<AudioSource>, { self.mixer.create_source(params.into()) } /// Stops a played audio source. #[inline] pub fn stop(&self, handle: AudioSourceHandle) { self.mixer.delete_source(handle); } /// Sets the emiiter position of playing sound. #[inline] pub fn set_position<T>(&self, handle: AudioSourceHandle, position: T) where T: Into<Vector3<f32>>, { self.mixer.set_position(handle, position.into()); } /// Sets the volume of a playing sound. #[inline] pub fn set_volume(&self, handle: AudioSourceHandle, volume: f32) { self.mixer.set_volume(handle, volume); } /// Sets the frequency-shift of a playing sound. #[inline] pub fn set_pitch(&self, handle: AudioSourceHandle, pitch: f32) { self.mixer.set_pitch(handle, pitch); } }
{ let clips = Arc::new(RwLock::new(ResourcePool::new(AudioClipLoader::new()))); let mixer = if crayon::application::headless() { Mixer::headless(clips.clone())? } else { Mixer::new(clips.clone())? }; let state = AudioState { clips: clips.clone(), }; Ok(AudioSystem { lis: crayon::application::attach(state), clips: clips, mixer: mixer, }) }
identifier_body
sbwatchpoint.rs
use super::*; cpp_class!(pub unsafe struct SBWatchpoint as "SBWatchpoint"); unsafe impl Send for SBWatchpoint {} impl SBWatchpoint { pub fn id(&self) -> WatchpointID { cpp!(unsafe [self as "SBWatchpoint*"] -> WatchpointID as "watch_id_t" { return self->GetID(); }) } } impl IsValid for SBWatchpoint { fn is_valid(&self) -> bool
} impl fmt::Debug for SBWatchpoint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let full = f.alternate(); debug_descr(f, |descr| { cpp!(unsafe [self as "SBWatchpoint*", descr as "SBStream*", full as "bool"] -> bool as "bool" { return self->GetDescription(*descr, full? eDescriptionLevelFull : eDescriptionLevelBrief); }) }) } }
{ cpp!(unsafe [self as "SBWatchpoint*"] -> bool as "bool" { return self->IsValid(); }) }
identifier_body
sbwatchpoint.rs
use super::*; cpp_class!(pub unsafe struct SBWatchpoint as "SBWatchpoint"); unsafe impl Send for SBWatchpoint {} impl SBWatchpoint { pub fn id(&self) -> WatchpointID { cpp!(unsafe [self as "SBWatchpoint*"] -> WatchpointID as "watch_id_t" { return self->GetID(); }) } } impl IsValid for SBWatchpoint { fn
(&self) -> bool { cpp!(unsafe [self as "SBWatchpoint*"] -> bool as "bool" { return self->IsValid(); }) } } impl fmt::Debug for SBWatchpoint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let full = f.alternate(); debug_descr(f, |descr| { cpp!(unsafe [self as "SBWatchpoint*", descr as "SBStream*", full as "bool"] -> bool as "bool" { return self->GetDescription(*descr, full? eDescriptionLevelFull : eDescriptionLevelBrief); }) }) } }
is_valid
identifier_name
sbwatchpoint.rs
use super::*; cpp_class!(pub unsafe struct SBWatchpoint as "SBWatchpoint"); unsafe impl Send for SBWatchpoint {} impl SBWatchpoint { pub fn id(&self) -> WatchpointID { cpp!(unsafe [self as "SBWatchpoint*"] -> WatchpointID as "watch_id_t" { return self->GetID(); }) } } impl IsValid for SBWatchpoint { fn is_valid(&self) -> bool { cpp!(unsafe [self as "SBWatchpoint*"] -> bool as "bool" { return self->IsValid(); }) } } impl fmt::Debug for SBWatchpoint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let full = f.alternate(); debug_descr(f, |descr| { cpp!(unsafe [self as "SBWatchpoint*", descr as "SBStream*", full as "bool"] -> bool as "bool" {
}) } }
return self->GetDescription(*descr, full ? eDescriptionLevelFull : eDescriptionLevelBrief); })
random_line_split
mod.rs
use std::collections::HashMap; use std::error::Error; use std::io::{self, Cursor}; use std::sync::Arc; use rustc_serialize::{json, Encodable}; use rustc_serialize::json::Json; use url; use conduit::{Request, Response, Handler}; use conduit_router::{RouteBuilder, RequestParams}; use db::RequestTransaction; use self::errors::NotFound; pub use self::errors::{CargoError, CargoResult, internal, human, internal_error}; pub use self::errors::{ChainError, std_error}; pub use self::hasher::{HashingReader}; pub use self::head::Head; pub use self::io_util::LimitErrorReader; pub use self::lazy_cell::LazyCell; pub use self::request_proxy::RequestProxy; pub mod errors; mod hasher; mod head; mod io_util; mod lazy_cell; mod request_proxy; pub trait RequestUtils { fn redirect(&self, url: String) -> Response; fn json<T: Encodable>(&self, t: &T) -> Response; fn query(&self) -> HashMap<String, String>; fn wants_json(&self) -> bool; fn pagination(&self, default: usize, max: usize) -> CargoResult<(i64, i64)>; } pub fn json_response<T: Encodable>(t: &T) -> Response { let s = json::encode(t).unwrap(); let json = fixup(s.parse().unwrap()).to_string(); let mut headers = HashMap::new(); headers.insert("Content-Type".to_string(), vec!["application/json; charset=utf-8".to_string()]); headers.insert("Content-Length".to_string(), vec![json.len().to_string()]); return Response { status: (200, "OK"), headers: headers, body: Box::new(Cursor::new(json.into_bytes())), }; fn fixup(json: Json) -> Json { match json { Json::Object(object) => { Json::Object(object.into_iter().map(|(k, v)| { let k = if k == "krate" { "crate".to_string() } else { k }; (k, fixup(v)) }).collect()) } Json::Array(list) => { Json::Array(list.into_iter().map(fixup).collect()) } j => j, } } } impl<'a> RequestUtils for Request + 'a { fn json<T: Encodable>(&self, t: &T) -> Response { json_response(t) } fn query(&self) -> HashMap<String, String> { url::form_urlencoded::parse(self.query_string().unwrap_or("") .as_bytes()) .into_iter().collect() }
fn redirect(&self, url: String) -> Response { let mut headers = HashMap::new(); headers.insert("Location".to_string(), vec![url.to_string()]); Response { status: (302, "Found"), headers: headers, body: Box::new(io::empty()), } } fn wants_json(&self) -> bool { let content = self.headers().find("Accept").unwrap_or(Vec::new()); content.iter().any(|s| s.contains("json")) } fn pagination(&self, default: usize, max: usize) -> CargoResult<(i64, i64)> { let query = self.query(); let page = query.get("page").and_then(|s| s.parse::<usize>().ok()) .unwrap_or(1); let limit = query.get("per_page").and_then(|s| s.parse::<usize>().ok()) .unwrap_or(default); if limit > max { return Err(human(format!("cannot request more than {} items", max))) } Ok((((page - 1) * limit) as i64, limit as i64)) } } pub struct C(pub fn(&mut Request) -> CargoResult<Response>); impl Handler for C { fn call(&self, req: &mut Request) -> Result<Response, Box<Error+Send>> { let C(f) = *self; match f(req) { Ok(resp) => { req.commit(); Ok(resp) } Err(e) => { match e.response() { Some(response) => Ok(response), None => Err(std_error(e)) } } } } } pub struct R<H>(pub Arc<H>); impl<H: Handler> Handler for R<H> { fn call(&self, req: &mut Request) -> Result<Response, Box<Error+Send>> { let path = req.params()["path"].to_string(); let R(ref sub_router) = *self; sub_router.call(&mut RequestProxy { other: req, path: Some(&path), method: None, }) } } pub struct R404(pub RouteBuilder); impl Handler for R404 { fn call(&self, req: &mut Request) -> Result<Response, Box<Error+Send>> { let R404(ref router) = *self; match router.recognize(&req.method(), req.path()) { Ok(m) => { req.mut_extensions().insert(m.params.clone()); m.handler.call(req) } Err(..) => Ok(NotFound.response().unwrap()), } } }
random_line_split
mod.rs
use std::collections::HashMap; use std::error::Error; use std::io::{self, Cursor}; use std::sync::Arc; use rustc_serialize::{json, Encodable}; use rustc_serialize::json::Json; use url; use conduit::{Request, Response, Handler}; use conduit_router::{RouteBuilder, RequestParams}; use db::RequestTransaction; use self::errors::NotFound; pub use self::errors::{CargoError, CargoResult, internal, human, internal_error}; pub use self::errors::{ChainError, std_error}; pub use self::hasher::{HashingReader}; pub use self::head::Head; pub use self::io_util::LimitErrorReader; pub use self::lazy_cell::LazyCell; pub use self::request_proxy::RequestProxy; pub mod errors; mod hasher; mod head; mod io_util; mod lazy_cell; mod request_proxy; pub trait RequestUtils { fn redirect(&self, url: String) -> Response; fn json<T: Encodable>(&self, t: &T) -> Response; fn query(&self) -> HashMap<String, String>; fn wants_json(&self) -> bool; fn pagination(&self, default: usize, max: usize) -> CargoResult<(i64, i64)>; } pub fn json_response<T: Encodable>(t: &T) -> Response { let s = json::encode(t).unwrap(); let json = fixup(s.parse().unwrap()).to_string(); let mut headers = HashMap::new(); headers.insert("Content-Type".to_string(), vec!["application/json; charset=utf-8".to_string()]); headers.insert("Content-Length".to_string(), vec![json.len().to_string()]); return Response { status: (200, "OK"), headers: headers, body: Box::new(Cursor::new(json.into_bytes())), }; fn fixup(json: Json) -> Json { match json { Json::Object(object) => { Json::Object(object.into_iter().map(|(k, v)| { let k = if k == "krate" { "crate".to_string() } else { k }; (k, fixup(v)) }).collect()) } Json::Array(list) => { Json::Array(list.into_iter().map(fixup).collect()) } j => j, } } } impl<'a> RequestUtils for Request + 'a { fn
<T: Encodable>(&self, t: &T) -> Response { json_response(t) } fn query(&self) -> HashMap<String, String> { url::form_urlencoded::parse(self.query_string().unwrap_or("") .as_bytes()) .into_iter().collect() } fn redirect(&self, url: String) -> Response { let mut headers = HashMap::new(); headers.insert("Location".to_string(), vec![url.to_string()]); Response { status: (302, "Found"), headers: headers, body: Box::new(io::empty()), } } fn wants_json(&self) -> bool { let content = self.headers().find("Accept").unwrap_or(Vec::new()); content.iter().any(|s| s.contains("json")) } fn pagination(&self, default: usize, max: usize) -> CargoResult<(i64, i64)> { let query = self.query(); let page = query.get("page").and_then(|s| s.parse::<usize>().ok()) .unwrap_or(1); let limit = query.get("per_page").and_then(|s| s.parse::<usize>().ok()) .unwrap_or(default); if limit > max { return Err(human(format!("cannot request more than {} items", max))) } Ok((((page - 1) * limit) as i64, limit as i64)) } } pub struct C(pub fn(&mut Request) -> CargoResult<Response>); impl Handler for C { fn call(&self, req: &mut Request) -> Result<Response, Box<Error+Send>> { let C(f) = *self; match f(req) { Ok(resp) => { req.commit(); Ok(resp) } Err(e) => { match e.response() { Some(response) => Ok(response), None => Err(std_error(e)) } } } } } pub struct R<H>(pub Arc<H>); impl<H: Handler> Handler for R<H> { fn call(&self, req: &mut Request) -> Result<Response, Box<Error+Send>> { let path = req.params()["path"].to_string(); let R(ref sub_router) = *self; sub_router.call(&mut RequestProxy { other: req, path: Some(&path), method: None, }) } } pub struct R404(pub RouteBuilder); impl Handler for R404 { fn call(&self, req: &mut Request) -> Result<Response, Box<Error+Send>> { let R404(ref router) = *self; match router.recognize(&req.method(), req.path()) { Ok(m) => { req.mut_extensions().insert(m.params.clone()); m.handler.call(req) } Err(..) => Ok(NotFound.response().unwrap()), } } }
json
identifier_name
shannon.rs
use super::Entropy; /// Implementation of Shannon entropy pub struct Shannon { frequency: Vec<f64>, probabilities: Vec<f64>, entropy: Option<f64>, data_len: usize, } impl Shannon { pub fn new() -> Self { Self { frequency: vec![0.0; 256], probabilities: vec![0.0; 256], entropy: None, data_len: 0, } } /// simple method to immediately return entropy for a blob of data /// /// # Examples /// /// ``` /// use entropy_rs::Shannon; /// let data = vec![0,1,2,3,4,5]; /// assert_eq!(2.584962500721156, Shannon::quick(&data)); /// /// ``` /// pub fn quick<T: AsRef<[u8]>>(data: T) -> f64 { let mut quick = Self::new(); quick.input(data); quick.calculate() } } impl Entropy for Shannon { fn input<T: AsRef<[u8]>>(&mut self, data: T) { self.data_len += data.as_ref().len(); data.as_ref().into_iter().for_each(|v| { self.frequency[*v as usize] += 1.0_f64; }); } fn calculate(&mut self) -> f64
fn reset(&mut self) { *self = Shannon::new(); } } #[cfg(test)] mod tests { #[test] fn shannon_test_quick() { use crate::Shannon; assert_eq!(Shannon::quick(vec![0, 1, 2, 3, 4, 5]) as f32, 2.5849626_f32); } }
{ if let Some(entropy) = self.entropy { entropy } else { let mut entropy = 0.0; for i in 0..256 { if self.frequency[i] != 0.0 { self.probabilities[i] = self.frequency[i] / self.data_len as f64; entropy += self.probabilities[i] * self.probabilities[i].log(2.0_f64); } } entropy *= -1.0; self.entropy = Some(entropy); entropy } }
identifier_body
shannon.rs
use super::Entropy; /// Implementation of Shannon entropy pub struct Shannon { frequency: Vec<f64>, probabilities: Vec<f64>, entropy: Option<f64>, data_len: usize, } impl Shannon { pub fn new() -> Self { Self { frequency: vec![0.0; 256], probabilities: vec![0.0; 256], entropy: None, data_len: 0, } } /// simple method to immediately return entropy for a blob of data /// /// # Examples /// /// ``` /// use entropy_rs::Shannon; /// let data = vec![0,1,2,3,4,5]; /// assert_eq!(2.584962500721156, Shannon::quick(&data)); /// /// ``` /// pub fn quick<T: AsRef<[u8]>>(data: T) -> f64 { let mut quick = Self::new(); quick.input(data); quick.calculate() } } impl Entropy for Shannon { fn input<T: AsRef<[u8]>>(&mut self, data: T) { self.data_len += data.as_ref().len(); data.as_ref().into_iter().for_each(|v| { self.frequency[*v as usize] += 1.0_f64; }); } fn calculate(&mut self) -> f64 { if let Some(entropy) = self.entropy { entropy } else { let mut entropy = 0.0; for i in 0..256 { if self.frequency[i]!= 0.0 { self.probabilities[i] = self.frequency[i] / self.data_len as f64; entropy += self.probabilities[i] * self.probabilities[i].log(2.0_f64); } } entropy *= -1.0; self.entropy = Some(entropy); entropy } } fn reset(&mut self) { *self = Shannon::new(); } } #[cfg(test)] mod tests { #[test] fn
() { use crate::Shannon; assert_eq!(Shannon::quick(vec![0, 1, 2, 3, 4, 5]) as f32, 2.5849626_f32); } }
shannon_test_quick
identifier_name
shannon.rs
use super::Entropy; /// Implementation of Shannon entropy pub struct Shannon { frequency: Vec<f64>, probabilities: Vec<f64>, entropy: Option<f64>, data_len: usize, } impl Shannon { pub fn new() -> Self { Self { frequency: vec![0.0; 256], probabilities: vec![0.0; 256], entropy: None, data_len: 0, } } /// simple method to immediately return entropy for a blob of data /// /// # Examples /// /// ```
/// let data = vec![0,1,2,3,4,5]; /// assert_eq!(2.584962500721156, Shannon::quick(&data)); /// /// ``` /// pub fn quick<T: AsRef<[u8]>>(data: T) -> f64 { let mut quick = Self::new(); quick.input(data); quick.calculate() } } impl Entropy for Shannon { fn input<T: AsRef<[u8]>>(&mut self, data: T) { self.data_len += data.as_ref().len(); data.as_ref().into_iter().for_each(|v| { self.frequency[*v as usize] += 1.0_f64; }); } fn calculate(&mut self) -> f64 { if let Some(entropy) = self.entropy { entropy } else { let mut entropy = 0.0; for i in 0..256 { if self.frequency[i]!= 0.0 { self.probabilities[i] = self.frequency[i] / self.data_len as f64; entropy += self.probabilities[i] * self.probabilities[i].log(2.0_f64); } } entropy *= -1.0; self.entropy = Some(entropy); entropy } } fn reset(&mut self) { *self = Shannon::new(); } } #[cfg(test)] mod tests { #[test] fn shannon_test_quick() { use crate::Shannon; assert_eq!(Shannon::quick(vec![0, 1, 2, 3, 4, 5]) as f32, 2.5849626_f32); } }
/// use entropy_rs::Shannon;
random_line_split
shannon.rs
use super::Entropy; /// Implementation of Shannon entropy pub struct Shannon { frequency: Vec<f64>, probabilities: Vec<f64>, entropy: Option<f64>, data_len: usize, } impl Shannon { pub fn new() -> Self { Self { frequency: vec![0.0; 256], probabilities: vec![0.0; 256], entropy: None, data_len: 0, } } /// simple method to immediately return entropy for a blob of data /// /// # Examples /// /// ``` /// use entropy_rs::Shannon; /// let data = vec![0,1,2,3,4,5]; /// assert_eq!(2.584962500721156, Shannon::quick(&data)); /// /// ``` /// pub fn quick<T: AsRef<[u8]>>(data: T) -> f64 { let mut quick = Self::new(); quick.input(data); quick.calculate() } } impl Entropy for Shannon { fn input<T: AsRef<[u8]>>(&mut self, data: T) { self.data_len += data.as_ref().len(); data.as_ref().into_iter().for_each(|v| { self.frequency[*v as usize] += 1.0_f64; }); } fn calculate(&mut self) -> f64 { if let Some(entropy) = self.entropy { entropy } else
} fn reset(&mut self) { *self = Shannon::new(); } } #[cfg(test)] mod tests { #[test] fn shannon_test_quick() { use crate::Shannon; assert_eq!(Shannon::quick(vec![0, 1, 2, 3, 4, 5]) as f32, 2.5849626_f32); } }
{ let mut entropy = 0.0; for i in 0..256 { if self.frequency[i] != 0.0 { self.probabilities[i] = self.frequency[i] / self.data_len as f64; entropy += self.probabilities[i] * self.probabilities[i].log(2.0_f64); } } entropy *= -1.0; self.entropy = Some(entropy); entropy }
conditional_block
primes.rs
//! Functions involving primes without dependencies. //! //! //! # Examples //! //! ``` //! use euler_library::primes as eu_primes; //! //! assert_eq!(eu_primes::prime_factors(84), [2, 2, 3, 7]); //! assert_eq!(eu_primes::prime_factors_unique(84), [2, 3, 7]); //! //! ``` /// Returns a vector of the prime factors n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::prime_factors(342), [2, 3, 3, 19]); /// assert_eq!(eu_primes::prime_factors(123), [3, 41]); /// ``` /// pub fn prime_factors(mut n: usize) -> Vec<usize> { let mut xs: Vec<usize> = Vec::new(); let mut i = 2; while n > 1 { while n % i == 0 { xs.push(i); n /= i; } i += 1; } xs }
/// Returns a vector of the unique prime factors n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::prime_factors_unique(342), [2, 3, 19]); /// assert_eq!(eu_primes::prime_factors_unique(123), [3, 41]); /// ``` /// pub fn prime_factors_unique(n: usize) -> Vec<usize> { let mut xs = prime_factors(n); xs.dedup(); xs } /// Returns the sum of unique prime factors of n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::sopf(342), 24); /// assert_eq!(eu_primes::sopf(123), 44); /// ``` /// pub fn sopf(n: usize) -> usize { prime_factors_unique(n).iter().fold(0, |acc, x| acc + x) } /// Return a vector of the count of unique prime factors of i in 0..n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::prime_factor_cnt(10), [0, 0, 1, 1, 1, 1, 2, 1, 1, 1]); /// /// let prime_factor_cnt_90_to_99 = /// eu_primes::prime_factor_cnt(100).into_iter().skip(90).take(10).collect::<Vec<_>>(); /// assert_eq!(prime_factor_cnt_90_to_99, [3, 2, 2, 2, 2, 2, 2, 1, 2, 2]); /// ``` /// pub fn prime_factor_cnt(n: usize) -> Vec<usize> { let mut s = vec![0 as usize; n]; for (i, _) in s.clone().iter().enumerate().skip(2) { if s[i] == 0 { let mut j = i; while j < n { s[j] += 1; j += i } } } s }
random_line_split
primes.rs
//! Functions involving primes without dependencies. //! //! //! # Examples //! //! ``` //! use euler_library::primes as eu_primes; //! //! assert_eq!(eu_primes::prime_factors(84), [2, 2, 3, 7]); //! assert_eq!(eu_primes::prime_factors_unique(84), [2, 3, 7]); //! //! ``` /// Returns a vector of the prime factors n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::prime_factors(342), [2, 3, 3, 19]); /// assert_eq!(eu_primes::prime_factors(123), [3, 41]); /// ``` /// pub fn
(mut n: usize) -> Vec<usize> { let mut xs: Vec<usize> = Vec::new(); let mut i = 2; while n > 1 { while n % i == 0 { xs.push(i); n /= i; } i += 1; } xs } /// Returns a vector of the unique prime factors n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::prime_factors_unique(342), [2, 3, 19]); /// assert_eq!(eu_primes::prime_factors_unique(123), [3, 41]); /// ``` /// pub fn prime_factors_unique(n: usize) -> Vec<usize> { let mut xs = prime_factors(n); xs.dedup(); xs } /// Returns the sum of unique prime factors of n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::sopf(342), 24); /// assert_eq!(eu_primes::sopf(123), 44); /// ``` /// pub fn sopf(n: usize) -> usize { prime_factors_unique(n).iter().fold(0, |acc, x| acc + x) } /// Return a vector of the count of unique prime factors of i in 0..n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::prime_factor_cnt(10), [0, 0, 1, 1, 1, 1, 2, 1, 1, 1]); /// /// let prime_factor_cnt_90_to_99 = /// eu_primes::prime_factor_cnt(100).into_iter().skip(90).take(10).collect::<Vec<_>>(); /// assert_eq!(prime_factor_cnt_90_to_99, [3, 2, 2, 2, 2, 2, 2, 1, 2, 2]); /// ``` /// pub fn prime_factor_cnt(n: usize) -> Vec<usize> { let mut s = vec![0 as usize; n]; for (i, _) in s.clone().iter().enumerate().skip(2) { if s[i] == 0 { let mut j = i; while j < n { s[j] += 1; j += i } } } s }
prime_factors
identifier_name
primes.rs
//! Functions involving primes without dependencies. //! //! //! # Examples //! //! ``` //! use euler_library::primes as eu_primes; //! //! assert_eq!(eu_primes::prime_factors(84), [2, 2, 3, 7]); //! assert_eq!(eu_primes::prime_factors_unique(84), [2, 3, 7]); //! //! ``` /// Returns a vector of the prime factors n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::prime_factors(342), [2, 3, 3, 19]); /// assert_eq!(eu_primes::prime_factors(123), [3, 41]); /// ``` /// pub fn prime_factors(mut n: usize) -> Vec<usize> { let mut xs: Vec<usize> = Vec::new(); let mut i = 2; while n > 1 { while n % i == 0 { xs.push(i); n /= i; } i += 1; } xs } /// Returns a vector of the unique prime factors n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::prime_factors_unique(342), [2, 3, 19]); /// assert_eq!(eu_primes::prime_factors_unique(123), [3, 41]); /// ``` /// pub fn prime_factors_unique(n: usize) -> Vec<usize> { let mut xs = prime_factors(n); xs.dedup(); xs } /// Returns the sum of unique prime factors of n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::sopf(342), 24); /// assert_eq!(eu_primes::sopf(123), 44); /// ``` /// pub fn sopf(n: usize) -> usize { prime_factors_unique(n).iter().fold(0, |acc, x| acc + x) } /// Return a vector of the count of unique prime factors of i in 0..n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::prime_factor_cnt(10), [0, 0, 1, 1, 1, 1, 2, 1, 1, 1]); /// /// let prime_factor_cnt_90_to_99 = /// eu_primes::prime_factor_cnt(100).into_iter().skip(90).take(10).collect::<Vec<_>>(); /// assert_eq!(prime_factor_cnt_90_to_99, [3, 2, 2, 2, 2, 2, 2, 1, 2, 2]); /// ``` /// pub fn prime_factor_cnt(n: usize) -> Vec<usize> { let mut s = vec![0 as usize; n]; for (i, _) in s.clone().iter().enumerate().skip(2) { if s[i] == 0
} s }
{ let mut j = i; while j < n { s[j] += 1; j += i } }
conditional_block
primes.rs
//! Functions involving primes without dependencies. //! //! //! # Examples //! //! ``` //! use euler_library::primes as eu_primes; //! //! assert_eq!(eu_primes::prime_factors(84), [2, 2, 3, 7]); //! assert_eq!(eu_primes::prime_factors_unique(84), [2, 3, 7]); //! //! ``` /// Returns a vector of the prime factors n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::prime_factors(342), [2, 3, 3, 19]); /// assert_eq!(eu_primes::prime_factors(123), [3, 41]); /// ``` /// pub fn prime_factors(mut n: usize) -> Vec<usize> { let mut xs: Vec<usize> = Vec::new(); let mut i = 2; while n > 1 { while n % i == 0 { xs.push(i); n /= i; } i += 1; } xs } /// Returns a vector of the unique prime factors n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::prime_factors_unique(342), [2, 3, 19]); /// assert_eq!(eu_primes::prime_factors_unique(123), [3, 41]); /// ``` /// pub fn prime_factors_unique(n: usize) -> Vec<usize>
/// Returns the sum of unique prime factors of n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::sopf(342), 24); /// assert_eq!(eu_primes::sopf(123), 44); /// ``` /// pub fn sopf(n: usize) -> usize { prime_factors_unique(n).iter().fold(0, |acc, x| acc + x) } /// Return a vector of the count of unique prime factors of i in 0..n. /// /// ``` /// use euler_library::primes as eu_primes; /// /// assert_eq!(eu_primes::prime_factor_cnt(10), [0, 0, 1, 1, 1, 1, 2, 1, 1, 1]); /// /// let prime_factor_cnt_90_to_99 = /// eu_primes::prime_factor_cnt(100).into_iter().skip(90).take(10).collect::<Vec<_>>(); /// assert_eq!(prime_factor_cnt_90_to_99, [3, 2, 2, 2, 2, 2, 2, 1, 2, 2]); /// ``` /// pub fn prime_factor_cnt(n: usize) -> Vec<usize> { let mut s = vec![0 as usize; n]; for (i, _) in s.clone().iter().enumerate().skip(2) { if s[i] == 0 { let mut j = i; while j < n { s[j] += 1; j += i } } } s }
{ let mut xs = prime_factors(n); xs.dedup(); xs }
identifier_body
borrowck-univariant-enum.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(managed_boxes)] use std::cell::Cell; enum newtype { newtype(int) } pub fn main()
{ // Test that borrowck treats enums with a single variant // specially. let x = @Cell::new(5); let y = @Cell::new(newtype(3)); let z = match y.get() { newtype(b) => { x.set(x.get() + 1); x.get() * b } }; assert_eq!(z, 18); }
identifier_body
borrowck-univariant-enum.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(managed_boxes)] use std::cell::Cell; enum newtype { newtype(int)
} pub fn main() { // Test that borrowck treats enums with a single variant // specially. let x = @Cell::new(5); let y = @Cell::new(newtype(3)); let z = match y.get() { newtype(b) => { x.set(x.get() + 1); x.get() * b } }; assert_eq!(z, 18); }
random_line_split
borrowck-univariant-enum.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(managed_boxes)] use std::cell::Cell; enum newtype { newtype(int) } pub fn
() { // Test that borrowck treats enums with a single variant // specially. let x = @Cell::new(5); let y = @Cell::new(newtype(3)); let z = match y.get() { newtype(b) => { x.set(x.get() + 1); x.get() * b } }; assert_eq!(z, 18); }
main
identifier_name
issue-6157.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. pub trait OpInt<'a> { fn call<'a>(&'a self, int, int) -> int; } impl<'a> OpInt<'a> for |int, int|: 'a -> int { fn call(&self, a:int, b:int) -> int { (*self)(a, b)
} } fn squarei<'a>(x: int, op: &'a OpInt) -> int { op.call(x, x) } fn muli(x:int, y:int) -> int { x * y } pub fn main() { let f = |x,y| muli(x,y); { let g = &f; let h = g as &OpInt; squarei(3, h); } }
random_line_split
issue-6157.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. pub trait OpInt<'a> { fn call<'a>(&'a self, int, int) -> int; } impl<'a> OpInt<'a> for |int, int|: 'a -> int { fn call(&self, a:int, b:int) -> int { (*self)(a, b) } } fn squarei<'a>(x: int, op: &'a OpInt) -> int { op.call(x, x) } fn muli(x:int, y:int) -> int { x * y } pub fn
() { let f = |x,y| muli(x,y); { let g = &f; let h = g as &OpInt; squarei(3, h); } }
main
identifier_name
issue-6157.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. pub trait OpInt<'a> { fn call<'a>(&'a self, int, int) -> int; } impl<'a> OpInt<'a> for |int, int|: 'a -> int { fn call(&self, a:int, b:int) -> int
} fn squarei<'a>(x: int, op: &'a OpInt) -> int { op.call(x, x) } fn muli(x:int, y:int) -> int { x * y } pub fn main() { let f = |x,y| muli(x,y); { let g = &f; let h = g as &OpInt; squarei(3, h); } }
{ (*self)(a, b) }
identifier_body
domparser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::DOMParserBinding; use dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::{Text_html, Text_xml}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::document::{Document, DocumentHelpers, IsHTMLDocument}; use dom::document::DocumentSource; use dom::window::{Window, WindowHelpers}; use parse::html::{HTMLInput, parse_html}; use util::str::DOMString; use std::borrow::ToOwned; #[dom_struct] pub struct DOMParser { reflector_: Reflector, window: JS<Window>, //XXXjdm Document instead? } impl DOMParser { fn new_inherited(window: JSRef<Window>) -> DOMParser { DOMParser { reflector_: Reflector::new(), window: JS::from_rooted(window), } } pub fn new(window: JSRef<Window>) -> Temporary<DOMParser> { reflect_dom_object(box DOMParser::new_inherited(window), GlobalRef::Window(window), DOMParserBinding::Wrap) }
pub fn Constructor(global: GlobalRef) -> Fallible<Temporary<DOMParser>> { Ok(DOMParser::new(global.as_window())) } } impl<'a> DOMParserMethods for JSRef<'a, DOMParser> { // http://domparsing.spec.whatwg.org/#the-domparser-interface fn ParseFromString(self, s: DOMString, ty: DOMParserBinding::SupportedType) -> Fallible<Temporary<Document>> { let window = self.window.root(); let url = window.r().get_url(); let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as usize].to_owned(); match ty { Text_html => { let document = Document::new(window.r(), Some(url.clone()), IsHTMLDocument::HTMLDocument, Some(content_type), DocumentSource::FromParser).root(); parse_html(document.r(), HTMLInput::InputString(s), &url); document.r().set_ready_state(DocumentReadyState::Complete); Ok(Temporary::from_rooted(document.r())) } Text_xml => { //FIXME: this should probably be FromParser when we actually parse the string (#3756). Ok(Document::new(window.r(), Some(url.clone()), IsHTMLDocument::NonHTMLDocument, Some(content_type), DocumentSource::NotFromParser)) } } } }
random_line_split
domparser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::DOMParserBinding; use dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::{Text_html, Text_xml}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::document::{Document, DocumentHelpers, IsHTMLDocument}; use dom::document::DocumentSource; use dom::window::{Window, WindowHelpers}; use parse::html::{HTMLInput, parse_html}; use util::str::DOMString; use std::borrow::ToOwned; #[dom_struct] pub struct DOMParser { reflector_: Reflector, window: JS<Window>, //XXXjdm Document instead? } impl DOMParser { fn new_inherited(window: JSRef<Window>) -> DOMParser { DOMParser { reflector_: Reflector::new(), window: JS::from_rooted(window), } } pub fn
(window: JSRef<Window>) -> Temporary<DOMParser> { reflect_dom_object(box DOMParser::new_inherited(window), GlobalRef::Window(window), DOMParserBinding::Wrap) } pub fn Constructor(global: GlobalRef) -> Fallible<Temporary<DOMParser>> { Ok(DOMParser::new(global.as_window())) } } impl<'a> DOMParserMethods for JSRef<'a, DOMParser> { // http://domparsing.spec.whatwg.org/#the-domparser-interface fn ParseFromString(self, s: DOMString, ty: DOMParserBinding::SupportedType) -> Fallible<Temporary<Document>> { let window = self.window.root(); let url = window.r().get_url(); let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as usize].to_owned(); match ty { Text_html => { let document = Document::new(window.r(), Some(url.clone()), IsHTMLDocument::HTMLDocument, Some(content_type), DocumentSource::FromParser).root(); parse_html(document.r(), HTMLInput::InputString(s), &url); document.r().set_ready_state(DocumentReadyState::Complete); Ok(Temporary::from_rooted(document.r())) } Text_xml => { //FIXME: this should probably be FromParser when we actually parse the string (#3756). Ok(Document::new(window.r(), Some(url.clone()), IsHTMLDocument::NonHTMLDocument, Some(content_type), DocumentSource::NotFromParser)) } } } }
new
identifier_name
domparser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::DOMParserBinding; use dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::{Text_html, Text_xml}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::document::{Document, DocumentHelpers, IsHTMLDocument}; use dom::document::DocumentSource; use dom::window::{Window, WindowHelpers}; use parse::html::{HTMLInput, parse_html}; use util::str::DOMString; use std::borrow::ToOwned; #[dom_struct] pub struct DOMParser { reflector_: Reflector, window: JS<Window>, //XXXjdm Document instead? } impl DOMParser { fn new_inherited(window: JSRef<Window>) -> DOMParser
pub fn new(window: JSRef<Window>) -> Temporary<DOMParser> { reflect_dom_object(box DOMParser::new_inherited(window), GlobalRef::Window(window), DOMParserBinding::Wrap) } pub fn Constructor(global: GlobalRef) -> Fallible<Temporary<DOMParser>> { Ok(DOMParser::new(global.as_window())) } } impl<'a> DOMParserMethods for JSRef<'a, DOMParser> { // http://domparsing.spec.whatwg.org/#the-domparser-interface fn ParseFromString(self, s: DOMString, ty: DOMParserBinding::SupportedType) -> Fallible<Temporary<Document>> { let window = self.window.root(); let url = window.r().get_url(); let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as usize].to_owned(); match ty { Text_html => { let document = Document::new(window.r(), Some(url.clone()), IsHTMLDocument::HTMLDocument, Some(content_type), DocumentSource::FromParser).root(); parse_html(document.r(), HTMLInput::InputString(s), &url); document.r().set_ready_state(DocumentReadyState::Complete); Ok(Temporary::from_rooted(document.r())) } Text_xml => { //FIXME: this should probably be FromParser when we actually parse the string (#3756). Ok(Document::new(window.r(), Some(url.clone()), IsHTMLDocument::NonHTMLDocument, Some(content_type), DocumentSource::NotFromParser)) } } } }
{ DOMParser { reflector_: Reflector::new(), window: JS::from_rooted(window), } }
identifier_body
settings.rs
//! The configuration settings definitions.
pub struct GithubSettings { /// The OAuth app "client ID" pub client_id: String, /// The OAuth app "client secret" pub client_secret: String, /// A random string used to authenticate requests from github. Can be any /// random secret value and can change. pub state: String, /// The github organization we require users to be a member of. pub required_org: String, } /// Setting for daemonization #[derive(Debug, Deserialize)] pub struct DaemonizeSettings { /// Where to store pid file when daemonizing pub pid_file: String, } /// Configuration settings for app #[derive(Debug, Deserialize)] pub struct Settings { /// Configures github login pub github: GithubSettings, /// Path for sqlite database. #[serde(default = "default_database_file")] pub database_file: String, /// Directory to look for the web resources #[serde(default = "default_resource_dir")] pub resource_dir: String, /// The web root prefix #[serde(default = "default_web_root")] pub web_root: String, /// Bind address for HTTP server #[serde(default = "default_bind")] pub bind: String, /// Logging config #[serde(default)] pub log: sloggers::LoggerConfig, /// If and how to daemonize after start. pub daemonize: Option<DaemonizeSettings>, } // We set some defaults below. This seems to be the easiest way of doing it.... fn default_database_file() -> String { "shaft.db".to_string() } fn default_resource_dir() -> String { "res".to_string() } fn default_web_root() -> String { "/".to_string() } fn default_bind() -> String { "127.0.0.1:8975".to_string() }
use serde::Deserialize; /// Settings for github login. To configure a github OAuth app must have been /// provisioned. #[derive(Debug, Deserialize)]
random_line_split
settings.rs
//! The configuration settings definitions. use serde::Deserialize; /// Settings for github login. To configure a github OAuth app must have been /// provisioned. #[derive(Debug, Deserialize)] pub struct GithubSettings { /// The OAuth app "client ID" pub client_id: String, /// The OAuth app "client secret" pub client_secret: String, /// A random string used to authenticate requests from github. Can be any /// random secret value and can change. pub state: String, /// The github organization we require users to be a member of. pub required_org: String, } /// Setting for daemonization #[derive(Debug, Deserialize)] pub struct DaemonizeSettings { /// Where to store pid file when daemonizing pub pid_file: String, } /// Configuration settings for app #[derive(Debug, Deserialize)] pub struct Settings { /// Configures github login pub github: GithubSettings, /// Path for sqlite database. #[serde(default = "default_database_file")] pub database_file: String, /// Directory to look for the web resources #[serde(default = "default_resource_dir")] pub resource_dir: String, /// The web root prefix #[serde(default = "default_web_root")] pub web_root: String, /// Bind address for HTTP server #[serde(default = "default_bind")] pub bind: String, /// Logging config #[serde(default)] pub log: sloggers::LoggerConfig, /// If and how to daemonize after start. pub daemonize: Option<DaemonizeSettings>, } // We set some defaults below. This seems to be the easiest way of doing it.... fn default_database_file() -> String { "shaft.db".to_string() } fn default_resource_dir() -> String { "res".to_string() } fn
() -> String { "/".to_string() } fn default_bind() -> String { "127.0.0.1:8975".to_string() }
default_web_root
identifier_name
presentation.rs
/* * Copyright 2017 Sreejith Krishnan R * * 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 ::props::{Color, DisplayStyle, ScriptLevel, ScriptMinSize, ScriptSizeMultiplier}; use super::ConcreteLayout; use ::platform::Context; use ::draw::{Drawable, Wrapper}; pub struct PresentationLayout { pub(crate) math_color: Color, pub(crate) math_background: Color, pub(crate) display_style: DisplayStyle, pub(crate) script_level: ScriptLevel, pub(crate) script_min_size: ScriptMinSize, pub(crate) script_size_multiplier: ScriptSizeMultiplier, } fn math_background_reader(element: &PresentationLayout) -> &Color
impl<'a, U: Drawable + 'a> ConcreteLayout<'a, Wrapper<'a, PresentationLayout, U>> for PresentationLayout { fn layout(&'a self, _: &Context) -> Wrapper<'a, PresentationLayout, U> { Wrapper::<'a, PresentationLayout, U>::new( self, math_background_reader ) } } // TODO remove impl PresentationLayout { pub fn new(math_color: Color, math_background: Color) -> PresentationLayout { PresentationLayout { math_color, math_background, display_style: false, script_level: ScriptLevel::new(0, 12.), script_min_size: 0.0, script_size_multiplier: 0.0 } } }
{ &element.math_background }
identifier_body
presentation.rs
/* * Copyright 2017 Sreejith Krishnan R * * 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 ::props::{Color, DisplayStyle, ScriptLevel, ScriptMinSize, ScriptSizeMultiplier}; use super::ConcreteLayout; use ::platform::Context; use ::draw::{Drawable, Wrapper}; pub struct PresentationLayout { pub(crate) math_color: Color, pub(crate) math_background: Color,
pub(crate) script_size_multiplier: ScriptSizeMultiplier, } fn math_background_reader(element: &PresentationLayout) -> &Color { &element.math_background } impl<'a, U: Drawable + 'a> ConcreteLayout<'a, Wrapper<'a, PresentationLayout, U>> for PresentationLayout { fn layout(&'a self, _: &Context) -> Wrapper<'a, PresentationLayout, U> { Wrapper::<'a, PresentationLayout, U>::new( self, math_background_reader ) } } // TODO remove impl PresentationLayout { pub fn new(math_color: Color, math_background: Color) -> PresentationLayout { PresentationLayout { math_color, math_background, display_style: false, script_level: ScriptLevel::new(0, 12.), script_min_size: 0.0, script_size_multiplier: 0.0 } } }
pub(crate) display_style: DisplayStyle, pub(crate) script_level: ScriptLevel, pub(crate) script_min_size: ScriptMinSize,
random_line_split
presentation.rs
/* * Copyright 2017 Sreejith Krishnan R * * 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 ::props::{Color, DisplayStyle, ScriptLevel, ScriptMinSize, ScriptSizeMultiplier}; use super::ConcreteLayout; use ::platform::Context; use ::draw::{Drawable, Wrapper}; pub struct PresentationLayout { pub(crate) math_color: Color, pub(crate) math_background: Color, pub(crate) display_style: DisplayStyle, pub(crate) script_level: ScriptLevel, pub(crate) script_min_size: ScriptMinSize, pub(crate) script_size_multiplier: ScriptSizeMultiplier, } fn math_background_reader(element: &PresentationLayout) -> &Color { &element.math_background } impl<'a, U: Drawable + 'a> ConcreteLayout<'a, Wrapper<'a, PresentationLayout, U>> for PresentationLayout { fn
(&'a self, _: &Context) -> Wrapper<'a, PresentationLayout, U> { Wrapper::<'a, PresentationLayout, U>::new( self, math_background_reader ) } } // TODO remove impl PresentationLayout { pub fn new(math_color: Color, math_background: Color) -> PresentationLayout { PresentationLayout { math_color, math_background, display_style: false, script_level: ScriptLevel::new(0, 12.), script_min_size: 0.0, script_size_multiplier: 0.0 } } }
layout
identifier_name
test.rs
use std::thread; use std::time::Duration; use std::sync::mpsc::channel; /// Check if a function `f` terminates within a given timeframe. /// /// It is used to check for deadlocks. /// /// If the function does not terminate, it keeps a thread alive forever, /// so don't run too many test (preferable just one) in sequence. pub fn terminates<F>(duration_ms: u64, f: F) -> bool where F: Send + FnOnce() -> () +'static,
pub fn terminates_async<F, F2>(duration_ms: u64, f: F, f2: F2) -> bool where F: Send + FnOnce() -> () +'static, F2: FnOnce() -> () { async(duration_ms, f, f2).is_some() } pub fn async<T, F, F2>(duration_ms: u64, f: F, f2: F2) -> Option<T> where F: Send + FnOnce() -> T +'static, F2: FnOnce() -> (), T: Send +'static, { let (tx, rx) = channel(); thread::spawn(move || { let t = f(); // wakeup other thread let _ = tx.send(t); }); f2(); if let a@Some(_) = rx.try_recv().ok() { return a; } for _ in 0..duration_ms/50 { thread::sleep(Duration::from_millis(50)); if let a@Some(_) = rx.try_recv().ok() { return a; } } thread::sleep(Duration::from_millis(duration_ms % 50)); rx.try_recv().ok() }
{ terminates_async(duration_ms, f, || {}) }
identifier_body
test.rs
use std::thread; use std::time::Duration; use std::sync::mpsc::channel; /// Check if a function `f` terminates within a given timeframe. /// /// It is used to check for deadlocks. /// /// If the function does not terminate, it keeps a thread alive forever, /// so don't run too many test (preferable just one) in sequence. pub fn terminates<F>(duration_ms: u64, f: F) -> bool where F: Send + FnOnce() -> () +'static, { terminates_async(duration_ms, f, || {}) } pub fn terminates_async<F, F2>(duration_ms: u64, f: F, f2: F2) -> bool where F: Send + FnOnce() -> () +'static, F2: FnOnce() -> () { async(duration_ms, f, f2).is_some() } pub fn async<T, F, F2>(duration_ms: u64, f: F, f2: F2) -> Option<T> where F: Send + FnOnce() -> T +'static, F2: FnOnce() -> (), T: Send +'static, { let (tx, rx) = channel(); thread::spawn(move || { let t = f(); // wakeup other thread let _ = tx.send(t); }); f2(); if let a@Some(_) = rx.try_recv().ok() { return a; } for _ in 0..duration_ms/50 { thread::sleep(Duration::from_millis(50)); if let a@Some(_) = rx.try_recv().ok()
} thread::sleep(Duration::from_millis(duration_ms % 50)); rx.try_recv().ok() }
{ return a; }
conditional_block
test.rs
use std::thread; use std::time::Duration; use std::sync::mpsc::channel; /// Check if a function `f` terminates within a given timeframe. /// /// It is used to check for deadlocks. /// /// If the function does not terminate, it keeps a thread alive forever, /// so don't run too many test (preferable just one) in sequence. pub fn terminates<F>(duration_ms: u64, f: F) -> bool where F: Send + FnOnce() -> () +'static, { terminates_async(duration_ms, f, || {}) } pub fn terminates_async<F, F2>(duration_ms: u64, f: F, f2: F2) -> bool where F: Send + FnOnce() -> () +'static, F2: FnOnce() -> () { async(duration_ms, f, f2).is_some() } pub fn async<T, F, F2>(duration_ms: u64, f: F, f2: F2) -> Option<T> where F: Send + FnOnce() -> T +'static, F2: FnOnce() -> (), T: Send +'static, { let (tx, rx) = channel(); thread::spawn(move || { let t = f(); // wakeup other thread let _ = tx.send(t); }); f2(); if let a@Some(_) = rx.try_recv().ok() { return a; } for _ in 0..duration_ms/50 { thread::sleep(Duration::from_millis(50)); if let a@Some(_) = rx.try_recv().ok() { return a; }
thread::sleep(Duration::from_millis(duration_ms % 50)); rx.try_recv().ok() }
}
random_line_split
test.rs
use std::thread; use std::time::Duration; use std::sync::mpsc::channel; /// Check if a function `f` terminates within a given timeframe. /// /// It is used to check for deadlocks. /// /// If the function does not terminate, it keeps a thread alive forever, /// so don't run too many test (preferable just one) in sequence. pub fn terminates<F>(duration_ms: u64, f: F) -> bool where F: Send + FnOnce() -> () +'static, { terminates_async(duration_ms, f, || {}) } pub fn terminates_async<F, F2>(duration_ms: u64, f: F, f2: F2) -> bool where F: Send + FnOnce() -> () +'static, F2: FnOnce() -> () { async(duration_ms, f, f2).is_some() } pub fn
<T, F, F2>(duration_ms: u64, f: F, f2: F2) -> Option<T> where F: Send + FnOnce() -> T +'static, F2: FnOnce() -> (), T: Send +'static, { let (tx, rx) = channel(); thread::spawn(move || { let t = f(); // wakeup other thread let _ = tx.send(t); }); f2(); if let a@Some(_) = rx.try_recv().ok() { return a; } for _ in 0..duration_ms/50 { thread::sleep(Duration::from_millis(50)); if let a@Some(_) = rx.try_recv().ok() { return a; } } thread::sleep(Duration::from_millis(duration_ms % 50)); rx.try_recv().ok() }
async
identifier_name
config.rs
// Copyright 2021 The Grin 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. //! Configuration file management use rand::distributions::{Alphanumeric, Distribution}; use rand::thread_rng; use std::env; use std::fs::{self, File}; use std::io::prelude::*; use std::io::BufReader; use std::path::PathBuf; use crate::comments::insert_comments; use crate::core::global; use crate::p2p; use crate::servers::ServerConfig; use crate::types::{ConfigError, ConfigMembers, GlobalConfig}; use crate::util::logger::LoggingConfig; /// The default file name to use when trying to derive /// the node config file location pub const SERVER_CONFIG_FILE_NAME: &str = "grin-server.toml"; const SERVER_LOG_FILE_NAME: &str = "grin-server.log"; const GRIN_HOME: &str = ".grin"; const GRIN_CHAIN_DIR: &str = "chain_data"; /// Node Rest API and V2 Owner API secret pub const API_SECRET_FILE_NAME: &str = ".api_secret"; /// Foreign API secret pub const FOREIGN_API_SECRET_FILE_NAME: &str = ".foreign_api_secret"; fn get_grin_path(chain_type: &global::ChainTypes) -> Result<PathBuf, ConfigError> { // Check if grin dir exists let mut grin_path = match dirs::home_dir() { Some(p) => p, None => PathBuf::new(), }; grin_path.push(GRIN_HOME); grin_path.push(chain_type.shortname()); // Create if the default path doesn't exist if!grin_path.exists() { fs::create_dir_all(grin_path.clone())?; } Ok(grin_path) } fn check_config_current_dir(path: &str) -> Option<PathBuf> { let p = env::current_dir(); let mut c = match p { Ok(c) => c, Err(_) => { return None; } }; c.push(path); if c.exists() { return Some(c); } None } /// Create file with api secret pub fn init_api_secret(api_secret_path: &PathBuf) -> Result<(), ConfigError> { let mut api_secret_file = File::create(api_secret_path)?; let api_secret: String = Alphanumeric .sample_iter(&mut thread_rng()) .take(20) .collect(); api_secret_file.write_all(api_secret.as_bytes())?; Ok(()) } /// Check if file contains a secret and nothing else pub fn check_api_secret(api_secret_path: &PathBuf) -> Result<(), ConfigError> { let api_secret_file = File::open(api_secret_path)?; let buf_reader = BufReader::new(api_secret_file); let mut lines_iter = buf_reader.lines(); let first_line = lines_iter.next(); if first_line.is_none() || first_line.unwrap().is_err() { fs::remove_file(api_secret_path)?; init_api_secret(api_secret_path)?; } Ok(()) } /// Check that the api secret files exist and are valid fn check_api_secret_files( chain_type: &global::ChainTypes, secret_file_name: &str, ) -> Result<(), ConfigError> { let grin_path = get_grin_path(chain_type)?; let mut api_secret_path = grin_path; api_secret_path.push(secret_file_name); if!api_secret_path.exists() { init_api_secret(&api_secret_path) } else { check_api_secret(&api_secret_path) } } /// Handles setup and detection of paths for node pub fn initial_setup_server(chain_type: &global::ChainTypes) -> Result<GlobalConfig, ConfigError> { check_api_secret_files(chain_type, API_SECRET_FILE_NAME)?; check_api_secret_files(chain_type, FOREIGN_API_SECRET_FILE_NAME)?; // Use config file if current directory if it exists,.grin home otherwise if let Some(p) = check_config_current_dir(SERVER_CONFIG_FILE_NAME) { GlobalConfig::new(p.to_str().unwrap()) } else { // Check if grin dir exists let grin_path = get_grin_path(chain_type)?; // Get path to default config file let mut config_path = grin_path.clone(); config_path.push(SERVER_CONFIG_FILE_NAME); // Spit it out if it doesn't exist if!config_path.exists() { let mut default_config = GlobalConfig::for_chain(chain_type); // update paths relative to current dir default_config.update_paths(&grin_path); default_config.write_to_file(config_path.to_str().unwrap())?; } GlobalConfig::new(config_path.to_str().unwrap()) } } /// Returns the defaults, as strewn throughout the code impl Default for ConfigMembers { fn default() -> ConfigMembers { ConfigMembers { config_file_version: Some(2), server: ServerConfig::default(), logging: Some(LoggingConfig::default()), } } } impl Default for GlobalConfig { fn default() -> GlobalConfig { GlobalConfig { config_file_path: None, members: Some(ConfigMembers::default()), } } } impl GlobalConfig { /// Same as GlobalConfig::default() but further tweaks parameters to /// apply defaults for each chain type pub fn for_chain(chain_type: &global::ChainTypes) -> GlobalConfig { let mut defaults_conf = GlobalConfig::default(); let mut defaults = &mut defaults_conf.members.as_mut().unwrap().server; defaults.chain_type = chain_type.clone(); match *chain_type { global::ChainTypes::Mainnet => {} global::ChainTypes::Testnet => { defaults.api_http_addr = "127.0.0.1:13413".to_owned(); defaults.p2p_config.port = 13414; defaults .stratum_mining_config .as_mut() .unwrap() .stratum_server_addr = Some("127.0.0.1:13416".to_owned()); defaults .stratum_mining_config .as_mut() .unwrap() .wallet_listener_url = "http://127.0.0.1:13415".to_owned(); } global::ChainTypes::UserTesting => { defaults.api_http_addr = "127.0.0.1:23413".to_owned(); defaults.p2p_config.port = 23414; defaults.p2p_config.seeding_type = p2p::Seeding::None; defaults .stratum_mining_config .as_mut() .unwrap() .stratum_server_addr = Some("127.0.0.1:23416".to_owned()); defaults .stratum_mining_config .as_mut() .unwrap() .wallet_listener_url = "http://127.0.0.1:23415".to_owned(); } global::ChainTypes::AutomatedTesting => { panic!("Can't run automated testing directly"); } } defaults_conf } /// Requires the path to a config file pub fn new(file_path: &str) -> Result<GlobalConfig, ConfigError> { let mut return_value = GlobalConfig::default(); return_value.config_file_path = Some(PathBuf::from(&file_path)); // Config file path is given but not valid let config_file = return_value.config_file_path.clone().unwrap(); if!config_file.exists() { return Err(ConfigError::FileNotFoundError(String::from( config_file.to_str().unwrap(), ))); } // Try to parse the config file if it exists, explode if it does exist but // something's wrong with it return_value.read_config() } /// Read config fn read_config(mut self) -> Result<GlobalConfig, ConfigError> { let config_file_path = self.config_file_path.as_ref().unwrap(); let contents = fs::read_to_string(config_file_path)?; let migrated = GlobalConfig::migrate_config_file_version_none_to_2(contents.clone()); if contents!= migrated { fs::write(config_file_path, &migrated)?; } let fixed = GlobalConfig::fix_warning_level(migrated); let decoded: Result<ConfigMembers, toml::de::Error> = toml::from_str(&fixed); match decoded { Ok(gc) => { self.members = Some(gc); return Ok(self); } Err(e) => { return Err(ConfigError::ParseError( self.config_file_path.unwrap().to_str().unwrap().to_string(), format!("{}", e), )); } } } /// Update paths pub fn update_paths(&mut self, grin_home: &PathBuf) { // need to update server chain path let mut chain_path = grin_home.clone(); chain_path.push(GRIN_CHAIN_DIR); self.members.as_mut().unwrap().server.db_root = chain_path.to_str().unwrap().to_owned(); let mut api_secret_path = grin_home.clone(); api_secret_path.push(API_SECRET_FILE_NAME); self.members.as_mut().unwrap().server.api_secret_path = Some(api_secret_path.to_str().unwrap().to_owned()); let mut foreign_api_secret_path = grin_home.clone(); foreign_api_secret_path.push(FOREIGN_API_SECRET_FILE_NAME); self.members .as_mut() .unwrap() .server .foreign_api_secret_path = Some(foreign_api_secret_path.to_str().unwrap().to_owned()); let mut log_path = grin_home.clone(); log_path.push(SERVER_LOG_FILE_NAME); self.members .as_mut() .unwrap() .logging .as_mut() .unwrap() .log_file_path = log_path.to_str().unwrap().to_owned(); } /// Enable mining pub fn stratum_enabled(&mut self) -> bool { return self .members .as_mut() .unwrap() .server .stratum_mining_config .as_mut() .unwrap() .enable_stratum_server .unwrap(); } /// Serialize config pub fn ser_config(&mut self) -> Result<String, ConfigError> { let encoded: Result<String, toml::ser::Error> = toml::to_string(self.members.as_mut().unwrap()); match encoded { Ok(enc) => return Ok(enc), Err(e) => { return Err(ConfigError::SerializationError(format!("{}", e))); } } } /// Write configuration to a file pub fn write_to_file(&mut self, name: &str) -> Result<(), ConfigError> { let conf_out = self.ser_config()?; let fixed_config = GlobalConfig::fix_log_level(conf_out); let commented_config = insert_comments(fixed_config); let mut file = File::create(name)?; file.write_all(commented_config.as_bytes())?; Ok(()) } /// This migration does the following: /// - Adds "config_file_version = 2" /// - If server.pool_config.accept_fee_base is 1000000, change it to 500000 /// - Remove "#a setting to 1000000 will be overridden to 500000 to respect the fixfees RFC" fn migrate_config_file_version_none_to_2(config_str: String) -> String { // Parse existing config and return unchanged if not eligible for migration let mut config: ConfigMembers = toml::from_str(&GlobalConfig::fix_warning_level(config_str.clone())).unwrap(); if config.config_file_version!= None { return config_str; } // Apply changes both textually and structurally let config_str = config_str.replace("\n#########################################\n### SERVER CONFIGURATION ###", "\nconfig_file_version = 2\n\n#########################################\n### SERVER CONFIGURATION ###"); config.config_file_version = Some(2); let config_str = config_str.replace( "\naccept_fee_base = 1000000\n", "\naccept_fee_base = 500000\n", ); if config.server.pool_config.accept_fee_base == 1000000 { config.server.pool_config.accept_fee_base = 500000; } let config_str = config_str.replace( "\n#a setting to 1000000 will be overridden to 500000 to respect the fixfees RFC\n", "\n", ); // Verify equivalence assert_eq!( config, toml::from_str(&GlobalConfig::fix_warning_level(config_str.clone())).unwrap() );
// For forwards compatibility old config needs `Warning` log level changed to standard log::Level `WARN` fn fix_warning_level(conf: String) -> String { conf.replace("Warning", "WARN") } // For backwards compatibility only first letter of log level should be capitalised. fn fix_log_level(conf: String) -> String { conf.replace("TRACE", "Trace") .replace("DEBUG", "Debug") .replace("INFO", "Info") .replace("WARN", "Warning") .replace("ERROR", "Error") } } #[test] fn test_fix_log_level() { let config = "TRACE DEBUG INFO WARN ERROR".to_string(); let fixed_config = GlobalConfig::fix_log_level(config); assert_eq!(fixed_config, "Trace Debug Info Warning Error"); } #[test] fn test_fix_warning_level() { let config = "Warning".to_string(); let fixed_config = GlobalConfig::fix_warning_level(config); assert_eq!(fixed_config, "WARN"); }
config_str }
random_line_split
config.rs
// Copyright 2021 The Grin 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. //! Configuration file management use rand::distributions::{Alphanumeric, Distribution}; use rand::thread_rng; use std::env; use std::fs::{self, File}; use std::io::prelude::*; use std::io::BufReader; use std::path::PathBuf; use crate::comments::insert_comments; use crate::core::global; use crate::p2p; use crate::servers::ServerConfig; use crate::types::{ConfigError, ConfigMembers, GlobalConfig}; use crate::util::logger::LoggingConfig; /// The default file name to use when trying to derive /// the node config file location pub const SERVER_CONFIG_FILE_NAME: &str = "grin-server.toml"; const SERVER_LOG_FILE_NAME: &str = "grin-server.log"; const GRIN_HOME: &str = ".grin"; const GRIN_CHAIN_DIR: &str = "chain_data"; /// Node Rest API and V2 Owner API secret pub const API_SECRET_FILE_NAME: &str = ".api_secret"; /// Foreign API secret pub const FOREIGN_API_SECRET_FILE_NAME: &str = ".foreign_api_secret"; fn get_grin_path(chain_type: &global::ChainTypes) -> Result<PathBuf, ConfigError> { // Check if grin dir exists let mut grin_path = match dirs::home_dir() { Some(p) => p, None => PathBuf::new(), }; grin_path.push(GRIN_HOME); grin_path.push(chain_type.shortname()); // Create if the default path doesn't exist if!grin_path.exists() { fs::create_dir_all(grin_path.clone())?; } Ok(grin_path) } fn check_config_current_dir(path: &str) -> Option<PathBuf> { let p = env::current_dir(); let mut c = match p { Ok(c) => c, Err(_) => { return None; } }; c.push(path); if c.exists() { return Some(c); } None } /// Create file with api secret pub fn init_api_secret(api_secret_path: &PathBuf) -> Result<(), ConfigError> { let mut api_secret_file = File::create(api_secret_path)?; let api_secret: String = Alphanumeric .sample_iter(&mut thread_rng()) .take(20) .collect(); api_secret_file.write_all(api_secret.as_bytes())?; Ok(()) } /// Check if file contains a secret and nothing else pub fn check_api_secret(api_secret_path: &PathBuf) -> Result<(), ConfigError> { let api_secret_file = File::open(api_secret_path)?; let buf_reader = BufReader::new(api_secret_file); let mut lines_iter = buf_reader.lines(); let first_line = lines_iter.next(); if first_line.is_none() || first_line.unwrap().is_err() { fs::remove_file(api_secret_path)?; init_api_secret(api_secret_path)?; } Ok(()) } /// Check that the api secret files exist and are valid fn check_api_secret_files( chain_type: &global::ChainTypes, secret_file_name: &str, ) -> Result<(), ConfigError> { let grin_path = get_grin_path(chain_type)?; let mut api_secret_path = grin_path; api_secret_path.push(secret_file_name); if!api_secret_path.exists() { init_api_secret(&api_secret_path) } else { check_api_secret(&api_secret_path) } } /// Handles setup and detection of paths for node pub fn initial_setup_server(chain_type: &global::ChainTypes) -> Result<GlobalConfig, ConfigError> { check_api_secret_files(chain_type, API_SECRET_FILE_NAME)?; check_api_secret_files(chain_type, FOREIGN_API_SECRET_FILE_NAME)?; // Use config file if current directory if it exists,.grin home otherwise if let Some(p) = check_config_current_dir(SERVER_CONFIG_FILE_NAME) { GlobalConfig::new(p.to_str().unwrap()) } else { // Check if grin dir exists let grin_path = get_grin_path(chain_type)?; // Get path to default config file let mut config_path = grin_path.clone(); config_path.push(SERVER_CONFIG_FILE_NAME); // Spit it out if it doesn't exist if!config_path.exists() { let mut default_config = GlobalConfig::for_chain(chain_type); // update paths relative to current dir default_config.update_paths(&grin_path); default_config.write_to_file(config_path.to_str().unwrap())?; } GlobalConfig::new(config_path.to_str().unwrap()) } } /// Returns the defaults, as strewn throughout the code impl Default for ConfigMembers { fn default() -> ConfigMembers { ConfigMembers { config_file_version: Some(2), server: ServerConfig::default(), logging: Some(LoggingConfig::default()), } } } impl Default for GlobalConfig { fn default() -> GlobalConfig { GlobalConfig { config_file_path: None, members: Some(ConfigMembers::default()), } } } impl GlobalConfig { /// Same as GlobalConfig::default() but further tweaks parameters to /// apply defaults for each chain type pub fn for_chain(chain_type: &global::ChainTypes) -> GlobalConfig { let mut defaults_conf = GlobalConfig::default(); let mut defaults = &mut defaults_conf.members.as_mut().unwrap().server; defaults.chain_type = chain_type.clone(); match *chain_type { global::ChainTypes::Mainnet => {} global::ChainTypes::Testnet => { defaults.api_http_addr = "127.0.0.1:13413".to_owned(); defaults.p2p_config.port = 13414; defaults .stratum_mining_config .as_mut() .unwrap() .stratum_server_addr = Some("127.0.0.1:13416".to_owned()); defaults .stratum_mining_config .as_mut() .unwrap() .wallet_listener_url = "http://127.0.0.1:13415".to_owned(); } global::ChainTypes::UserTesting => { defaults.api_http_addr = "127.0.0.1:23413".to_owned(); defaults.p2p_config.port = 23414; defaults.p2p_config.seeding_type = p2p::Seeding::None; defaults .stratum_mining_config .as_mut() .unwrap() .stratum_server_addr = Some("127.0.0.1:23416".to_owned()); defaults .stratum_mining_config .as_mut() .unwrap() .wallet_listener_url = "http://127.0.0.1:23415".to_owned(); } global::ChainTypes::AutomatedTesting => { panic!("Can't run automated testing directly"); } } defaults_conf } /// Requires the path to a config file pub fn new(file_path: &str) -> Result<GlobalConfig, ConfigError> { let mut return_value = GlobalConfig::default(); return_value.config_file_path = Some(PathBuf::from(&file_path)); // Config file path is given but not valid let config_file = return_value.config_file_path.clone().unwrap(); if!config_file.exists() { return Err(ConfigError::FileNotFoundError(String::from( config_file.to_str().unwrap(), ))); } // Try to parse the config file if it exists, explode if it does exist but // something's wrong with it return_value.read_config() } /// Read config fn read_config(mut self) -> Result<GlobalConfig, ConfigError> { let config_file_path = self.config_file_path.as_ref().unwrap(); let contents = fs::read_to_string(config_file_path)?; let migrated = GlobalConfig::migrate_config_file_version_none_to_2(contents.clone()); if contents!= migrated { fs::write(config_file_path, &migrated)?; } let fixed = GlobalConfig::fix_warning_level(migrated); let decoded: Result<ConfigMembers, toml::de::Error> = toml::from_str(&fixed); match decoded { Ok(gc) => { self.members = Some(gc); return Ok(self); } Err(e) => { return Err(ConfigError::ParseError( self.config_file_path.unwrap().to_str().unwrap().to_string(), format!("{}", e), )); } } } /// Update paths pub fn update_paths(&mut self, grin_home: &PathBuf) { // need to update server chain path let mut chain_path = grin_home.clone(); chain_path.push(GRIN_CHAIN_DIR); self.members.as_mut().unwrap().server.db_root = chain_path.to_str().unwrap().to_owned(); let mut api_secret_path = grin_home.clone(); api_secret_path.push(API_SECRET_FILE_NAME); self.members.as_mut().unwrap().server.api_secret_path = Some(api_secret_path.to_str().unwrap().to_owned()); let mut foreign_api_secret_path = grin_home.clone(); foreign_api_secret_path.push(FOREIGN_API_SECRET_FILE_NAME); self.members .as_mut() .unwrap() .server .foreign_api_secret_path = Some(foreign_api_secret_path.to_str().unwrap().to_owned()); let mut log_path = grin_home.clone(); log_path.push(SERVER_LOG_FILE_NAME); self.members .as_mut() .unwrap() .logging .as_mut() .unwrap() .log_file_path = log_path.to_str().unwrap().to_owned(); } /// Enable mining pub fn stratum_enabled(&mut self) -> bool { return self .members .as_mut() .unwrap() .server .stratum_mining_config .as_mut() .unwrap() .enable_stratum_server .unwrap(); } /// Serialize config pub fn ser_config(&mut self) -> Result<String, ConfigError> { let encoded: Result<String, toml::ser::Error> = toml::to_string(self.members.as_mut().unwrap()); match encoded { Ok(enc) => return Ok(enc), Err(e) => { return Err(ConfigError::SerializationError(format!("{}", e))); } } } /// Write configuration to a file pub fn write_to_file(&mut self, name: &str) -> Result<(), ConfigError>
/// This migration does the following: /// - Adds "config_file_version = 2" /// - If server.pool_config.accept_fee_base is 1000000, change it to 500000 /// - Remove "#a setting to 1000000 will be overridden to 500000 to respect the fixfees RFC" fn migrate_config_file_version_none_to_2(config_str: String) -> String { // Parse existing config and return unchanged if not eligible for migration let mut config: ConfigMembers = toml::from_str(&GlobalConfig::fix_warning_level(config_str.clone())).unwrap(); if config.config_file_version!= None { return config_str; } // Apply changes both textually and structurally let config_str = config_str.replace("\n#########################################\n### SERVER CONFIGURATION ###", "\nconfig_file_version = 2\n\n#########################################\n### SERVER CONFIGURATION ###"); config.config_file_version = Some(2); let config_str = config_str.replace( "\naccept_fee_base = 1000000\n", "\naccept_fee_base = 500000\n", ); if config.server.pool_config.accept_fee_base == 1000000 { config.server.pool_config.accept_fee_base = 500000; } let config_str = config_str.replace( "\n#a setting to 1000000 will be overridden to 500000 to respect the fixfees RFC\n", "\n", ); // Verify equivalence assert_eq!( config, toml::from_str(&GlobalConfig::fix_warning_level(config_str.clone())).unwrap() ); config_str } // For forwards compatibility old config needs `Warning` log level changed to standard log::Level `WARN` fn fix_warning_level(conf: String) -> String { conf.replace("Warning", "WARN") } // For backwards compatibility only first letter of log level should be capitalised. fn fix_log_level(conf: String) -> String { conf.replace("TRACE", "Trace") .replace("DEBUG", "Debug") .replace("INFO", "Info") .replace("WARN", "Warning") .replace("ERROR", "Error") } } #[test] fn test_fix_log_level() { let config = "TRACE DEBUG INFO WARN ERROR".to_string(); let fixed_config = GlobalConfig::fix_log_level(config); assert_eq!(fixed_config, "Trace Debug Info Warning Error"); } #[test] fn test_fix_warning_level() { let config = "Warning".to_string(); let fixed_config = GlobalConfig::fix_warning_level(config); assert_eq!(fixed_config, "WARN"); }
{ let conf_out = self.ser_config()?; let fixed_config = GlobalConfig::fix_log_level(conf_out); let commented_config = insert_comments(fixed_config); let mut file = File::create(name)?; file.write_all(commented_config.as_bytes())?; Ok(()) }
identifier_body
config.rs
// Copyright 2021 The Grin 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. //! Configuration file management use rand::distributions::{Alphanumeric, Distribution}; use rand::thread_rng; use std::env; use std::fs::{self, File}; use std::io::prelude::*; use std::io::BufReader; use std::path::PathBuf; use crate::comments::insert_comments; use crate::core::global; use crate::p2p; use crate::servers::ServerConfig; use crate::types::{ConfigError, ConfigMembers, GlobalConfig}; use crate::util::logger::LoggingConfig; /// The default file name to use when trying to derive /// the node config file location pub const SERVER_CONFIG_FILE_NAME: &str = "grin-server.toml"; const SERVER_LOG_FILE_NAME: &str = "grin-server.log"; const GRIN_HOME: &str = ".grin"; const GRIN_CHAIN_DIR: &str = "chain_data"; /// Node Rest API and V2 Owner API secret pub const API_SECRET_FILE_NAME: &str = ".api_secret"; /// Foreign API secret pub const FOREIGN_API_SECRET_FILE_NAME: &str = ".foreign_api_secret"; fn get_grin_path(chain_type: &global::ChainTypes) -> Result<PathBuf, ConfigError> { // Check if grin dir exists let mut grin_path = match dirs::home_dir() { Some(p) => p, None => PathBuf::new(), }; grin_path.push(GRIN_HOME); grin_path.push(chain_type.shortname()); // Create if the default path doesn't exist if!grin_path.exists() { fs::create_dir_all(grin_path.clone())?; } Ok(grin_path) } fn check_config_current_dir(path: &str) -> Option<PathBuf> { let p = env::current_dir(); let mut c = match p { Ok(c) => c, Err(_) => { return None; } }; c.push(path); if c.exists() { return Some(c); } None } /// Create file with api secret pub fn init_api_secret(api_secret_path: &PathBuf) -> Result<(), ConfigError> { let mut api_secret_file = File::create(api_secret_path)?; let api_secret: String = Alphanumeric .sample_iter(&mut thread_rng()) .take(20) .collect(); api_secret_file.write_all(api_secret.as_bytes())?; Ok(()) } /// Check if file contains a secret and nothing else pub fn check_api_secret(api_secret_path: &PathBuf) -> Result<(), ConfigError> { let api_secret_file = File::open(api_secret_path)?; let buf_reader = BufReader::new(api_secret_file); let mut lines_iter = buf_reader.lines(); let first_line = lines_iter.next(); if first_line.is_none() || first_line.unwrap().is_err() { fs::remove_file(api_secret_path)?; init_api_secret(api_secret_path)?; } Ok(()) } /// Check that the api secret files exist and are valid fn check_api_secret_files( chain_type: &global::ChainTypes, secret_file_name: &str, ) -> Result<(), ConfigError> { let grin_path = get_grin_path(chain_type)?; let mut api_secret_path = grin_path; api_secret_path.push(secret_file_name); if!api_secret_path.exists() { init_api_secret(&api_secret_path) } else { check_api_secret(&api_secret_path) } } /// Handles setup and detection of paths for node pub fn initial_setup_server(chain_type: &global::ChainTypes) -> Result<GlobalConfig, ConfigError> { check_api_secret_files(chain_type, API_SECRET_FILE_NAME)?; check_api_secret_files(chain_type, FOREIGN_API_SECRET_FILE_NAME)?; // Use config file if current directory if it exists,.grin home otherwise if let Some(p) = check_config_current_dir(SERVER_CONFIG_FILE_NAME) { GlobalConfig::new(p.to_str().unwrap()) } else { // Check if grin dir exists let grin_path = get_grin_path(chain_type)?; // Get path to default config file let mut config_path = grin_path.clone(); config_path.push(SERVER_CONFIG_FILE_NAME); // Spit it out if it doesn't exist if!config_path.exists() { let mut default_config = GlobalConfig::for_chain(chain_type); // update paths relative to current dir default_config.update_paths(&grin_path); default_config.write_to_file(config_path.to_str().unwrap())?; } GlobalConfig::new(config_path.to_str().unwrap()) } } /// Returns the defaults, as strewn throughout the code impl Default for ConfigMembers { fn default() -> ConfigMembers { ConfigMembers { config_file_version: Some(2), server: ServerConfig::default(), logging: Some(LoggingConfig::default()), } } } impl Default for GlobalConfig { fn default() -> GlobalConfig { GlobalConfig { config_file_path: None, members: Some(ConfigMembers::default()), } } } impl GlobalConfig { /// Same as GlobalConfig::default() but further tweaks parameters to /// apply defaults for each chain type pub fn for_chain(chain_type: &global::ChainTypes) -> GlobalConfig { let mut defaults_conf = GlobalConfig::default(); let mut defaults = &mut defaults_conf.members.as_mut().unwrap().server; defaults.chain_type = chain_type.clone(); match *chain_type { global::ChainTypes::Mainnet => {} global::ChainTypes::Testnet => { defaults.api_http_addr = "127.0.0.1:13413".to_owned(); defaults.p2p_config.port = 13414; defaults .stratum_mining_config .as_mut() .unwrap() .stratum_server_addr = Some("127.0.0.1:13416".to_owned()); defaults .stratum_mining_config .as_mut() .unwrap() .wallet_listener_url = "http://127.0.0.1:13415".to_owned(); } global::ChainTypes::UserTesting => { defaults.api_http_addr = "127.0.0.1:23413".to_owned(); defaults.p2p_config.port = 23414; defaults.p2p_config.seeding_type = p2p::Seeding::None; defaults .stratum_mining_config .as_mut() .unwrap() .stratum_server_addr = Some("127.0.0.1:23416".to_owned()); defaults .stratum_mining_config .as_mut() .unwrap() .wallet_listener_url = "http://127.0.0.1:23415".to_owned(); } global::ChainTypes::AutomatedTesting => { panic!("Can't run automated testing directly"); } } defaults_conf } /// Requires the path to a config file pub fn new(file_path: &str) -> Result<GlobalConfig, ConfigError> { let mut return_value = GlobalConfig::default(); return_value.config_file_path = Some(PathBuf::from(&file_path)); // Config file path is given but not valid let config_file = return_value.config_file_path.clone().unwrap(); if!config_file.exists() { return Err(ConfigError::FileNotFoundError(String::from( config_file.to_str().unwrap(), ))); } // Try to parse the config file if it exists, explode if it does exist but // something's wrong with it return_value.read_config() } /// Read config fn read_config(mut self) -> Result<GlobalConfig, ConfigError> { let config_file_path = self.config_file_path.as_ref().unwrap(); let contents = fs::read_to_string(config_file_path)?; let migrated = GlobalConfig::migrate_config_file_version_none_to_2(contents.clone()); if contents!= migrated { fs::write(config_file_path, &migrated)?; } let fixed = GlobalConfig::fix_warning_level(migrated); let decoded: Result<ConfigMembers, toml::de::Error> = toml::from_str(&fixed); match decoded { Ok(gc) => { self.members = Some(gc); return Ok(self); } Err(e) => { return Err(ConfigError::ParseError( self.config_file_path.unwrap().to_str().unwrap().to_string(), format!("{}", e), )); } } } /// Update paths pub fn update_paths(&mut self, grin_home: &PathBuf) { // need to update server chain path let mut chain_path = grin_home.clone(); chain_path.push(GRIN_CHAIN_DIR); self.members.as_mut().unwrap().server.db_root = chain_path.to_str().unwrap().to_owned(); let mut api_secret_path = grin_home.clone(); api_secret_path.push(API_SECRET_FILE_NAME); self.members.as_mut().unwrap().server.api_secret_path = Some(api_secret_path.to_str().unwrap().to_owned()); let mut foreign_api_secret_path = grin_home.clone(); foreign_api_secret_path.push(FOREIGN_API_SECRET_FILE_NAME); self.members .as_mut() .unwrap() .server .foreign_api_secret_path = Some(foreign_api_secret_path.to_str().unwrap().to_owned()); let mut log_path = grin_home.clone(); log_path.push(SERVER_LOG_FILE_NAME); self.members .as_mut() .unwrap() .logging .as_mut() .unwrap() .log_file_path = log_path.to_str().unwrap().to_owned(); } /// Enable mining pub fn stratum_enabled(&mut self) -> bool { return self .members .as_mut() .unwrap() .server .stratum_mining_config .as_mut() .unwrap() .enable_stratum_server .unwrap(); } /// Serialize config pub fn ser_config(&mut self) -> Result<String, ConfigError> { let encoded: Result<String, toml::ser::Error> = toml::to_string(self.members.as_mut().unwrap()); match encoded { Ok(enc) => return Ok(enc), Err(e) => { return Err(ConfigError::SerializationError(format!("{}", e))); } } } /// Write configuration to a file pub fn write_to_file(&mut self, name: &str) -> Result<(), ConfigError> { let conf_out = self.ser_config()?; let fixed_config = GlobalConfig::fix_log_level(conf_out); let commented_config = insert_comments(fixed_config); let mut file = File::create(name)?; file.write_all(commented_config.as_bytes())?; Ok(()) } /// This migration does the following: /// - Adds "config_file_version = 2" /// - If server.pool_config.accept_fee_base is 1000000, change it to 500000 /// - Remove "#a setting to 1000000 will be overridden to 500000 to respect the fixfees RFC" fn migrate_config_file_version_none_to_2(config_str: String) -> String { // Parse existing config and return unchanged if not eligible for migration let mut config: ConfigMembers = toml::from_str(&GlobalConfig::fix_warning_level(config_str.clone())).unwrap(); if config.config_file_version!= None { return config_str; } // Apply changes both textually and structurally let config_str = config_str.replace("\n#########################################\n### SERVER CONFIGURATION ###", "\nconfig_file_version = 2\n\n#########################################\n### SERVER CONFIGURATION ###"); config.config_file_version = Some(2); let config_str = config_str.replace( "\naccept_fee_base = 1000000\n", "\naccept_fee_base = 500000\n", ); if config.server.pool_config.accept_fee_base == 1000000 { config.server.pool_config.accept_fee_base = 500000; } let config_str = config_str.replace( "\n#a setting to 1000000 will be overridden to 500000 to respect the fixfees RFC\n", "\n", ); // Verify equivalence assert_eq!( config, toml::from_str(&GlobalConfig::fix_warning_level(config_str.clone())).unwrap() ); config_str } // For forwards compatibility old config needs `Warning` log level changed to standard log::Level `WARN` fn fix_warning_level(conf: String) -> String { conf.replace("Warning", "WARN") } // For backwards compatibility only first letter of log level should be capitalised. fn
(conf: String) -> String { conf.replace("TRACE", "Trace") .replace("DEBUG", "Debug") .replace("INFO", "Info") .replace("WARN", "Warning") .replace("ERROR", "Error") } } #[test] fn test_fix_log_level() { let config = "TRACE DEBUG INFO WARN ERROR".to_string(); let fixed_config = GlobalConfig::fix_log_level(config); assert_eq!(fixed_config, "Trace Debug Info Warning Error"); } #[test] fn test_fix_warning_level() { let config = "Warning".to_string(); let fixed_config = GlobalConfig::fix_warning_level(config); assert_eq!(fixed_config, "WARN"); }
fix_log_level
identifier_name
encode.rs
extern crate criterion; use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; use image::{ColorType, bmp::BmpEncoder, jpeg::JpegEncoder}; use std::fs::File; use std::io::{BufWriter, Write, Seek, SeekFrom}; trait Encoder { fn encode_raw(&self, into: &mut Vec<u8>, im: &[u8], dims: u32, color: ColorType); fn encode_bufvec(&self, into: &mut Vec<u8>, im: &[u8], dims: u32, color: ColorType); fn encode_file(&self, file: &File, im: &[u8], dims: u32, color: ColorType); } #[derive(Clone, Copy)] struct BenchDef { with: &'static dyn Encoder, name: &'static str, sizes: &'static [u32], colors: &'static [ColorType], } fn encode_all(c: &mut Criterion) { const BENCH_DEFS: &'static [BenchDef] = &[ BenchDef { with: &Bmp, name: "bmp", sizes: &[100u32, 200, 400], colors: &[ColorType::L8, ColorType::Rgb8, ColorType::Rgba8], }, BenchDef { with: &Jpeg, name: "jpeg", sizes: &[64u32, 128, 256], colors: &[ColorType::L8, ColorType::Rgb8, ColorType::Rgba8], }, ]; for definition in BENCH_DEFS { encode_definition(c, definition) } } criterion_group!(benches, encode_all); criterion_main!(benches); type BenchGroup<'a> = criterion::BenchmarkGroup<'a, criterion::measurement::WallTime>; /// Benchmarks encoding a zeroed image. /// /// For compressed formats this is surely not representative of encoding a normal image but it's a /// start for benchmarking. fn encode_zeroed(group: &mut BenchGroup, with: &dyn Encoder, size: u32, color: ColorType) { let bytes = size as usize * usize::from(color.bytes_per_pixel()); let im = vec![0; bytes * bytes]; group.bench_with_input(BenchmarkId::new(format!("zero-{:?}-rawvec", color), size), &im, |b, image| { let mut v = vec![]; with.encode_raw(&mut v, &im, size, color); b.iter(|| with.encode_raw(&mut v, image, size, color)); }); group.bench_with_input(BenchmarkId::new(format!("zero-{:?}-bufvec", color), size), &im, |b, image| { let mut v = vec![]; with.encode_raw(&mut v, &im, size, color); b.iter(|| with.encode_bufvec(&mut v, image, size, color)); }); group.bench_with_input(BenchmarkId::new(format!("zero-{:?}-file", color), size), &im, |b, image| { let file = File::create("temp.bmp").unwrap(); b.iter(|| with.encode_file(&file, image, size, color)); }); } fn encode_definition(criterion: &mut Criterion, def: &BenchDef) { let mut group = criterion.benchmark_group(format!("encode-{}", def.name)); for &color in def.colors { for &size in def.sizes { encode_zeroed(&mut group, def.with, size, color); } } } struct Bmp; struct Jpeg; trait EncoderBase { fn encode(&self, into: impl Write, im: &[u8], dims: u32, color: ColorType); } impl<T: EncoderBase> Encoder for T { fn encode_raw(&self, into: &mut Vec<u8>, im: &[u8], dims: u32, color: ColorType) { into.clear(); self.encode(into, im, dims, color); } fn encode_bufvec(&self, into: &mut Vec<u8>, im: &[u8], dims: u32, color: ColorType) { into.clear(); let buf = BufWriter::new(into); self.encode(buf, im, dims, color); } fn encode_file(&self, mut file: &File, im: &[u8], dims: u32, color: ColorType) { file.seek(SeekFrom::Start(0)).unwrap(); let buf = BufWriter::new(file); self.encode(buf, im, dims, color); } } impl EncoderBase for Bmp { fn encode(&self, mut into: impl Write, im: &[u8], size: u32, color: ColorType) { let mut x = BmpEncoder::new(&mut into); x.encode(im, size, size, color).unwrap(); } } impl EncoderBase for Jpeg { fn encode(&self, mut into: impl Write, im: &[u8], size: u32, color: ColorType)
}
{ let mut x = JpegEncoder::new(&mut into); x.encode(im, size, size, color).unwrap(); }
identifier_body
encode.rs
extern crate criterion; use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; use image::{ColorType, bmp::BmpEncoder, jpeg::JpegEncoder}; use std::fs::File; use std::io::{BufWriter, Write, Seek, SeekFrom}; trait Encoder { fn encode_raw(&self, into: &mut Vec<u8>, im: &[u8], dims: u32, color: ColorType); fn encode_bufvec(&self, into: &mut Vec<u8>, im: &[u8], dims: u32, color: ColorType); fn encode_file(&self, file: &File, im: &[u8], dims: u32, color: ColorType); } #[derive(Clone, Copy)] struct BenchDef { with: &'static dyn Encoder, name: &'static str, sizes: &'static [u32], colors: &'static [ColorType], } fn encode_all(c: &mut Criterion) { const BENCH_DEFS: &'static [BenchDef] = &[ BenchDef { with: &Bmp, name: "bmp", sizes: &[100u32, 200, 400], colors: &[ColorType::L8, ColorType::Rgb8, ColorType::Rgba8], }, BenchDef { with: &Jpeg, name: "jpeg", sizes: &[64u32, 128, 256], colors: &[ColorType::L8, ColorType::Rgb8, ColorType::Rgba8], }, ]; for definition in BENCH_DEFS { encode_definition(c, definition) } } criterion_group!(benches, encode_all); criterion_main!(benches); type BenchGroup<'a> = criterion::BenchmarkGroup<'a, criterion::measurement::WallTime>; /// Benchmarks encoding a zeroed image. /// /// For compressed formats this is surely not representative of encoding a normal image but it's a /// start for benchmarking. fn encode_zeroed(group: &mut BenchGroup, with: &dyn Encoder, size: u32, color: ColorType) { let bytes = size as usize * usize::from(color.bytes_per_pixel()); let im = vec![0; bytes * bytes]; group.bench_with_input(BenchmarkId::new(format!("zero-{:?}-rawvec", color), size), &im, |b, image| { let mut v = vec![]; with.encode_raw(&mut v, &im, size, color); b.iter(|| with.encode_raw(&mut v, image, size, color)); }); group.bench_with_input(BenchmarkId::new(format!("zero-{:?}-bufvec", color), size), &im, |b, image| { let mut v = vec![]; with.encode_raw(&mut v, &im, size, color); b.iter(|| with.encode_bufvec(&mut v, image, size, color)); }); group.bench_with_input(BenchmarkId::new(format!("zero-{:?}-file", color), size), &im, |b, image| { let file = File::create("temp.bmp").unwrap(); b.iter(|| with.encode_file(&file, image, size, color)); }); } fn encode_definition(criterion: &mut Criterion, def: &BenchDef) { let mut group = criterion.benchmark_group(format!("encode-{}", def.name)); for &color in def.colors { for &size in def.sizes { encode_zeroed(&mut group, def.with, size, color); } } } struct Bmp; struct Jpeg; trait EncoderBase { fn encode(&self, into: impl Write, im: &[u8], dims: u32, color: ColorType); } impl<T: EncoderBase> Encoder for T { fn encode_raw(&self, into: &mut Vec<u8>, im: &[u8], dims: u32, color: ColorType) { into.clear(); self.encode(into, im, dims, color); } fn encode_bufvec(&self, into: &mut Vec<u8>, im: &[u8], dims: u32, color: ColorType) { into.clear(); let buf = BufWriter::new(into); self.encode(buf, im, dims, color); } fn
(&self, mut file: &File, im: &[u8], dims: u32, color: ColorType) { file.seek(SeekFrom::Start(0)).unwrap(); let buf = BufWriter::new(file); self.encode(buf, im, dims, color); } } impl EncoderBase for Bmp { fn encode(&self, mut into: impl Write, im: &[u8], size: u32, color: ColorType) { let mut x = BmpEncoder::new(&mut into); x.encode(im, size, size, color).unwrap(); } } impl EncoderBase for Jpeg { fn encode(&self, mut into: impl Write, im: &[u8], size: u32, color: ColorType) { let mut x = JpegEncoder::new(&mut into); x.encode(im, size, size, color).unwrap(); } }
encode_file
identifier_name
encode.rs
extern crate criterion; use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; use image::{ColorType, bmp::BmpEncoder, jpeg::JpegEncoder}; use std::fs::File; use std::io::{BufWriter, Write, Seek, SeekFrom}; trait Encoder { fn encode_raw(&self, into: &mut Vec<u8>, im: &[u8], dims: u32, color: ColorType); fn encode_bufvec(&self, into: &mut Vec<u8>, im: &[u8], dims: u32, color: ColorType); fn encode_file(&self, file: &File, im: &[u8], dims: u32, color: ColorType); } #[derive(Clone, Copy)] struct BenchDef { with: &'static dyn Encoder, name: &'static str, sizes: &'static [u32], colors: &'static [ColorType], } fn encode_all(c: &mut Criterion) { const BENCH_DEFS: &'static [BenchDef] = &[ BenchDef { with: &Bmp, name: "bmp", sizes: &[100u32, 200, 400], colors: &[ColorType::L8, ColorType::Rgb8, ColorType::Rgba8], }, BenchDef { with: &Jpeg, name: "jpeg", sizes: &[64u32, 128, 256], colors: &[ColorType::L8, ColorType::Rgb8, ColorType::Rgba8], }, ]; for definition in BENCH_DEFS { encode_definition(c, definition) } } criterion_group!(benches, encode_all); criterion_main!(benches); type BenchGroup<'a> = criterion::BenchmarkGroup<'a, criterion::measurement::WallTime>; /// Benchmarks encoding a zeroed image. /// /// For compressed formats this is surely not representative of encoding a normal image but it's a /// start for benchmarking. fn encode_zeroed(group: &mut BenchGroup, with: &dyn Encoder, size: u32, color: ColorType) { let bytes = size as usize * usize::from(color.bytes_per_pixel()); let im = vec![0; bytes * bytes]; group.bench_with_input(BenchmarkId::new(format!("zero-{:?}-rawvec", color), size), &im, |b, image| { let mut v = vec![]; with.encode_raw(&mut v, &im, size, color); b.iter(|| with.encode_raw(&mut v, image, size, color)); }); group.bench_with_input(BenchmarkId::new(format!("zero-{:?}-bufvec", color), size), &im, |b, image| { let mut v = vec![]; with.encode_raw(&mut v, &im, size, color); b.iter(|| with.encode_bufvec(&mut v, image, size, color)); }); group.bench_with_input(BenchmarkId::new(format!("zero-{:?}-file", color), size), &im, |b, image| { let file = File::create("temp.bmp").unwrap(); b.iter(|| with.encode_file(&file, image, size, color)); }); } fn encode_definition(criterion: &mut Criterion, def: &BenchDef) { let mut group = criterion.benchmark_group(format!("encode-{}", def.name)); for &color in def.colors { for &size in def.sizes { encode_zeroed(&mut group, def.with, size, color); } } } struct Bmp; struct Jpeg; trait EncoderBase { fn encode(&self, into: impl Write, im: &[u8], dims: u32, color: ColorType); } impl<T: EncoderBase> Encoder for T { fn encode_raw(&self, into: &mut Vec<u8>, im: &[u8], dims: u32, color: ColorType) { into.clear(); self.encode(into, im, dims, color); } fn encode_bufvec(&self, into: &mut Vec<u8>, im: &[u8], dims: u32, color: ColorType) { into.clear(); let buf = BufWriter::new(into); self.encode(buf, im, dims, color); } fn encode_file(&self, mut file: &File, im: &[u8], dims: u32, color: ColorType) { file.seek(SeekFrom::Start(0)).unwrap(); let buf = BufWriter::new(file); self.encode(buf, im, dims, color); } } impl EncoderBase for Bmp { fn encode(&self, mut into: impl Write, im: &[u8], size: u32, color: ColorType) { let mut x = BmpEncoder::new(&mut into); x.encode(im, size, size, color).unwrap(); } } impl EncoderBase for Jpeg { fn encode(&self, mut into: impl Write, im: &[u8], size: u32, color: ColorType) {
let mut x = JpegEncoder::new(&mut into); x.encode(im, size, size, color).unwrap(); } }
random_line_split
main.rs
extern crate gmp; extern crate time; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::str::FromStr; use asm::assembler::Assembler; use asm::environment::Environment; use std::env; use std::collections::HashMap; mod asm; fn load_text(asm: &mut Assembler, code: &str) { let mut linenum = 0; for line in code.lines() { for s in line.split(';') { linenum += 1; asm.parse_line(&s.to_string(), linenum, None); } } } fn load_file(asm: &mut Assembler, file_name:&str) { let file = File::open(file_name).unwrap(); let buffer = BufReader::new(&file); let mut linenum = 0; for line in buffer.lines() { let l:String = line.unwrap(); linenum += 1; asm.parse_line(&l, linenum, Some(file_name.to_string())); } } enum Req { Yes, Maybe, No } struct ArgType { name:String, short:Option<String>, arg:Req } fn main() { let valid_args = vec![ ArgType{name:"help".to_string(), short:Some("h".to_string()), arg:Req::No}, ArgType{name:"file".to_string(), short:Some("h".to_string()), arg:Req::Yes}, ArgType{name:"text".to_string(), short:Some("h".to_string()), arg:Req::Yes}, ArgType{name:"print-stack".to_string(), short:Some("s".to_string()), arg:Req::Maybe}, ArgType{name:"print-parsed".to_string(), short:Some("p".to_string()), arg:Req::No}, ]; let mut args:HashMap<String, String> = HashMap::new(); let mut current_arg_name:String = "file".to_string(); let mut is_first = true; for element in env::args().collect::<Vec<String>>() { if is_first { is_first = false; continue; } //argument if element.len() >= 2 && &element[0..2] == "--" { let element = &element[2..]; let does_contain = valid_args.iter().filter( |a| a.name == element ).count()!= 0; if!does_contain { panic!("No such argument of name '{}'!", element); } current_arg_name = element.to_string(); args.insert(current_arg_name.clone(), "".to_string()); //shortened argument } else if element.len() >= 1 && &element[0..1] == "-" { let element = &element[1..]; let mut arg_name = "".to_string(); for arg in &valid_args { if arg.short == Some(element.to_string()) { arg_name = arg.name.clone(); break; } } if arg_name == "" { panic!("No such argument of name '{}'!", element); } else { current_arg_name = arg_name; } args.insert(current_arg_name.clone(), "".to_string()); //not an argument } else { println!("{}", element); let arg = args.get_mut(&current_arg_name).expect("No argument");
} let do_print_parsed = args.contains_key("print-parsed"); let do_stack_print = args.contains_key("print-stack"); let mut env = Environment::new(); let mut asm = Assembler::new(do_print_parsed); let mut do_run = false; if args.contains_key("help") { println!("{}", "Welcome to Bit Assembly! For help on how to write Bit Assembly, refer to the 'doc.md' file. Usage: bit-asm --file {file name}.asm bit-asm --text {assembly} Options: --print-stack {bits} prints stack as a sequence of bytes --print-parsed prints each line as they are parsed"); } else if args.contains_key("file") { load_file(&mut asm, args.get("file").expect("This shouldnt happen")); do_run = true; } else if args.contains_key("text") { load_text(&mut asm, args.get("text").expect("This shouldnt happen")); do_run = true; } else { println!("type 'bit-asm --help' for help on how to use bit assembly"); } if do_run { asm.run(&mut env); if do_stack_print { let bits = usize::from_str( match args.get("print-stack").unwrap_or(&"64".to_string()).as_ref() { "" => "64", other => other } ).expect("print-stack argument is not valid!"); env.print_bytes(bits); } } }
arg.push_str(element.as_ref()); }
random_line_split
main.rs
extern crate gmp; extern crate time; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::str::FromStr; use asm::assembler::Assembler; use asm::environment::Environment; use std::env; use std::collections::HashMap; mod asm; fn load_text(asm: &mut Assembler, code: &str) { let mut linenum = 0; for line in code.lines() { for s in line.split(';') { linenum += 1; asm.parse_line(&s.to_string(), linenum, None); } } } fn load_file(asm: &mut Assembler, file_name:&str) { let file = File::open(file_name).unwrap(); let buffer = BufReader::new(&file); let mut linenum = 0; for line in buffer.lines() { let l:String = line.unwrap(); linenum += 1; asm.parse_line(&l, linenum, Some(file_name.to_string())); } } enum Req { Yes, Maybe, No } struct ArgType { name:String, short:Option<String>, arg:Req } fn main() { let valid_args = vec![ ArgType{name:"help".to_string(), short:Some("h".to_string()), arg:Req::No}, ArgType{name:"file".to_string(), short:Some("h".to_string()), arg:Req::Yes}, ArgType{name:"text".to_string(), short:Some("h".to_string()), arg:Req::Yes}, ArgType{name:"print-stack".to_string(), short:Some("s".to_string()), arg:Req::Maybe}, ArgType{name:"print-parsed".to_string(), short:Some("p".to_string()), arg:Req::No}, ]; let mut args:HashMap<String, String> = HashMap::new(); let mut current_arg_name:String = "file".to_string(); let mut is_first = true; for element in env::args().collect::<Vec<String>>() { if is_first { is_first = false; continue; } //argument if element.len() >= 2 && &element[0..2] == "--" { let element = &element[2..]; let does_contain = valid_args.iter().filter( |a| a.name == element ).count()!= 0; if!does_contain { panic!("No such argument of name '{}'!", element); } current_arg_name = element.to_string(); args.insert(current_arg_name.clone(), "".to_string()); //shortened argument } else if element.len() >= 1 && &element[0..1] == "-"
else { println!("{}", element); let arg = args.get_mut(&current_arg_name).expect("No argument"); arg.push_str(element.as_ref()); } } let do_print_parsed = args.contains_key("print-parsed"); let do_stack_print = args.contains_key("print-stack"); let mut env = Environment::new(); let mut asm = Assembler::new(do_print_parsed); let mut do_run = false; if args.contains_key("help") { println!("{}", "Welcome to Bit Assembly! For help on how to write Bit Assembly, refer to the 'doc.md' file. Usage: bit-asm --file {file name}.asm bit-asm --text {assembly} Options: --print-stack {bits} prints stack as a sequence of bytes --print-parsed prints each line as they are parsed"); } else if args.contains_key("file") { load_file(&mut asm, args.get("file").expect("This shouldnt happen")); do_run = true; } else if args.contains_key("text") { load_text(&mut asm, args.get("text").expect("This shouldnt happen")); do_run = true; } else { println!("type 'bit-asm --help' for help on how to use bit assembly"); } if do_run { asm.run(&mut env); if do_stack_print { let bits = usize::from_str( match args.get("print-stack").unwrap_or(&"64".to_string()).as_ref() { "" => "64", other => other } ).expect("print-stack argument is not valid!"); env.print_bytes(bits); } } }
{ let element = &element[1..]; let mut arg_name = "".to_string(); for arg in &valid_args { if arg.short == Some(element.to_string()) { arg_name = arg.name.clone(); break; } } if arg_name == "" { panic!("No such argument of name '{}'!", element); } else { current_arg_name = arg_name; } args.insert(current_arg_name.clone(), "".to_string()); //not an argument }
conditional_block
main.rs
extern crate gmp; extern crate time; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::str::FromStr; use asm::assembler::Assembler; use asm::environment::Environment; use std::env; use std::collections::HashMap; mod asm; fn
(asm: &mut Assembler, code: &str) { let mut linenum = 0; for line in code.lines() { for s in line.split(';') { linenum += 1; asm.parse_line(&s.to_string(), linenum, None); } } } fn load_file(asm: &mut Assembler, file_name:&str) { let file = File::open(file_name).unwrap(); let buffer = BufReader::new(&file); let mut linenum = 0; for line in buffer.lines() { let l:String = line.unwrap(); linenum += 1; asm.parse_line(&l, linenum, Some(file_name.to_string())); } } enum Req { Yes, Maybe, No } struct ArgType { name:String, short:Option<String>, arg:Req } fn main() { let valid_args = vec![ ArgType{name:"help".to_string(), short:Some("h".to_string()), arg:Req::No}, ArgType{name:"file".to_string(), short:Some("h".to_string()), arg:Req::Yes}, ArgType{name:"text".to_string(), short:Some("h".to_string()), arg:Req::Yes}, ArgType{name:"print-stack".to_string(), short:Some("s".to_string()), arg:Req::Maybe}, ArgType{name:"print-parsed".to_string(), short:Some("p".to_string()), arg:Req::No}, ]; let mut args:HashMap<String, String> = HashMap::new(); let mut current_arg_name:String = "file".to_string(); let mut is_first = true; for element in env::args().collect::<Vec<String>>() { if is_first { is_first = false; continue; } //argument if element.len() >= 2 && &element[0..2] == "--" { let element = &element[2..]; let does_contain = valid_args.iter().filter( |a| a.name == element ).count()!= 0; if!does_contain { panic!("No such argument of name '{}'!", element); } current_arg_name = element.to_string(); args.insert(current_arg_name.clone(), "".to_string()); //shortened argument } else if element.len() >= 1 && &element[0..1] == "-" { let element = &element[1..]; let mut arg_name = "".to_string(); for arg in &valid_args { if arg.short == Some(element.to_string()) { arg_name = arg.name.clone(); break; } } if arg_name == "" { panic!("No such argument of name '{}'!", element); } else { current_arg_name = arg_name; } args.insert(current_arg_name.clone(), "".to_string()); //not an argument } else { println!("{}", element); let arg = args.get_mut(&current_arg_name).expect("No argument"); arg.push_str(element.as_ref()); } } let do_print_parsed = args.contains_key("print-parsed"); let do_stack_print = args.contains_key("print-stack"); let mut env = Environment::new(); let mut asm = Assembler::new(do_print_parsed); let mut do_run = false; if args.contains_key("help") { println!("{}", "Welcome to Bit Assembly! For help on how to write Bit Assembly, refer to the 'doc.md' file. Usage: bit-asm --file {file name}.asm bit-asm --text {assembly} Options: --print-stack {bits} prints stack as a sequence of bytes --print-parsed prints each line as they are parsed"); } else if args.contains_key("file") { load_file(&mut asm, args.get("file").expect("This shouldnt happen")); do_run = true; } else if args.contains_key("text") { load_text(&mut asm, args.get("text").expect("This shouldnt happen")); do_run = true; } else { println!("type 'bit-asm --help' for help on how to use bit assembly"); } if do_run { asm.run(&mut env); if do_stack_print { let bits = usize::from_str( match args.get("print-stack").unwrap_or(&"64".to_string()).as_ref() { "" => "64", other => other } ).expect("print-stack argument is not valid!"); env.print_bytes(bits); } } }
load_text
identifier_name
args.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Global storage for command line arguments //! //! The current incarnation of the Rust runtime expects for //! the processes `argc` and `argv` arguments to be stored //! in a globally-accessible location for use by the `os` module. //! //! Only valid to call on linux. Mac and Windows use syscalls to //! discover the command line arguments. //! //! FIXME #7756: Would be nice for this to not exist. //! FIXME #7756: This has a lot of C glue for lack of globals. use option::Option; /// One-time global initialization. pub unsafe fn init(argc: int, argv: **u8) { imp::init(argc, argv) } /// One-time global cleanup. pub fn cleanup() { imp::cleanup() } /// Take the global arguments from global storage. pub fn take() -> Option<~[~str]> { imp::take() } /// Give the global arguments to global storage. /// /// It is an error if the arguments already exist. pub fn put(args: ~[~str]) { imp::put(args) } /// Make a clone of the global arguments. pub fn clone() -> Option<~[~str]> { imp::clone() } #[cfg(target_os = "linux")] #[cfg(target_os = "android")] #[cfg(target_os = "freebsd")] mod imp { use libc; use option::{Option, Some, None}; use iter::Iterator; use str; use unstable::finally::Finally; use util; use vec; pub unsafe fn init(argc: int, argv: **u8) { let args = load_argc_and_argv(argc, argv); put(args); } pub fn cleanup() { rtassert!(take().is_some()); } pub fn take() -> Option<~[~str]> { with_lock(|| unsafe { let ptr = get_global_ptr(); let val = util::replace(&mut *ptr, None); val.as_ref().map(|s: &~~[~str]| (**s).clone()) }) } pub fn put(args: ~[~str]) { with_lock(|| unsafe { let ptr = get_global_ptr(); rtassert!((*ptr).is_none()); (*ptr) = Some(~args.clone()); }) } pub fn clone() -> Option<~[~str]> { with_lock(|| unsafe { let ptr = get_global_ptr(); (*ptr).as_ref().map(|s: &~~[~str]| (**s).clone()) }) } fn with_lock<T>(f: &fn() -> T) -> T { do (|| { unsafe { rust_take_global_args_lock(); f() } }).finally { unsafe { rust_drop_global_args_lock(); } } } fn get_global_ptr() -> *mut Option<~~[~str]> { unsafe { rust_get_global_args_ptr() } } // Copied from `os`. unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> ~[~str] { do vec::from_fn(argc as uint) |i| { str::raw::from_c_str(*(argv as **libc::c_char).offset(i as int)) } } externfn!(fn rust_take_global_args_lock()) externfn!(fn rust_drop_global_args_lock()) externfn!(fn rust_get_global_args_ptr() -> *mut Option<~~[~str]>) #[cfg(test)] mod tests { use option::{Some, None}; use super::*; use unstable::finally::Finally; #[test] fn smoke_test() { // Preserve the actual global state. let saved_value = take(); let expected = ~[~"happy", ~"today?"]; put(expected.clone()); assert!(clone() == Some(expected.clone())); assert!(take() == Some(expected.clone())); assert!(take() == None); do (|| { }).finally { // Restore the actual global state. match saved_value { Some(ref args) => put(args.clone()), None => () } } } } } #[cfg(target_os = "macos")] #[cfg(target_os = "win32")] mod imp { use option::Option; pub unsafe fn init(_argc: int, _argv: **u8) { } pub fn cleanup() { } pub fn take() -> Option<~[~str]>
pub fn put(_args: ~[~str]) { fail2!() } pub fn clone() -> Option<~[~str]> { fail2!() } }
{ fail2!() }
identifier_body
args.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Global storage for command line arguments //! //! The current incarnation of the Rust runtime expects for //! the processes `argc` and `argv` arguments to be stored //! in a globally-accessible location for use by the `os` module. //! //! Only valid to call on linux. Mac and Windows use syscalls to //! discover the command line arguments. //! //! FIXME #7756: Would be nice for this to not exist. //! FIXME #7756: This has a lot of C glue for lack of globals. use option::Option; /// One-time global initialization. pub unsafe fn init(argc: int, argv: **u8) { imp::init(argc, argv) } /// One-time global cleanup. pub fn cleanup() { imp::cleanup() } /// Take the global arguments from global storage. pub fn take() -> Option<~[~str]> { imp::take() } /// Give the global arguments to global storage. /// /// It is an error if the arguments already exist. pub fn put(args: ~[~str]) { imp::put(args) } /// Make a clone of the global arguments. pub fn clone() -> Option<~[~str]> { imp::clone() } #[cfg(target_os = "linux")] #[cfg(target_os = "android")] #[cfg(target_os = "freebsd")] mod imp { use libc; use option::{Option, Some, None}; use iter::Iterator; use str; use unstable::finally::Finally; use util; use vec; pub unsafe fn init(argc: int, argv: **u8) { let args = load_argc_and_argv(argc, argv); put(args); } pub fn cleanup() { rtassert!(take().is_some()); } pub fn take() -> Option<~[~str]> { with_lock(|| unsafe { let ptr = get_global_ptr(); let val = util::replace(&mut *ptr, None); val.as_ref().map(|s: &~~[~str]| (**s).clone()) }) } pub fn put(args: ~[~str]) { with_lock(|| unsafe { let ptr = get_global_ptr(); rtassert!((*ptr).is_none()); (*ptr) = Some(~args.clone()); }) } pub fn
() -> Option<~[~str]> { with_lock(|| unsafe { let ptr = get_global_ptr(); (*ptr).as_ref().map(|s: &~~[~str]| (**s).clone()) }) } fn with_lock<T>(f: &fn() -> T) -> T { do (|| { unsafe { rust_take_global_args_lock(); f() } }).finally { unsafe { rust_drop_global_args_lock(); } } } fn get_global_ptr() -> *mut Option<~~[~str]> { unsafe { rust_get_global_args_ptr() } } // Copied from `os`. unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> ~[~str] { do vec::from_fn(argc as uint) |i| { str::raw::from_c_str(*(argv as **libc::c_char).offset(i as int)) } } externfn!(fn rust_take_global_args_lock()) externfn!(fn rust_drop_global_args_lock()) externfn!(fn rust_get_global_args_ptr() -> *mut Option<~~[~str]>) #[cfg(test)] mod tests { use option::{Some, None}; use super::*; use unstable::finally::Finally; #[test] fn smoke_test() { // Preserve the actual global state. let saved_value = take(); let expected = ~[~"happy", ~"today?"]; put(expected.clone()); assert!(clone() == Some(expected.clone())); assert!(take() == Some(expected.clone())); assert!(take() == None); do (|| { }).finally { // Restore the actual global state. match saved_value { Some(ref args) => put(args.clone()), None => () } } } } } #[cfg(target_os = "macos")] #[cfg(target_os = "win32")] mod imp { use option::Option; pub unsafe fn init(_argc: int, _argv: **u8) { } pub fn cleanup() { } pub fn take() -> Option<~[~str]> { fail2!() } pub fn put(_args: ~[~str]) { fail2!() } pub fn clone() -> Option<~[~str]> { fail2!() } }
clone
identifier_name
args.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Global storage for command line arguments //! //! The current incarnation of the Rust runtime expects for //! the processes `argc` and `argv` arguments to be stored //! in a globally-accessible location for use by the `os` module. //! //! Only valid to call on linux. Mac and Windows use syscalls to //! discover the command line arguments. //! //! FIXME #7756: Would be nice for this to not exist. //! FIXME #7756: This has a lot of C glue for lack of globals. use option::Option; /// One-time global initialization. pub unsafe fn init(argc: int, argv: **u8) { imp::init(argc, argv) } /// One-time global cleanup. pub fn cleanup() { imp::cleanup() } /// Take the global arguments from global storage. pub fn take() -> Option<~[~str]> { imp::take() } /// Give the global arguments to global storage. /// /// It is an error if the arguments already exist. pub fn put(args: ~[~str]) { imp::put(args) } /// Make a clone of the global arguments. pub fn clone() -> Option<~[~str]> { imp::clone() } #[cfg(target_os = "linux")] #[cfg(target_os = "android")] #[cfg(target_os = "freebsd")] mod imp { use libc; use option::{Option, Some, None}; use iter::Iterator; use str; use unstable::finally::Finally; use util; use vec; pub unsafe fn init(argc: int, argv: **u8) { let args = load_argc_and_argv(argc, argv); put(args); } pub fn cleanup() { rtassert!(take().is_some()); } pub fn take() -> Option<~[~str]> { with_lock(|| unsafe { let ptr = get_global_ptr(); let val = util::replace(&mut *ptr, None); val.as_ref().map(|s: &~~[~str]| (**s).clone()) }) } pub fn put(args: ~[~str]) { with_lock(|| unsafe { let ptr = get_global_ptr(); rtassert!((*ptr).is_none()); (*ptr) = Some(~args.clone()); }) } pub fn clone() -> Option<~[~str]> { with_lock(|| unsafe { let ptr = get_global_ptr(); (*ptr).as_ref().map(|s: &~~[~str]| (**s).clone()) }) } fn with_lock<T>(f: &fn() -> T) -> T { do (|| { unsafe {
rust_drop_global_args_lock(); } } } fn get_global_ptr() -> *mut Option<~~[~str]> { unsafe { rust_get_global_args_ptr() } } // Copied from `os`. unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> ~[~str] { do vec::from_fn(argc as uint) |i| { str::raw::from_c_str(*(argv as **libc::c_char).offset(i as int)) } } externfn!(fn rust_take_global_args_lock()) externfn!(fn rust_drop_global_args_lock()) externfn!(fn rust_get_global_args_ptr() -> *mut Option<~~[~str]>) #[cfg(test)] mod tests { use option::{Some, None}; use super::*; use unstable::finally::Finally; #[test] fn smoke_test() { // Preserve the actual global state. let saved_value = take(); let expected = ~[~"happy", ~"today?"]; put(expected.clone()); assert!(clone() == Some(expected.clone())); assert!(take() == Some(expected.clone())); assert!(take() == None); do (|| { }).finally { // Restore the actual global state. match saved_value { Some(ref args) => put(args.clone()), None => () } } } } } #[cfg(target_os = "macos")] #[cfg(target_os = "win32")] mod imp { use option::Option; pub unsafe fn init(_argc: int, _argv: **u8) { } pub fn cleanup() { } pub fn take() -> Option<~[~str]> { fail2!() } pub fn put(_args: ~[~str]) { fail2!() } pub fn clone() -> Option<~[~str]> { fail2!() } }
rust_take_global_args_lock(); f() } }).finally { unsafe {
random_line_split
mod.rs
//! Encoding of portable pixmap Images pub use self::encoder::PPMEncoder as PPMEncoder; pub use self::decoder::PPMDecoder as PPMDecoder; mod encoder; mod decoder; #[cfg(test)] mod test { use color::ColorType; use image::{ImageDecoder, DecodingResult}; #[test] fn test_roundtrip_ppm()
}; } let mut decoder = match super::PPMDecoder::new(&stream[..]) { Ok(img) => img, Err(e) => panic!("PPM decoder failed with {}", e), }; match decoder.read_image() { Ok(DecodingResult::U8(vec)) => { assert_eq!(&buf[..], &vec[..]); }, r => { panic!("PPM: Got a strange image result {:?}", r); } } } #[test] fn test_roundtrip_ppm_16bit() { // 3x3 image that tries all the 0/65535 RGB combinations plus a few more values // that check for big-endian conversion correctness let buf: [u16; 27] = [ 0, 0, 0, 0, 0, 65535, 0, 65535, 0, 0, 65535, 65535, 65535, 0, 0, 65535, 0, 65535, 65535, 65535, 0, 65535, 65535, 65535, 1000, 2000, 3000, ]; let mut bytebuf = [0 as u8; 54]; for (o, i) in bytebuf.chunks_mut(2).zip(buf.iter()) { o[0] = (i >> 8) as u8; o[1] = (i & 0xff) as u8; } let mut stream = Vec::<u8>::new(); { let mut encoder = super::PPMEncoder::new(&mut stream); match encoder.encode(&bytebuf, 3, 3, ColorType::RGB(16)) { Ok(_) => {}, Err(_) => panic!("PPM encoder failed"), }; } let mut decoder = match super::PPMDecoder::new(&stream[..]) { Ok(img) => img, Err(e) => panic!("PPM decoder failed with {}", e), }; match decoder.read_image() { Ok(DecodingResult::U16(vec)) => { assert_eq!(&buf[..], &vec[..]); }, r => { panic!("PPM: Got a strange image result {:?}", r); } } } }
{ // 3x3 image that tries all the 0/255 RGB combinations let buf: [u8; 27] = [ 0, 0, 0, 0, 0, 255, 0, 255, 0, 0, 255, 255, 255, 0, 0, 255, 0, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, ]; let mut stream = Vec::<u8>::new(); { let mut encoder = super::PPMEncoder::new(&mut stream); match encoder.encode(&buf, 3, 3, ColorType::RGB(8)) { Ok(_) => {}, Err(_) => panic!("PPM encoder failed"),
identifier_body
mod.rs
//! Encoding of portable pixmap Images pub use self::encoder::PPMEncoder as PPMEncoder; pub use self::decoder::PPMDecoder as PPMDecoder; mod encoder; mod decoder; #[cfg(test)] mod test { use color::ColorType; use image::{ImageDecoder, DecodingResult}; #[test] fn
() { // 3x3 image that tries all the 0/255 RGB combinations let buf: [u8; 27] = [ 0, 0, 0, 0, 0, 255, 0, 255, 0, 0, 255, 255, 255, 0, 0, 255, 0, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, ]; let mut stream = Vec::<u8>::new(); { let mut encoder = super::PPMEncoder::new(&mut stream); match encoder.encode(&buf, 3, 3, ColorType::RGB(8)) { Ok(_) => {}, Err(_) => panic!("PPM encoder failed"), }; } let mut decoder = match super::PPMDecoder::new(&stream[..]) { Ok(img) => img, Err(e) => panic!("PPM decoder failed with {}", e), }; match decoder.read_image() { Ok(DecodingResult::U8(vec)) => { assert_eq!(&buf[..], &vec[..]); }, r => { panic!("PPM: Got a strange image result {:?}", r); } } } #[test] fn test_roundtrip_ppm_16bit() { // 3x3 image that tries all the 0/65535 RGB combinations plus a few more values // that check for big-endian conversion correctness let buf: [u16; 27] = [ 0, 0, 0, 0, 0, 65535, 0, 65535, 0, 0, 65535, 65535, 65535, 0, 0, 65535, 0, 65535, 65535, 65535, 0, 65535, 65535, 65535, 1000, 2000, 3000, ]; let mut bytebuf = [0 as u8; 54]; for (o, i) in bytebuf.chunks_mut(2).zip(buf.iter()) { o[0] = (i >> 8) as u8; o[1] = (i & 0xff) as u8; } let mut stream = Vec::<u8>::new(); { let mut encoder = super::PPMEncoder::new(&mut stream); match encoder.encode(&bytebuf, 3, 3, ColorType::RGB(16)) { Ok(_) => {}, Err(_) => panic!("PPM encoder failed"), }; } let mut decoder = match super::PPMDecoder::new(&stream[..]) { Ok(img) => img, Err(e) => panic!("PPM decoder failed with {}", e), }; match decoder.read_image() { Ok(DecodingResult::U16(vec)) => { assert_eq!(&buf[..], &vec[..]); }, r => { panic!("PPM: Got a strange image result {:?}", r); } } } }
test_roundtrip_ppm
identifier_name
mod.rs
//! Encoding of portable pixmap Images pub use self::encoder::PPMEncoder as PPMEncoder; pub use self::decoder::PPMDecoder as PPMDecoder; mod encoder; mod decoder; #[cfg(test)] mod test { use color::ColorType; use image::{ImageDecoder, DecodingResult}; #[test] fn test_roundtrip_ppm() { // 3x3 image that tries all the 0/255 RGB combinations let buf: [u8; 27] = [ 0, 0, 0, 0, 0, 255, 0, 255, 0, 0, 255, 255, 255, 0, 0, 255, 0, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, ]; let mut stream = Vec::<u8>::new(); { let mut encoder = super::PPMEncoder::new(&mut stream); match encoder.encode(&buf, 3, 3, ColorType::RGB(8)) { Ok(_) => {}, Err(_) => panic!("PPM encoder failed"), }; } let mut decoder = match super::PPMDecoder::new(&stream[..]) { Ok(img) => img, Err(e) => panic!("PPM decoder failed with {}", e), }; match decoder.read_image() { Ok(DecodingResult::U8(vec)) => { assert_eq!(&buf[..], &vec[..]); }, r => { panic!("PPM: Got a strange image result {:?}", r); } } } #[test] fn test_roundtrip_ppm_16bit() { // 3x3 image that tries all the 0/65535 RGB combinations plus a few more values // that check for big-endian conversion correctness let buf: [u16; 27] = [ 0, 0, 0, 0, 0, 65535, 0, 65535, 0, 0, 65535, 65535, 65535, 0, 0, 65535, 0, 65535, 65535, 65535, 0, 65535, 65535, 65535, 1000, 2000, 3000,
o[0] = (i >> 8) as u8; o[1] = (i & 0xff) as u8; } let mut stream = Vec::<u8>::new(); { let mut encoder = super::PPMEncoder::new(&mut stream); match encoder.encode(&bytebuf, 3, 3, ColorType::RGB(16)) { Ok(_) => {}, Err(_) => panic!("PPM encoder failed"), }; } let mut decoder = match super::PPMDecoder::new(&stream[..]) { Ok(img) => img, Err(e) => panic!("PPM decoder failed with {}", e), }; match decoder.read_image() { Ok(DecodingResult::U16(vec)) => { assert_eq!(&buf[..], &vec[..]); }, r => { panic!("PPM: Got a strange image result {:?}", r); } } } }
]; let mut bytebuf = [0 as u8; 54]; for (o, i) in bytebuf.chunks_mut(2).zip(buf.iter()) {
random_line_split
namespaced-enum-glob-import-no-impls.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. mod m2 { pub enum Foo { A, B(isize), C { a: isize }, } impl Foo { pub fn foo() {} pub fn
(&self) {} } } mod m { pub use m2::Foo::*; } pub fn main() { use m2::Foo::*; foo(); //~ ERROR cannot find function `foo` in this scope m::foo(); //~ ERROR cannot find function `foo` in module `m` bar(); //~ ERROR cannot find function `bar` in this scope m::bar(); //~ ERROR cannot find function `bar` in module `m` }
bar
identifier_name
namespaced-enum-glob-import-no-impls.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. mod m2 { pub enum Foo { A, B(isize), C { a: isize }, } impl Foo { pub fn foo() {} pub fn bar(&self) {} } } mod m { pub use m2::Foo::*; } pub fn main()
{ use m2::Foo::*; foo(); //~ ERROR cannot find function `foo` in this scope m::foo(); //~ ERROR cannot find function `foo` in module `m` bar(); //~ ERROR cannot find function `bar` in this scope m::bar(); //~ ERROR cannot find function `bar` in module `m` }
identifier_body
namespaced-enum-glob-import-no-impls.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. mod m2 { pub enum Foo { A, B(isize), C { a: isize }, }
pub fn bar(&self) {} } } mod m { pub use m2::Foo::*; } pub fn main() { use m2::Foo::*; foo(); //~ ERROR cannot find function `foo` in this scope m::foo(); //~ ERROR cannot find function `foo` in module `m` bar(); //~ ERROR cannot find function `bar` in this scope m::bar(); //~ ERROR cannot find function `bar` in module `m` }
impl Foo { pub fn foo() {}
random_line_split
parser.rs
use std::num; #[derive(Debug)] pub enum ParseError { UnexpectedChar(char), UnexpectedEnd, InvalidNumber(String, num::ParseIntError), } pub type ParseResult<T> = Result<T, ParseError>; pub struct Parser<'src> { source: &'src str, position: usize, } #[derive(Debug)] pub enum Expr { Ident(String), Number(u64), } impl<'src> Parser<'src> { pub fn new(source: &'src str) -> Parser<'src> { Parser { source: source, position: 0, } } fn parse_expr(&mut self) -> ParseResult<Expr> { let c = try!(self.peek_char().ok_or(ParseError::UnexpectedEnd)); match c { '(' => unimplemented!(), c if is_ident_start(c) => Ok(self.parse_ident()), c if is_digit(c) => self.parse_number(), _ => Err(ParseError::UnexpectedChar(c)), } } fn parse_number(&mut self) -> ParseResult<Expr> { let mut number = String::new(); while let Some(digit) = self.read_char() { // Eagerly read all valid identifier characters so that "123foo" doesn't lex as a // number followed by an identifier. if!is_ident_char(digit) { self.unread_char(); break; } number.push(digit); } match number.parse::<u64>() { Ok(value) => Ok(Expr::Number(value)), Err(reason) => Err(ParseError::InvalidNumber(number, reason)), } } fn parse_ident(&mut self) -> Expr { let mut ident = String::new(); while let Some(c) = self.read_char() { if!is_ident_char(c) { self.unread_char(); break; } ident.push(c); } Expr::Ident(ident) } fn skip_whitespace(&mut self) { while let Some(c) = self.read_char() { if!is_whitespace(c) { self.unread_char(); break; } } } fn peek_char(&mut self) -> Option<char> { self.source[self.position..].chars().next() } fn read_char(&mut self) -> Option<char> { let opt_c = self.peek_char(); if let Some(c) = opt_c { self.position += c.len_utf8(); } opt_c } /// Step backwards one `char` in the input. Must not be called more times than `read_char` has /// been called. fn unread_char(&mut self) { assert!(self.position!= 0); let (prev_pos, _) = self.source[..self.position].char_indices().next_back().unwrap(); self.position = prev_pos; } fn at_end(&self) -> bool { self.position == self.source.len() } } impl<'src> Iterator for Parser<'src> { type Item = ParseResult<Expr>; fn
(&mut self) -> Option<ParseResult<Expr>> { self.skip_whitespace(); if self.at_end() { None } else { Some(self.parse_expr()) } } } /// Returns `true` if the given character is whitespace. fn is_whitespace(c: char) -> bool { match c { '' | '\t' | '\n' => true, _ => false, } } /// Returns `true` if the given character is a digit. fn is_digit(c: char) -> bool { match c { '0'...'9' => true, _ => false, } } /// Returns `true` if the given character is valid at the start of an identifier. fn is_ident_start(c: char) -> bool { match c { 'a'...'z' | 'A'...'Z' | '_' | '!' | '?' | '*' | '-' | '+' | '/' | '=' | '<' | '>' => true, _ => false, } } /// Returns `true` if the given character is valid in an identifier. fn is_ident_char(c: char) -> bool { is_ident_start(c) || is_digit(c) }
next
identifier_name
parser.rs
use std::num; #[derive(Debug)] pub enum ParseError { UnexpectedChar(char), UnexpectedEnd, InvalidNumber(String, num::ParseIntError), } pub type ParseResult<T> = Result<T, ParseError>; pub struct Parser<'src> { source: &'src str, position: usize, } #[derive(Debug)] pub enum Expr { Ident(String), Number(u64), } impl<'src> Parser<'src> { pub fn new(source: &'src str) -> Parser<'src> { Parser { source: source, position: 0, } } fn parse_expr(&mut self) -> ParseResult<Expr> { let c = try!(self.peek_char().ok_or(ParseError::UnexpectedEnd)); match c { '(' => unimplemented!(), c if is_ident_start(c) => Ok(self.parse_ident()), c if is_digit(c) => self.parse_number(), _ => Err(ParseError::UnexpectedChar(c)), } } fn parse_number(&mut self) -> ParseResult<Expr> { let mut number = String::new(); while let Some(digit) = self.read_char() { // Eagerly read all valid identifier characters so that "123foo" doesn't lex as a // number followed by an identifier. if!is_ident_char(digit) { self.unread_char(); break; } number.push(digit); } match number.parse::<u64>() { Ok(value) => Ok(Expr::Number(value)), Err(reason) => Err(ParseError::InvalidNumber(number, reason)), } } fn parse_ident(&mut self) -> Expr { let mut ident = String::new(); while let Some(c) = self.read_char() { if!is_ident_char(c) { self.unread_char(); break; } ident.push(c); } Expr::Ident(ident) } fn skip_whitespace(&mut self) { while let Some(c) = self.read_char() { if!is_whitespace(c) { self.unread_char(); break; } } } fn peek_char(&mut self) -> Option<char> { self.source[self.position..].chars().next() } fn read_char(&mut self) -> Option<char> { let opt_c = self.peek_char(); if let Some(c) = opt_c { self.position += c.len_utf8(); } opt_c } /// Step backwards one `char` in the input. Must not be called more times than `read_char` has /// been called. fn unread_char(&mut self) { assert!(self.position!= 0); let (prev_pos, _) = self.source[..self.position].char_indices().next_back().unwrap(); self.position = prev_pos; } fn at_end(&self) -> bool { self.position == self.source.len() } } impl<'src> Iterator for Parser<'src> { type Item = ParseResult<Expr>; fn next(&mut self) -> Option<ParseResult<Expr>> { self.skip_whitespace(); if self.at_end() { None } else
} } /// Returns `true` if the given character is whitespace. fn is_whitespace(c: char) -> bool { match c { '' | '\t' | '\n' => true, _ => false, } } /// Returns `true` if the given character is a digit. fn is_digit(c: char) -> bool { match c { '0'...'9' => true, _ => false, } } /// Returns `true` if the given character is valid at the start of an identifier. fn is_ident_start(c: char) -> bool { match c { 'a'...'z' | 'A'...'Z' | '_' | '!' | '?' | '*' | '-' | '+' | '/' | '=' | '<' | '>' => true, _ => false, } } /// Returns `true` if the given character is valid in an identifier. fn is_ident_char(c: char) -> bool { is_ident_start(c) || is_digit(c) }
{ Some(self.parse_expr()) }
conditional_block
parser.rs
use std::num; #[derive(Debug)] pub enum ParseError { UnexpectedChar(char), UnexpectedEnd, InvalidNumber(String, num::ParseIntError), } pub type ParseResult<T> = Result<T, ParseError>; pub struct Parser<'src> { source: &'src str, position: usize, } #[derive(Debug)] pub enum Expr { Ident(String), Number(u64), } impl<'src> Parser<'src> { pub fn new(source: &'src str) -> Parser<'src> { Parser { source: source, position: 0, } } fn parse_expr(&mut self) -> ParseResult<Expr> { let c = try!(self.peek_char().ok_or(ParseError::UnexpectedEnd)); match c { '(' => unimplemented!(), c if is_ident_start(c) => Ok(self.parse_ident()), c if is_digit(c) => self.parse_number(), _ => Err(ParseError::UnexpectedChar(c)), } } fn parse_number(&mut self) -> ParseResult<Expr> { let mut number = String::new(); while let Some(digit) = self.read_char() { // Eagerly read all valid identifier characters so that "123foo" doesn't lex as a // number followed by an identifier. if!is_ident_char(digit) { self.unread_char(); break; } number.push(digit); } match number.parse::<u64>() { Ok(value) => Ok(Expr::Number(value)), Err(reason) => Err(ParseError::InvalidNumber(number, reason)), } } fn parse_ident(&mut self) -> Expr { let mut ident = String::new(); while let Some(c) = self.read_char() { if!is_ident_char(c) { self.unread_char(); break; } ident.push(c); } Expr::Ident(ident) } fn skip_whitespace(&mut self) { while let Some(c) = self.read_char() { if!is_whitespace(c) { self.unread_char(); break; } } } fn peek_char(&mut self) -> Option<char> { self.source[self.position..].chars().next() } fn read_char(&mut self) -> Option<char> { let opt_c = self.peek_char(); if let Some(c) = opt_c { self.position += c.len_utf8();
/// Step backwards one `char` in the input. Must not be called more times than `read_char` has /// been called. fn unread_char(&mut self) { assert!(self.position!= 0); let (prev_pos, _) = self.source[..self.position].char_indices().next_back().unwrap(); self.position = prev_pos; } fn at_end(&self) -> bool { self.position == self.source.len() } } impl<'src> Iterator for Parser<'src> { type Item = ParseResult<Expr>; fn next(&mut self) -> Option<ParseResult<Expr>> { self.skip_whitespace(); if self.at_end() { None } else { Some(self.parse_expr()) } } } /// Returns `true` if the given character is whitespace. fn is_whitespace(c: char) -> bool { match c { '' | '\t' | '\n' => true, _ => false, } } /// Returns `true` if the given character is a digit. fn is_digit(c: char) -> bool { match c { '0'...'9' => true, _ => false, } } /// Returns `true` if the given character is valid at the start of an identifier. fn is_ident_start(c: char) -> bool { match c { 'a'...'z' | 'A'...'Z' | '_' | '!' | '?' | '*' | '-' | '+' | '/' | '=' | '<' | '>' => true, _ => false, } } /// Returns `true` if the given character is valid in an identifier. fn is_ident_char(c: char) -> bool { is_ident_start(c) || is_digit(c) }
} opt_c }
random_line_split
allapps.rs
#pragma version(1) #pragma stateVertex(PV) #pragma stateFragment(PFTexNearest) #pragma stateStore(PSIcons) #define PI 3.14159f int g_SpecialHWWar; // Attraction to center values from page edge to page center. float g_AttractionTable[9]; float g_FrictionTable[9]; float g_PhysicsTableSize; float g_PosPage; float g_PosVelocity; float g_LastPositionX; int g_LastTouchDown; float g_DT; int g_LastTime; int g_PosMax; float g_Zoom; float g_Animation; float g_OldPosPage; float g_OldPosVelocity; float g_OldZoom; float g_MoveToTotalTime; float g_MoveToTime; float g_MoveToOldPos; int g_Cols; int g_Rows; // Drawing constants, should be parameters ====== #define VIEW_ANGLE 1.28700222f int g_DrawLastFrame; int lastFrame(int draw) { // We draw one extra frame to work around the last frame post bug. // We also need to track if we drew the last frame to deal with large DT // in the physics. int ret = g_DrawLastFrame | draw; g_DrawLastFrame = draw; return ret; // should return draw instead. } void updateReadback() { if ((g_OldPosPage!= g_PosPage) || (g_OldPosVelocity!= g_PosVelocity) || (g_OldZoom!= g_Zoom)) { g_OldPosPage = g_PosPage; g_OldPosVelocity = g_PosVelocity; g_OldZoom = g_Zoom; int i[3]; i[0] = g_PosPage * (1 << 16); i[1] = g_PosVelocity * (1 << 16); i[2] = g_OldZoom * (1 << 16); sendToClient(&i[0], 1, 12, 1); } } void setColor(float r, float g, float b, float a) { if (g_SpecialHWWar) { color(0, 0, 0, 0.001f); } else { color(r, g, b, a); } } void init() { g_AttractionTable[0] = 20.0f; g_AttractionTable[1] = 20.0f; g_AttractionTable[2] = 20.0f; g_AttractionTable[3] = 10.0f; g_AttractionTable[4] = -10.0f; g_AttractionTable[5] = -20.0f; g_AttractionTable[6] = -20.0f; g_AttractionTable[7] = -20.0f; g_AttractionTable[8] = -20.0f; // dup 7 to avoid a clamp later g_FrictionTable[0] = 10.0f; g_FrictionTable[1] = 10.0f; g_FrictionTable[2] = 11.0f; g_FrictionTable[3] = 15.0f; g_FrictionTable[4] = 15.0f; g_FrictionTable[5] = 11.0f; g_FrictionTable[6] = 10.0f; g_FrictionTable[7] = 10.0f; g_FrictionTable[8] = 10.0f; // dup 7 to avoid a clamp later g_PhysicsTableSize = 7; g_PosVelocity = 0; g_PosPage = 0; g_LastTouchDown = 0; g_LastPositionX = 0; g_Zoom = 0; g_Animation = 1.f; g_SpecialHWWar = 1; g_MoveToTime = 0; g_MoveToOldPos = 0; g_MoveToTotalTime = 0.2f; // Duration of scrolling 1 line } void resetHWWar() { g_SpecialHWWar = 1; } void move() { if (g_LastTouchDown) { float dx = -(state->newPositionX - g_LastPositionX); g_PosVelocity = 0; g_PosPage += dx * 5.2f; float pmin = -0.49f; float pmax = g_PosMax + 0.49f; g_PosPage = clampf(g_PosPage, pmin, pmax); } g_LastTouchDown = state->newTouchDown; g_LastPositionX = state->newPositionX; g_MoveToTime = 0; //debugF("Move P", g_PosPage); } void moveTo() { g_MoveToTime = g_MoveToTotalTime; g_PosVelocity = 0; g_MoveToOldPos = g_PosPage; // debugF("======= moveTo", state->targetPos); } void setZoom() { g_Zoom = state->zoomTarget; g_DrawLastFrame = 1; updateReadback(); } void fling() { g_LastTouchDown = 0; g_PosVelocity = -state->flingVelocity * 4; float av = fabsf(g_PosVelocity); float minVel = 3.5f; minVel *= 1.f - (fabsf(fracf(g_PosPage + 0.5f) - 0.5f) * 0.45f); if (av < minVel && av > 0.2f) { if (g_PosVelocity > 0) { g_PosVelocity = minVel; } else { g_PosVelocity = -minVel; } } if (g_PosPage <= 0) { g_PosVelocity = maxf(0, g_PosVelocity); } if (g_PosPage > g_PosMax) { g_PosVelocity = minf(0, g_PosVelocity); } } float modf(float x, float y) { return x-(y*floorf(x/y)); } /* * Interpolates values in the range 0..1 to a curve that eases in * and out. */ float getInterpolation(float input) { return (cosf((input + 1) * PI) / 2.0f) + 0.5f; } void updatePos() { if (g_LastTouchDown) { return; } float tablePosNorm = fracf(g_PosPage + 0.5f); float tablePosF = tablePosNorm * g_PhysicsTableSize; int tablePosI = tablePosF; float tablePosFrac = tablePosF - tablePosI; float accel = lerpf(g_AttractionTable[tablePosI], g_AttractionTable[tablePosI + 1], tablePosFrac) * g_DT; float friction = lerpf(g_FrictionTable[tablePosI], g_FrictionTable[tablePosI + 1], tablePosFrac) * g_DT; if (g_MoveToTime) { // New position is old posiition + (total distance) * (interpolated time) g_PosPage = g_MoveToOldPos + (state->targetPos - g_MoveToOldPos) * getInterpolation((g_MoveToTotalTime - g_MoveToTime) / g_MoveToTotalTime); g_MoveToTime -= g_DT; if (g_MoveToTime <= 0)
return; } // If our velocity is low OR acceleration is opposing it, apply it. if (fabsf(g_PosVelocity) < 4.0f || (g_PosVelocity * accel) < 0) { g_PosVelocity += accel; } //debugF("g_PosPage", g_PosPage); //debugF(" g_PosVelocity", g_PosVelocity); //debugF(" friction", friction); //debugF(" accel", accel); // Normal physics if (g_PosVelocity > 0) { g_PosVelocity -= friction; g_PosVelocity = maxf(g_PosVelocity, 0); } else { g_PosVelocity += friction; g_PosVelocity = minf(g_PosVelocity, 0); } if ((friction > fabsf(g_PosVelocity)) && (friction > fabsf(accel))) { // Special get back to center and overcome friction physics. float t = tablePosNorm - 0.5f; if (fabsf(t) < (friction * g_DT)) { // really close, just snap g_PosPage = roundf(g_PosPage); g_PosVelocity = 0; } else { if (t > 0) { g_PosVelocity = -friction; } else { g_PosVelocity = friction; } } } // Check for out of boundry conditions. if (g_PosPage < 0 && g_PosVelocity < 0) { float damp = 1.0 + (g_PosPage * 4); damp = clampf(damp, 0.f, 0.9f); g_PosVelocity *= damp; } if (g_PosPage > g_PosMax && g_PosVelocity > 0) { float damp = 1.0 - ((g_PosPage - g_PosMax) * 4); damp = clampf(damp, 0.f, 0.9f); g_PosVelocity *= damp; } g_PosPage += g_PosVelocity * g_DT; g_PosPage = clampf(g_PosPage, -0.49, g_PosMax + 0.49); } void draw_home_button() { setColor(1.0f, 1.0f, 1.0f, 1.0f); bindTexture(NAMED_PFTexNearest, 0, state->homeButtonId); float w = getWidth(); float h = getHeight(); float x; float y; if (getWidth() > getHeight()) { x = w - (params->homeButtonTextureWidth * (1 - g_Animation)) + 20; y = (h - params->homeButtonTextureHeight) * 0.5f; } else { x = (w - params->homeButtonTextureWidth) / 2; y = -g_Animation * params->homeButtonTextureHeight; y -= 30; // move the house to the edge of the screen as it doesn't fill the texture. } drawSpriteScreenspace(x, y, 0, params->homeButtonTextureWidth, params->homeButtonTextureHeight); } void drawFrontGrid(float rowOffset, float p) { float h = getHeight(); float w = getWidth(); int intRowOffset = rowOffset; float rowFrac = rowOffset - intRowOffset; float colWidth = 120.f;//getWidth() / 4; float rowHeight = colWidth + 25.f; float yoff = 0.5f * h + 1.5f * rowHeight; int row, col; int colCount = 4; if (w > h) { colCount = 6; rowHeight -= 12.f; yoff = 0.47f * h + 1.0f * rowHeight; } int iconNum = (intRowOffset - 5) * colCount; bindProgramVertex(NAMED_PVCurve); vpConstants->Position.z = p; setColor(1.0f, 1.0f, 1.0f, 1.0f); for (row = -5; row < 15; row++) { float y = yoff - ((-rowFrac + row) * rowHeight); for (col=0; col < colCount; col++) { if (iconNum >= state->iconCount) { return; } if (iconNum >= 0) { float x = colWidth * col + (colWidth / 2); vpConstants->Position.x = x + 0.2f; if (state->selectedIconIndex == iconNum &&!p) { bindProgramFragment(NAMED_PFTexNearest); bindTexture(NAMED_PFTexNearest, 0, state->selectedIconTexture); vpConstants->ImgSize.x = SELECTION_TEXTURE_WIDTH_PX; vpConstants->ImgSize.y = SELECTION_TEXTURE_HEIGHT_PX; vpConstants->Position.y = y - (SELECTION_TEXTURE_HEIGHT_PX - ICON_TEXTURE_HEIGHT_PX) * 0.5f; drawSimpleMesh(NAMED_SMCell); } bindProgramFragment(NAMED_PFTexMip); vpConstants->ImgSize.x = ICON_TEXTURE_WIDTH_PX; vpConstants->ImgSize.y = ICON_TEXTURE_HEIGHT_PX; vpConstants->Position.y = y - 0.2f; bindTexture(NAMED_PFTexMip, 0, loadI32(ALLOC_ICON_IDS, iconNum)); drawSimpleMesh(NAMED_SMCell); bindProgramFragment(NAMED_PFTexMipAlpha); vpConstants->ImgSize.x = 120.f; vpConstants->ImgSize.y = 64.f; vpConstants->Position.y = y - 64.f - 0.2f; bindTexture(NAMED_PFTexMipAlpha, 0, loadI32(ALLOC_LABEL_IDS, iconNum)); drawSimpleMesh(NAMED_SMCell); } iconNum++; } } } int main(int launchID) { // Compute dt in seconds. int newTime = uptimeMillis(); g_DT = (newTime - g_LastTime) / 1000.f; g_LastTime = newTime; if (!g_DrawLastFrame) { // If we stopped rendering we cannot use DT. // assume 30fps in this case. g_DT = 0.033f; } // physics may break if DT is large. g_DT = minf(g_DT, 0.2f); if (g_Zoom!= state->zoomTarget) { float dz = g_DT * 1.7f; if (state->zoomTarget < 0.5f) { dz = -dz; } if (fabsf(g_Zoom - state->zoomTarget) < fabsf(dz)) { g_Zoom = state->zoomTarget; } else { g_Zoom += dz; } updateReadback(); } g_Animation = powf(1-g_Zoom, 3); // Set clear value to dim the background based on the zoom position. if ((g_Zoom < 0.001f) && (state->zoomTarget < 0.001f) &&!g_SpecialHWWar) { pfClearColor(0.0f, 0.0f, 0.0f, 0.0f); // When we're zoomed out and not tracking motion events, reset the pos to 0. if (!g_LastTouchDown) { g_PosPage = 0; } return lastFrame(0); } else { pfClearColor(0.0f, 0.0f, 0.0f, g_Zoom); } // icons & labels int iconCount = state->iconCount; if (getWidth() > getHeight()) { g_Cols = 6; g_Rows = 3; } else { g_Cols = 4; g_Rows = 4; } g_PosMax = ((iconCount + (g_Cols-1)) / g_Cols) - g_Rows; if (g_PosMax < 0) g_PosMax = 0; updatePos(); updateReadback(); //debugF(" draw g_PosPage", g_PosPage); // Draw the icons ======================================== drawFrontGrid(g_PosPage, g_Animation); bindProgramFragment(NAMED_PFTexNearest); draw_home_button(); // This is a WAR to do a rendering pass without drawing during init to // force the driver to preload and compile its shaders. // Without this the first animation does not appear due to the time it // takes to init the driver state. if (g_SpecialHWWar) { g_SpecialHWWar = 0; return 1; } // Bug workaround where the last frame is not always displayed // So we keep rendering until the bug is fixed. return lastFrame((g_PosVelocity!= 0) || fracf(g_PosPage) || g_Zoom!= state->zoomTarget || (g_MoveToTime!= 0)); }
{ g_MoveToTime = 0; g_PosPage = state->targetPos; }
conditional_block
allapps.rs
#pragma version(1) #pragma stateVertex(PV) #pragma stateFragment(PFTexNearest) #pragma stateStore(PSIcons) #define PI 3.14159f int g_SpecialHWWar; // Attraction to center values from page edge to page center. float g_AttractionTable[9]; float g_FrictionTable[9]; float g_PhysicsTableSize; float g_PosPage; float g_PosVelocity; float g_LastPositionX; int g_LastTouchDown; float g_DT; int g_LastTime; int g_PosMax; float g_Zoom; float g_Animation; float g_OldPosPage; float g_OldPosVelocity; float g_OldZoom; float g_MoveToTotalTime; float g_MoveToTime; float g_MoveToOldPos; int g_Cols; int g_Rows; // Drawing constants, should be parameters ====== #define VIEW_ANGLE 1.28700222f int g_DrawLastFrame; int lastFrame(int draw) { // We draw one extra frame to work around the last frame post bug. // We also need to track if we drew the last frame to deal with large DT // in the physics. int ret = g_DrawLastFrame | draw; g_DrawLastFrame = draw; return ret; // should return draw instead. } void updateReadback() { if ((g_OldPosPage!= g_PosPage) || (g_OldPosVelocity!= g_PosVelocity) || (g_OldZoom!= g_Zoom)) { g_OldPosPage = g_PosPage; g_OldPosVelocity = g_PosVelocity; g_OldZoom = g_Zoom; int i[3]; i[0] = g_PosPage * (1 << 16); i[1] = g_PosVelocity * (1 << 16); i[2] = g_OldZoom * (1 << 16); sendToClient(&i[0], 1, 12, 1); } } void setColor(float r, float g, float b, float a) { if (g_SpecialHWWar) { color(0, 0, 0, 0.001f); } else { color(r, g, b, a); } } void init() { g_AttractionTable[0] = 20.0f; g_AttractionTable[1] = 20.0f; g_AttractionTable[2] = 20.0f; g_AttractionTable[3] = 10.0f; g_AttractionTable[4] = -10.0f; g_AttractionTable[5] = -20.0f; g_AttractionTable[6] = -20.0f; g_AttractionTable[7] = -20.0f; g_AttractionTable[8] = -20.0f; // dup 7 to avoid a clamp later g_FrictionTable[0] = 10.0f; g_FrictionTable[1] = 10.0f; g_FrictionTable[2] = 11.0f; g_FrictionTable[3] = 15.0f; g_FrictionTable[4] = 15.0f; g_FrictionTable[5] = 11.0f; g_FrictionTable[6] = 10.0f; g_FrictionTable[7] = 10.0f; g_FrictionTable[8] = 10.0f; // dup 7 to avoid a clamp later g_PhysicsTableSize = 7; g_PosVelocity = 0; g_PosPage = 0; g_LastTouchDown = 0; g_LastPositionX = 0; g_Zoom = 0; g_Animation = 1.f; g_SpecialHWWar = 1; g_MoveToTime = 0; g_MoveToOldPos = 0; g_MoveToTotalTime = 0.2f; // Duration of scrolling 1 line } void resetHWWar() { g_SpecialHWWar = 1; } void move() { if (g_LastTouchDown) { float dx = -(state->newPositionX - g_LastPositionX); g_PosVelocity = 0; g_PosPage += dx * 5.2f; float pmin = -0.49f; float pmax = g_PosMax + 0.49f; g_PosPage = clampf(g_PosPage, pmin, pmax); } g_LastTouchDown = state->newTouchDown; g_LastPositionX = state->newPositionX; g_MoveToTime = 0; //debugF("Move P", g_PosPage); } void moveTo() { g_MoveToTime = g_MoveToTotalTime; g_PosVelocity = 0; g_MoveToOldPos = g_PosPage; // debugF("======= moveTo", state->targetPos); } void setZoom() { g_Zoom = state->zoomTarget; g_DrawLastFrame = 1; updateReadback(); } void fling() { g_LastTouchDown = 0; g_PosVelocity = -state->flingVelocity * 4; float av = fabsf(g_PosVelocity); float minVel = 3.5f; minVel *= 1.f - (fabsf(fracf(g_PosPage + 0.5f) - 0.5f) * 0.45f); if (av < minVel && av > 0.2f) { if (g_PosVelocity > 0) { g_PosVelocity = minVel; } else { g_PosVelocity = -minVel; } } if (g_PosPage <= 0) { g_PosVelocity = maxf(0, g_PosVelocity); } if (g_PosPage > g_PosMax) { g_PosVelocity = minf(0, g_PosVelocity); } } float modf(float x, float y) { return x-(y*floorf(x/y)); } /* * Interpolates values in the range 0..1 to a curve that eases in * and out. */ float getInterpolation(float input) { return (cosf((input + 1) * PI) / 2.0f) + 0.5f; } void updatePos() { if (g_LastTouchDown) { return; } float tablePosNorm = fracf(g_PosPage + 0.5f); float tablePosF = tablePosNorm * g_PhysicsTableSize; int tablePosI = tablePosF; float tablePosFrac = tablePosF - tablePosI; float accel = lerpf(g_AttractionTable[tablePosI], g_AttractionTable[tablePosI + 1], tablePosFrac) * g_DT; float friction = lerpf(g_FrictionTable[tablePosI], g_FrictionTable[tablePosI + 1], tablePosFrac) * g_DT; if (g_MoveToTime) { // New position is old posiition + (total distance) * (interpolated time) g_PosPage = g_MoveToOldPos + (state->targetPos - g_MoveToOldPos) * getInterpolation((g_MoveToTotalTime - g_MoveToTime) / g_MoveToTotalTime); g_MoveToTime -= g_DT; if (g_MoveToTime <= 0) { g_MoveToTime = 0; g_PosPage = state->targetPos; } return; } // If our velocity is low OR acceleration is opposing it, apply it. if (fabsf(g_PosVelocity) < 4.0f || (g_PosVelocity * accel) < 0) { g_PosVelocity += accel; } //debugF("g_PosPage", g_PosPage); //debugF(" g_PosVelocity", g_PosVelocity); //debugF(" friction", friction); //debugF(" accel", accel); // Normal physics if (g_PosVelocity > 0) { g_PosVelocity -= friction; g_PosVelocity = maxf(g_PosVelocity, 0); } else { g_PosVelocity += friction; g_PosVelocity = minf(g_PosVelocity, 0); } if ((friction > fabsf(g_PosVelocity)) && (friction > fabsf(accel))) { // Special get back to center and overcome friction physics. float t = tablePosNorm - 0.5f; if (fabsf(t) < (friction * g_DT)) { // really close, just snap g_PosPage = roundf(g_PosPage); g_PosVelocity = 0; } else { if (t > 0) { g_PosVelocity = -friction; } else { g_PosVelocity = friction; } } } // Check for out of boundry conditions. if (g_PosPage < 0 && g_PosVelocity < 0) { float damp = 1.0 + (g_PosPage * 4); damp = clampf(damp, 0.f, 0.9f); g_PosVelocity *= damp; } if (g_PosPage > g_PosMax && g_PosVelocity > 0) { float damp = 1.0 - ((g_PosPage - g_PosMax) * 4); damp = clampf(damp, 0.f, 0.9f); g_PosVelocity *= damp; } g_PosPage += g_PosVelocity * g_DT; g_PosPage = clampf(g_PosPage, -0.49, g_PosMax + 0.49); } void draw_home_button() { setColor(1.0f, 1.0f, 1.0f, 1.0f); bindTexture(NAMED_PFTexNearest, 0, state->homeButtonId); float w = getWidth(); float h = getHeight(); float x; float y; if (getWidth() > getHeight()) { x = w - (params->homeButtonTextureWidth * (1 - g_Animation)) + 20; y = (h - params->homeButtonTextureHeight) * 0.5f; } else { x = (w - params->homeButtonTextureWidth) / 2; y = -g_Animation * params->homeButtonTextureHeight; y -= 30; // move the house to the edge of the screen as it doesn't fill the texture. } drawSpriteScreenspace(x, y, 0, params->homeButtonTextureWidth, params->homeButtonTextureHeight); } void drawFrontGrid(float rowOffset, float p) { float h = getHeight(); float w = getWidth(); int intRowOffset = rowOffset; float rowFrac = rowOffset - intRowOffset; float colWidth = 120.f;//getWidth() / 4; float rowHeight = colWidth + 25.f; float yoff = 0.5f * h + 1.5f * rowHeight; int row, col; int colCount = 4; if (w > h) { colCount = 6; rowHeight -= 12.f; yoff = 0.47f * h + 1.0f * rowHeight; } int iconNum = (intRowOffset - 5) * colCount; bindProgramVertex(NAMED_PVCurve); vpConstants->Position.z = p; setColor(1.0f, 1.0f, 1.0f, 1.0f); for (row = -5; row < 15; row++) { float y = yoff - ((-rowFrac + row) * rowHeight); for (col=0; col < colCount; col++) { if (iconNum >= state->iconCount) { return; } if (iconNum >= 0) { float x = colWidth * col + (colWidth / 2); vpConstants->Position.x = x + 0.2f; if (state->selectedIconIndex == iconNum &&!p) { bindProgramFragment(NAMED_PFTexNearest); bindTexture(NAMED_PFTexNearest, 0, state->selectedIconTexture); vpConstants->ImgSize.x = SELECTION_TEXTURE_WIDTH_PX; vpConstants->ImgSize.y = SELECTION_TEXTURE_HEIGHT_PX; vpConstants->Position.y = y - (SELECTION_TEXTURE_HEIGHT_PX - ICON_TEXTURE_HEIGHT_PX) * 0.5f; drawSimpleMesh(NAMED_SMCell); } bindProgramFragment(NAMED_PFTexMip); vpConstants->ImgSize.x = ICON_TEXTURE_WIDTH_PX; vpConstants->ImgSize.y = ICON_TEXTURE_HEIGHT_PX; vpConstants->Position.y = y - 0.2f; bindTexture(NAMED_PFTexMip, 0, loadI32(ALLOC_ICON_IDS, iconNum)); drawSimpleMesh(NAMED_SMCell); bindProgramFragment(NAMED_PFTexMipAlpha); vpConstants->ImgSize.x = 120.f; vpConstants->ImgSize.y = 64.f; vpConstants->Position.y = y - 64.f - 0.2f; bindTexture(NAMED_PFTexMipAlpha, 0, loadI32(ALLOC_LABEL_IDS, iconNum)); drawSimpleMesh(NAMED_SMCell); } iconNum++; } } } int main(int launchID) { // Compute dt in seconds. int newTime = uptimeMillis(); g_DT = (newTime - g_LastTime) / 1000.f; g_LastTime = newTime; if (!g_DrawLastFrame) { // If we stopped rendering we cannot use DT. // assume 30fps in this case. g_DT = 0.033f; } // physics may break if DT is large. g_DT = minf(g_DT, 0.2f); if (g_Zoom!= state->zoomTarget) { float dz = g_DT * 1.7f; if (state->zoomTarget < 0.5f) { dz = -dz; } if (fabsf(g_Zoom - state->zoomTarget) < fabsf(dz)) { g_Zoom = state->zoomTarget; } else { g_Zoom += dz; } updateReadback(); } g_Animation = powf(1-g_Zoom, 3); // Set clear value to dim the background based on the zoom position. if ((g_Zoom < 0.001f) && (state->zoomTarget < 0.001f) &&!g_SpecialHWWar) { pfClearColor(0.0f, 0.0f, 0.0f, 0.0f); // When we're zoomed out and not tracking motion events, reset the pos to 0. if (!g_LastTouchDown) { g_PosPage = 0; } return lastFrame(0); } else { pfClearColor(0.0f, 0.0f, 0.0f, g_Zoom); } // icons & labels int iconCount = state->iconCount; if (getWidth() > getHeight()) { g_Cols = 6;
g_Rows = 4; } g_PosMax = ((iconCount + (g_Cols-1)) / g_Cols) - g_Rows; if (g_PosMax < 0) g_PosMax = 0; updatePos(); updateReadback(); //debugF(" draw g_PosPage", g_PosPage); // Draw the icons ======================================== drawFrontGrid(g_PosPage, g_Animation); bindProgramFragment(NAMED_PFTexNearest); draw_home_button(); // This is a WAR to do a rendering pass without drawing during init to // force the driver to preload and compile its shaders. // Without this the first animation does not appear due to the time it // takes to init the driver state. if (g_SpecialHWWar) { g_SpecialHWWar = 0; return 1; } // Bug workaround where the last frame is not always displayed // So we keep rendering until the bug is fixed. return lastFrame((g_PosVelocity!= 0) || fracf(g_PosPage) || g_Zoom!= state->zoomTarget || (g_MoveToTime!= 0)); }
g_Rows = 3; } else { g_Cols = 4;
random_line_split
base16.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Base16 iterator //! //! The main radix tree uses base16 to support hex string prefix lookups and //! make the space usage more efficient. #[derive(Debug, Copy, Clone)] pub struct
<'a, T>(&'a T, usize, usize); impl<'a, T: AsRef<[u8]>> Base16Iter<'a, T> { /// Convert base256 binary sequence to a base16 iterator. pub fn from_bin(binary: &'a T) -> Self { let len = binary.as_ref().len() * 2; Base16Iter(binary, 0, len) } } /// Base16 iterator for [u8] impl<'a, T: AsRef<[u8]>> Iterator for Base16Iter<'a, T> { type Item = u8; #[inline] fn next(&mut self) -> Option<u8> { if self.2 <= self.1 { None } else { let i = self.1; self.1 = i + 1; let v = self.0.as_ref()[i / 2]; if i & 1 == 0 { v >> 4 } else { v & 0xf }.into() } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let len = self.len(); (len, Some(len)) } #[inline] fn count(self) -> usize { self.len() } } impl<'a, T: AsRef<[u8]>> DoubleEndedIterator for Base16Iter<'a, T> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { if self.2 <= self.1 { None } else { let i = self.2 - 1; self.2 = i; let v = self.0.as_ref()[i / 2]; if i & 1 == 0 { v >> 4 } else { v & 0xf }.into() } } } impl<'a, T: AsRef<[u8]>> ExactSizeIterator for Base16Iter<'a, T> { #[inline] fn len(&self) -> usize { self.2 - self.1 } } impl<'a, T: AsRef<[u8]>> Base16Iter<'a, T> { #[inline] pub fn skip(self, n: usize) -> Self { Base16Iter(self.0, self.1 + n, self.2) } #[inline] pub fn take(self, n: usize) -> Self { // TODO: Use (self.1 + n).min(self.2) once ord_max_min is available (Rust 1.22) let mut end = self.1 + n; if self.2 < end { end = self.2 } Base16Iter(self.0, self.1, end) } } #[cfg(test)] mod tests { use quickcheck::quickcheck; use super::*; quickcheck! { fn check_skip_rev(src: Vec<u8>) -> bool { let iter = Base16Iter::from_bin(&src); let full: Vec<u8> = iter.clone().collect(); let rev: Vec<u8> = iter.clone().rev().collect(); (0..full.len()).all(|i| { let v: Vec<u8> = iter.clone().skip(i).collect(); let r: Vec<u8> = iter.clone().skip(i).rev().rev().rev().collect(); v.capacity() == v.len() && v[..] == full[i..] && r.capacity() == r.len() && r[..] == rev[..(rev.len() - i)] }) } } // The below patterns (skip, zip, rev; skip, take, rev) are used in radix.rs. // Make sure they work at iterator level without needing an extra container. #[test] fn test_zip_skip_rev() { let x = [0x12, 0x34, 0x56, 0x21u8]; let y = [0x78, 0x90, 0xab, 0xcdu8]; let i = Base16Iter::from_bin(&x) .skip(2) .zip(Base16Iter::from_bin(&y).skip(3)) .rev(); //.rev() works directly let v: Vec<(u8, u8)> = i.collect(); assert_eq!(v.capacity(), v.len()); assert_eq!(v, vec![(2, 0xd), (6, 0xc), (5, 0xb), (4, 0xa), (3, 0)]); } #[test] fn test_skip_take_rev() { let x = [0x12, 0x34, 0x56u8]; let i = Base16Iter::from_bin(&x).skip(3).take(3).rev(); //.rev() works directly let v: Vec<u8> = i.collect(); assert_eq!(v.capacity(), v.len()); assert_eq!(v, vec![6, 5, 4]); } }
Base16Iter
identifier_name
base16.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Base16 iterator //! //! The main radix tree uses base16 to support hex string prefix lookups and //! make the space usage more efficient. #[derive(Debug, Copy, Clone)] pub struct Base16Iter<'a, T>(&'a T, usize, usize); impl<'a, T: AsRef<[u8]>> Base16Iter<'a, T> { /// Convert base256 binary sequence to a base16 iterator. pub fn from_bin(binary: &'a T) -> Self { let len = binary.as_ref().len() * 2; Base16Iter(binary, 0, len) } } /// Base16 iterator for [u8] impl<'a, T: AsRef<[u8]>> Iterator for Base16Iter<'a, T> { type Item = u8; #[inline] fn next(&mut self) -> Option<u8> { if self.2 <= self.1 { None } else { let i = self.1; self.1 = i + 1; let v = self.0.as_ref()[i / 2]; if i & 1 == 0 { v >> 4 } else { v & 0xf }.into() } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let len = self.len(); (len, Some(len)) } #[inline] fn count(self) -> usize { self.len() } } impl<'a, T: AsRef<[u8]>> DoubleEndedIterator for Base16Iter<'a, T> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { if self.2 <= self.1
else { let i = self.2 - 1; self.2 = i; let v = self.0.as_ref()[i / 2]; if i & 1 == 0 { v >> 4 } else { v & 0xf }.into() } } } impl<'a, T: AsRef<[u8]>> ExactSizeIterator for Base16Iter<'a, T> { #[inline] fn len(&self) -> usize { self.2 - self.1 } } impl<'a, T: AsRef<[u8]>> Base16Iter<'a, T> { #[inline] pub fn skip(self, n: usize) -> Self { Base16Iter(self.0, self.1 + n, self.2) } #[inline] pub fn take(self, n: usize) -> Self { // TODO: Use (self.1 + n).min(self.2) once ord_max_min is available (Rust 1.22) let mut end = self.1 + n; if self.2 < end { end = self.2 } Base16Iter(self.0, self.1, end) } } #[cfg(test)] mod tests { use quickcheck::quickcheck; use super::*; quickcheck! { fn check_skip_rev(src: Vec<u8>) -> bool { let iter = Base16Iter::from_bin(&src); let full: Vec<u8> = iter.clone().collect(); let rev: Vec<u8> = iter.clone().rev().collect(); (0..full.len()).all(|i| { let v: Vec<u8> = iter.clone().skip(i).collect(); let r: Vec<u8> = iter.clone().skip(i).rev().rev().rev().collect(); v.capacity() == v.len() && v[..] == full[i..] && r.capacity() == r.len() && r[..] == rev[..(rev.len() - i)] }) } } // The below patterns (skip, zip, rev; skip, take, rev) are used in radix.rs. // Make sure they work at iterator level without needing an extra container. #[test] fn test_zip_skip_rev() { let x = [0x12, 0x34, 0x56, 0x21u8]; let y = [0x78, 0x90, 0xab, 0xcdu8]; let i = Base16Iter::from_bin(&x) .skip(2) .zip(Base16Iter::from_bin(&y).skip(3)) .rev(); //.rev() works directly let v: Vec<(u8, u8)> = i.collect(); assert_eq!(v.capacity(), v.len()); assert_eq!(v, vec![(2, 0xd), (6, 0xc), (5, 0xb), (4, 0xa), (3, 0)]); } #[test] fn test_skip_take_rev() { let x = [0x12, 0x34, 0x56u8]; let i = Base16Iter::from_bin(&x).skip(3).take(3).rev(); //.rev() works directly let v: Vec<u8> = i.collect(); assert_eq!(v.capacity(), v.len()); assert_eq!(v, vec![6, 5, 4]); } }
{ None }
conditional_block
base16.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Base16 iterator //! //! The main radix tree uses base16 to support hex string prefix lookups and //! make the space usage more efficient. #[derive(Debug, Copy, Clone)] pub struct Base16Iter<'a, T>(&'a T, usize, usize); impl<'a, T: AsRef<[u8]>> Base16Iter<'a, T> { /// Convert base256 binary sequence to a base16 iterator. pub fn from_bin(binary: &'a T) -> Self { let len = binary.as_ref().len() * 2; Base16Iter(binary, 0, len) } } /// Base16 iterator for [u8] impl<'a, T: AsRef<[u8]>> Iterator for Base16Iter<'a, T> { type Item = u8; #[inline] fn next(&mut self) -> Option<u8> { if self.2 <= self.1 { None } else { let i = self.1; self.1 = i + 1; let v = self.0.as_ref()[i / 2]; if i & 1 == 0 { v >> 4 } else { v & 0xf }.into() } } #[inline] fn size_hint(&self) -> (usize, Option<usize>)
#[inline] fn count(self) -> usize { self.len() } } impl<'a, T: AsRef<[u8]>> DoubleEndedIterator for Base16Iter<'a, T> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { if self.2 <= self.1 { None } else { let i = self.2 - 1; self.2 = i; let v = self.0.as_ref()[i / 2]; if i & 1 == 0 { v >> 4 } else { v & 0xf }.into() } } } impl<'a, T: AsRef<[u8]>> ExactSizeIterator for Base16Iter<'a, T> { #[inline] fn len(&self) -> usize { self.2 - self.1 } } impl<'a, T: AsRef<[u8]>> Base16Iter<'a, T> { #[inline] pub fn skip(self, n: usize) -> Self { Base16Iter(self.0, self.1 + n, self.2) } #[inline] pub fn take(self, n: usize) -> Self { // TODO: Use (self.1 + n).min(self.2) once ord_max_min is available (Rust 1.22) let mut end = self.1 + n; if self.2 < end { end = self.2 } Base16Iter(self.0, self.1, end) } } #[cfg(test)] mod tests { use quickcheck::quickcheck; use super::*; quickcheck! { fn check_skip_rev(src: Vec<u8>) -> bool { let iter = Base16Iter::from_bin(&src); let full: Vec<u8> = iter.clone().collect(); let rev: Vec<u8> = iter.clone().rev().collect(); (0..full.len()).all(|i| { let v: Vec<u8> = iter.clone().skip(i).collect(); let r: Vec<u8> = iter.clone().skip(i).rev().rev().rev().collect(); v.capacity() == v.len() && v[..] == full[i..] && r.capacity() == r.len() && r[..] == rev[..(rev.len() - i)] }) } } // The below patterns (skip, zip, rev; skip, take, rev) are used in radix.rs. // Make sure they work at iterator level without needing an extra container. #[test] fn test_zip_skip_rev() { let x = [0x12, 0x34, 0x56, 0x21u8]; let y = [0x78, 0x90, 0xab, 0xcdu8]; let i = Base16Iter::from_bin(&x) .skip(2) .zip(Base16Iter::from_bin(&y).skip(3)) .rev(); //.rev() works directly let v: Vec<(u8, u8)> = i.collect(); assert_eq!(v.capacity(), v.len()); assert_eq!(v, vec![(2, 0xd), (6, 0xc), (5, 0xb), (4, 0xa), (3, 0)]); } #[test] fn test_skip_take_rev() { let x = [0x12, 0x34, 0x56u8]; let i = Base16Iter::from_bin(&x).skip(3).take(3).rev(); //.rev() works directly let v: Vec<u8> = i.collect(); assert_eq!(v.capacity(), v.len()); assert_eq!(v, vec![6, 5, 4]); } }
{ let len = self.len(); (len, Some(len)) }
identifier_body
base16.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Base16 iterator //! //! The main radix tree uses base16 to support hex string prefix lookups and //! make the space usage more efficient. #[derive(Debug, Copy, Clone)] pub struct Base16Iter<'a, T>(&'a T, usize, usize); impl<'a, T: AsRef<[u8]>> Base16Iter<'a, T> { /// Convert base256 binary sequence to a base16 iterator. pub fn from_bin(binary: &'a T) -> Self { let len = binary.as_ref().len() * 2; Base16Iter(binary, 0, len) } } /// Base16 iterator for [u8] impl<'a, T: AsRef<[u8]>> Iterator for Base16Iter<'a, T> { type Item = u8; #[inline] fn next(&mut self) -> Option<u8> { if self.2 <= self.1 { None } else { let i = self.1; self.1 = i + 1; let v = self.0.as_ref()[i / 2]; if i & 1 == 0 { v >> 4 } else { v & 0xf }.into() } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let len = self.len(); (len, Some(len)) } #[inline] fn count(self) -> usize { self.len() } } impl<'a, T: AsRef<[u8]>> DoubleEndedIterator for Base16Iter<'a, T> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { if self.2 <= self.1 { None } else { let i = self.2 - 1; self.2 = i; let v = self.0.as_ref()[i / 2]; if i & 1 == 0 { v >> 4 } else { v & 0xf }.into() } } } impl<'a, T: AsRef<[u8]>> ExactSizeIterator for Base16Iter<'a, T> { #[inline] fn len(&self) -> usize { self.2 - self.1 } } impl<'a, T: AsRef<[u8]>> Base16Iter<'a, T> { #[inline] pub fn skip(self, n: usize) -> Self { Base16Iter(self.0, self.1 + n, self.2) } #[inline] pub fn take(self, n: usize) -> Self { // TODO: Use (self.1 + n).min(self.2) once ord_max_min is available (Rust 1.22) let mut end = self.1 + n; if self.2 < end { end = self.2 } Base16Iter(self.0, self.1, end) } } #[cfg(test)] mod tests { use quickcheck::quickcheck; use super::*;
fn check_skip_rev(src: Vec<u8>) -> bool { let iter = Base16Iter::from_bin(&src); let full: Vec<u8> = iter.clone().collect(); let rev: Vec<u8> = iter.clone().rev().collect(); (0..full.len()).all(|i| { let v: Vec<u8> = iter.clone().skip(i).collect(); let r: Vec<u8> = iter.clone().skip(i).rev().rev().rev().collect(); v.capacity() == v.len() && v[..] == full[i..] && r.capacity() == r.len() && r[..] == rev[..(rev.len() - i)] }) } } // The below patterns (skip, zip, rev; skip, take, rev) are used in radix.rs. // Make sure they work at iterator level without needing an extra container. #[test] fn test_zip_skip_rev() { let x = [0x12, 0x34, 0x56, 0x21u8]; let y = [0x78, 0x90, 0xab, 0xcdu8]; let i = Base16Iter::from_bin(&x) .skip(2) .zip(Base16Iter::from_bin(&y).skip(3)) .rev(); //.rev() works directly let v: Vec<(u8, u8)> = i.collect(); assert_eq!(v.capacity(), v.len()); assert_eq!(v, vec![(2, 0xd), (6, 0xc), (5, 0xb), (4, 0xa), (3, 0)]); } #[test] fn test_skip_take_rev() { let x = [0x12, 0x34, 0x56u8]; let i = Base16Iter::from_bin(&x).skip(3).take(3).rev(); //.rev() works directly let v: Vec<u8> = i.collect(); assert_eq!(v.capacity(), v.len()); assert_eq!(v, vec![6, 5, 4]); } }
quickcheck! {
random_line_split
game.rs
use rand::{thread_rng, Rng}; use sdl2::render; use sdl2::rect::Rect; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use basic2d::Vec2; use snake::{Snake, Move}; // Game structure pub struct Game { pub snakes: Vec<Snake>, fruit: Vec2<i32>, width: u32, height: u32, grid_size: u32 } impl Game { /// Initialises the game pub fn new(width: u32, height: u32, grid_size: u32) -> Game { let mut game = Game { snakes: vec![Snake::new_with_defaults(Vec2::new(5, 5))], fruit: Vec2::new(0, 0), width: width, height: height, grid_size: grid_size }; game.fruit = game.rand_grid_point(); game } /// Draws the game pub fn
(&mut self, renderer: &mut render::Renderer) { // Draw fruit renderer.set_draw_color(Color::RGB(0xAA, 0x30, 0x30)); renderer.fill_rect(self.point_to_rect(self.fruit)).unwrap(); // Draw snakes renderer.set_draw_color(Color::RGB(0x60, 0xAA, 0x60)); for snake in &self.snakes { let head = snake.get_head(); renderer.fill_rect(self.point_to_rect(head)).unwrap(); let tail_components = snake.tail_to_points(); for &component in &tail_components { renderer.fill_rect(self.point_to_rect(component)).unwrap(); } } } fn point_to_rect(&self, point: Vec2<i32>) -> Rect { Rect::new( self.grid_size as i32 * point.x, self.grid_size as i32 * point.y, self.grid_size, self.grid_size, ) } /// Updates the game using the time elapsed since the last update pub fn update(&mut self, elapsed_time: f32) { for i in 0..self.snakes.len() { self.snakes[i].update(elapsed_time); let collision = self.snakes[i].check_collision(self.width, self.height, &self.snakes[i].tail_to_points()); if collision { self.snakes[i].dead = true; } let head = self.snakes[i].get_head(); if head == self.fruit { self.snakes[i].score += 10; self.snakes[i].add_segment(); self.new_fruit(); } } } pub fn key_down(&mut self, keycode: Keycode) { match keycode { Keycode::Up => self.snakes[0].set_move(Move::Up), Keycode::Down => self.snakes[0].set_move(Move::Down), Keycode::Left => self.snakes[0].set_move(Move::Left), Keycode::Right => self.snakes[0].set_move(Move::Right), _ => {}, } } // Generates a random point on the grid fn rand_grid_point(&self) -> Vec2<i32> { Vec2::new( (thread_rng().gen::<u32>() % self.width) as i32, (thread_rng().gen::<u32>() % self.height) as i32 ) } /// Randomizes the position of the fruit pub fn new_fruit(&mut self) { // FIXME: snakes should return iterators that iterate through their // components instead of allocating vectors. let mut walls = vec![]; for snake in &self.snakes { walls.extend(snake.tail_to_points()); walls.push(snake.get_head()); } // Move until the fruit is not covered by the snake while walls.iter().any(|&w| self.fruit == w) { self.fruit = self.rand_grid_point(); } } }
draw
identifier_name
game.rs
use rand::{thread_rng, Rng}; use sdl2::render; use sdl2::rect::Rect; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use basic2d::Vec2; use snake::{Snake, Move}; // Game structure pub struct Game { pub snakes: Vec<Snake>, fruit: Vec2<i32>, width: u32, height: u32, grid_size: u32 } impl Game { /// Initialises the game pub fn new(width: u32, height: u32, grid_size: u32) -> Game { let mut game = Game { snakes: vec![Snake::new_with_defaults(Vec2::new(5, 5))], fruit: Vec2::new(0, 0), width: width, height: height, grid_size: grid_size }; game.fruit = game.rand_grid_point(); game } /// Draws the game pub fn draw(&mut self, renderer: &mut render::Renderer) { // Draw fruit renderer.set_draw_color(Color::RGB(0xAA, 0x30, 0x30)); renderer.fill_rect(self.point_to_rect(self.fruit)).unwrap(); // Draw snakes renderer.set_draw_color(Color::RGB(0x60, 0xAA, 0x60)); for snake in &self.snakes { let head = snake.get_head(); renderer.fill_rect(self.point_to_rect(head)).unwrap(); let tail_components = snake.tail_to_points(); for &component in &tail_components { renderer.fill_rect(self.point_to_rect(component)).unwrap(); } } } fn point_to_rect(&self, point: Vec2<i32>) -> Rect { Rect::new( self.grid_size as i32 * point.x, self.grid_size as i32 * point.y, self.grid_size, self.grid_size, ) } /// Updates the game using the time elapsed since the last update pub fn update(&mut self, elapsed_time: f32) { for i in 0..self.snakes.len() { self.snakes[i].update(elapsed_time); let collision = self.snakes[i].check_collision(self.width, self.height, &self.snakes[i].tail_to_points()); if collision
let head = self.snakes[i].get_head(); if head == self.fruit { self.snakes[i].score += 10; self.snakes[i].add_segment(); self.new_fruit(); } } } pub fn key_down(&mut self, keycode: Keycode) { match keycode { Keycode::Up => self.snakes[0].set_move(Move::Up), Keycode::Down => self.snakes[0].set_move(Move::Down), Keycode::Left => self.snakes[0].set_move(Move::Left), Keycode::Right => self.snakes[0].set_move(Move::Right), _ => {}, } } // Generates a random point on the grid fn rand_grid_point(&self) -> Vec2<i32> { Vec2::new( (thread_rng().gen::<u32>() % self.width) as i32, (thread_rng().gen::<u32>() % self.height) as i32 ) } /// Randomizes the position of the fruit pub fn new_fruit(&mut self) { // FIXME: snakes should return iterators that iterate through their // components instead of allocating vectors. let mut walls = vec![]; for snake in &self.snakes { walls.extend(snake.tail_to_points()); walls.push(snake.get_head()); } // Move until the fruit is not covered by the snake while walls.iter().any(|&w| self.fruit == w) { self.fruit = self.rand_grid_point(); } } }
{ self.snakes[i].dead = true; }
conditional_block
game.rs
use rand::{thread_rng, Rng}; use sdl2::render; use sdl2::rect::Rect; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use basic2d::Vec2; use snake::{Snake, Move}; // Game structure pub struct Game { pub snakes: Vec<Snake>, fruit: Vec2<i32>, width: u32, height: u32, grid_size: u32 } impl Game { /// Initialises the game pub fn new(width: u32, height: u32, grid_size: u32) -> Game { let mut game = Game { snakes: vec![Snake::new_with_defaults(Vec2::new(5, 5))], fruit: Vec2::new(0, 0), width: width, height: height, grid_size: grid_size }; game.fruit = game.rand_grid_point(); game } /// Draws the game pub fn draw(&mut self, renderer: &mut render::Renderer) { // Draw fruit renderer.set_draw_color(Color::RGB(0xAA, 0x30, 0x30)); renderer.fill_rect(self.point_to_rect(self.fruit)).unwrap(); // Draw snakes renderer.set_draw_color(Color::RGB(0x60, 0xAA, 0x60)); for snake in &self.snakes { let head = snake.get_head(); renderer.fill_rect(self.point_to_rect(head)).unwrap(); let tail_components = snake.tail_to_points(); for &component in &tail_components { renderer.fill_rect(self.point_to_rect(component)).unwrap(); } } } fn point_to_rect(&self, point: Vec2<i32>) -> Rect { Rect::new( self.grid_size as i32 * point.x, self.grid_size as i32 * point.y, self.grid_size, self.grid_size, ) } /// Updates the game using the time elapsed since the last update pub fn update(&mut self, elapsed_time: f32) { for i in 0..self.snakes.len() { self.snakes[i].update(elapsed_time); let collision = self.snakes[i].check_collision(self.width, self.height, &self.snakes[i].tail_to_points()); if collision { self.snakes[i].dead = true; } let head = self.snakes[i].get_head(); if head == self.fruit { self.snakes[i].score += 10; self.snakes[i].add_segment(); self.new_fruit(); } } } pub fn key_down(&mut self, keycode: Keycode) { match keycode { Keycode::Up => self.snakes[0].set_move(Move::Up), Keycode::Down => self.snakes[0].set_move(Move::Down), Keycode::Left => self.snakes[0].set_move(Move::Left), Keycode::Right => self.snakes[0].set_move(Move::Right), _ => {}, } } // Generates a random point on the grid fn rand_grid_point(&self) -> Vec2<i32> { Vec2::new(
(thread_rng().gen::<u32>() % self.width) as i32, (thread_rng().gen::<u32>() % self.height) as i32 ) } /// Randomizes the position of the fruit pub fn new_fruit(&mut self) { // FIXME: snakes should return iterators that iterate through their // components instead of allocating vectors. let mut walls = vec![]; for snake in &self.snakes { walls.extend(snake.tail_to_points()); walls.push(snake.get_head()); } // Move until the fruit is not covered by the snake while walls.iter().any(|&w| self.fruit == w) { self.fruit = self.rand_grid_point(); } } }
random_line_split
instr_aesdeclast.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn
() { run_test(&Instruction { mnemonic: Mnemonic::AESDECLAST, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 223, 202], OperandSize::Dword) } #[test] fn aesdeclast_2() { run_test(&Instruction { mnemonic: Mnemonic::AESDECLAST, operand1: Some(Direct(XMM4)), operand2: Some(IndirectScaledDisplaced(EAX, Four, 1919230320, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 223, 36, 133, 112, 33, 101, 114], OperandSize::Dword) } #[test] fn aesdeclast_3() { run_test(&Instruction { mnemonic: Mnemonic::AESDECLAST, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 223, 212], OperandSize::Qword) } #[test] fn aesdeclast_4() { run_test(&Instruction { mnemonic: Mnemonic::AESDECLAST, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexed(RBX, RSI, Two, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 223, 52, 115], OperandSize::Qword) }
aesdeclast_1
identifier_name
instr_aesdeclast.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn aesdeclast_1() { run_test(&Instruction { mnemonic: Mnemonic::AESDECLAST, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 223, 202], OperandSize::Dword) } #[test] fn aesdeclast_2() { run_test(&Instruction { mnemonic: Mnemonic::AESDECLAST, operand1: Some(Direct(XMM4)), operand2: Some(IndirectScaledDisplaced(EAX, Four, 1919230320, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 223, 36, 133, 112, 33, 101, 114], OperandSize::Dword) } #[test] fn aesdeclast_3() { run_test(&Instruction { mnemonic: Mnemonic::AESDECLAST, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 223, 212], OperandSize::Qword) } #[test] fn aesdeclast_4()
{ run_test(&Instruction { mnemonic: Mnemonic::AESDECLAST, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexed(RBX, RSI, Two, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 223, 52, 115], OperandSize::Qword) }
identifier_body
instr_aesdeclast.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn aesdeclast_1() { run_test(&Instruction { mnemonic: Mnemonic::AESDECLAST, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 223, 202], OperandSize::Dword) } #[test]
run_test(&Instruction { mnemonic: Mnemonic::AESDECLAST, operand1: Some(Direct(XMM4)), operand2: Some(IndirectScaledDisplaced(EAX, Four, 1919230320, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 223, 36, 133, 112, 33, 101, 114], OperandSize::Dword) } #[test] fn aesdeclast_3() { run_test(&Instruction { mnemonic: Mnemonic::AESDECLAST, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 223, 212], OperandSize::Qword) } #[test] fn aesdeclast_4() { run_test(&Instruction { mnemonic: Mnemonic::AESDECLAST, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexed(RBX, RSI, Two, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 223, 52, 115], OperandSize::Qword) }
fn aesdeclast_2() {
random_line_split
parsing.rs
//! Utility functions for Header implementations. use language_tags::LanguageTag; use std::str; use std::str::FromStr; use std::fmt::{self, Display}; use url::percent_encoding; use header::shared::Charset; /// Reads a single raw string when parsing a header. pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> ::Result<T> { if raw.len()!= 1 || unsafe { raw.get_unchecked(0) } == b"" { return Err(::Error::Header) } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. from_raw_str(& unsafe { raw.get_unchecked(0) }) } /// Reads a raw string into a value. pub fn from_raw_str<T: str::FromStr>(raw: &[u8]) -> ::Result<T> { let s = try!(str::from_utf8(raw)); T::from_str(s).or(Err(::Error::Header)) } /// Reads a comma-delimited raw header into a Vec. #[inline] pub fn from_comma_delimited<T: str::FromStr>(raw: &[Vec<u8>]) -> ::Result<Vec<T>> { if raw.len()!= 1 { return Err(::Error::Header); } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. from_one_comma_delimited(& unsafe { raw.get_unchecked(0) }[..]) } /// Reads a comma-delimited raw string into a Vec. pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> ::Result<Vec<T>> { let s = try!(str::from_utf8(raw)); Ok(s.split(',') .filter_map(|x| match x.trim() { "" => None, y => Some(y) }) .filter_map(|x| x.parse().ok()) .collect()) } /// Format an array into a comma-delimited string. pub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result { for (i, part) in parts.iter().enumerate() { if i!= 0 { try!(f.write_str(", ")); } try!(Display::fmt(part, f)); } Ok(()) } /// An extended header parameter value (i.e., tagged with a character set and optionally, /// a language), as defined in [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2). pub struct ExtendedValue { pub charset: Charset, pub language_tag: Option<LanguageTag>, pub value: Vec<u8>, } /// Parses extended header parameter values (`ext-value`), as defined in /// [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2). /// /// Extended values are denoted by parameter names that end with `*`. /// /// ## ABNF /// ```plain /// ext-value = charset "'" [ language ] "'" value-chars /// ; like RFC 2231's <extended-initial-value> /// ; (see [RFC2231], Section 7) /// /// charset = "UTF-8" / "ISO-8859-1" / mime-charset /// /// mime-charset = 1*mime-charsetc /// mime-charsetc = ALPHA / DIGIT /// / "!" / "#" / "$" / "%" / "&" /// / "+" / "-" / "^" / "_" / "`" /// / "{" / "}" / "~" /// ; as <mime-charset> in Section 2.3 of [RFC2978] /// ; except that the single quote is not included /// ; SHOULD be registered in the IANA charset registry /// /// language = <Language-Tag, defined in [RFC5646], Section 2.1> /// /// value-chars = *( pct-encoded / attr-char ) /// /// pct-encoded = "%" HEXDIG HEXDIG /// ; see [RFC3986], Section 2.1 /// /// attr-char = ALPHA / DIGIT /// / "!" / "#" / "$" / "&" / "+" / "-" / "." /// / "^" / "_" / "`" / "|" / "~" /// ; token except ( "*" / "'" / "%" ) /// ``` pub fn parse_extended_value(val: &str) -> ::Result<ExtendedValue> { // Break into three pieces separated by the single-quote character let mut parts = val.splitn(3,'\''); // Interpret the first piece as a Charset let charset: Charset = match parts.next() { None => return Err(::Error::Header), Some(n) => try!(FromStr::from_str(n)), }; // Interpret the second piece as a language tag let lang: Option<LanguageTag> = match parts.next() { None => return Err(::Error::Header), Some("") => None, Some(s) => match s.parse() { Ok(lt) => Some(lt), Err(_) => return Err(::Error::Header), } }; // Interpret the third piece as a sequence of value characters let value: Vec<u8> = match parts.next() { None => return Err(::Error::Header), Some(v) => percent_encoding::percent_decode(v.as_bytes()), }; Ok(ExtendedValue { charset: charset, language_tag: lang, value: value, }) } #[cfg(test)] mod tests { use header::shared::Charset; use super::parse_extended_value; #[test] fn test_parse_extended_value_with_encoding_and_language_tag() { let expected_language_tag = langtag!(en); // RFC 5987, Section 3.2.2 // Extended notation, using the Unicode character U+00A3 (POUND SIGN) let result = parse_extended_value("iso-8859-1'en'%A3%20rates"); assert!(result.is_ok()); let extended_value = result.unwrap(); assert_eq!(Charset::Iso_8859_1, extended_value.charset); assert!(extended_value.language_tag.is_some()); assert_eq!(expected_language_tag, extended_value.language_tag.unwrap()); assert_eq!(vec![163, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value); } #[test] fn test_parse_extended_value_with_encoding() { // RFC 5987, Section 3.2.2 // Extended notation, using the Unicode characters U+00A3 (POUND SIGN) // and U+20AC (EURO SIGN) let result = parse_extended_value("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates"); assert!(result.is_ok()); let extended_value = result.unwrap(); assert_eq!(Charset::Ext("UTF-8".to_string()), extended_value.charset); assert!(extended_value.language_tag.is_none()); assert_eq!(vec![194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value); } #[test] fn test_parse_extended_value_missing_language_tag_and_encoding() { // From: https://greenbytes.de/tech/tc2231/#attwithfn2231quot2 let result = parse_extended_value("foo%20bar.html"); assert!(result.is_err()); } #[test] fn test_parse_extended_value_partially_formatted()
#[test] fn test_parse_extended_value_partially_formatted_blank() { let result = parse_extended_value("blank second part'"); assert!(result.is_err()); } }
{ let result = parse_extended_value("UTF-8'missing third part"); assert!(result.is_err()); }
identifier_body
parsing.rs
//! Utility functions for Header implementations. use language_tags::LanguageTag; use std::str; use std::str::FromStr; use std::fmt::{self, Display}; use url::percent_encoding; use header::shared::Charset; /// Reads a single raw string when parsing a header. pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> ::Result<T> { if raw.len()!= 1 || unsafe { raw.get_unchecked(0) } == b"" { return Err(::Error::Header) } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. from_raw_str(& unsafe { raw.get_unchecked(0) }) } /// Reads a raw string into a value. pub fn from_raw_str<T: str::FromStr>(raw: &[u8]) -> ::Result<T> { let s = try!(str::from_utf8(raw)); T::from_str(s).or(Err(::Error::Header)) } /// Reads a comma-delimited raw header into a Vec. #[inline] pub fn from_comma_delimited<T: str::FromStr>(raw: &[Vec<u8>]) -> ::Result<Vec<T>> { if raw.len()!= 1 { return Err(::Error::Header); } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. from_one_comma_delimited(& unsafe { raw.get_unchecked(0) }[..]) } /// Reads a comma-delimited raw string into a Vec. pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> ::Result<Vec<T>> { let s = try!(str::from_utf8(raw)); Ok(s.split(',') .filter_map(|x| match x.trim() { "" => None, y => Some(y) }) .filter_map(|x| x.parse().ok()) .collect()) } /// Format an array into a comma-delimited string. pub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result { for (i, part) in parts.iter().enumerate() { if i!= 0 { try!(f.write_str(", ")); } try!(Display::fmt(part, f)); } Ok(()) } /// An extended header parameter value (i.e., tagged with a character set and optionally, /// a language), as defined in [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2). pub struct ExtendedValue { pub charset: Charset, pub language_tag: Option<LanguageTag>, pub value: Vec<u8>, } /// Parses extended header parameter values (`ext-value`), as defined in /// [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2). /// /// Extended values are denoted by parameter names that end with `*`. /// /// ## ABNF /// ```plain /// ext-value = charset "'" [ language ] "'" value-chars /// ; like RFC 2231's <extended-initial-value> /// ; (see [RFC2231], Section 7) /// /// charset = "UTF-8" / "ISO-8859-1" / mime-charset /// /// mime-charset = 1*mime-charsetc /// mime-charsetc = ALPHA / DIGIT /// / "!" / "#" / "$" / "%" / "&" /// / "+" / "-" / "^" / "_" / "`" /// / "{" / "}" / "~" /// ; as <mime-charset> in Section 2.3 of [RFC2978] /// ; except that the single quote is not included /// ; SHOULD be registered in the IANA charset registry /// /// language = <Language-Tag, defined in [RFC5646], Section 2.1> /// /// value-chars = *( pct-encoded / attr-char ) /// /// pct-encoded = "%" HEXDIG HEXDIG /// ; see [RFC3986], Section 2.1 /// /// attr-char = ALPHA / DIGIT /// / "!" / "#" / "$" / "&" / "+" / "-" / "." /// / "^" / "_" / "`" / "|" / "~" /// ; token except ( "*" / "'" / "%" ) /// ``` pub fn parse_extended_value(val: &str) -> ::Result<ExtendedValue> { // Break into three pieces separated by the single-quote character let mut parts = val.splitn(3,'\''); // Interpret the first piece as a Charset let charset: Charset = match parts.next() { None => return Err(::Error::Header), Some(n) => try!(FromStr::from_str(n)), }; // Interpret the second piece as a language tag let lang: Option<LanguageTag> = match parts.next() { None => return Err(::Error::Header), Some("") => None, Some(s) => match s.parse() { Ok(lt) => Some(lt), Err(_) => return Err(::Error::Header), } }; // Interpret the third piece as a sequence of value characters let value: Vec<u8> = match parts.next() { None => return Err(::Error::Header), Some(v) => percent_encoding::percent_decode(v.as_bytes()), }; Ok(ExtendedValue {
charset: charset, language_tag: lang, value: value, }) } #[cfg(test)] mod tests { use header::shared::Charset; use super::parse_extended_value; #[test] fn test_parse_extended_value_with_encoding_and_language_tag() { let expected_language_tag = langtag!(en); // RFC 5987, Section 3.2.2 // Extended notation, using the Unicode character U+00A3 (POUND SIGN) let result = parse_extended_value("iso-8859-1'en'%A3%20rates"); assert!(result.is_ok()); let extended_value = result.unwrap(); assert_eq!(Charset::Iso_8859_1, extended_value.charset); assert!(extended_value.language_tag.is_some()); assert_eq!(expected_language_tag, extended_value.language_tag.unwrap()); assert_eq!(vec![163, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value); } #[test] fn test_parse_extended_value_with_encoding() { // RFC 5987, Section 3.2.2 // Extended notation, using the Unicode characters U+00A3 (POUND SIGN) // and U+20AC (EURO SIGN) let result = parse_extended_value("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates"); assert!(result.is_ok()); let extended_value = result.unwrap(); assert_eq!(Charset::Ext("UTF-8".to_string()), extended_value.charset); assert!(extended_value.language_tag.is_none()); assert_eq!(vec![194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value); } #[test] fn test_parse_extended_value_missing_language_tag_and_encoding() { // From: https://greenbytes.de/tech/tc2231/#attwithfn2231quot2 let result = parse_extended_value("foo%20bar.html"); assert!(result.is_err()); } #[test] fn test_parse_extended_value_partially_formatted() { let result = parse_extended_value("UTF-8'missing third part"); assert!(result.is_err()); } #[test] fn test_parse_extended_value_partially_formatted_blank() { let result = parse_extended_value("blank second part'"); assert!(result.is_err()); } }
random_line_split
parsing.rs
//! Utility functions for Header implementations. use language_tags::LanguageTag; use std::str; use std::str::FromStr; use std::fmt::{self, Display}; use url::percent_encoding; use header::shared::Charset; /// Reads a single raw string when parsing a header. pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> ::Result<T> { if raw.len()!= 1 || unsafe { raw.get_unchecked(0) } == b"" { return Err(::Error::Header) } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. from_raw_str(& unsafe { raw.get_unchecked(0) }) } /// Reads a raw string into a value. pub fn from_raw_str<T: str::FromStr>(raw: &[u8]) -> ::Result<T> { let s = try!(str::from_utf8(raw)); T::from_str(s).or(Err(::Error::Header)) } /// Reads a comma-delimited raw header into a Vec. #[inline] pub fn from_comma_delimited<T: str::FromStr>(raw: &[Vec<u8>]) -> ::Result<Vec<T>> { if raw.len()!= 1 { return Err(::Error::Header); } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. from_one_comma_delimited(& unsafe { raw.get_unchecked(0) }[..]) } /// Reads a comma-delimited raw string into a Vec. pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> ::Result<Vec<T>> { let s = try!(str::from_utf8(raw)); Ok(s.split(',') .filter_map(|x| match x.trim() { "" => None, y => Some(y) }) .filter_map(|x| x.parse().ok()) .collect()) } /// Format an array into a comma-delimited string. pub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result { for (i, part) in parts.iter().enumerate() { if i!= 0 { try!(f.write_str(", ")); } try!(Display::fmt(part, f)); } Ok(()) } /// An extended header parameter value (i.e., tagged with a character set and optionally, /// a language), as defined in [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2). pub struct ExtendedValue { pub charset: Charset, pub language_tag: Option<LanguageTag>, pub value: Vec<u8>, } /// Parses extended header parameter values (`ext-value`), as defined in /// [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2). /// /// Extended values are denoted by parameter names that end with `*`. /// /// ## ABNF /// ```plain /// ext-value = charset "'" [ language ] "'" value-chars /// ; like RFC 2231's <extended-initial-value> /// ; (see [RFC2231], Section 7) /// /// charset = "UTF-8" / "ISO-8859-1" / mime-charset /// /// mime-charset = 1*mime-charsetc /// mime-charsetc = ALPHA / DIGIT /// / "!" / "#" / "$" / "%" / "&" /// / "+" / "-" / "^" / "_" / "`" /// / "{" / "}" / "~" /// ; as <mime-charset> in Section 2.3 of [RFC2978] /// ; except that the single quote is not included /// ; SHOULD be registered in the IANA charset registry /// /// language = <Language-Tag, defined in [RFC5646], Section 2.1> /// /// value-chars = *( pct-encoded / attr-char ) /// /// pct-encoded = "%" HEXDIG HEXDIG /// ; see [RFC3986], Section 2.1 /// /// attr-char = ALPHA / DIGIT /// / "!" / "#" / "$" / "&" / "+" / "-" / "." /// / "^" / "_" / "`" / "|" / "~" /// ; token except ( "*" / "'" / "%" ) /// ``` pub fn
(val: &str) -> ::Result<ExtendedValue> { // Break into three pieces separated by the single-quote character let mut parts = val.splitn(3,'\''); // Interpret the first piece as a Charset let charset: Charset = match parts.next() { None => return Err(::Error::Header), Some(n) => try!(FromStr::from_str(n)), }; // Interpret the second piece as a language tag let lang: Option<LanguageTag> = match parts.next() { None => return Err(::Error::Header), Some("") => None, Some(s) => match s.parse() { Ok(lt) => Some(lt), Err(_) => return Err(::Error::Header), } }; // Interpret the third piece as a sequence of value characters let value: Vec<u8> = match parts.next() { None => return Err(::Error::Header), Some(v) => percent_encoding::percent_decode(v.as_bytes()), }; Ok(ExtendedValue { charset: charset, language_tag: lang, value: value, }) } #[cfg(test)] mod tests { use header::shared::Charset; use super::parse_extended_value; #[test] fn test_parse_extended_value_with_encoding_and_language_tag() { let expected_language_tag = langtag!(en); // RFC 5987, Section 3.2.2 // Extended notation, using the Unicode character U+00A3 (POUND SIGN) let result = parse_extended_value("iso-8859-1'en'%A3%20rates"); assert!(result.is_ok()); let extended_value = result.unwrap(); assert_eq!(Charset::Iso_8859_1, extended_value.charset); assert!(extended_value.language_tag.is_some()); assert_eq!(expected_language_tag, extended_value.language_tag.unwrap()); assert_eq!(vec![163, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value); } #[test] fn test_parse_extended_value_with_encoding() { // RFC 5987, Section 3.2.2 // Extended notation, using the Unicode characters U+00A3 (POUND SIGN) // and U+20AC (EURO SIGN) let result = parse_extended_value("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates"); assert!(result.is_ok()); let extended_value = result.unwrap(); assert_eq!(Charset::Ext("UTF-8".to_string()), extended_value.charset); assert!(extended_value.language_tag.is_none()); assert_eq!(vec![194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value); } #[test] fn test_parse_extended_value_missing_language_tag_and_encoding() { // From: https://greenbytes.de/tech/tc2231/#attwithfn2231quot2 let result = parse_extended_value("foo%20bar.html"); assert!(result.is_err()); } #[test] fn test_parse_extended_value_partially_formatted() { let result = parse_extended_value("UTF-8'missing third part"); assert!(result.is_err()); } #[test] fn test_parse_extended_value_partially_formatted_blank() { let result = parse_extended_value("blank second part'"); assert!(result.is_err()); } }
parse_extended_value
identifier_name
lib.rs
extern crate regex; extern crate fall_tree; extern crate fall_parse; mod rust; pub use self::rust::language as lang_rust; pub use self::rust::{ WHITESPACE, LINE_COMMENT, BLOCK_COMMENT, UNION, AS, CRATE, EXTERN, FN, LET, PUB, STRUCT, USE, MOD, IF, ELSE, ENUM, IMPL, SELF, SUPER, TYPE, CONST, STATIC, FOR, LOOP, WHILE, MOVE, MUT, REF, TRAIT, MATCH, RETURN, CONTINUE, BREAK, IN, UNSAFE, WHERE,
R_ANGLE, L_BRACK, R_BRACK, SHL, SHL_EQ, SHR, SHR_EQ, AND, OR, THIN_ARROW, FAT_ARROW, EQ, EQEQ, BANGEQ, GTET, LTEQ, SEMI, COLON, COLONCOLON, COMMA, DOT, DOTDOT, DOTDOTDOT, HASH, DOLLAR, STAR, STAR_EQ, SLASH, SLASH_EQ, PERCENT, PERCENT_EQ, PLUS, PLUS_EQ, MINUS, MINUS_EQ, AMPERSAND, AMPERSAND_EQ, PIPE, PIPE_EQ, UNDERSCORE, BANG, QUESTION, CARET, CARET_EQ, CHAR, LIFETIME, BOOL, NUMBER, STRING, RAW_STRING, IDENT, FILE, USE_DECL, USE_SPEC, USE_SPEC_ENTRY, EXTERN_CRATE_DECL, FN_DEF, LINKAGE, VALUE_PARAM, LAMBDA_VALUE_PARAM, SELF_PARAMETER, STRUCT_DEF, STRUCT_FIELD, TUPLE_FIELD, ENUM_DEF, ENUM_VARIANT, MOD_DEF, IMPL_DEF, TRAIT_DEF, MEMBERS, TYPE_DEF, CONST_DEF, MACRO_ITEM, EXTERN_BLOCK, TYPE_PARAMETERS, TYPE_PARAMETER, TYPE_BOUND, LIFETIME_PARAMETER, VISIBILITY, WHERE_CLAUSE, PATH, TRAIT_PROJECTION_PATH, PATH_SEGMENT, TYPE_ARGUMENTS, FN_TRAIT_SUGAR, ALIAS, TYPE_REFERENCE, PATH_TYPE, REFERENCE_TYPE, POINTER_TYPE, PLACEHOLDER_TYPE, UNIT_TYPE, PAREN_TYPE, TUPLE_TYPE, NEVER_TYPE, ARRAY_TYPE, FN_POINTER_TYPE, FOR_TYPE, WILDCARD_PATTERN, PATH_PATTERN, TUPE_STRUCT_PATTERN, STRUCT_PATTERN, STRUCT_PATTERN_FIELD, BINDING_PATTERN, LITERAL_PATTERN, UNIT_PATTERN, PAREN_PATTERN, TUPLE_PATTERN, REFERENCE_PATTERN, EXPR, LITERAL, PATH_EXPR, STRUCT_LITERAL, STRUCT_LITERAL_FIELD, UNIT_EXPR, PAREN_EXPR, TUPLE_EXPR, ARRAY_LITERAL, LAMBDA_EXPR, RETURN_EXPR, LOOP_CF_EXPR, BLOCK_EXPR, LET_STMT, TYPE_ASCRIPTION, EMPTY_STMT, EXPR_STMT, IF_EXPR, WHILE_EXPR, LOOP_EXPR, FOR_EXPR, MATCH_EXPR, MATCH_ARM, GUARD, BLOCK_MACRO_EXPR, LINE_MACRO_EXPR, METHOD_CALL_EXPR, CALL_EXPR, VALUE_ARGUMENT, FIELD_EXPR, INDEX_EXPR, TRY_EXPR, CAST_EXPR, REFERENCE_EXPR, DEREFERENCE_EXPR, NEGATION_EXPR, NOT_EXPR, PRODUCT_EXPR, SUM_EXPR, BIT_SHIFT, BIT_AND, BIT_XOR, BIT_OR, COMPARISON, LOGICAL_AND, LOGICAL_OR, RANGE_EXPR, ASSIGNMENT_EXPR, ATTRIBUTE, INNER_ATTRIBUTE, ATTR_VALUE, BLOCK_MACRO, LINE_MACRO, TT, }; pub use self::rust::{ NameOwner, TypeParametersOwner, FnDef, StructDef, EnumDef, TraitDef, TypeDef, ModDef, ImplDef, UseDecl, TypeParameter, TypeReference, LetStmt, ExprStmt, };
L_PAREN, R_PAREN, L_CURLY, R_CURLY, L_ANGLE,
random_line_split
value.rs
use std::ffi::CString; use std::{fmt, mem, ptr}; use std::ops::{Deref, Index}; use libc::{c_char, c_int, c_uint}; use ffi::core; use ffi::prelude::LLVMValueRef; use ffi::LLVMAttribute; use ffi::core::{ LLVMConstStringInContext, LLVMConstStructInContext, LLVMConstVector, LLVMGetValueName, LLVMSetValueName, LLVMGetElementType, LLVMGetEntryBasicBlock, LLVMAppendBasicBlockInContext, LLVMAddAttribute, LLVMGetAttribute, LLVMRemoveAttribute, LLVMAddFunctionAttr, LLVMGetFunctionAttr, LLVMRemoveFunctionAttr, LLVMGetParam, LLVMCountParams, LLVMGetFirstParam, LLVMGetNextParam, LLVMGetInitializer, LLVMSetInitializer, LLVMIsAGlobalValue, LLVMGetUndef, LLVMTypeOf, }; use block::BasicBlock; use context::{Context, GetContext}; use util::{self, CastFrom}; use ty::{FunctionType, Type}; /// A typed value that can be used as an operand in instructions. pub struct Value; native_ref!(&Value = LLVMValueRef); impl_display!(Value, LLVMPrintValueToString); impl Value { /// Create a new constant struct from the values given. pub fn new_struct<'a>(context: &'a Context, vals: &[&'a Value], packed: bool) -> &'a Value { unsafe { LLVMConstStructInContext(context.into(), vals.as_ptr() as *mut LLVMValueRef, vals.len() as c_uint, packed as c_int) }.into() } /// Create a new constant vector from the values given. pub fn new_vector<'a>(vals: &[&'a Value]) -> &'a Value { unsafe { LLVMConstVector(vals.as_ptr() as *mut LLVMValueRef, vals.len() as c_uint) }.into() } /// Create a new constant C string from the text given. pub fn new_string<'a>(context: &'a Context, text: &str, rust_style: bool) -> &'a Value { unsafe { let ptr = text.as_ptr() as *const c_char; let len = text.len() as c_uint; LLVMConstStringInContext(context.into(), ptr, len, rust_style as c_int).into() } } /// Create a new constant undefined value of the given type. pub fn new_undef<'a>(ty: &'a Type) -> &'a Value { unsafe { LLVMGetUndef(ty.into()) }.into() } /// Returns the name of this value, or `None` if it lacks a name pub fn get_name(&self) -> Option<&str> { unsafe { let c_name = LLVMGetValueName(self.into()); util::to_null_str(c_name as *mut i8) } } /// Sets the name of this value pub fn set_name(&self, name: &str) { let c_name = CString::new(name).unwrap(); unsafe { LLVMSetValueName(self.into(), c_name.as_ptr()) } } /// Returns the type of this value pub fn get_type(&self) -> &Type { unsafe { LLVMTypeOf(self.into()) }.into() } } pub struct GlobalValue;
deref!(GlobalValue, Value); impl GlobalValue { /// Sets the initial value for this global. pub fn set_initializer(&self, value: &Value) { unsafe { LLVMSetInitializer(self.into(), value.into()) } } /// Gets the initial value for this global. pub fn get_initializer(&self) -> &Value { unsafe { LLVMGetInitializer(self.into()) }.into() } } impl CastFrom for GlobalValue { type From = Value; fn cast<'a>(val: &'a Value) -> Option<&'a GlobalValue> { let gv = unsafe { LLVMIsAGlobalValue(val.into()) }; if gv == ptr::null_mut() { None } else { Some(gv.into()) } } } /// Comparative operations on values. #[derive(Copy, Clone, Eq, PartialEq)] pub enum Predicate { Equal, NotEqual, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual } /// A function argument. pub struct Arg; native_ref!(&Arg = LLVMValueRef); impl Deref for Arg { type Target = Value; fn deref(&self) -> &Value { unsafe { mem::transmute(self) } } } impl Arg { /// Add the attribute given to this argument. pub fn add_attribute(&self, attr: Attribute) { unsafe { LLVMAddAttribute(self.into(), attr.into()) } } /// Add all the attributes given to this argument. pub fn add_attributes(&self, attrs: &[Attribute]) { let mut sum = LLVMAttribute::empty(); for attr in attrs { let attr:LLVMAttribute = (*attr).into(); sum = sum | attr; } unsafe { LLVMAddAttribute(self.into(), sum.into()) } } /// Returns true if this argument has the attribute given. pub fn has_attribute(&self, attr: Attribute) -> bool { unsafe { let other = LLVMGetAttribute(self.into()); other.contains(attr.into()) } } /// Returns true if this argument has all the attributes given. pub fn has_attributes(&self, attrs: &[Attribute]) -> bool { unsafe { let other = LLVMGetAttribute(self.into()); for &attr in attrs { if!other.contains(attr.into()) { return false; } } return true; } } /// Remove an attribute from this argument. pub fn remove_attribute(&self, attr: Attribute) { unsafe { LLVMRemoveAttribute(self.into(), attr.into()) } } } /// A function that can be called and contains blocks. pub struct Function; native_ref!(&Function = LLVMValueRef); impl Deref for Function { type Target = Value; fn deref(&self) -> &Value { unsafe { mem::transmute(self) } } } impl Index<usize> for Function { type Output = Arg; fn index(&self, index: usize) -> &Arg { unsafe { if index < LLVMCountParams(self.into()) as usize { LLVMGetParam(self.into(), index as c_uint).into() } else { panic!("no such index {} on {:?}", index, self.get_type()) } } } } impl CastFrom for Function { type From = Value; fn cast<'a>(val: &'a Value) -> Option<&'a Function> { let ty = val.get_type(); let mut is_func = ty.is_function(); if let Some(elem) = ty.get_element() { is_func = is_func || elem.is_function() } if is_func { Some(unsafe { mem::transmute(val) }) } else { None } } } impl Function { /// Add a basic block with the name given to the function and return it. pub fn append<'a>(&'a self, name: &str) -> &'a BasicBlock { util::with_cstr(name, |ptr| unsafe { LLVMAppendBasicBlockInContext(self.get_context().into(), self.into(), ptr).into() }) } /// Returns the entry block of this function or `None` if there is none. pub fn get_entry(&self) -> Option<&BasicBlock> { unsafe { mem::transmute(LLVMGetEntryBasicBlock(self.into())) } } /// Returns the name of this function. pub fn get_name(&self) -> &str { unsafe { let c_name = LLVMGetValueName(self.into()); util::to_str(c_name as *mut i8) } } /// Returns the function signature representing this function's signature. pub fn get_signature(&self) -> &FunctionType { unsafe { let ty = LLVMTypeOf(self.into()); LLVMGetElementType(ty).into() } } /// Returns the number of function parameters pub fn num_params(&self) -> usize { unsafe { LLVMCountParams(self.into()) as usize } } /// Add the attribute given to this function. pub fn add_attribute(&self, attr: Attribute) { unsafe { LLVMAddFunctionAttr(self.into(), attr.into()) } } /// Add all the attributes given to this function. pub fn add_attributes(&self, attrs: &[Attribute]) { let mut sum = LLVMAttribute::empty(); for attr in attrs { let attr:LLVMAttribute = (*attr).into(); sum = sum | attr; } unsafe { LLVMAddFunctionAttr(self.into(), sum.into()) } } /// Returns true if the attribute given is set in this function. pub fn has_attribute(&self, attr: Attribute) -> bool { unsafe { let other = LLVMGetFunctionAttr(self.into()); other.contains(attr.into()) } } /// Returns true if all the attributes given is set in this function. pub fn has_attributes(&self, attrs: &[Attribute]) -> bool { unsafe { let other = LLVMGetFunctionAttr(self.into()); for &attr in attrs { if!other.contains(attr.into()) { return false; } } return true; } } /// Remove the attribute given from this function. pub fn remove_attribute(&self, attr: Attribute) { unsafe { LLVMRemoveFunctionAttr(self.into(), attr.into()) } } } impl<'a> IntoIterator for &'a Function { type Item = &'a Arg; type IntoIter = ValueIter<'a, &'a Arg>; /// Iterate through the functions in the module fn into_iter(self) -> ValueIter<'a, &'a Arg> { ValueIter::new( unsafe { LLVMGetFirstParam(self.into()) }, LLVMGetNextParam) } } impl GetContext for Function { fn get_context(&self) -> &Context { self.get_type().get_context() } } /// A way of indicating to LLVM how you want arguments / functions to be handled. #[derive(Copy, Clone, Eq, PartialEq, Debug)] #[repr(C)] pub enum Attribute { /// Zero-extended before or after call. ZExt = 0b1, /// Sign-extended before or after call. SExt = 0b10, /// Mark the function as not returning. NoReturn = 0b100, /// Force argument to be passed in register. InReg = 0b1000, /// Hidden pointer to structure to return. StructRet = 0b10000, /// Function doesn't unwind stack. NoUnwind = 0b100000, /// Consider to not alias after call. NoAlias = 0b1000000, /// Pass structure by value. ByVal = 0b10000000, /// Nested function static chain. Nest = 0b100000000, /// Function doesn't access memory. ReadNone = 0b1000000000, /// Function only reads from memory. ReadOnly = 0b10000000000, /// Never inline this function. NoInline = 0b100000000000, /// Always inline this function. AlwaysInline = 0b1000000000000, /// Optimize this function for size. OptimizeForSize = 0b10000000000000, /// Stack protection. StackProtect = 0b100000000000000, /// Stack protection required. StackProtectReq = 0b1000000000000000, /// Alignment of parameter (5 bits) stored as log2 of alignment with +1 bias 0 means unaligned (different from align(1)). Alignment = 0b10000000000000000, /// Function creates no aliases of pointer. NoCapture = 0b100000000000000000, /// Disable redzone. NoRedZone = 0b1000000000000000000, /// Disable implicit float instructions. NoImplicitFloat = 0b10000000000000000000, /// Naked function. Naked = 0b100000000000000000000, /// The source language has marked this function as inline. InlineHint = 0b1000000000000000000000, /// Alignment of stack for function (3 bits) stored as log2 of alignment with +1 bias 0 means unaligned (different from alignstack=(1)). StackAlignment = 0b11100000000000000000000000000, /// This function returns twice. ReturnsTwice = 0b100000000000000000000000000000, /// Function must be in unwind table. UWTable = 0b1000000000000000000000000000000, /// Function is called early/often, so lazy binding isn't effective. NonLazyBind = 0b10000000000000000000000000000000 } impl From<LLVMAttribute> for Attribute { fn from(attr: LLVMAttribute) -> Attribute { unsafe { mem::transmute(attr) } } } impl From<Attribute> for LLVMAttribute { fn from(attr: Attribute) -> LLVMAttribute { unsafe { mem::transmute(attr) } } } impl GetContext for Value { fn get_context(&self) -> &Context { self.get_type().get_context() } } /// Value Iterator implementation. /// /// T can be all descendent types of LLVMValueRef. #[derive(Copy, Clone)] pub struct ValueIter<'a, T: From<LLVMValueRef>> { cur : LLVMValueRef, step : unsafe extern "C" fn(LLVMValueRef) -> LLVMValueRef, marker1: ::std::marker::PhantomData<&'a ()>, marker2: ::std::marker::PhantomData<T>, } impl<'a, T: From<LLVMValueRef>> ValueIter<'a, T> { pub fn new(cur: LLVMValueRef, step: unsafe extern "C" fn(LLVMValueRef) -> LLVMValueRef) -> Self { ValueIter { cur: cur, step: step, marker1: ::std::marker::PhantomData, marker2: ::std::marker::PhantomData } } } impl<'a, T: From<LLVMValueRef>> Iterator for ValueIter<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { let old: LLVMValueRef = self.cur; if!old.is_null() { self.cur = unsafe { (self.step)(old) }; Some(old.into()) } else { None } } }
native_ref!(&GlobalValue = LLVMValueRef);
random_line_split
value.rs
use std::ffi::CString; use std::{fmt, mem, ptr}; use std::ops::{Deref, Index}; use libc::{c_char, c_int, c_uint}; use ffi::core; use ffi::prelude::LLVMValueRef; use ffi::LLVMAttribute; use ffi::core::{ LLVMConstStringInContext, LLVMConstStructInContext, LLVMConstVector, LLVMGetValueName, LLVMSetValueName, LLVMGetElementType, LLVMGetEntryBasicBlock, LLVMAppendBasicBlockInContext, LLVMAddAttribute, LLVMGetAttribute, LLVMRemoveAttribute, LLVMAddFunctionAttr, LLVMGetFunctionAttr, LLVMRemoveFunctionAttr, LLVMGetParam, LLVMCountParams, LLVMGetFirstParam, LLVMGetNextParam, LLVMGetInitializer, LLVMSetInitializer, LLVMIsAGlobalValue, LLVMGetUndef, LLVMTypeOf, }; use block::BasicBlock; use context::{Context, GetContext}; use util::{self, CastFrom}; use ty::{FunctionType, Type}; /// A typed value that can be used as an operand in instructions. pub struct Value; native_ref!(&Value = LLVMValueRef); impl_display!(Value, LLVMPrintValueToString); impl Value { /// Create a new constant struct from the values given. pub fn new_struct<'a>(context: &'a Context, vals: &[&'a Value], packed: bool) -> &'a Value { unsafe { LLVMConstStructInContext(context.into(), vals.as_ptr() as *mut LLVMValueRef, vals.len() as c_uint, packed as c_int) }.into() } /// Create a new constant vector from the values given. pub fn new_vector<'a>(vals: &[&'a Value]) -> &'a Value { unsafe { LLVMConstVector(vals.as_ptr() as *mut LLVMValueRef, vals.len() as c_uint) }.into() } /// Create a new constant C string from the text given. pub fn new_string<'a>(context: &'a Context, text: &str, rust_style: bool) -> &'a Value { unsafe { let ptr = text.as_ptr() as *const c_char; let len = text.len() as c_uint; LLVMConstStringInContext(context.into(), ptr, len, rust_style as c_int).into() } } /// Create a new constant undefined value of the given type. pub fn new_undef<'a>(ty: &'a Type) -> &'a Value { unsafe { LLVMGetUndef(ty.into()) }.into() } /// Returns the name of this value, or `None` if it lacks a name pub fn get_name(&self) -> Option<&str> { unsafe { let c_name = LLVMGetValueName(self.into()); util::to_null_str(c_name as *mut i8) } } /// Sets the name of this value pub fn set_name(&self, name: &str) { let c_name = CString::new(name).unwrap(); unsafe { LLVMSetValueName(self.into(), c_name.as_ptr()) } } /// Returns the type of this value pub fn get_type(&self) -> &Type { unsafe { LLVMTypeOf(self.into()) }.into() } } pub struct GlobalValue; native_ref!(&GlobalValue = LLVMValueRef); deref!(GlobalValue, Value); impl GlobalValue { /// Sets the initial value for this global. pub fn set_initializer(&self, value: &Value) { unsafe { LLVMSetInitializer(self.into(), value.into()) } } /// Gets the initial value for this global. pub fn get_initializer(&self) -> &Value { unsafe { LLVMGetInitializer(self.into()) }.into() } } impl CastFrom for GlobalValue { type From = Value; fn cast<'a>(val: &'a Value) -> Option<&'a GlobalValue> { let gv = unsafe { LLVMIsAGlobalValue(val.into()) }; if gv == ptr::null_mut() { None } else { Some(gv.into()) } } } /// Comparative operations on values. #[derive(Copy, Clone, Eq, PartialEq)] pub enum Predicate { Equal, NotEqual, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual } /// A function argument. pub struct Arg; native_ref!(&Arg = LLVMValueRef); impl Deref for Arg { type Target = Value; fn deref(&self) -> &Value { unsafe { mem::transmute(self) } } } impl Arg { /// Add the attribute given to this argument. pub fn add_attribute(&self, attr: Attribute) { unsafe { LLVMAddAttribute(self.into(), attr.into()) } } /// Add all the attributes given to this argument. pub fn add_attributes(&self, attrs: &[Attribute]) { let mut sum = LLVMAttribute::empty(); for attr in attrs { let attr:LLVMAttribute = (*attr).into(); sum = sum | attr; } unsafe { LLVMAddAttribute(self.into(), sum.into()) } } /// Returns true if this argument has the attribute given. pub fn has_attribute(&self, attr: Attribute) -> bool { unsafe { let other = LLVMGetAttribute(self.into()); other.contains(attr.into()) } } /// Returns true if this argument has all the attributes given. pub fn has_attributes(&self, attrs: &[Attribute]) -> bool { unsafe { let other = LLVMGetAttribute(self.into()); for &attr in attrs { if!other.contains(attr.into()) { return false; } } return true; } } /// Remove an attribute from this argument. pub fn remove_attribute(&self, attr: Attribute) { unsafe { LLVMRemoveAttribute(self.into(), attr.into()) } } } /// A function that can be called and contains blocks. pub struct Function; native_ref!(&Function = LLVMValueRef); impl Deref for Function { type Target = Value; fn deref(&self) -> &Value { unsafe { mem::transmute(self) } } } impl Index<usize> for Function { type Output = Arg; fn index(&self, index: usize) -> &Arg { unsafe { if index < LLVMCountParams(self.into()) as usize { LLVMGetParam(self.into(), index as c_uint).into() } else { panic!("no such index {} on {:?}", index, self.get_type()) } } } } impl CastFrom for Function { type From = Value; fn cast<'a>(val: &'a Value) -> Option<&'a Function> { let ty = val.get_type(); let mut is_func = ty.is_function(); if let Some(elem) = ty.get_element() { is_func = is_func || elem.is_function() } if is_func { Some(unsafe { mem::transmute(val) }) } else { None } } } impl Function { /// Add a basic block with the name given to the function and return it. pub fn append<'a>(&'a self, name: &str) -> &'a BasicBlock { util::with_cstr(name, |ptr| unsafe { LLVMAppendBasicBlockInContext(self.get_context().into(), self.into(), ptr).into() }) } /// Returns the entry block of this function or `None` if there is none. pub fn get_entry(&self) -> Option<&BasicBlock> { unsafe { mem::transmute(LLVMGetEntryBasicBlock(self.into())) } } /// Returns the name of this function. pub fn get_name(&self) -> &str { unsafe { let c_name = LLVMGetValueName(self.into()); util::to_str(c_name as *mut i8) } } /// Returns the function signature representing this function's signature. pub fn get_signature(&self) -> &FunctionType { unsafe { let ty = LLVMTypeOf(self.into()); LLVMGetElementType(ty).into() } } /// Returns the number of function parameters pub fn num_params(&self) -> usize { unsafe { LLVMCountParams(self.into()) as usize } } /// Add the attribute given to this function. pub fn add_attribute(&self, attr: Attribute) { unsafe { LLVMAddFunctionAttr(self.into(), attr.into()) } } /// Add all the attributes given to this function. pub fn add_attributes(&self, attrs: &[Attribute]) { let mut sum = LLVMAttribute::empty(); for attr in attrs { let attr:LLVMAttribute = (*attr).into(); sum = sum | attr; } unsafe { LLVMAddFunctionAttr(self.into(), sum.into()) } } /// Returns true if the attribute given is set in this function. pub fn has_attribute(&self, attr: Attribute) -> bool { unsafe { let other = LLVMGetFunctionAttr(self.into()); other.contains(attr.into()) } } /// Returns true if all the attributes given is set in this function. pub fn has_attributes(&self, attrs: &[Attribute]) -> bool { unsafe { let other = LLVMGetFunctionAttr(self.into()); for &attr in attrs { if!other.contains(attr.into()) { return false; } } return true; } } /// Remove the attribute given from this function. pub fn remove_attribute(&self, attr: Attribute) { unsafe { LLVMRemoveFunctionAttr(self.into(), attr.into()) } } } impl<'a> IntoIterator for &'a Function { type Item = &'a Arg; type IntoIter = ValueIter<'a, &'a Arg>; /// Iterate through the functions in the module fn into_iter(self) -> ValueIter<'a, &'a Arg> { ValueIter::new( unsafe { LLVMGetFirstParam(self.into()) }, LLVMGetNextParam) } } impl GetContext for Function { fn get_context(&self) -> &Context { self.get_type().get_context() } } /// A way of indicating to LLVM how you want arguments / functions to be handled. #[derive(Copy, Clone, Eq, PartialEq, Debug)] #[repr(C)] pub enum Attribute { /// Zero-extended before or after call. ZExt = 0b1, /// Sign-extended before or after call. SExt = 0b10, /// Mark the function as not returning. NoReturn = 0b100, /// Force argument to be passed in register. InReg = 0b1000, /// Hidden pointer to structure to return. StructRet = 0b10000, /// Function doesn't unwind stack. NoUnwind = 0b100000, /// Consider to not alias after call. NoAlias = 0b1000000, /// Pass structure by value. ByVal = 0b10000000, /// Nested function static chain. Nest = 0b100000000, /// Function doesn't access memory. ReadNone = 0b1000000000, /// Function only reads from memory. ReadOnly = 0b10000000000, /// Never inline this function. NoInline = 0b100000000000, /// Always inline this function. AlwaysInline = 0b1000000000000, /// Optimize this function for size. OptimizeForSize = 0b10000000000000, /// Stack protection. StackProtect = 0b100000000000000, /// Stack protection required. StackProtectReq = 0b1000000000000000, /// Alignment of parameter (5 bits) stored as log2 of alignment with +1 bias 0 means unaligned (different from align(1)). Alignment = 0b10000000000000000, /// Function creates no aliases of pointer. NoCapture = 0b100000000000000000, /// Disable redzone. NoRedZone = 0b1000000000000000000, /// Disable implicit float instructions. NoImplicitFloat = 0b10000000000000000000, /// Naked function. Naked = 0b100000000000000000000, /// The source language has marked this function as inline. InlineHint = 0b1000000000000000000000, /// Alignment of stack for function (3 bits) stored as log2 of alignment with +1 bias 0 means unaligned (different from alignstack=(1)). StackAlignment = 0b11100000000000000000000000000, /// This function returns twice. ReturnsTwice = 0b100000000000000000000000000000, /// Function must be in unwind table. UWTable = 0b1000000000000000000000000000000, /// Function is called early/often, so lazy binding isn't effective. NonLazyBind = 0b10000000000000000000000000000000 } impl From<LLVMAttribute> for Attribute { fn from(attr: LLVMAttribute) -> Attribute { unsafe { mem::transmute(attr) } } } impl From<Attribute> for LLVMAttribute { fn from(attr: Attribute) -> LLVMAttribute { unsafe { mem::transmute(attr) } } } impl GetContext for Value { fn get_context(&self) -> &Context { self.get_type().get_context() } } /// Value Iterator implementation. /// /// T can be all descendent types of LLVMValueRef. #[derive(Copy, Clone)] pub struct ValueIter<'a, T: From<LLVMValueRef>> { cur : LLVMValueRef, step : unsafe extern "C" fn(LLVMValueRef) -> LLVMValueRef, marker1: ::std::marker::PhantomData<&'a ()>, marker2: ::std::marker::PhantomData<T>, } impl<'a, T: From<LLVMValueRef>> ValueIter<'a, T> { pub fn new(cur: LLVMValueRef, step: unsafe extern "C" fn(LLVMValueRef) -> LLVMValueRef) -> Self { ValueIter { cur: cur, step: step, marker1: ::std::marker::PhantomData, marker2: ::std::marker::PhantomData } } } impl<'a, T: From<LLVMValueRef>> Iterator for ValueIter<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { let old: LLVMValueRef = self.cur; if!old.is_null()
else { None } } }
{ self.cur = unsafe { (self.step)(old) }; Some(old.into()) }
conditional_block
value.rs
use std::ffi::CString; use std::{fmt, mem, ptr}; use std::ops::{Deref, Index}; use libc::{c_char, c_int, c_uint}; use ffi::core; use ffi::prelude::LLVMValueRef; use ffi::LLVMAttribute; use ffi::core::{ LLVMConstStringInContext, LLVMConstStructInContext, LLVMConstVector, LLVMGetValueName, LLVMSetValueName, LLVMGetElementType, LLVMGetEntryBasicBlock, LLVMAppendBasicBlockInContext, LLVMAddAttribute, LLVMGetAttribute, LLVMRemoveAttribute, LLVMAddFunctionAttr, LLVMGetFunctionAttr, LLVMRemoveFunctionAttr, LLVMGetParam, LLVMCountParams, LLVMGetFirstParam, LLVMGetNextParam, LLVMGetInitializer, LLVMSetInitializer, LLVMIsAGlobalValue, LLVMGetUndef, LLVMTypeOf, }; use block::BasicBlock; use context::{Context, GetContext}; use util::{self, CastFrom}; use ty::{FunctionType, Type}; /// A typed value that can be used as an operand in instructions. pub struct Value; native_ref!(&Value = LLVMValueRef); impl_display!(Value, LLVMPrintValueToString); impl Value { /// Create a new constant struct from the values given. pub fn new_struct<'a>(context: &'a Context, vals: &[&'a Value], packed: bool) -> &'a Value { unsafe { LLVMConstStructInContext(context.into(), vals.as_ptr() as *mut LLVMValueRef, vals.len() as c_uint, packed as c_int) }.into() } /// Create a new constant vector from the values given. pub fn new_vector<'a>(vals: &[&'a Value]) -> &'a Value { unsafe { LLVMConstVector(vals.as_ptr() as *mut LLVMValueRef, vals.len() as c_uint) }.into() } /// Create a new constant C string from the text given. pub fn
<'a>(context: &'a Context, text: &str, rust_style: bool) -> &'a Value { unsafe { let ptr = text.as_ptr() as *const c_char; let len = text.len() as c_uint; LLVMConstStringInContext(context.into(), ptr, len, rust_style as c_int).into() } } /// Create a new constant undefined value of the given type. pub fn new_undef<'a>(ty: &'a Type) -> &'a Value { unsafe { LLVMGetUndef(ty.into()) }.into() } /// Returns the name of this value, or `None` if it lacks a name pub fn get_name(&self) -> Option<&str> { unsafe { let c_name = LLVMGetValueName(self.into()); util::to_null_str(c_name as *mut i8) } } /// Sets the name of this value pub fn set_name(&self, name: &str) { let c_name = CString::new(name).unwrap(); unsafe { LLVMSetValueName(self.into(), c_name.as_ptr()) } } /// Returns the type of this value pub fn get_type(&self) -> &Type { unsafe { LLVMTypeOf(self.into()) }.into() } } pub struct GlobalValue; native_ref!(&GlobalValue = LLVMValueRef); deref!(GlobalValue, Value); impl GlobalValue { /// Sets the initial value for this global. pub fn set_initializer(&self, value: &Value) { unsafe { LLVMSetInitializer(self.into(), value.into()) } } /// Gets the initial value for this global. pub fn get_initializer(&self) -> &Value { unsafe { LLVMGetInitializer(self.into()) }.into() } } impl CastFrom for GlobalValue { type From = Value; fn cast<'a>(val: &'a Value) -> Option<&'a GlobalValue> { let gv = unsafe { LLVMIsAGlobalValue(val.into()) }; if gv == ptr::null_mut() { None } else { Some(gv.into()) } } } /// Comparative operations on values. #[derive(Copy, Clone, Eq, PartialEq)] pub enum Predicate { Equal, NotEqual, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual } /// A function argument. pub struct Arg; native_ref!(&Arg = LLVMValueRef); impl Deref for Arg { type Target = Value; fn deref(&self) -> &Value { unsafe { mem::transmute(self) } } } impl Arg { /// Add the attribute given to this argument. pub fn add_attribute(&self, attr: Attribute) { unsafe { LLVMAddAttribute(self.into(), attr.into()) } } /// Add all the attributes given to this argument. pub fn add_attributes(&self, attrs: &[Attribute]) { let mut sum = LLVMAttribute::empty(); for attr in attrs { let attr:LLVMAttribute = (*attr).into(); sum = sum | attr; } unsafe { LLVMAddAttribute(self.into(), sum.into()) } } /// Returns true if this argument has the attribute given. pub fn has_attribute(&self, attr: Attribute) -> bool { unsafe { let other = LLVMGetAttribute(self.into()); other.contains(attr.into()) } } /// Returns true if this argument has all the attributes given. pub fn has_attributes(&self, attrs: &[Attribute]) -> bool { unsafe { let other = LLVMGetAttribute(self.into()); for &attr in attrs { if!other.contains(attr.into()) { return false; } } return true; } } /// Remove an attribute from this argument. pub fn remove_attribute(&self, attr: Attribute) { unsafe { LLVMRemoveAttribute(self.into(), attr.into()) } } } /// A function that can be called and contains blocks. pub struct Function; native_ref!(&Function = LLVMValueRef); impl Deref for Function { type Target = Value; fn deref(&self) -> &Value { unsafe { mem::transmute(self) } } } impl Index<usize> for Function { type Output = Arg; fn index(&self, index: usize) -> &Arg { unsafe { if index < LLVMCountParams(self.into()) as usize { LLVMGetParam(self.into(), index as c_uint).into() } else { panic!("no such index {} on {:?}", index, self.get_type()) } } } } impl CastFrom for Function { type From = Value; fn cast<'a>(val: &'a Value) -> Option<&'a Function> { let ty = val.get_type(); let mut is_func = ty.is_function(); if let Some(elem) = ty.get_element() { is_func = is_func || elem.is_function() } if is_func { Some(unsafe { mem::transmute(val) }) } else { None } } } impl Function { /// Add a basic block with the name given to the function and return it. pub fn append<'a>(&'a self, name: &str) -> &'a BasicBlock { util::with_cstr(name, |ptr| unsafe { LLVMAppendBasicBlockInContext(self.get_context().into(), self.into(), ptr).into() }) } /// Returns the entry block of this function or `None` if there is none. pub fn get_entry(&self) -> Option<&BasicBlock> { unsafe { mem::transmute(LLVMGetEntryBasicBlock(self.into())) } } /// Returns the name of this function. pub fn get_name(&self) -> &str { unsafe { let c_name = LLVMGetValueName(self.into()); util::to_str(c_name as *mut i8) } } /// Returns the function signature representing this function's signature. pub fn get_signature(&self) -> &FunctionType { unsafe { let ty = LLVMTypeOf(self.into()); LLVMGetElementType(ty).into() } } /// Returns the number of function parameters pub fn num_params(&self) -> usize { unsafe { LLVMCountParams(self.into()) as usize } } /// Add the attribute given to this function. pub fn add_attribute(&self, attr: Attribute) { unsafe { LLVMAddFunctionAttr(self.into(), attr.into()) } } /// Add all the attributes given to this function. pub fn add_attributes(&self, attrs: &[Attribute]) { let mut sum = LLVMAttribute::empty(); for attr in attrs { let attr:LLVMAttribute = (*attr).into(); sum = sum | attr; } unsafe { LLVMAddFunctionAttr(self.into(), sum.into()) } } /// Returns true if the attribute given is set in this function. pub fn has_attribute(&self, attr: Attribute) -> bool { unsafe { let other = LLVMGetFunctionAttr(self.into()); other.contains(attr.into()) } } /// Returns true if all the attributes given is set in this function. pub fn has_attributes(&self, attrs: &[Attribute]) -> bool { unsafe { let other = LLVMGetFunctionAttr(self.into()); for &attr in attrs { if!other.contains(attr.into()) { return false; } } return true; } } /// Remove the attribute given from this function. pub fn remove_attribute(&self, attr: Attribute) { unsafe { LLVMRemoveFunctionAttr(self.into(), attr.into()) } } } impl<'a> IntoIterator for &'a Function { type Item = &'a Arg; type IntoIter = ValueIter<'a, &'a Arg>; /// Iterate through the functions in the module fn into_iter(self) -> ValueIter<'a, &'a Arg> { ValueIter::new( unsafe { LLVMGetFirstParam(self.into()) }, LLVMGetNextParam) } } impl GetContext for Function { fn get_context(&self) -> &Context { self.get_type().get_context() } } /// A way of indicating to LLVM how you want arguments / functions to be handled. #[derive(Copy, Clone, Eq, PartialEq, Debug)] #[repr(C)] pub enum Attribute { /// Zero-extended before or after call. ZExt = 0b1, /// Sign-extended before or after call. SExt = 0b10, /// Mark the function as not returning. NoReturn = 0b100, /// Force argument to be passed in register. InReg = 0b1000, /// Hidden pointer to structure to return. StructRet = 0b10000, /// Function doesn't unwind stack. NoUnwind = 0b100000, /// Consider to not alias after call. NoAlias = 0b1000000, /// Pass structure by value. ByVal = 0b10000000, /// Nested function static chain. Nest = 0b100000000, /// Function doesn't access memory. ReadNone = 0b1000000000, /// Function only reads from memory. ReadOnly = 0b10000000000, /// Never inline this function. NoInline = 0b100000000000, /// Always inline this function. AlwaysInline = 0b1000000000000, /// Optimize this function for size. OptimizeForSize = 0b10000000000000, /// Stack protection. StackProtect = 0b100000000000000, /// Stack protection required. StackProtectReq = 0b1000000000000000, /// Alignment of parameter (5 bits) stored as log2 of alignment with +1 bias 0 means unaligned (different from align(1)). Alignment = 0b10000000000000000, /// Function creates no aliases of pointer. NoCapture = 0b100000000000000000, /// Disable redzone. NoRedZone = 0b1000000000000000000, /// Disable implicit float instructions. NoImplicitFloat = 0b10000000000000000000, /// Naked function. Naked = 0b100000000000000000000, /// The source language has marked this function as inline. InlineHint = 0b1000000000000000000000, /// Alignment of stack for function (3 bits) stored as log2 of alignment with +1 bias 0 means unaligned (different from alignstack=(1)). StackAlignment = 0b11100000000000000000000000000, /// This function returns twice. ReturnsTwice = 0b100000000000000000000000000000, /// Function must be in unwind table. UWTable = 0b1000000000000000000000000000000, /// Function is called early/often, so lazy binding isn't effective. NonLazyBind = 0b10000000000000000000000000000000 } impl From<LLVMAttribute> for Attribute { fn from(attr: LLVMAttribute) -> Attribute { unsafe { mem::transmute(attr) } } } impl From<Attribute> for LLVMAttribute { fn from(attr: Attribute) -> LLVMAttribute { unsafe { mem::transmute(attr) } } } impl GetContext for Value { fn get_context(&self) -> &Context { self.get_type().get_context() } } /// Value Iterator implementation. /// /// T can be all descendent types of LLVMValueRef. #[derive(Copy, Clone)] pub struct ValueIter<'a, T: From<LLVMValueRef>> { cur : LLVMValueRef, step : unsafe extern "C" fn(LLVMValueRef) -> LLVMValueRef, marker1: ::std::marker::PhantomData<&'a ()>, marker2: ::std::marker::PhantomData<T>, } impl<'a, T: From<LLVMValueRef>> ValueIter<'a, T> { pub fn new(cur: LLVMValueRef, step: unsafe extern "C" fn(LLVMValueRef) -> LLVMValueRef) -> Self { ValueIter { cur: cur, step: step, marker1: ::std::marker::PhantomData, marker2: ::std::marker::PhantomData } } } impl<'a, T: From<LLVMValueRef>> Iterator for ValueIter<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { let old: LLVMValueRef = self.cur; if!old.is_null() { self.cur = unsafe { (self.step)(old) }; Some(old.into()) } else { None } } }
new_string
identifier_name
value.rs
use std::ffi::CString; use std::{fmt, mem, ptr}; use std::ops::{Deref, Index}; use libc::{c_char, c_int, c_uint}; use ffi::core; use ffi::prelude::LLVMValueRef; use ffi::LLVMAttribute; use ffi::core::{ LLVMConstStringInContext, LLVMConstStructInContext, LLVMConstVector, LLVMGetValueName, LLVMSetValueName, LLVMGetElementType, LLVMGetEntryBasicBlock, LLVMAppendBasicBlockInContext, LLVMAddAttribute, LLVMGetAttribute, LLVMRemoveAttribute, LLVMAddFunctionAttr, LLVMGetFunctionAttr, LLVMRemoveFunctionAttr, LLVMGetParam, LLVMCountParams, LLVMGetFirstParam, LLVMGetNextParam, LLVMGetInitializer, LLVMSetInitializer, LLVMIsAGlobalValue, LLVMGetUndef, LLVMTypeOf, }; use block::BasicBlock; use context::{Context, GetContext}; use util::{self, CastFrom}; use ty::{FunctionType, Type}; /// A typed value that can be used as an operand in instructions. pub struct Value; native_ref!(&Value = LLVMValueRef); impl_display!(Value, LLVMPrintValueToString); impl Value { /// Create a new constant struct from the values given. pub fn new_struct<'a>(context: &'a Context, vals: &[&'a Value], packed: bool) -> &'a Value { unsafe { LLVMConstStructInContext(context.into(), vals.as_ptr() as *mut LLVMValueRef, vals.len() as c_uint, packed as c_int) }.into() } /// Create a new constant vector from the values given. pub fn new_vector<'a>(vals: &[&'a Value]) -> &'a Value { unsafe { LLVMConstVector(vals.as_ptr() as *mut LLVMValueRef, vals.len() as c_uint) }.into() } /// Create a new constant C string from the text given. pub fn new_string<'a>(context: &'a Context, text: &str, rust_style: bool) -> &'a Value { unsafe { let ptr = text.as_ptr() as *const c_char; let len = text.len() as c_uint; LLVMConstStringInContext(context.into(), ptr, len, rust_style as c_int).into() } } /// Create a new constant undefined value of the given type. pub fn new_undef<'a>(ty: &'a Type) -> &'a Value { unsafe { LLVMGetUndef(ty.into()) }.into() } /// Returns the name of this value, or `None` if it lacks a name pub fn get_name(&self) -> Option<&str> { unsafe { let c_name = LLVMGetValueName(self.into()); util::to_null_str(c_name as *mut i8) } } /// Sets the name of this value pub fn set_name(&self, name: &str) { let c_name = CString::new(name).unwrap(); unsafe { LLVMSetValueName(self.into(), c_name.as_ptr()) } } /// Returns the type of this value pub fn get_type(&self) -> &Type
} pub struct GlobalValue; native_ref!(&GlobalValue = LLVMValueRef); deref!(GlobalValue, Value); impl GlobalValue { /// Sets the initial value for this global. pub fn set_initializer(&self, value: &Value) { unsafe { LLVMSetInitializer(self.into(), value.into()) } } /// Gets the initial value for this global. pub fn get_initializer(&self) -> &Value { unsafe { LLVMGetInitializer(self.into()) }.into() } } impl CastFrom for GlobalValue { type From = Value; fn cast<'a>(val: &'a Value) -> Option<&'a GlobalValue> { let gv = unsafe { LLVMIsAGlobalValue(val.into()) }; if gv == ptr::null_mut() { None } else { Some(gv.into()) } } } /// Comparative operations on values. #[derive(Copy, Clone, Eq, PartialEq)] pub enum Predicate { Equal, NotEqual, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual } /// A function argument. pub struct Arg; native_ref!(&Arg = LLVMValueRef); impl Deref for Arg { type Target = Value; fn deref(&self) -> &Value { unsafe { mem::transmute(self) } } } impl Arg { /// Add the attribute given to this argument. pub fn add_attribute(&self, attr: Attribute) { unsafe { LLVMAddAttribute(self.into(), attr.into()) } } /// Add all the attributes given to this argument. pub fn add_attributes(&self, attrs: &[Attribute]) { let mut sum = LLVMAttribute::empty(); for attr in attrs { let attr:LLVMAttribute = (*attr).into(); sum = sum | attr; } unsafe { LLVMAddAttribute(self.into(), sum.into()) } } /// Returns true if this argument has the attribute given. pub fn has_attribute(&self, attr: Attribute) -> bool { unsafe { let other = LLVMGetAttribute(self.into()); other.contains(attr.into()) } } /// Returns true if this argument has all the attributes given. pub fn has_attributes(&self, attrs: &[Attribute]) -> bool { unsafe { let other = LLVMGetAttribute(self.into()); for &attr in attrs { if!other.contains(attr.into()) { return false; } } return true; } } /// Remove an attribute from this argument. pub fn remove_attribute(&self, attr: Attribute) { unsafe { LLVMRemoveAttribute(self.into(), attr.into()) } } } /// A function that can be called and contains blocks. pub struct Function; native_ref!(&Function = LLVMValueRef); impl Deref for Function { type Target = Value; fn deref(&self) -> &Value { unsafe { mem::transmute(self) } } } impl Index<usize> for Function { type Output = Arg; fn index(&self, index: usize) -> &Arg { unsafe { if index < LLVMCountParams(self.into()) as usize { LLVMGetParam(self.into(), index as c_uint).into() } else { panic!("no such index {} on {:?}", index, self.get_type()) } } } } impl CastFrom for Function { type From = Value; fn cast<'a>(val: &'a Value) -> Option<&'a Function> { let ty = val.get_type(); let mut is_func = ty.is_function(); if let Some(elem) = ty.get_element() { is_func = is_func || elem.is_function() } if is_func { Some(unsafe { mem::transmute(val) }) } else { None } } } impl Function { /// Add a basic block with the name given to the function and return it. pub fn append<'a>(&'a self, name: &str) -> &'a BasicBlock { util::with_cstr(name, |ptr| unsafe { LLVMAppendBasicBlockInContext(self.get_context().into(), self.into(), ptr).into() }) } /// Returns the entry block of this function or `None` if there is none. pub fn get_entry(&self) -> Option<&BasicBlock> { unsafe { mem::transmute(LLVMGetEntryBasicBlock(self.into())) } } /// Returns the name of this function. pub fn get_name(&self) -> &str { unsafe { let c_name = LLVMGetValueName(self.into()); util::to_str(c_name as *mut i8) } } /// Returns the function signature representing this function's signature. pub fn get_signature(&self) -> &FunctionType { unsafe { let ty = LLVMTypeOf(self.into()); LLVMGetElementType(ty).into() } } /// Returns the number of function parameters pub fn num_params(&self) -> usize { unsafe { LLVMCountParams(self.into()) as usize } } /// Add the attribute given to this function. pub fn add_attribute(&self, attr: Attribute) { unsafe { LLVMAddFunctionAttr(self.into(), attr.into()) } } /// Add all the attributes given to this function. pub fn add_attributes(&self, attrs: &[Attribute]) { let mut sum = LLVMAttribute::empty(); for attr in attrs { let attr:LLVMAttribute = (*attr).into(); sum = sum | attr; } unsafe { LLVMAddFunctionAttr(self.into(), sum.into()) } } /// Returns true if the attribute given is set in this function. pub fn has_attribute(&self, attr: Attribute) -> bool { unsafe { let other = LLVMGetFunctionAttr(self.into()); other.contains(attr.into()) } } /// Returns true if all the attributes given is set in this function. pub fn has_attributes(&self, attrs: &[Attribute]) -> bool { unsafe { let other = LLVMGetFunctionAttr(self.into()); for &attr in attrs { if!other.contains(attr.into()) { return false; } } return true; } } /// Remove the attribute given from this function. pub fn remove_attribute(&self, attr: Attribute) { unsafe { LLVMRemoveFunctionAttr(self.into(), attr.into()) } } } impl<'a> IntoIterator for &'a Function { type Item = &'a Arg; type IntoIter = ValueIter<'a, &'a Arg>; /// Iterate through the functions in the module fn into_iter(self) -> ValueIter<'a, &'a Arg> { ValueIter::new( unsafe { LLVMGetFirstParam(self.into()) }, LLVMGetNextParam) } } impl GetContext for Function { fn get_context(&self) -> &Context { self.get_type().get_context() } } /// A way of indicating to LLVM how you want arguments / functions to be handled. #[derive(Copy, Clone, Eq, PartialEq, Debug)] #[repr(C)] pub enum Attribute { /// Zero-extended before or after call. ZExt = 0b1, /// Sign-extended before or after call. SExt = 0b10, /// Mark the function as not returning. NoReturn = 0b100, /// Force argument to be passed in register. InReg = 0b1000, /// Hidden pointer to structure to return. StructRet = 0b10000, /// Function doesn't unwind stack. NoUnwind = 0b100000, /// Consider to not alias after call. NoAlias = 0b1000000, /// Pass structure by value. ByVal = 0b10000000, /// Nested function static chain. Nest = 0b100000000, /// Function doesn't access memory. ReadNone = 0b1000000000, /// Function only reads from memory. ReadOnly = 0b10000000000, /// Never inline this function. NoInline = 0b100000000000, /// Always inline this function. AlwaysInline = 0b1000000000000, /// Optimize this function for size. OptimizeForSize = 0b10000000000000, /// Stack protection. StackProtect = 0b100000000000000, /// Stack protection required. StackProtectReq = 0b1000000000000000, /// Alignment of parameter (5 bits) stored as log2 of alignment with +1 bias 0 means unaligned (different from align(1)). Alignment = 0b10000000000000000, /// Function creates no aliases of pointer. NoCapture = 0b100000000000000000, /// Disable redzone. NoRedZone = 0b1000000000000000000, /// Disable implicit float instructions. NoImplicitFloat = 0b10000000000000000000, /// Naked function. Naked = 0b100000000000000000000, /// The source language has marked this function as inline. InlineHint = 0b1000000000000000000000, /// Alignment of stack for function (3 bits) stored as log2 of alignment with +1 bias 0 means unaligned (different from alignstack=(1)). StackAlignment = 0b11100000000000000000000000000, /// This function returns twice. ReturnsTwice = 0b100000000000000000000000000000, /// Function must be in unwind table. UWTable = 0b1000000000000000000000000000000, /// Function is called early/often, so lazy binding isn't effective. NonLazyBind = 0b10000000000000000000000000000000 } impl From<LLVMAttribute> for Attribute { fn from(attr: LLVMAttribute) -> Attribute { unsafe { mem::transmute(attr) } } } impl From<Attribute> for LLVMAttribute { fn from(attr: Attribute) -> LLVMAttribute { unsafe { mem::transmute(attr) } } } impl GetContext for Value { fn get_context(&self) -> &Context { self.get_type().get_context() } } /// Value Iterator implementation. /// /// T can be all descendent types of LLVMValueRef. #[derive(Copy, Clone)] pub struct ValueIter<'a, T: From<LLVMValueRef>> { cur : LLVMValueRef, step : unsafe extern "C" fn(LLVMValueRef) -> LLVMValueRef, marker1: ::std::marker::PhantomData<&'a ()>, marker2: ::std::marker::PhantomData<T>, } impl<'a, T: From<LLVMValueRef>> ValueIter<'a, T> { pub fn new(cur: LLVMValueRef, step: unsafe extern "C" fn(LLVMValueRef) -> LLVMValueRef) -> Self { ValueIter { cur: cur, step: step, marker1: ::std::marker::PhantomData, marker2: ::std::marker::PhantomData } } } impl<'a, T: From<LLVMValueRef>> Iterator for ValueIter<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { let old: LLVMValueRef = self.cur; if!old.is_null() { self.cur = unsafe { (self.step)(old) }; Some(old.into()) } else { None } } }
{ unsafe { LLVMTypeOf(self.into()) }.into() }
identifier_body
mod.rs
use gst::{glib, prelude::*}; pub(crate) mod bin; glib::wrapper! { pub struct RendererBin(ObjectSubclass<bin::RendererBin>) @extends gst::Bin, gst::Element, gst::Object; } impl RendererBin { /// Asynchronoulsy call the provided function on the parent. /// /// This is useful to set the state of the pipeline. fn
(&self, f: impl FnOnce(&RendererBin, &gst::Element) + Send +'static) { match self.parent() { Some(parent) => parent.downcast_ref::<gst::Element>().unwrap().call_async( glib::clone!(@weak self as bin => @default-panic, move |parent| f(&bin, parent)), ), None => unreachable!("media-toc renderer bin has no parent"), } } } unsafe impl Send for RendererBin {} unsafe impl Sync for RendererBin {} pub use bin::NAME as RENDERER_BIN_NAME; glib::wrapper! { pub struct Renderer(ObjectSubclass<renderer::Renderer>) @extends gst::Element, gst::Object; } unsafe impl Send for Renderer {} unsafe impl Sync for Renderer {} pub(crate) mod renderer; pub use renderer::{ SeekField, SegmentField, BUFFER_SIZE_PROP, CLOCK_REF_PROP, DBL_RENDERER_IMPL_PROP, MUST_REFRESH_SIGNAL, NAME as RENDERER_NAME, SEGMENT_DONE_SIGNAL, }; pub(crate) use renderer::GET_WINDOW_TIMESTAMPS_SIGNAL; pub const PLAY_RANGE_DONE_SIGNAL: &str = "play-range-done"; gst::plugin_define!( mediatocvisu, env!("CARGO_PKG_DESCRIPTION"), plugin_init, concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), "MIT/X11", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_NAME"), env!("CARGO_PKG_REPOSITORY"), env!("BUILD_REL_DATE") ); pub fn init() { use std::sync::Once; static INIT: Once = Once::new(); INIT.call_once(|| { gst::init().unwrap(); self::plugin_register_static().expect("media-toc rendering plugin init"); }); } fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { gst::Element::register( Some(plugin), bin::NAME, gst::Rank::None, RendererBin::static_type(), )?; gst::Element::register( Some(plugin), renderer::NAME, gst::Rank::None, Renderer::static_type(), )?; Ok(()) }
parent_call_async
identifier_name
mod.rs
use gst::{glib, prelude::*}; pub(crate) mod bin; glib::wrapper! { pub struct RendererBin(ObjectSubclass<bin::RendererBin>) @extends gst::Bin, gst::Element, gst::Object; } impl RendererBin { /// Asynchronoulsy call the provided function on the parent. /// /// This is useful to set the state of the pipeline. fn parent_call_async(&self, f: impl FnOnce(&RendererBin, &gst::Element) + Send +'static)
} unsafe impl Send for RendererBin {} unsafe impl Sync for RendererBin {} pub use bin::NAME as RENDERER_BIN_NAME; glib::wrapper! { pub struct Renderer(ObjectSubclass<renderer::Renderer>) @extends gst::Element, gst::Object; } unsafe impl Send for Renderer {} unsafe impl Sync for Renderer {} pub(crate) mod renderer; pub use renderer::{ SeekField, SegmentField, BUFFER_SIZE_PROP, CLOCK_REF_PROP, DBL_RENDERER_IMPL_PROP, MUST_REFRESH_SIGNAL, NAME as RENDERER_NAME, SEGMENT_DONE_SIGNAL, }; pub(crate) use renderer::GET_WINDOW_TIMESTAMPS_SIGNAL; pub const PLAY_RANGE_DONE_SIGNAL: &str = "play-range-done"; gst::plugin_define!( mediatocvisu, env!("CARGO_PKG_DESCRIPTION"), plugin_init, concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), "MIT/X11", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_NAME"), env!("CARGO_PKG_REPOSITORY"), env!("BUILD_REL_DATE") ); pub fn init() { use std::sync::Once; static INIT: Once = Once::new(); INIT.call_once(|| { gst::init().unwrap(); self::plugin_register_static().expect("media-toc rendering plugin init"); }); } fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { gst::Element::register( Some(plugin), bin::NAME, gst::Rank::None, RendererBin::static_type(), )?; gst::Element::register( Some(plugin), renderer::NAME, gst::Rank::None, Renderer::static_type(), )?; Ok(()) }
{ match self.parent() { Some(parent) => parent.downcast_ref::<gst::Element>().unwrap().call_async( glib::clone!(@weak self as bin => @default-panic, move |parent| f(&bin, parent)), ), None => unreachable!("media-toc renderer bin has no parent"), } }
identifier_body
mod.rs
use gst::{glib, prelude::*}; pub(crate) mod bin; glib::wrapper! { pub struct RendererBin(ObjectSubclass<bin::RendererBin>) @extends gst::Bin, gst::Element, gst::Object; } impl RendererBin { /// Asynchronoulsy call the provided function on the parent. /// /// This is useful to set the state of the pipeline. fn parent_call_async(&self, f: impl FnOnce(&RendererBin, &gst::Element) + Send +'static) { match self.parent() { Some(parent) => parent.downcast_ref::<gst::Element>().unwrap().call_async( glib::clone!(@weak self as bin => @default-panic, move |parent| f(&bin, parent)), ), None => unreachable!("media-toc renderer bin has no parent"), } } } unsafe impl Send for RendererBin {} unsafe impl Sync for RendererBin {} pub use bin::NAME as RENDERER_BIN_NAME; glib::wrapper! { pub struct Renderer(ObjectSubclass<renderer::Renderer>) @extends gst::Element, gst::Object; } unsafe impl Send for Renderer {} unsafe impl Sync for Renderer {} pub(crate) mod renderer; pub use renderer::{ SeekField, SegmentField, BUFFER_SIZE_PROP, CLOCK_REF_PROP, DBL_RENDERER_IMPL_PROP, MUST_REFRESH_SIGNAL, NAME as RENDERER_NAME, SEGMENT_DONE_SIGNAL, }; pub(crate) use renderer::GET_WINDOW_TIMESTAMPS_SIGNAL; pub const PLAY_RANGE_DONE_SIGNAL: &str = "play-range-done"; gst::plugin_define!( mediatocvisu, env!("CARGO_PKG_DESCRIPTION"), plugin_init, concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), "MIT/X11", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_NAME"), env!("CARGO_PKG_REPOSITORY"), env!("BUILD_REL_DATE") ); pub fn init() { use std::sync::Once; static INIT: Once = Once::new(); INIT.call_once(|| {
fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { gst::Element::register( Some(plugin), bin::NAME, gst::Rank::None, RendererBin::static_type(), )?; gst::Element::register( Some(plugin), renderer::NAME, gst::Rank::None, Renderer::static_type(), )?; Ok(()) }
gst::init().unwrap(); self::plugin_register_static().expect("media-toc rendering plugin init"); }); }
random_line_split
sharedmem.rs
use crate::{OSHandle, OSMem, Result}; use core::mem; use core::ops::{Deref, DerefMut}; use syscall; fn align_down(value: usize, round: usize) -> usize { value &!(round - 1) } fn align_up(value: usize, round: usize) -> usize { align_down(value + round - 1, round) } pub struct SharedMem<T> { handle: OSHandle, writable: bool, mem: OSMem<T>, } impl<T> SharedMem<T> where T: Copy, { pub fn from_raw(handle: OSHandle, len: usize, writable: bool) -> Result<Self> { let byte_len = len * mem::size_of::<T>(); let ptr = syscall::map_shared_mem(handle.get(), byte_len, writable)? as *mut T; let mem = unsafe { OSMem::from_raw(ptr, len) }; Ok(Self { handle, writable, mem }) } pub fn new(len: usize, writable: bool) -> Result<Self> {
pub fn resize(&mut self, new_len: usize) -> Result<()> { let old_byte_len = self.mem.len() * mem::size_of::<T>(); let new_byte_len = new_len * mem::size_of::<T>(); if align_up(new_byte_len, 4096) == align_up(old_byte_len, 4096) { return Ok(()); } let ptr = syscall::map_shared_mem(self.handle.get(), new_byte_len, self.writable)? as *mut T; self.mem = unsafe { OSMem::from_raw(ptr, new_len) }; Ok(()) } } impl<T> SharedMem<T> { pub fn as_handle(&self) -> &OSHandle { &self.handle } pub fn into_inner(self) -> (OSHandle, OSMem<T>) { (self.handle, self.mem) } } impl<T> Deref for SharedMem<T> { type Target = [T]; fn deref(&self) -> &[T] { self.mem.as_ref() } } impl<T> DerefMut for SharedMem<T> { fn deref_mut(&mut self) -> &mut [T] { self.mem.as_mut() } }
let handle = OSHandle::from_raw(syscall::create_shared_mem()); Self::from_raw(handle, len, writable) }
random_line_split
sharedmem.rs
use crate::{OSHandle, OSMem, Result}; use core::mem; use core::ops::{Deref, DerefMut}; use syscall; fn align_down(value: usize, round: usize) -> usize { value &!(round - 1) } fn align_up(value: usize, round: usize) -> usize { align_down(value + round - 1, round) } pub struct SharedMem<T> { handle: OSHandle, writable: bool, mem: OSMem<T>, } impl<T> SharedMem<T> where T: Copy, { pub fn from_raw(handle: OSHandle, len: usize, writable: bool) -> Result<Self> { let byte_len = len * mem::size_of::<T>(); let ptr = syscall::map_shared_mem(handle.get(), byte_len, writable)? as *mut T; let mem = unsafe { OSMem::from_raw(ptr, len) }; Ok(Self { handle, writable, mem }) } pub fn new(len: usize, writable: bool) -> Result<Self> { let handle = OSHandle::from_raw(syscall::create_shared_mem()); Self::from_raw(handle, len, writable) } pub fn resize(&mut self, new_len: usize) -> Result<()> { let old_byte_len = self.mem.len() * mem::size_of::<T>(); let new_byte_len = new_len * mem::size_of::<T>(); if align_up(new_byte_len, 4096) == align_up(old_byte_len, 4096)
let ptr = syscall::map_shared_mem(self.handle.get(), new_byte_len, self.writable)? as *mut T; self.mem = unsafe { OSMem::from_raw(ptr, new_len) }; Ok(()) } } impl<T> SharedMem<T> { pub fn as_handle(&self) -> &OSHandle { &self.handle } pub fn into_inner(self) -> (OSHandle, OSMem<T>) { (self.handle, self.mem) } } impl<T> Deref for SharedMem<T> { type Target = [T]; fn deref(&self) -> &[T] { self.mem.as_ref() } } impl<T> DerefMut for SharedMem<T> { fn deref_mut(&mut self) -> &mut [T] { self.mem.as_mut() } }
{ return Ok(()); }
conditional_block
sharedmem.rs
use crate::{OSHandle, OSMem, Result}; use core::mem; use core::ops::{Deref, DerefMut}; use syscall; fn align_down(value: usize, round: usize) -> usize
fn align_up(value: usize, round: usize) -> usize { align_down(value + round - 1, round) } pub struct SharedMem<T> { handle: OSHandle, writable: bool, mem: OSMem<T>, } impl<T> SharedMem<T> where T: Copy, { pub fn from_raw(handle: OSHandle, len: usize, writable: bool) -> Result<Self> { let byte_len = len * mem::size_of::<T>(); let ptr = syscall::map_shared_mem(handle.get(), byte_len, writable)? as *mut T; let mem = unsafe { OSMem::from_raw(ptr, len) }; Ok(Self { handle, writable, mem }) } pub fn new(len: usize, writable: bool) -> Result<Self> { let handle = OSHandle::from_raw(syscall::create_shared_mem()); Self::from_raw(handle, len, writable) } pub fn resize(&mut self, new_len: usize) -> Result<()> { let old_byte_len = self.mem.len() * mem::size_of::<T>(); let new_byte_len = new_len * mem::size_of::<T>(); if align_up(new_byte_len, 4096) == align_up(old_byte_len, 4096) { return Ok(()); } let ptr = syscall::map_shared_mem(self.handle.get(), new_byte_len, self.writable)? as *mut T; self.mem = unsafe { OSMem::from_raw(ptr, new_len) }; Ok(()) } } impl<T> SharedMem<T> { pub fn as_handle(&self) -> &OSHandle { &self.handle } pub fn into_inner(self) -> (OSHandle, OSMem<T>) { (self.handle, self.mem) } } impl<T> Deref for SharedMem<T> { type Target = [T]; fn deref(&self) -> &[T] { self.mem.as_ref() } } impl<T> DerefMut for SharedMem<T> { fn deref_mut(&mut self) -> &mut [T] { self.mem.as_mut() } }
{ value & !(round - 1) }
identifier_body
sharedmem.rs
use crate::{OSHandle, OSMem, Result}; use core::mem; use core::ops::{Deref, DerefMut}; use syscall; fn align_down(value: usize, round: usize) -> usize { value &!(round - 1) } fn align_up(value: usize, round: usize) -> usize { align_down(value + round - 1, round) } pub struct SharedMem<T> { handle: OSHandle, writable: bool, mem: OSMem<T>, } impl<T> SharedMem<T> where T: Copy, { pub fn from_raw(handle: OSHandle, len: usize, writable: bool) -> Result<Self> { let byte_len = len * mem::size_of::<T>(); let ptr = syscall::map_shared_mem(handle.get(), byte_len, writable)? as *mut T; let mem = unsafe { OSMem::from_raw(ptr, len) }; Ok(Self { handle, writable, mem }) } pub fn new(len: usize, writable: bool) -> Result<Self> { let handle = OSHandle::from_raw(syscall::create_shared_mem()); Self::from_raw(handle, len, writable) } pub fn resize(&mut self, new_len: usize) -> Result<()> { let old_byte_len = self.mem.len() * mem::size_of::<T>(); let new_byte_len = new_len * mem::size_of::<T>(); if align_up(new_byte_len, 4096) == align_up(old_byte_len, 4096) { return Ok(()); } let ptr = syscall::map_shared_mem(self.handle.get(), new_byte_len, self.writable)? as *mut T; self.mem = unsafe { OSMem::from_raw(ptr, new_len) }; Ok(()) } } impl<T> SharedMem<T> { pub fn as_handle(&self) -> &OSHandle { &self.handle } pub fn
(self) -> (OSHandle, OSMem<T>) { (self.handle, self.mem) } } impl<T> Deref for SharedMem<T> { type Target = [T]; fn deref(&self) -> &[T] { self.mem.as_ref() } } impl<T> DerefMut for SharedMem<T> { fn deref_mut(&mut self) -> &mut [T] { self.mem.as_mut() } }
into_inner
identifier_name
connect.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::sync::Arc; use std::collections::BTreeSet; use std::io; use std::time::Duration; use std::net::SocketAddr; use futures::{Future, Poll, Async}; use tokio_core::reactor::Handle; use tokio_core::net::{TcpStream, TcpStreamNew}; use key_server_cluster::{Error, NodeId, NodeKeyPair}; use key_server_cluster::io::{handshake, Handshake, Deadline, deadline}; use key_server_cluster::net::Connection; /// Create future for connecting to other node. pub fn connect(address: &SocketAddr, handle: &Handle, self_key_pair: Arc<NodeKeyPair>, trusted_nodes: BTreeSet<NodeId>) -> Deadline<Connect> { let connect = Connect { state: ConnectState::TcpConnect(TcpStream::connect(address, handle)), address: address.clone(), self_key_pair: self_key_pair, trusted_nodes: trusted_nodes, }; deadline(Duration::new(5, 0), handle, connect).expect("Failed to create timeout") } enum ConnectState { TcpConnect(TcpStreamNew), Handshake(Handshake<TcpStream>), Connected, } /// Future for connecting to other node. pub struct Connect { state: ConnectState, address: SocketAddr, self_key_pair: Arc<NodeKeyPair>, trusted_nodes: BTreeSet<NodeId>, } impl Future for Connect { type Item = Result<Connection, Error>; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error>
}, ConnectState::Connected => panic!("poll Connect after it's done"), }; self.state = next; match result { // by polling again, we register new future Async::NotReady => self.poll(), result => Ok(result) } } }
{ let (next, result) = match self.state { ConnectState::TcpConnect(ref mut future) => { let stream = try_ready!(future.poll()); let handshake = handshake(stream, self.self_key_pair.clone(), self.trusted_nodes.clone()); (ConnectState::Handshake(handshake), Async::NotReady) }, ConnectState::Handshake(ref mut future) => { let (stream, result) = try_ready!(future.poll()); let result = match result { Ok(result) => result, Err(err) => return Ok(Async::Ready(Err(err))), }; let connection = Connection { stream: stream.into(), address: self.address, node_id: result.node_id, key: result.shared_key, }; (ConnectState::Connected, Async::Ready(Ok(connection)))
identifier_body
connect.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::sync::Arc; use std::collections::BTreeSet; use std::io; use std::time::Duration; use std::net::SocketAddr; use futures::{Future, Poll, Async}; use tokio_core::reactor::Handle; use tokio_core::net::{TcpStream, TcpStreamNew}; use key_server_cluster::{Error, NodeId, NodeKeyPair}; use key_server_cluster::io::{handshake, Handshake, Deadline, deadline}; use key_server_cluster::net::Connection; /// Create future for connecting to other node. pub fn connect(address: &SocketAddr, handle: &Handle, self_key_pair: Arc<NodeKeyPair>, trusted_nodes: BTreeSet<NodeId>) -> Deadline<Connect> { let connect = Connect { state: ConnectState::TcpConnect(TcpStream::connect(address, handle)), address: address.clone(), self_key_pair: self_key_pair, trusted_nodes: trusted_nodes, }; deadline(Duration::new(5, 0), handle, connect).expect("Failed to create timeout") } enum ConnectState { TcpConnect(TcpStreamNew), Handshake(Handshake<TcpStream>), Connected, } /// Future for connecting to other node. pub struct Connect { state: ConnectState, address: SocketAddr, self_key_pair: Arc<NodeKeyPair>, trusted_nodes: BTreeSet<NodeId>, } impl Future for Connect { type Item = Result<Connection, Error>; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { let (next, result) = match self.state { ConnectState::TcpConnect(ref mut future) => { let stream = try_ready!(future.poll()); let handshake = handshake(stream, self.self_key_pair.clone(), self.trusted_nodes.clone()); (ConnectState::Handshake(handshake), Async::NotReady) }, ConnectState::Handshake(ref mut future) => { let (stream, result) = try_ready!(future.poll()); let result = match result { Ok(result) => result, Err(err) => return Ok(Async::Ready(Err(err))), }; let connection = Connection { stream: stream.into(), address: self.address, node_id: result.node_id, key: result.shared_key, }; (ConnectState::Connected, Async::Ready(Ok(connection))) }, ConnectState::Connected => panic!("poll Connect after it's done"), }; self.state = next; match result { // by polling again, we register new future Async::NotReady => self.poll(),
} } }
result => Ok(result)
random_line_split
connect.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::sync::Arc; use std::collections::BTreeSet; use std::io; use std::time::Duration; use std::net::SocketAddr; use futures::{Future, Poll, Async}; use tokio_core::reactor::Handle; use tokio_core::net::{TcpStream, TcpStreamNew}; use key_server_cluster::{Error, NodeId, NodeKeyPair}; use key_server_cluster::io::{handshake, Handshake, Deadline, deadline}; use key_server_cluster::net::Connection; /// Create future for connecting to other node. pub fn
(address: &SocketAddr, handle: &Handle, self_key_pair: Arc<NodeKeyPair>, trusted_nodes: BTreeSet<NodeId>) -> Deadline<Connect> { let connect = Connect { state: ConnectState::TcpConnect(TcpStream::connect(address, handle)), address: address.clone(), self_key_pair: self_key_pair, trusted_nodes: trusted_nodes, }; deadline(Duration::new(5, 0), handle, connect).expect("Failed to create timeout") } enum ConnectState { TcpConnect(TcpStreamNew), Handshake(Handshake<TcpStream>), Connected, } /// Future for connecting to other node. pub struct Connect { state: ConnectState, address: SocketAddr, self_key_pair: Arc<NodeKeyPair>, trusted_nodes: BTreeSet<NodeId>, } impl Future for Connect { type Item = Result<Connection, Error>; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { let (next, result) = match self.state { ConnectState::TcpConnect(ref mut future) => { let stream = try_ready!(future.poll()); let handshake = handshake(stream, self.self_key_pair.clone(), self.trusted_nodes.clone()); (ConnectState::Handshake(handshake), Async::NotReady) }, ConnectState::Handshake(ref mut future) => { let (stream, result) = try_ready!(future.poll()); let result = match result { Ok(result) => result, Err(err) => return Ok(Async::Ready(Err(err))), }; let connection = Connection { stream: stream.into(), address: self.address, node_id: result.node_id, key: result.shared_key, }; (ConnectState::Connected, Async::Ready(Ok(connection))) }, ConnectState::Connected => panic!("poll Connect after it's done"), }; self.state = next; match result { // by polling again, we register new future Async::NotReady => self.poll(), result => Ok(result) } } }
connect
identifier_name
match-pipe-binding.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 fn test1() { // from issue 6338 match ((1, "a".to_string()), (2, "b".to_string())) { ((1, a), (2, b)) | ((2, b), (1, a)) => { assert_eq!(a, "a".to_string()); assert_eq!(b, "b".to_string()); },
match (1, 2, 3) { (1, a, b) | (2, b, a) => { assert_eq!(a, 2); assert_eq!(b, 3); }, _ => panic!(), } } fn test3() { match (1, 2, 3) { (1, ref a, ref b) | (2, ref b, ref a) => { assert_eq!(*a, 2); assert_eq!(*b, 3); }, _ => panic!(), } } fn test4() { match (1, 2, 3) { (1, a, b) | (2, b, a) if a == 2 => { assert_eq!(a, 2); assert_eq!(b, 3); }, _ => panic!(), } } fn test5() { match (1, 2, 3) { (1, ref a, ref b) | (2, ref b, ref a) if *a == 2 => { assert_eq!(*a, 2); assert_eq!(*b, 3); }, _ => panic!(), } } pub fn main() { test1(); test2(); test3(); test4(); test5(); }
_ => panic!(), } } fn test2() {
random_line_split
match-pipe-binding.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 fn test1() { // from issue 6338 match ((1, "a".to_string()), (2, "b".to_string())) { ((1, a), (2, b)) | ((2, b), (1, a)) => { assert_eq!(a, "a".to_string()); assert_eq!(b, "b".to_string()); }, _ => panic!(), } } fn test2() { match (1, 2, 3) { (1, a, b) | (2, b, a) => { assert_eq!(a, 2); assert_eq!(b, 3); }, _ => panic!(), } } fn test3() { match (1, 2, 3) { (1, ref a, ref b) | (2, ref b, ref a) => { assert_eq!(*a, 2); assert_eq!(*b, 3); }, _ => panic!(), } } fn test4() { match (1, 2, 3) { (1, a, b) | (2, b, a) if a == 2 => { assert_eq!(a, 2); assert_eq!(b, 3); }, _ => panic!(), } } fn test5() { match (1, 2, 3) { (1, ref a, ref b) | (2, ref b, ref a) if *a == 2 => { assert_eq!(*a, 2); assert_eq!(*b, 3); }, _ => panic!(), } } pub fn main()
{ test1(); test2(); test3(); test4(); test5(); }
identifier_body
match-pipe-binding.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 fn
() { // from issue 6338 match ((1, "a".to_string()), (2, "b".to_string())) { ((1, a), (2, b)) | ((2, b), (1, a)) => { assert_eq!(a, "a".to_string()); assert_eq!(b, "b".to_string()); }, _ => panic!(), } } fn test2() { match (1, 2, 3) { (1, a, b) | (2, b, a) => { assert_eq!(a, 2); assert_eq!(b, 3); }, _ => panic!(), } } fn test3() { match (1, 2, 3) { (1, ref a, ref b) | (2, ref b, ref a) => { assert_eq!(*a, 2); assert_eq!(*b, 3); }, _ => panic!(), } } fn test4() { match (1, 2, 3) { (1, a, b) | (2, b, a) if a == 2 => { assert_eq!(a, 2); assert_eq!(b, 3); }, _ => panic!(), } } fn test5() { match (1, 2, 3) { (1, ref a, ref b) | (2, ref b, ref a) if *a == 2 => { assert_eq!(*a, 2); assert_eq!(*b, 3); }, _ => panic!(), } } pub fn main() { test1(); test2(); test3(); test4(); test5(); }
test1
identifier_name
future.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * A type representing values that may be computed concurrently and * operations for working with them. * * # Example * * ```rust * use std::sync::Future; * # fn fib(n: uint) -> uint {42}; * # fn make_a_sandwich() {}; * let mut delayed_fib = Future::spawn(proc() { fib(5000) }); * make_a_sandwich(); * println!("fib(5000) = {}", delayed_fib.get()) * ``` */ #![allow(missing_doc)] use core::prelude::*; use core::mem::replace; use comm::{Receiver, channel}; use task::spawn; /// A type encapsulating the result of a computation which may not be complete pub struct Future<A> { state: FutureState<A>, } enum FutureState<A> { Pending(proc():Send -> A), Evaluating, Forced(A) } /// Methods on the `future` type impl<A:Clone> Future<A> { pub fn get(&mut self) -> A { //! Get the value of the future. (*(self.get_ref())).clone() } } impl<A> Future<A> { /// Gets the value from this future, forcing evaluation. pub fn unwrap(mut self) -> A { self.get_ref(); let state = replace(&mut self.state, Evaluating); match state { Forced(v) => v, _ => fail!( "Logic error." ), } } pub fn get_ref<'a>(&'a mut self) -> &'a A { /*! * Executes the future's closure and then returns a reference * to the result. The reference lasts as long as * the future. */ match self.state { Forced(ref v) => return v, Evaluating => fail!("Recursive forcing of future!"), Pending(_) => { match replace(&mut self.state, Evaluating) { Forced(_) | Evaluating => fail!("Logic error."), Pending(f) => { self.state = Forced(f()); self.get_ref() } } } } } pub fn from_value(val: A) -> Future<A> { /*! * Create a future from a value. * * The value is immediately available and calling `get` later will * not block. */ Future {state: Forced(val)} } pub fn from_fn(f: proc():Send -> A) -> Future<A> { /*! * Create a future from a function. * * The first time that the value is requested it will be retrieved by * calling the function. Note that this function is a local * function. It is not spawned into another task. */ Future {state: Pending(f)} } } impl<A:Send> Future<A> { pub fn from_receiver(rx: Receiver<A>) -> Future<A> { /*! * Create a future from a port * * The first time that the value is requested the task will block * waiting for the result to be received on the port. */ Future::from_fn(proc() { rx.recv() }) } pub fn spawn(blk: proc():Send -> A) -> Future<A> { /*! * Create a future from a unique closure. * * The closure will be run in a new task and its result used as the * value of the future. */ let (tx, rx) = channel(); spawn(proc() { // Don't fail if the other end has hung up let _ = tx.send_opt(blk()); }); Future::from_receiver(rx) } } #[cfg(test)] mod test { use prelude::*; use sync::Future; use task; use comm::{channel, Sender}; #[test] fn test_from_value() { let mut f = Future::from_value("snail".to_string()); assert_eq!(f.get(), "snail".to_string()); } #[test] fn test_from_receiver() { let (tx, rx) = channel(); tx.send("whale".to_string()); let mut f = Future::from_receiver(rx); assert_eq!(f.get(), "whale".to_string()); } #[test] fn test_from_fn() { let mut f = Future::from_fn(proc() "brail".to_string()); assert_eq!(f.get(), "brail".to_string()); } #[test] fn test_interface_get() { let mut f = Future::from_value("fail".to_string()); assert_eq!(f.get(), "fail".to_string()); } #[test] fn test_interface_unwrap() { let f = Future::from_value("fail".to_string()); assert_eq!(f.unwrap(), "fail".to_string()); } #[test] fn test_get_ref_method() { let mut f = Future::from_value(22i); assert_eq!(*f.get_ref(), 22); } #[test] fn test_spawn() { let mut f = Future::spawn(proc() "bale".to_string()); assert_eq!(f.get(), "bale".to_string()); } #[test] #[should_fail] fn test_futurefail() { let mut f = Future::spawn(proc() fail!()); let _x: String = f.get(); } #[test] fn test_sendable_future() { let expected = "schlorf"; let (tx, rx) = channel(); let f = Future::spawn(proc() { expected }); task::spawn(proc() { let mut f = f; tx.send(f.get()); }); assert_eq!(rx.recv(), expected); } #[test] fn
() { struct Bomb(Sender<bool>); local_data_key!(LOCAL: Bomb) impl Drop for Bomb { fn drop(&mut self) { let Bomb(ref tx) = *self; tx.send(task::failing()); } } // Spawn a future, but drop it immediately. When we receive the result // later on, we should never view the task as having failed. let (tx, rx) = channel(); drop(Future::spawn(proc() { LOCAL.replace(Some(Bomb(tx))); })); // Make sure the future didn't fail the task. assert!(!rx.recv()); } }
test_dropped_future_doesnt_fail
identifier_name
future.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * A type representing values that may be computed concurrently and * operations for working with them. * * # Example * * ```rust * use std::sync::Future; * # fn fib(n: uint) -> uint {42}; * # fn make_a_sandwich() {}; * let mut delayed_fib = Future::spawn(proc() { fib(5000) }); * make_a_sandwich(); * println!("fib(5000) = {}", delayed_fib.get()) * ``` */ #![allow(missing_doc)] use core::prelude::*; use core::mem::replace; use comm::{Receiver, channel}; use task::spawn; /// A type encapsulating the result of a computation which may not be complete pub struct Future<A> { state: FutureState<A>, } enum FutureState<A> { Pending(proc():Send -> A), Evaluating, Forced(A) } /// Methods on the `future` type
(*(self.get_ref())).clone() } } impl<A> Future<A> { /// Gets the value from this future, forcing evaluation. pub fn unwrap(mut self) -> A { self.get_ref(); let state = replace(&mut self.state, Evaluating); match state { Forced(v) => v, _ => fail!( "Logic error." ), } } pub fn get_ref<'a>(&'a mut self) -> &'a A { /*! * Executes the future's closure and then returns a reference * to the result. The reference lasts as long as * the future. */ match self.state { Forced(ref v) => return v, Evaluating => fail!("Recursive forcing of future!"), Pending(_) => { match replace(&mut self.state, Evaluating) { Forced(_) | Evaluating => fail!("Logic error."), Pending(f) => { self.state = Forced(f()); self.get_ref() } } } } } pub fn from_value(val: A) -> Future<A> { /*! * Create a future from a value. * * The value is immediately available and calling `get` later will * not block. */ Future {state: Forced(val)} } pub fn from_fn(f: proc():Send -> A) -> Future<A> { /*! * Create a future from a function. * * The first time that the value is requested it will be retrieved by * calling the function. Note that this function is a local * function. It is not spawned into another task. */ Future {state: Pending(f)} } } impl<A:Send> Future<A> { pub fn from_receiver(rx: Receiver<A>) -> Future<A> { /*! * Create a future from a port * * The first time that the value is requested the task will block * waiting for the result to be received on the port. */ Future::from_fn(proc() { rx.recv() }) } pub fn spawn(blk: proc():Send -> A) -> Future<A> { /*! * Create a future from a unique closure. * * The closure will be run in a new task and its result used as the * value of the future. */ let (tx, rx) = channel(); spawn(proc() { // Don't fail if the other end has hung up let _ = tx.send_opt(blk()); }); Future::from_receiver(rx) } } #[cfg(test)] mod test { use prelude::*; use sync::Future; use task; use comm::{channel, Sender}; #[test] fn test_from_value() { let mut f = Future::from_value("snail".to_string()); assert_eq!(f.get(), "snail".to_string()); } #[test] fn test_from_receiver() { let (tx, rx) = channel(); tx.send("whale".to_string()); let mut f = Future::from_receiver(rx); assert_eq!(f.get(), "whale".to_string()); } #[test] fn test_from_fn() { let mut f = Future::from_fn(proc() "brail".to_string()); assert_eq!(f.get(), "brail".to_string()); } #[test] fn test_interface_get() { let mut f = Future::from_value("fail".to_string()); assert_eq!(f.get(), "fail".to_string()); } #[test] fn test_interface_unwrap() { let f = Future::from_value("fail".to_string()); assert_eq!(f.unwrap(), "fail".to_string()); } #[test] fn test_get_ref_method() { let mut f = Future::from_value(22i); assert_eq!(*f.get_ref(), 22); } #[test] fn test_spawn() { let mut f = Future::spawn(proc() "bale".to_string()); assert_eq!(f.get(), "bale".to_string()); } #[test] #[should_fail] fn test_futurefail() { let mut f = Future::spawn(proc() fail!()); let _x: String = f.get(); } #[test] fn test_sendable_future() { let expected = "schlorf"; let (tx, rx) = channel(); let f = Future::spawn(proc() { expected }); task::spawn(proc() { let mut f = f; tx.send(f.get()); }); assert_eq!(rx.recv(), expected); } #[test] fn test_dropped_future_doesnt_fail() { struct Bomb(Sender<bool>); local_data_key!(LOCAL: Bomb) impl Drop for Bomb { fn drop(&mut self) { let Bomb(ref tx) = *self; tx.send(task::failing()); } } // Spawn a future, but drop it immediately. When we receive the result // later on, we should never view the task as having failed. let (tx, rx) = channel(); drop(Future::spawn(proc() { LOCAL.replace(Some(Bomb(tx))); })); // Make sure the future didn't fail the task. assert!(!rx.recv()); } }
impl<A:Clone> Future<A> { pub fn get(&mut self) -> A { //! Get the value of the future.
random_line_split
local-drop-glue.rs
// Copyright 2016 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. // ignore-tidy-linelength // We specify -Z incremental here because we want to test the partitioning for // incremental compilation // compile-flags:-Zprint-mono-items=lazy -Zincremental=tmp/partitioning-tests/local-drop-glue // compile-flags:-Zinline-in-all-cgus #![allow(dead_code)] #![crate_type="rlib"] //~ MONO_ITEM fn core::ptr[0]::real_drop_in_place[0]<local_drop_glue::Struct[0]> @@ local_drop_glue[Internal] local_drop_glue-mod1[Internal] struct Struct { _a: u32 } impl Drop for Struct { //~ MONO_ITEM fn local_drop_glue::{{impl}}[0]::drop[0] @@ local_drop_glue[External] fn drop(&mut self) {} } //~ MONO_ITEM fn core::ptr[0]::real_drop_in_place[0]<local_drop_glue::Outer[0]> @@ local_drop_glue[Internal] struct Outer { _a: Struct } //~ MONO_ITEM fn local_drop_glue::user[0] @@ local_drop_glue[External] pub fn user()
pub mod mod1 { use super::Struct; //~ MONO_ITEM fn core::ptr[0]::real_drop_in_place[0]<local_drop_glue::mod1[0]::Struct2[0]> @@ local_drop_glue-mod1[Internal] struct Struct2 { _a: Struct, //~ MONO_ITEM fn core::ptr[0]::real_drop_in_place[0]<(u32, local_drop_glue::Struct[0])> @@ local_drop_glue-mod1[Internal] _b: (u32, Struct), } //~ MONO_ITEM fn local_drop_glue::mod1[0]::user[0] @@ local_drop_glue-mod1[External] pub fn user() { let _ = Struct2 { _a: Struct { _a: 0 }, _b: (0, Struct { _a: 0 }), }; } }
{ let _ = Outer { _a: Struct { _a: 0 } }; }
identifier_body
local-drop-glue.rs
// Copyright 2016 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. // ignore-tidy-linelength // We specify -Z incremental here because we want to test the partitioning for // incremental compilation // compile-flags:-Zprint-mono-items=lazy -Zincremental=tmp/partitioning-tests/local-drop-glue // compile-flags:-Zinline-in-all-cgus #![allow(dead_code)] #![crate_type="rlib"] //~ MONO_ITEM fn core::ptr[0]::real_drop_in_place[0]<local_drop_glue::Struct[0]> @@ local_drop_glue[Internal] local_drop_glue-mod1[Internal] struct Struct { _a: u32 } impl Drop for Struct { //~ MONO_ITEM fn local_drop_glue::{{impl}}[0]::drop[0] @@ local_drop_glue[External] fn drop(&mut self) {} } //~ MONO_ITEM fn core::ptr[0]::real_drop_in_place[0]<local_drop_glue::Outer[0]> @@ local_drop_glue[Internal] struct Outer { _a: Struct } //~ MONO_ITEM fn local_drop_glue::user[0] @@ local_drop_glue[External] pub fn
() { let _ = Outer { _a: Struct { _a: 0 } }; } pub mod mod1 { use super::Struct; //~ MONO_ITEM fn core::ptr[0]::real_drop_in_place[0]<local_drop_glue::mod1[0]::Struct2[0]> @@ local_drop_glue-mod1[Internal] struct Struct2 { _a: Struct, //~ MONO_ITEM fn core::ptr[0]::real_drop_in_place[0]<(u32, local_drop_glue::Struct[0])> @@ local_drop_glue-mod1[Internal] _b: (u32, Struct), } //~ MONO_ITEM fn local_drop_glue::mod1[0]::user[0] @@ local_drop_glue-mod1[External] pub fn user() { let _ = Struct2 { _a: Struct { _a: 0 }, _b: (0, Struct { _a: 0 }), }; } }
user
identifier_name
local-drop-glue.rs
// Copyright 2016 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. // ignore-tidy-linelength // We specify -Z incremental here because we want to test the partitioning for // incremental compilation // compile-flags:-Zprint-mono-items=lazy -Zincremental=tmp/partitioning-tests/local-drop-glue // compile-flags:-Zinline-in-all-cgus #![allow(dead_code)] #![crate_type="rlib"] //~ MONO_ITEM fn core::ptr[0]::real_drop_in_place[0]<local_drop_glue::Struct[0]> @@ local_drop_glue[Internal] local_drop_glue-mod1[Internal] struct Struct { _a: u32 } impl Drop for Struct { //~ MONO_ITEM fn local_drop_glue::{{impl}}[0]::drop[0] @@ local_drop_glue[External] fn drop(&mut self) {} } //~ MONO_ITEM fn core::ptr[0]::real_drop_in_place[0]<local_drop_glue::Outer[0]> @@ local_drop_glue[Internal] struct Outer { _a: Struct } //~ MONO_ITEM fn local_drop_glue::user[0] @@ local_drop_glue[External] pub fn user() { let _ = Outer { _a: Struct { _a: 0 } }; } pub mod mod1 { use super::Struct; //~ MONO_ITEM fn core::ptr[0]::real_drop_in_place[0]<local_drop_glue::mod1[0]::Struct2[0]> @@ local_drop_glue-mod1[Internal] struct Struct2 { _a: Struct, //~ MONO_ITEM fn core::ptr[0]::real_drop_in_place[0]<(u32, local_drop_glue::Struct[0])> @@ local_drop_glue-mod1[Internal] _b: (u32, Struct), } //~ MONO_ITEM fn local_drop_glue::mod1[0]::user[0] @@ local_drop_glue-mod1[External] pub fn user()
}; } }
{ let _ = Struct2 { _a: Struct { _a: 0 }, _b: (0, Struct { _a: 0 }),
random_line_split
desc.rs
/// Used in `SQLColAttributeW`. #[repr(u16)] #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum
{ /// `SQL_DESC_COUNT`. Returned in `NumericAttributePtr`. The number of columns available in the /// result set. This returns 0 if there are no columns in the result set. The value in the /// `column_number` argument is ignored. Count = 1001, /// `SQL_DESC_TYPE`. Retruned in `NumericAttributePtr`. A numeric value that specifies the SQL /// data type. When ColumnNumber is equal to 0, SQL_BINARY is returned for variable-length /// bookmarks and SQL_INTEGER is returned for fixed-length bookmarks. For the datetime and /// interval data types, this field returns the verbose data type: SQL_DATETIME or SQL_INTERVAL. /// Note: To work against ODBC 2.x drivers, use `SQL_DESC_CONCISE_TYPE` instead. Type = 1002, /// `SQL_DESC_LENGTH`. Returned in `NumericAttributePtr`. A numeric value that is either the /// maximum or actual character length of a character string or binary data type. It is the /// maximum character length for a fixed-length data type, or the actual character length for a /// variable-length data type. Its value always excludes the null-termination byte that ends the /// character string. Length = 1003, /// `SQL_DESC_OCTET_LENGTH_PTR`. OctetLengthPtr = 1004, /// `SQL_DESC_PRECISION`. Returned in `NumericAttributePtr`. A numeric value that for a numeric /// data type denotes the applicable precision. For data types SQL_TYPE_TIME, /// SQL_TYPE_TIMESTAMP, and all the interval data types that represent a time interval, its /// value is the applicable precision of the fractional seconds component. Precision = 1005, /// `SQL_DESC_SCALE`. Returned in `NumericAttributePtr`. A numeric value that is the applicable /// scale for a numeric data type. For DECIMAL and NUMERIC data types, this is the defined /// scale. It is undefined for all other data types. Scale = 1006, /// `SQL_DESC_DATETIME_INTERVAL_CODE`. DatetimeIntervalCode = 1007, /// `SQL_DESC_NULLABLE`. Returned in `NumericAttributePtr`. `SQL_ NULLABLE` if the column can /// have NULL values; SQL_NO_NULLS if the column does not have NULL values; or /// SQL_NULLABLE_UNKNOWN if it is not known whether the column accepts NULL values. Nullable = 1008, /// `SQL_DESC_INDICATOR_PTR` IndicatorPtr = 1009, /// `SQL_DESC_DATA_PTR`. DataPtr = 1010, /// `SQL_DESC_NAME`. Returned in `CharacterAttributePtr`. The column alias, if it applies. If /// the column alias does not apply, the column name is returned. In either case, /// SQL_DESC_UNNAMED is set to SQL_NAMED. If there is no column name or a column alias, an empty /// string is returned and SQL_DESC_UNNAMED is set to SQL_UNNAMED. Name = 1011, /// `SQL_DESC_UNNAMED`. Returned in `NumericAttributePtr`. SQL_NAMED or SQL_UNNAMED. If the /// SQL_DESC_NAME field of the IRD contains a column alias or a column name, SQL_NAMED is /// returned. If there is no column name or column alias, SQL_UNNAMED is returned. Unnamed = 1012, /// `SQL_DESC_OCTET_LENGTH`. Returned in `NumericAttributePtr`. The length, in bytes, of a /// character string or binary data type. For fixed-length character or binary types, this is /// the actual length in bytes. For variable-length character or binary types, this is the /// maximum length in bytes. This value does not include the null terminator. OctetLength = 1013, /// `SQL_DESC_ALLOC_TYPE`. AllocType = 1099, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_CHARACTER_SET_CATALOG`. CharacterSetCatalog = 1018, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_CHARACTER_SET_SCHEMA` CharacterSetSchema = 1019, #[cfg(feature = "odbc_version_4")] // `SQL_DESC_CHARACTER_SET_NAME`. #[cfg(feature = "odbc_version_4")] CharacterSetName = 1020, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_COLLATION_CATALOG` CollationCatalog = 1015, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_COLLATION_SCHEMA` CollationSchema = 1016, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_COLLATION_NAME` CollationName = 1017, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_USER_DEFINED_TYPE_CATALOG` UserDefinedTypeCatalog = 1026, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_USER_DEFINED_TYPE_SCHEMA`. UserDefinedTypeSchema = 1027, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_USER_DEFINED_TYPE_NAME`. UserDefinedTypeName = 1028, // Extended Descriptors /// `SQL_DESC_ARRAY_SIZE` ArraySize = 20, /// `SQL_DESC_ARRAY_STATUS_PTR` ArrayStatusPtr = 21, /// `SQL_DESC_AUTO_UNIQUE_VALUE`. Returned in `NumericAttributePtr`. `true` if the column is an /// autoincrementing column. `false` if the column is not an autoincrementing column or is not /// numeric. This field is valid for numeric data type columns only. An application can insert /// values into a row containing an autoincrement column, but typically cannot update values in /// the column. When an insert is made into an autoincrement column, a unique value is inserted /// into the column at insert time. The increment is not defined, but is data source-specific. /// An application should not assume that an autoincrement column starts at any particular point /// or increments by any particular value. AutoUniqueValue = 11, /// `SQL_DESC_BASE_COLUMN_NAME`. Returned in `CharacterAttributePtr`. The base column name for /// the result set column. If a base column name does not exist (as in the case of columns that /// are expressions), then this variable contains an empty string. BaseColumnName = 22, /// `SQL_DESC_BASE_TABLE_NAME`. Returned in `CharacterAttributePtr`. The name of the base table /// that contains the column. If the base table name cannot be defined or is not applicable, /// then this variable contains an empty string. BaseTableName = 23, /// `SQL_DESC_BIND_OFFSET_PTR`. BindOffsetPtr = 24, /// `SQL_DESC_BIND_TYPE`. BindType = 25, /// `SQL_DESC_CASE_SENSITIVE`. Returned in `NumericAttributePtr`. `true` if the column is /// treated as case-sensitive for collations and comparisons. `false` if the column is not /// treated as case-sensitive for collations and comparisons or is noncharacter. CaseSensitive = 12, /// `SQL_DESC_CATALOG_NAME`. Returned in `CharacterAttributePtr`. The catalog of the table that /// contains the column. The returned value is implementation-defined if the column is an /// expression or if the column is part of a view. If the data source does not support catalogs /// or the catalog name cannot be determined, an empty string is returned. This VARCHAR record /// field is not limited to 128 characters. CatalogName = 17, /// `SQL_DESC_CONCISE_TYPE`. Returned in `NumericAttributePtr`. The concise data type. For the /// datetime and interval data types, this field returns the concise data type; for example, /// SQL_TYPE_TIME or SQL_INTERVAL_YEAR. ConciseType = 2, /// `SQL_DESC_DATETIME_INTERVAL_PRECISION` DatetimeIntervalPrecision = 26, /// `SQL_DESC_DISPLAY_SIZE`. Returned in `NumericAttributePtr`. Maximum number of characters /// required to display data from the column. DisplaySize = 6, /// `SQL_DESC_FIXED_PREC_SCALE`. Returned in `NumericAttributePtr`. `true` if the column has a /// fixed precision and nonzero scale that are data source-specific. `false` if the column does /// not have a fixed precision and nonzero scale that are data source-specific. FixedPrecScale = 9, /// `SQL_DESC_LABEL`. Returned in `CharacterAttributePtr`. The column label or title. For /// example, a column named EmpName might be labeled Employee Name or might be labeled with an /// alias. If a column does not have a label, the column name is returned. If the column is /// unlabeled and unnamed, an empty string is returned. Label = 18, /// `SQL_DESC_LITERAL_PREFIX`. Returned in `CharacterAttributePtr`. This VARCHAR(128) record /// field contains the character or characters that the driver recognizes as a prefix for a /// literal of this data type. This field contains an empty string for a data type for which a /// literal prefix is not applicable. LiteralPrefix = 27, /// `SQL_DESC_LITERAL_SUFFIX`. Returned in `CharacterAttributePtr`. This VARCHAR(128) record /// field contains the character or characters that the driver recognizes as a suffix for a /// literal of this data type. This field contains an empty string for a data type for which a /// literal suffix is not applicable. LiteralSuffix = 28, /// `SQL_DESC_LOCAL_TYPE_NAME`. Returned in `CharacterAttributePtr`. This VARCHAR(128) record /// field contains any localized (native language) name for the data type that may be different /// from the regular name of the data type. If there is no localized name, then an empty string /// is returned. This field is for display purposes only. The character set of the string is /// locale-dependent and is typically the default character set of the server. LocalTypeName = 29, /// `SQL_DESC_MAXIMUM_SCALE`. MaximumScale = 30, /// `SQL_DESC_MINIMUM_SCALE`. MinimumScale = 31, /// `SQL_DESC_NUM_PREC_RADIX`. Returned in `NumericAttributePtr`. If the data type in the /// SQL_DESC_TYPE field is an approximate numeric data type, this SQLINTEGER field contains a /// value of 2 because the SQL_DESC_PRECISION field contains the number of bits. If the data /// type in the SQL_DESC_TYPE field is an exact numeric data type, this field contains a value /// of 10 because the SQL_DESC_PRECISION field contains the number of decimal digits. This field /// is set to 0 for all non-numeric data types. NumPrecRadix = 32, /// `SQL_DESC_PARAMETER_TYPE`. ParameterType = 33, /// `SQL_DESC_ROWS_PROCESSED_PTR`. RowsProcessedPtr = 34, #[cfg(feature = "odbc_version_3_50")] /// `SQL_DESC_ROWVER`. RowVer = 35, /// `SQL_DESC_SCHEMA_NAME`. Returned in `CharacterAttributePtr`. The schema of the table that /// contains the column. The returned value is implementation-defined if the column is an /// expression or if the column is part of a view. If the data source does not support schemas /// or the schema name cannot be determined, an empty string is returned. This VARCHAR record /// field is not limited to 128 characters. SchemaName = 16, /// `SQL_DESC_SEARCHABLE`. Returned in `NumericAttributePtr`. `SQL_PRED_NONE` if the column /// cannot be used in a WHERE clause. `SQL_PRED_CHAR` if the column can be used in a WHERE /// clause but only with the LIKE predicate. `SQL_PRED_BASIC` if the column can be used in a /// WHERE clause with all the comparison operators except LIKE. `SQL_PRED_SEARCHABLE` if the /// column can be used in a WHERE clause with any comparison operator. Columns of type /// `SQL_LONGVARCHAR` and `SQL_LONGVARBINARY` usually return `SQL_PRED_CHAR`. Searchable = 13, /// `SQL_DESC_TYPE_NAME`. Returned in `CharacterAttributePtr`. Data source-dependent data type /// name; for example, "CHAR", "VARCHAR", "MONEY", "LONG VARBINARY", or "CHAR ( ) FOR BIT DATA". /// If the type is unknown, an empty string is returned. TypeName = 14, /// `SQL_DESC_TABLE_NAME`. Returned in `CharacterAttributePtr`. The name of the table that /// contains the column. The returned value is implementation-defined if the column is an /// expression or if the column is part of a view. If the table name can not be determined an /// empty string is returned. TableName = 15, /// `SQL_DESC_UNSIGNED`. Returned in `NumericAttributePtr`. `true` if the column is unsigned (or /// not numeric). `false` if the column is signed. Unsigned = 8, /// `SQL_DESC_UPDATABLE`. Returned in `NumericAttributePtr`. Column is described by the values /// for the defined constants: `SQL_ATTR_READONLY`, `SQL_ATTR_WRITE`, /// `SQL_ATTR_READWRITE_UNKNOWN`. /// `Updatable` Describes the updatability of the column in the result set, not the column in /// the base table. The updatability of the base column on which the result set column is based /// may be different from the value in this field. Whether a column is updatable can be based on /// the data type, user privileges, and the definition of the result set itself. If it is /// unclear whether a column is updatable, `SQL_ATTR_READWRITE_UNKNOWN` should be returned. Updatable = 10, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_MIME_TYPE`. MimeType = 36, }
Desc
identifier_name
desc.rs
/// Used in `SQLColAttributeW`. #[repr(u16)] #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Desc { /// `SQL_DESC_COUNT`. Returned in `NumericAttributePtr`. The number of columns available in the /// result set. This returns 0 if there are no columns in the result set. The value in the /// `column_number` argument is ignored. Count = 1001, /// `SQL_DESC_TYPE`. Retruned in `NumericAttributePtr`. A numeric value that specifies the SQL /// data type. When ColumnNumber is equal to 0, SQL_BINARY is returned for variable-length /// bookmarks and SQL_INTEGER is returned for fixed-length bookmarks. For the datetime and /// interval data types, this field returns the verbose data type: SQL_DATETIME or SQL_INTERVAL. /// Note: To work against ODBC 2.x drivers, use `SQL_DESC_CONCISE_TYPE` instead. Type = 1002, /// `SQL_DESC_LENGTH`. Returned in `NumericAttributePtr`. A numeric value that is either the /// maximum or actual character length of a character string or binary data type. It is the /// maximum character length for a fixed-length data type, or the actual character length for a /// variable-length data type. Its value always excludes the null-termination byte that ends the /// character string. Length = 1003, /// `SQL_DESC_OCTET_LENGTH_PTR`. OctetLengthPtr = 1004, /// `SQL_DESC_PRECISION`. Returned in `NumericAttributePtr`. A numeric value that for a numeric /// data type denotes the applicable precision. For data types SQL_TYPE_TIME, /// SQL_TYPE_TIMESTAMP, and all the interval data types that represent a time interval, its /// value is the applicable precision of the fractional seconds component. Precision = 1005, /// `SQL_DESC_SCALE`. Returned in `NumericAttributePtr`. A numeric value that is the applicable /// scale for a numeric data type. For DECIMAL and NUMERIC data types, this is the defined /// scale. It is undefined for all other data types. Scale = 1006, /// `SQL_DESC_DATETIME_INTERVAL_CODE`. DatetimeIntervalCode = 1007, /// `SQL_DESC_NULLABLE`. Returned in `NumericAttributePtr`. `SQL_ NULLABLE` if the column can /// have NULL values; SQL_NO_NULLS if the column does not have NULL values; or /// SQL_NULLABLE_UNKNOWN if it is not known whether the column accepts NULL values. Nullable = 1008, /// `SQL_DESC_INDICATOR_PTR` IndicatorPtr = 1009, /// `SQL_DESC_DATA_PTR`. DataPtr = 1010, /// `SQL_DESC_NAME`. Returned in `CharacterAttributePtr`. The column alias, if it applies. If /// the column alias does not apply, the column name is returned. In either case, /// SQL_DESC_UNNAMED is set to SQL_NAMED. If there is no column name or a column alias, an empty /// string is returned and SQL_DESC_UNNAMED is set to SQL_UNNAMED. Name = 1011, /// `SQL_DESC_UNNAMED`. Returned in `NumericAttributePtr`. SQL_NAMED or SQL_UNNAMED. If the /// SQL_DESC_NAME field of the IRD contains a column alias or a column name, SQL_NAMED is /// returned. If there is no column name or column alias, SQL_UNNAMED is returned. Unnamed = 1012, /// `SQL_DESC_OCTET_LENGTH`. Returned in `NumericAttributePtr`. The length, in bytes, of a /// character string or binary data type. For fixed-length character or binary types, this is /// the actual length in bytes. For variable-length character or binary types, this is the /// maximum length in bytes. This value does not include the null terminator. OctetLength = 1013, /// `SQL_DESC_ALLOC_TYPE`. AllocType = 1099, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_CHARACTER_SET_CATALOG`. CharacterSetCatalog = 1018, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_CHARACTER_SET_SCHEMA` CharacterSetSchema = 1019, #[cfg(feature = "odbc_version_4")] // `SQL_DESC_CHARACTER_SET_NAME`. #[cfg(feature = "odbc_version_4")] CharacterSetName = 1020, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_COLLATION_CATALOG` CollationCatalog = 1015, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_COLLATION_SCHEMA` CollationSchema = 1016, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_COLLATION_NAME` CollationName = 1017, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_USER_DEFINED_TYPE_CATALOG` UserDefinedTypeCatalog = 1026, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_USER_DEFINED_TYPE_SCHEMA`. UserDefinedTypeSchema = 1027, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_USER_DEFINED_TYPE_NAME`. UserDefinedTypeName = 1028, // Extended Descriptors /// `SQL_DESC_ARRAY_SIZE` ArraySize = 20, /// `SQL_DESC_ARRAY_STATUS_PTR` ArrayStatusPtr = 21, /// `SQL_DESC_AUTO_UNIQUE_VALUE`. Returned in `NumericAttributePtr`. `true` if the column is an /// autoincrementing column. `false` if the column is not an autoincrementing column or is not /// numeric. This field is valid for numeric data type columns only. An application can insert /// values into a row containing an autoincrement column, but typically cannot update values in /// the column. When an insert is made into an autoincrement column, a unique value is inserted /// into the column at insert time. The increment is not defined, but is data source-specific. /// An application should not assume that an autoincrement column starts at any particular point /// or increments by any particular value. AutoUniqueValue = 11, /// `SQL_DESC_BASE_COLUMN_NAME`. Returned in `CharacterAttributePtr`. The base column name for /// the result set column. If a base column name does not exist (as in the case of columns that /// are expressions), then this variable contains an empty string. BaseColumnName = 22, /// `SQL_DESC_BASE_TABLE_NAME`. Returned in `CharacterAttributePtr`. The name of the base table /// that contains the column. If the base table name cannot be defined or is not applicable, /// then this variable contains an empty string. BaseTableName = 23, /// `SQL_DESC_BIND_OFFSET_PTR`. BindOffsetPtr = 24, /// `SQL_DESC_BIND_TYPE`. BindType = 25, /// `SQL_DESC_CASE_SENSITIVE`. Returned in `NumericAttributePtr`. `true` if the column is /// treated as case-sensitive for collations and comparisons. `false` if the column is not /// treated as case-sensitive for collations and comparisons or is noncharacter. CaseSensitive = 12, /// `SQL_DESC_CATALOG_NAME`. Returned in `CharacterAttributePtr`. The catalog of the table that /// contains the column. The returned value is implementation-defined if the column is an /// expression or if the column is part of a view. If the data source does not support catalogs /// or the catalog name cannot be determined, an empty string is returned. This VARCHAR record /// field is not limited to 128 characters. CatalogName = 17, /// `SQL_DESC_CONCISE_TYPE`. Returned in `NumericAttributePtr`. The concise data type. For the /// datetime and interval data types, this field returns the concise data type; for example, /// SQL_TYPE_TIME or SQL_INTERVAL_YEAR. ConciseType = 2, /// `SQL_DESC_DATETIME_INTERVAL_PRECISION` DatetimeIntervalPrecision = 26, /// `SQL_DESC_DISPLAY_SIZE`. Returned in `NumericAttributePtr`. Maximum number of characters /// required to display data from the column. DisplaySize = 6, /// `SQL_DESC_FIXED_PREC_SCALE`. Returned in `NumericAttributePtr`. `true` if the column has a /// fixed precision and nonzero scale that are data source-specific. `false` if the column does /// not have a fixed precision and nonzero scale that are data source-specific. FixedPrecScale = 9, /// `SQL_DESC_LABEL`. Returned in `CharacterAttributePtr`. The column label or title. For /// example, a column named EmpName might be labeled Employee Name or might be labeled with an /// alias. If a column does not have a label, the column name is returned. If the column is /// unlabeled and unnamed, an empty string is returned. Label = 18, /// `SQL_DESC_LITERAL_PREFIX`. Returned in `CharacterAttributePtr`. This VARCHAR(128) record /// field contains the character or characters that the driver recognizes as a prefix for a /// literal of this data type. This field contains an empty string for a data type for which a /// literal prefix is not applicable. LiteralPrefix = 27, /// `SQL_DESC_LITERAL_SUFFIX`. Returned in `CharacterAttributePtr`. This VARCHAR(128) record /// field contains the character or characters that the driver recognizes as a suffix for a /// literal of this data type. This field contains an empty string for a data type for which a /// literal suffix is not applicable. LiteralSuffix = 28, /// `SQL_DESC_LOCAL_TYPE_NAME`. Returned in `CharacterAttributePtr`. This VARCHAR(128) record /// field contains any localized (native language) name for the data type that may be different /// from the regular name of the data type. If there is no localized name, then an empty string /// is returned. This field is for display purposes only. The character set of the string is /// locale-dependent and is typically the default character set of the server. LocalTypeName = 29, /// `SQL_DESC_MAXIMUM_SCALE`. MaximumScale = 30, /// `SQL_DESC_MINIMUM_SCALE`. MinimumScale = 31, /// `SQL_DESC_NUM_PREC_RADIX`. Returned in `NumericAttributePtr`. If the data type in the /// SQL_DESC_TYPE field is an approximate numeric data type, this SQLINTEGER field contains a /// value of 2 because the SQL_DESC_PRECISION field contains the number of bits. If the data /// type in the SQL_DESC_TYPE field is an exact numeric data type, this field contains a value /// of 10 because the SQL_DESC_PRECISION field contains the number of decimal digits. This field /// is set to 0 for all non-numeric data types. NumPrecRadix = 32, /// `SQL_DESC_PARAMETER_TYPE`.
/// `SQL_DESC_ROWS_PROCESSED_PTR`. RowsProcessedPtr = 34, #[cfg(feature = "odbc_version_3_50")] /// `SQL_DESC_ROWVER`. RowVer = 35, /// `SQL_DESC_SCHEMA_NAME`. Returned in `CharacterAttributePtr`. The schema of the table that /// contains the column. The returned value is implementation-defined if the column is an /// expression or if the column is part of a view. If the data source does not support schemas /// or the schema name cannot be determined, an empty string is returned. This VARCHAR record /// field is not limited to 128 characters. SchemaName = 16, /// `SQL_DESC_SEARCHABLE`. Returned in `NumericAttributePtr`. `SQL_PRED_NONE` if the column /// cannot be used in a WHERE clause. `SQL_PRED_CHAR` if the column can be used in a WHERE /// clause but only with the LIKE predicate. `SQL_PRED_BASIC` if the column can be used in a /// WHERE clause with all the comparison operators except LIKE. `SQL_PRED_SEARCHABLE` if the /// column can be used in a WHERE clause with any comparison operator. Columns of type /// `SQL_LONGVARCHAR` and `SQL_LONGVARBINARY` usually return `SQL_PRED_CHAR`. Searchable = 13, /// `SQL_DESC_TYPE_NAME`. Returned in `CharacterAttributePtr`. Data source-dependent data type /// name; for example, "CHAR", "VARCHAR", "MONEY", "LONG VARBINARY", or "CHAR ( ) FOR BIT DATA". /// If the type is unknown, an empty string is returned. TypeName = 14, /// `SQL_DESC_TABLE_NAME`. Returned in `CharacterAttributePtr`. The name of the table that /// contains the column. The returned value is implementation-defined if the column is an /// expression or if the column is part of a view. If the table name can not be determined an /// empty string is returned. TableName = 15, /// `SQL_DESC_UNSIGNED`. Returned in `NumericAttributePtr`. `true` if the column is unsigned (or /// not numeric). `false` if the column is signed. Unsigned = 8, /// `SQL_DESC_UPDATABLE`. Returned in `NumericAttributePtr`. Column is described by the values /// for the defined constants: `SQL_ATTR_READONLY`, `SQL_ATTR_WRITE`, /// `SQL_ATTR_READWRITE_UNKNOWN`. /// `Updatable` Describes the updatability of the column in the result set, not the column in /// the base table. The updatability of the base column on which the result set column is based /// may be different from the value in this field. Whether a column is updatable can be based on /// the data type, user privileges, and the definition of the result set itself. If it is /// unclear whether a column is updatable, `SQL_ATTR_READWRITE_UNKNOWN` should be returned. Updatable = 10, #[cfg(feature = "odbc_version_4")] /// `SQL_DESC_MIME_TYPE`. MimeType = 36, }
ParameterType = 33,
random_line_split
counter.rs
// 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::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; /// Naive implementation of a `Counter`. #[derive(Debug)] pub struct StdCounter { /// The counter value. value: AtomicUsize, } /// A snapshot of the current value of a `Counter`. #[derive(Debug)] pub struct CounterSnapshot { /// The snapshot of the counter value. pub value: usize, } /// `Counter` is a `Metric` that represents a single numerical value that can /// increases over time. pub trait Counter: Send + Sync { /// Clear the counter, setting the value to `0`. fn clear(&self);
fn add(&self, value: usize); /// Take a snapshot of the current value for use with a `Reporter`. fn snapshot(&self) -> CounterSnapshot; } impl Counter for StdCounter { fn clear(&self) { self.value.store(0, Ordering::Relaxed); } fn inc(&self) { self.value.fetch_add(1, Ordering::Relaxed); } fn add(&self, value: usize) { self.value.fetch_add(value, Ordering::Relaxed); } fn snapshot(&self) -> CounterSnapshot { CounterSnapshot { value: self.value.load(Ordering::Relaxed) } } } impl StdCounter { /// Create a new `StdCounter`. pub fn new() -> Arc<Self> { Arc::new(Self::default()) } } impl Default for StdCounter { fn default() -> Self { StdCounter { value: AtomicUsize::new(0) } } } #[cfg(test)] mod test { use super::*; #[test] fn a_counting_counter() { let c = StdCounter::new(); c.add(1); assert_eq!(c.snapshot().value, 1); let c = StdCounter::new(); c.inc(); assert_eq!(c.snapshot().value, 1); } #[test] fn validate_snapshots() { let c = StdCounter::new(); let snapshot_1 = c.snapshot(); c.add(1); let snapshot_2 = c.snapshot(); assert_eq!(snapshot_1.value, 0); assert_eq!(snapshot_2.value, 1); } }
/// Increment the counter by 1. fn inc(&self); /// Increment the counter by the given amount. MUST check that v >= 0.
random_line_split