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
borrowck-assign-comp-idx.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. struct Point { x: isize, y: isize, } fn a() { let mut p = vec![1]; // Create an immutable pointer into p's contents: let q: &isize = &p[0]; p[0] = 5; //~ ERROR cannot borrow println!("{}", *q); } fn borrow<F>(_x: &[isize], _f: F) where F: FnOnce() {} fn b() { // here we alias the mutable vector into an imm slice and try to // modify the original: let mut p = vec![1]; borrow( &p, || p[0] = 5); //~ ERROR cannot borrow `p` as mutable } fn c() { // Legal because the scope of the borrow does not include the // modification: let mut p = vec![1]; borrow(&p, ||{}); p[0] = 5; } fn main()
{ }
identifier_body
borrowck-assign-comp-idx.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. struct Point { x: isize, y: isize, } fn a() { let mut p = vec![1]; // Create an immutable pointer into p's contents: let q: &isize = &p[0]; p[0] = 5; //~ ERROR cannot borrow println!("{}", *q); } fn borrow<F>(_x: &[isize], _f: F) where F: FnOnce() {} fn b() { // here we alias the mutable vector into an imm slice and try to // modify the original: let mut p = vec![1]; borrow( &p, || p[0] = 5); //~ ERROR cannot borrow `p` as mutable } fn c() { // Legal because the scope of the borrow does not include the // modification: let mut p = vec![1]; borrow(&p, ||{}); p[0] = 5;
fn main() { }
}
random_line_split
borrowck-assign-comp-idx.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. struct Point { x: isize, y: isize, } fn a() { let mut p = vec![1]; // Create an immutable pointer into p's contents: let q: &isize = &p[0]; p[0] = 5; //~ ERROR cannot borrow println!("{}", *q); } fn
<F>(_x: &[isize], _f: F) where F: FnOnce() {} fn b() { // here we alias the mutable vector into an imm slice and try to // modify the original: let mut p = vec![1]; borrow( &p, || p[0] = 5); //~ ERROR cannot borrow `p` as mutable } fn c() { // Legal because the scope of the borrow does not include the // modification: let mut p = vec![1]; borrow(&p, ||{}); p[0] = 5; } fn main() { }
borrow
identifier_name
objc_protocol_inheritance.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![cfg(target_os = "macos")] #[macro_use] extern crate objc; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; pub trait PFoo: Sized + std::ops::Deref {} #[repr(transparent)] #[derive(Clone)] pub struct Foo(pub id);
fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Foo {} impl Foo { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Foo), alloc) }) } } impl PFoo for Foo {} impl IFoo for Foo {} pub trait IFoo: Sized + std::ops::Deref {} #[repr(transparent)] #[derive(Clone)] pub struct Bar(pub id); impl std::ops::Deref for Bar { type Target = objc::runtime::Object; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Bar {} impl Bar { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Bar), alloc) }) } } impl IFoo for Bar {} impl PFoo for Bar {} impl From<Bar> for Foo { fn from(child: Bar) -> Foo { Foo(child.0) } } impl std::convert::TryFrom<Foo> for Bar { type Error = &'static str; fn try_from(parent: Foo) -> Result<Bar, Self::Error> { let is_kind_of: bool = unsafe { msg_send!(parent, isKindOfClass: class!(Bar)) }; if is_kind_of { Ok(Bar(parent.0)) } else { Err("This Foo cannot be downcasted to Bar") } } } impl IBar for Bar {} pub trait IBar: Sized + std::ops::Deref {}
impl std::ops::Deref for Foo { type Target = objc::runtime::Object;
random_line_split
objc_protocol_inheritance.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![cfg(target_os = "macos")] #[macro_use] extern crate objc; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; pub trait PFoo: Sized + std::ops::Deref {} #[repr(transparent)] #[derive(Clone)] pub struct Foo(pub id); impl std::ops::Deref for Foo { type Target = objc::runtime::Object; fn deref(&self) -> &Self::Target
} unsafe impl objc::Message for Foo {} impl Foo { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Foo), alloc) }) } } impl PFoo for Foo {} impl IFoo for Foo {} pub trait IFoo: Sized + std::ops::Deref {} #[repr(transparent)] #[derive(Clone)] pub struct Bar(pub id); impl std::ops::Deref for Bar { type Target = objc::runtime::Object; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Bar {} impl Bar { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Bar), alloc) }) } } impl IFoo for Bar {} impl PFoo for Bar {} impl From<Bar> for Foo { fn from(child: Bar) -> Foo { Foo(child.0) } } impl std::convert::TryFrom<Foo> for Bar { type Error = &'static str; fn try_from(parent: Foo) -> Result<Bar, Self::Error> { let is_kind_of: bool = unsafe { msg_send!(parent, isKindOfClass: class!(Bar)) }; if is_kind_of { Ok(Bar(parent.0)) } else { Err("This Foo cannot be downcasted to Bar") } } } impl IBar for Bar {} pub trait IBar: Sized + std::ops::Deref {}
{ unsafe { &*self.0 } }
identifier_body
objc_protocol_inheritance.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![cfg(target_os = "macos")] #[macro_use] extern crate objc; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; pub trait PFoo: Sized + std::ops::Deref {} #[repr(transparent)] #[derive(Clone)] pub struct Foo(pub id); impl std::ops::Deref for Foo { type Target = objc::runtime::Object; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Foo {} impl Foo { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Foo), alloc) }) } } impl PFoo for Foo {} impl IFoo for Foo {} pub trait IFoo: Sized + std::ops::Deref {} #[repr(transparent)] #[derive(Clone)] pub struct
(pub id); impl std::ops::Deref for Bar { type Target = objc::runtime::Object; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Bar {} impl Bar { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Bar), alloc) }) } } impl IFoo for Bar {} impl PFoo for Bar {} impl From<Bar> for Foo { fn from(child: Bar) -> Foo { Foo(child.0) } } impl std::convert::TryFrom<Foo> for Bar { type Error = &'static str; fn try_from(parent: Foo) -> Result<Bar, Self::Error> { let is_kind_of: bool = unsafe { msg_send!(parent, isKindOfClass: class!(Bar)) }; if is_kind_of { Ok(Bar(parent.0)) } else { Err("This Foo cannot be downcasted to Bar") } } } impl IBar for Bar {} pub trait IBar: Sized + std::ops::Deref {}
Bar
identifier_name
objc_protocol_inheritance.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![cfg(target_os = "macos")] #[macro_use] extern crate objc; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; pub trait PFoo: Sized + std::ops::Deref {} #[repr(transparent)] #[derive(Clone)] pub struct Foo(pub id); impl std::ops::Deref for Foo { type Target = objc::runtime::Object; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Foo {} impl Foo { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Foo), alloc) }) } } impl PFoo for Foo {} impl IFoo for Foo {} pub trait IFoo: Sized + std::ops::Deref {} #[repr(transparent)] #[derive(Clone)] pub struct Bar(pub id); impl std::ops::Deref for Bar { type Target = objc::runtime::Object; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Bar {} impl Bar { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Bar), alloc) }) } } impl IFoo for Bar {} impl PFoo for Bar {} impl From<Bar> for Foo { fn from(child: Bar) -> Foo { Foo(child.0) } } impl std::convert::TryFrom<Foo> for Bar { type Error = &'static str; fn try_from(parent: Foo) -> Result<Bar, Self::Error> { let is_kind_of: bool = unsafe { msg_send!(parent, isKindOfClass: class!(Bar)) }; if is_kind_of
else { Err("This Foo cannot be downcasted to Bar") } } } impl IBar for Bar {} pub trait IBar: Sized + std::ops::Deref {}
{ Ok(Bar(parent.0)) }
conditional_block
regions-implied-bounds-projection-gap-2.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. // Along with the other tests in this series, illustrates the // "projection gap": in this test, we know that `T: 'x`, and that is
#![allow(unused_variables)] trait Trait1<'x> { type Foo; } // calling this fn should trigger a check that the type argument // supplied is well-formed. fn wf<T>() { } fn func<'x, T:Trait1<'x>>(t: &'x T) { wf::<&'x T::Foo>(); } fn main() { }
// enough to conclude that `T::Foo: 'x`. // compile-pass #![allow(dead_code)]
random_line_split
regions-implied-bounds-projection-gap-2.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. // Along with the other tests in this series, illustrates the // "projection gap": in this test, we know that `T: 'x`, and that is // enough to conclude that `T::Foo: 'x`. // compile-pass #![allow(dead_code)] #![allow(unused_variables)] trait Trait1<'x> { type Foo; } // calling this fn should trigger a check that the type argument // supplied is well-formed. fn wf<T>() { } fn func<'x, T:Trait1<'x>>(t: &'x T) { wf::<&'x T::Foo>(); } fn
() { }
main
identifier_name
regions-implied-bounds-projection-gap-2.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. // Along with the other tests in this series, illustrates the // "projection gap": in this test, we know that `T: 'x`, and that is // enough to conclude that `T::Foo: 'x`. // compile-pass #![allow(dead_code)] #![allow(unused_variables)] trait Trait1<'x> { type Foo; } // calling this fn should trigger a check that the type argument // supplied is well-formed. fn wf<T>() { } fn func<'x, T:Trait1<'x>>(t: &'x T)
fn main() { }
{ wf::<&'x T::Foo>(); }
identifier_body
enable_transparency.rs
use super::internal_prelude::*; use imageflow_types::{PixelFormat, CompositingMode}; use crate::ffi::BitmapCompositingMode; use crate::graphics::bitmaps::BitmapCompositing; pub static ENABLE_TRANSPARENCY: EnableTransparencyDef = EnableTransparencyDef{}; pub static ENABLE_TRANSPARENCY_MUT: EnableTransparencyMutDef = EnableTransparencyMutDef{}; #[derive(Debug,Clone)] pub struct EnableTransparencyDef; impl NodeDef for EnableTransparencyDef{ fn as_one_input_expand(&self) -> Option<&dyn NodeDefOneInputExpand>{ Some(self) } } impl NodeDefOneInputExpand for EnableTransparencyDef{ fn fqn(&self) -> &'static str{ "imazen.enable_transparency" } fn expand(&self, ctx: &mut OpCtxMut, ix: NodeIndex, p: NodeParams, parent: FrameInfo) -> Result<()> { if parent.fmt == PixelFormat::Bgra32
else if parent.fmt == PixelFormat::Bgr32 { let mutate = ctx.graph .add_node(Node::n(&ENABLE_TRANSPARENCY_MUT, NodeParams::None)); ctx.replace_node_with_existing(ix, mutate); Ok(()) } else { let canvas_params = imageflow_types::Node::CreateCanvas { w: parent.h as usize, h: parent.w as usize, format: PixelFormat::Bgra32, color: imageflow_types::Color::Transparent, }; let copy_rect_params = imageflow_types::Node::CopyRectToCanvas { from_x: 0, from_y: 0, w: parent.w as u32, h: parent.h as u32, x: 0, y: 0 }; let canvas = ctx.graph .add_node(Node::n(&CREATE_CANVAS, NodeParams::Json(canvas_params))); let copy = ctx.graph .add_node(Node::n(&COPY_RECT, NodeParams::Json(copy_rect_params))); ctx.graph.add_edge(canvas, copy, EdgeKind::Canvas).unwrap(); ctx.replace_node_with_existing(ix, copy); Ok(()) } } } #[derive(Debug, Clone)] pub struct EnableTransparencyMutDef; impl NodeDef for EnableTransparencyMutDef{ fn as_one_mutate_bitmap(&self) -> Option<&dyn NodeDefMutateBitmap>{ Some(self) } } impl NodeDefMutateBitmap for EnableTransparencyMutDef{ fn fqn(&self) -> &'static str{ "imazen.enable_transparency_mut" } fn mutate(&self, c: &Context, bitmap_key: BitmapKey, p: &NodeParams) -> Result<()> { let bitmaps = c.borrow_bitmaps() .map_err(|e| e.at(here!()))?; let mut bitmap_bitmap = bitmaps.try_borrow_mut(bitmap_key) .map_err(|e| e.at(here!()))?; if bitmap_bitmap.info().alpha_meaningful(){ Err(nerror!(crate::ErrorKind::InvalidNodeConnections, "Need Bgr32 input image to convert to bgra32")) }else{ let mut bitmap = unsafe { bitmap_bitmap.get_window_u8().unwrap().to_bitmap_bgra()? }; bitmap.normalize_alpha()?; bitmap_bitmap.set_alpha_meaningful(true); bitmap_bitmap.set_compositing(BitmapCompositing::BlendWithSelf); Ok(()) } } }
{ ctx.delete_node_and_snap_together(ix); Ok(()) }
conditional_block
enable_transparency.rs
use super::internal_prelude::*; use imageflow_types::{PixelFormat, CompositingMode}; use crate::ffi::BitmapCompositingMode; use crate::graphics::bitmaps::BitmapCompositing; pub static ENABLE_TRANSPARENCY: EnableTransparencyDef = EnableTransparencyDef{}; pub static ENABLE_TRANSPARENCY_MUT: EnableTransparencyMutDef = EnableTransparencyMutDef{}; #[derive(Debug,Clone)] pub struct EnableTransparencyDef; impl NodeDef for EnableTransparencyDef{ fn as_one_input_expand(&self) -> Option<&dyn NodeDefOneInputExpand>{ Some(self) } } impl NodeDefOneInputExpand for EnableTransparencyDef{ fn fqn(&self) -> &'static str{ "imazen.enable_transparency" } fn expand(&self, ctx: &mut OpCtxMut, ix: NodeIndex, p: NodeParams, parent: FrameInfo) -> Result<()> { if parent.fmt == PixelFormat::Bgra32{ ctx.delete_node_and_snap_together(ix); Ok(()) }else if parent.fmt == PixelFormat::Bgr32 { let mutate = ctx.graph .add_node(Node::n(&ENABLE_TRANSPARENCY_MUT, NodeParams::None)); ctx.replace_node_with_existing(ix, mutate); Ok(()) } else { let canvas_params = imageflow_types::Node::CreateCanvas { w: parent.h as usize, h: parent.w as usize, format: PixelFormat::Bgra32, color: imageflow_types::Color::Transparent, }; let copy_rect_params = imageflow_types::Node::CopyRectToCanvas {
w: parent.w as u32, h: parent.h as u32, x: 0, y: 0 }; let canvas = ctx.graph .add_node(Node::n(&CREATE_CANVAS, NodeParams::Json(canvas_params))); let copy = ctx.graph .add_node(Node::n(&COPY_RECT, NodeParams::Json(copy_rect_params))); ctx.graph.add_edge(canvas, copy, EdgeKind::Canvas).unwrap(); ctx.replace_node_with_existing(ix, copy); Ok(()) } } } #[derive(Debug, Clone)] pub struct EnableTransparencyMutDef; impl NodeDef for EnableTransparencyMutDef{ fn as_one_mutate_bitmap(&self) -> Option<&dyn NodeDefMutateBitmap>{ Some(self) } } impl NodeDefMutateBitmap for EnableTransparencyMutDef{ fn fqn(&self) -> &'static str{ "imazen.enable_transparency_mut" } fn mutate(&self, c: &Context, bitmap_key: BitmapKey, p: &NodeParams) -> Result<()> { let bitmaps = c.borrow_bitmaps() .map_err(|e| e.at(here!()))?; let mut bitmap_bitmap = bitmaps.try_borrow_mut(bitmap_key) .map_err(|e| e.at(here!()))?; if bitmap_bitmap.info().alpha_meaningful(){ Err(nerror!(crate::ErrorKind::InvalidNodeConnections, "Need Bgr32 input image to convert to bgra32")) }else{ let mut bitmap = unsafe { bitmap_bitmap.get_window_u8().unwrap().to_bitmap_bgra()? }; bitmap.normalize_alpha()?; bitmap_bitmap.set_alpha_meaningful(true); bitmap_bitmap.set_compositing(BitmapCompositing::BlendWithSelf); Ok(()) } } }
from_x: 0, from_y: 0,
random_line_split
enable_transparency.rs
use super::internal_prelude::*; use imageflow_types::{PixelFormat, CompositingMode}; use crate::ffi::BitmapCompositingMode; use crate::graphics::bitmaps::BitmapCompositing; pub static ENABLE_TRANSPARENCY: EnableTransparencyDef = EnableTransparencyDef{}; pub static ENABLE_TRANSPARENCY_MUT: EnableTransparencyMutDef = EnableTransparencyMutDef{}; #[derive(Debug,Clone)] pub struct EnableTransparencyDef; impl NodeDef for EnableTransparencyDef{ fn as_one_input_expand(&self) -> Option<&dyn NodeDefOneInputExpand>{ Some(self) } } impl NodeDefOneInputExpand for EnableTransparencyDef{ fn fqn(&self) -> &'static str
fn expand(&self, ctx: &mut OpCtxMut, ix: NodeIndex, p: NodeParams, parent: FrameInfo) -> Result<()> { if parent.fmt == PixelFormat::Bgra32{ ctx.delete_node_and_snap_together(ix); Ok(()) }else if parent.fmt == PixelFormat::Bgr32 { let mutate = ctx.graph .add_node(Node::n(&ENABLE_TRANSPARENCY_MUT, NodeParams::None)); ctx.replace_node_with_existing(ix, mutate); Ok(()) } else { let canvas_params = imageflow_types::Node::CreateCanvas { w: parent.h as usize, h: parent.w as usize, format: PixelFormat::Bgra32, color: imageflow_types::Color::Transparent, }; let copy_rect_params = imageflow_types::Node::CopyRectToCanvas { from_x: 0, from_y: 0, w: parent.w as u32, h: parent.h as u32, x: 0, y: 0 }; let canvas = ctx.graph .add_node(Node::n(&CREATE_CANVAS, NodeParams::Json(canvas_params))); let copy = ctx.graph .add_node(Node::n(&COPY_RECT, NodeParams::Json(copy_rect_params))); ctx.graph.add_edge(canvas, copy, EdgeKind::Canvas).unwrap(); ctx.replace_node_with_existing(ix, copy); Ok(()) } } } #[derive(Debug, Clone)] pub struct EnableTransparencyMutDef; impl NodeDef for EnableTransparencyMutDef{ fn as_one_mutate_bitmap(&self) -> Option<&dyn NodeDefMutateBitmap>{ Some(self) } } impl NodeDefMutateBitmap for EnableTransparencyMutDef{ fn fqn(&self) -> &'static str{ "imazen.enable_transparency_mut" } fn mutate(&self, c: &Context, bitmap_key: BitmapKey, p: &NodeParams) -> Result<()> { let bitmaps = c.borrow_bitmaps() .map_err(|e| e.at(here!()))?; let mut bitmap_bitmap = bitmaps.try_borrow_mut(bitmap_key) .map_err(|e| e.at(here!()))?; if bitmap_bitmap.info().alpha_meaningful(){ Err(nerror!(crate::ErrorKind::InvalidNodeConnections, "Need Bgr32 input image to convert to bgra32")) }else{ let mut bitmap = unsafe { bitmap_bitmap.get_window_u8().unwrap().to_bitmap_bgra()? }; bitmap.normalize_alpha()?; bitmap_bitmap.set_alpha_meaningful(true); bitmap_bitmap.set_compositing(BitmapCompositing::BlendWithSelf); Ok(()) } } }
{ "imazen.enable_transparency" }
identifier_body
enable_transparency.rs
use super::internal_prelude::*; use imageflow_types::{PixelFormat, CompositingMode}; use crate::ffi::BitmapCompositingMode; use crate::graphics::bitmaps::BitmapCompositing; pub static ENABLE_TRANSPARENCY: EnableTransparencyDef = EnableTransparencyDef{}; pub static ENABLE_TRANSPARENCY_MUT: EnableTransparencyMutDef = EnableTransparencyMutDef{}; #[derive(Debug,Clone)] pub struct EnableTransparencyDef; impl NodeDef for EnableTransparencyDef{ fn as_one_input_expand(&self) -> Option<&dyn NodeDefOneInputExpand>{ Some(self) } } impl NodeDefOneInputExpand for EnableTransparencyDef{ fn fqn(&self) -> &'static str{ "imazen.enable_transparency" } fn expand(&self, ctx: &mut OpCtxMut, ix: NodeIndex, p: NodeParams, parent: FrameInfo) -> Result<()> { if parent.fmt == PixelFormat::Bgra32{ ctx.delete_node_and_snap_together(ix); Ok(()) }else if parent.fmt == PixelFormat::Bgr32 { let mutate = ctx.graph .add_node(Node::n(&ENABLE_TRANSPARENCY_MUT, NodeParams::None)); ctx.replace_node_with_existing(ix, mutate); Ok(()) } else { let canvas_params = imageflow_types::Node::CreateCanvas { w: parent.h as usize, h: parent.w as usize, format: PixelFormat::Bgra32, color: imageflow_types::Color::Transparent, }; let copy_rect_params = imageflow_types::Node::CopyRectToCanvas { from_x: 0, from_y: 0, w: parent.w as u32, h: parent.h as u32, x: 0, y: 0 }; let canvas = ctx.graph .add_node(Node::n(&CREATE_CANVAS, NodeParams::Json(canvas_params))); let copy = ctx.graph .add_node(Node::n(&COPY_RECT, NodeParams::Json(copy_rect_params))); ctx.graph.add_edge(canvas, copy, EdgeKind::Canvas).unwrap(); ctx.replace_node_with_existing(ix, copy); Ok(()) } } } #[derive(Debug, Clone)] pub struct
; impl NodeDef for EnableTransparencyMutDef{ fn as_one_mutate_bitmap(&self) -> Option<&dyn NodeDefMutateBitmap>{ Some(self) } } impl NodeDefMutateBitmap for EnableTransparencyMutDef{ fn fqn(&self) -> &'static str{ "imazen.enable_transparency_mut" } fn mutate(&self, c: &Context, bitmap_key: BitmapKey, p: &NodeParams) -> Result<()> { let bitmaps = c.borrow_bitmaps() .map_err(|e| e.at(here!()))?; let mut bitmap_bitmap = bitmaps.try_borrow_mut(bitmap_key) .map_err(|e| e.at(here!()))?; if bitmap_bitmap.info().alpha_meaningful(){ Err(nerror!(crate::ErrorKind::InvalidNodeConnections, "Need Bgr32 input image to convert to bgra32")) }else{ let mut bitmap = unsafe { bitmap_bitmap.get_window_u8().unwrap().to_bitmap_bgra()? }; bitmap.normalize_alpha()?; bitmap_bitmap.set_alpha_meaningful(true); bitmap_bitmap.set_compositing(BitmapCompositing::BlendWithSelf); Ok(()) } } }
EnableTransparencyMutDef
identifier_name
main.rs
extern crate rand; use rand::{thread_rng, Rng}; use std::io::stdin; const LOWEST: isize = 1; const HIGHEST: isize = 100; fn main()
None => println!("numbers only, please"), Some(n) if n == number => { println!("you got it in {} tries!", num_guesses); break; } Some(n) if n < number => println!("too low!"), Some(n) if n > number => println!("too high!"), Some(_) => println!("something went wrong"), } } } }
{ let mut rng = thread_rng(); loop { let number: isize = rng.gen_range(LOWEST, HIGHEST + 1); let mut num_guesses = 0; println!( "I have chosen my number between {} and {}. You know what to do", LOWEST, HIGHEST ); loop { num_guesses += 1; let mut line = String::new(); let res = stdin().read_line(&mut line); let input: Option<isize> = res.ok().and_then(|_| line.trim().parse().ok()); match input {
identifier_body
main.rs
extern crate rand; use rand::{thread_rng, Rng}; use std::io::stdin; const LOWEST: isize = 1; const HIGHEST: isize = 100; fn
() { let mut rng = thread_rng(); loop { let number: isize = rng.gen_range(LOWEST, HIGHEST + 1); let mut num_guesses = 0; println!( "I have chosen my number between {} and {}. You know what to do", LOWEST, HIGHEST ); loop { num_guesses += 1; let mut line = String::new(); let res = stdin().read_line(&mut line); let input: Option<isize> = res.ok().and_then(|_| line.trim().parse().ok()); match input { None => println!("numbers only, please"), Some(n) if n == number => { println!("you got it in {} tries!", num_guesses); break; } Some(n) if n < number => println!("too low!"), Some(n) if n > number => println!("too high!"), Some(_) => println!("something went wrong"), } } } }
main
identifier_name
main.rs
extern crate rand; use rand::{thread_rng, Rng}; use std::io::stdin; const LOWEST: isize = 1; const HIGHEST: isize = 100; fn main() { let mut rng = thread_rng(); loop { let number: isize = rng.gen_range(LOWEST, HIGHEST + 1); let mut num_guesses = 0; println!( "I have chosen my number between {} and {}. You know what to do", LOWEST, HIGHEST ); loop { num_guesses += 1; let mut line = String::new(); let res = stdin().read_line(&mut line); let input: Option<isize> = res.ok().and_then(|_| line.trim().parse().ok()); match input { None => println!("numbers only, please"), Some(n) if n == number => { println!("you got it in {} tries!", num_guesses); break; } Some(n) if n < number => println!("too low!"), Some(n) if n > number => println!("too high!"),
} } }
Some(_) => println!("something went wrong"), }
random_line_split
assistant.rs
use std::mem::transmute; use std::boxed::Box as Box_; use Assistant; use ffi; use glib::object::IsA; use glib_ffi; pub trait AssistantExtManual { fn set_forward_page_func<F: Fn(i32) -> i32 +'static>(&self, f: F); } impl<O: IsA<Assistant>> AssistantExtManual for O { fn set_forward_page_func<F: Fn(i32) -> i32 +'static>(&self, f: F) { unsafe { let f: Box_<Box_<Fn(i32) -> i32 +'static>> = Box_::new(Box_::new(f)); ffi::gtk_assistant_set_forward_page_func(self.to_glib_none().0,
} unsafe extern "C" fn forward_page_trampoline(current_page: i32, f: glib_ffi::gpointer) -> i32 { callback_guard!(); let f: &Box_<Fn(i32) -> i32 +'static> = transmute(f); f(current_page) } unsafe extern "C" fn destroy_closure(ptr: glib_ffi::gpointer) { callback_guard!(); Box_::<Box_<Fn(i32) -> i32 +'static>>::from_raw(ptr as *mut _); }
Some(forward_page_trampoline), Box_::into_raw(f) as *mut _, Some(destroy_closure)) } }
random_line_split
assistant.rs
use std::mem::transmute; use std::boxed::Box as Box_; use Assistant; use ffi; use glib::object::IsA; use glib_ffi; pub trait AssistantExtManual { fn set_forward_page_func<F: Fn(i32) -> i32 +'static>(&self, f: F); } impl<O: IsA<Assistant>> AssistantExtManual for O { fn set_forward_page_func<F: Fn(i32) -> i32 +'static>(&self, f: F) { unsafe { let f: Box_<Box_<Fn(i32) -> i32 +'static>> = Box_::new(Box_::new(f)); ffi::gtk_assistant_set_forward_page_func(self.to_glib_none().0, Some(forward_page_trampoline), Box_::into_raw(f) as *mut _, Some(destroy_closure)) } } } unsafe extern "C" fn
(current_page: i32, f: glib_ffi::gpointer) -> i32 { callback_guard!(); let f: &Box_<Fn(i32) -> i32 +'static> = transmute(f); f(current_page) } unsafe extern "C" fn destroy_closure(ptr: glib_ffi::gpointer) { callback_guard!(); Box_::<Box_<Fn(i32) -> i32 +'static>>::from_raw(ptr as *mut _); }
forward_page_trampoline
identifier_name
assistant.rs
use std::mem::transmute; use std::boxed::Box as Box_; use Assistant; use ffi; use glib::object::IsA; use glib_ffi; pub trait AssistantExtManual { fn set_forward_page_func<F: Fn(i32) -> i32 +'static>(&self, f: F); } impl<O: IsA<Assistant>> AssistantExtManual for O { fn set_forward_page_func<F: Fn(i32) -> i32 +'static>(&self, f: F) { unsafe { let f: Box_<Box_<Fn(i32) -> i32 +'static>> = Box_::new(Box_::new(f)); ffi::gtk_assistant_set_forward_page_func(self.to_glib_none().0, Some(forward_page_trampoline), Box_::into_raw(f) as *mut _, Some(destroy_closure)) } } } unsafe extern "C" fn forward_page_trampoline(current_page: i32, f: glib_ffi::gpointer) -> i32 { callback_guard!(); let f: &Box_<Fn(i32) -> i32 +'static> = transmute(f); f(current_page) } unsafe extern "C" fn destroy_closure(ptr: glib_ffi::gpointer)
{ callback_guard!(); Box_::<Box_<Fn(i32) -> i32 + 'static>>::from_raw(ptr as *mut _); }
identifier_body
test.rs
use std::thread::{self, sleep_ms}; use std::sync::{Arc}; use std::sync::atomic::{AtomicUsize}; use std::sync::atomic::Ordering::{SeqCst}; use spsc::unbounded::{new}; use super::{Select, Selectable}; fn ms_sleep(ms: i64) { sleep_ms(ms as u32); } #[test] fn no_wait_one() { let (send, recv) = new(); send.send(1u8).unwrap(); let select = Select::new(); select.add(&recv); assert!(select.wait(&mut [0]).len() == 1); } #[test] fn wait_one() { let (send, recv) = new(); thread::spawn(move || { ms_sleep(100); send.send(1u8).unwrap(); }); let select = Select::new(); select.add(&recv); assert!(select.wait(&mut [0]) == &mut [recv.id()][..]); } #[test] fn ready_list_one() { let (send, recv) = new(); let select = Select::new(); select.add(&recv); send.send(1u8).unwrap(); assert!(select.wait_timeout(&mut [0], None) == Some(&mut [recv.id()][..])); } #[test] fn no_wait_two() { let (send, recv) = new(); let (send2, recv2) = new(); send.send(1u8).unwrap(); send2.send(1u8).unwrap(); let select = Select::new(); select.add(&recv); select.add(&recv2); assert!(select.wait(&mut [0, 0]).len() == 2); } #[test] fn wait_two() { let (send, recv) = new(); let (send2, recv2) = new(); thread::spawn(move || { ms_sleep(100); send.send(1u8).unwrap(); }); thread::spawn(move || { ms_sleep(200); send2.send(1u8).unwrap(); }); let select = Select::new(); select.add(&recv); select.add(&recv2); let mut saw1 = false; 'outer: loop { let mut buf = [0, 0]; for &mut id in select.wait(&mut buf) { if id == recv.id() && recv.recv_sync().is_err() { saw1 = true; } if id == recv2.id() && recv2.recv_sync().is_err() { break 'outer; } } } assert!(saw1); } #[test] fn select_wrong_thread()
// make sure that we wait for the other thread before dropping anything else drop(thread); } #[test] fn select_chance() { // Check that only one selecting thread wakes up. let counter1 = Arc::new(AtomicUsize::new(0)); let counter2 = counter1.clone(); let counter3 = counter1.clone(); let (send, recv) = new(); let select1 = Arc::new(Select::new()); let select2 = select1.clone(); select1.add(&recv); thread::spawn(move || { select1.wait(&mut []); counter2.fetch_add(1, SeqCst); }); thread::spawn(move || { select2.wait(&mut []); counter3.fetch_add(1, SeqCst); }); ms_sleep(100); send.send(1u8).unwrap(); ms_sleep(100); assert_eq!(counter1.swap(0, SeqCst), 1); }
{ // Check that cross thread selecting works. let (send1, recv1) = new(); let (send2, recv2) = new(); let id1 = recv1.id(); let id2 = recv2.id(); let select1 = Arc::new(Select::new()); let select2 = select1.clone(); let thread = thread::scoped(move || { select2.add(&recv2); send2.send(1u8).unwrap(); ms_sleep(100); // clear the second channel so that wait below will remove it from the ready list recv2.recv_sync().unwrap(); assert_eq!(select2.wait(&mut [0, 0]), &mut [id1][..]); }); select1.add(&recv1); assert_eq!(select1.wait(&mut [0, 0]), &mut [id2][..]); send1.send(2u8).unwrap();
identifier_body
test.rs
use std::thread::{self, sleep_ms}; use std::sync::{Arc}; use std::sync::atomic::{AtomicUsize}; use std::sync::atomic::Ordering::{SeqCst}; use spsc::unbounded::{new}; use super::{Select, Selectable}; fn ms_sleep(ms: i64) { sleep_ms(ms as u32); } #[test] fn no_wait_one() { let (send, recv) = new(); send.send(1u8).unwrap(); let select = Select::new(); select.add(&recv); assert!(select.wait(&mut [0]).len() == 1); } #[test] fn wait_one() { let (send, recv) = new(); thread::spawn(move || { ms_sleep(100); send.send(1u8).unwrap(); }); let select = Select::new(); select.add(&recv); assert!(select.wait(&mut [0]) == &mut [recv.id()][..]); } #[test] fn ready_list_one() { let (send, recv) = new(); let select = Select::new(); select.add(&recv); send.send(1u8).unwrap(); assert!(select.wait_timeout(&mut [0], None) == Some(&mut [recv.id()][..])); } #[test] fn no_wait_two() { let (send, recv) = new(); let (send2, recv2) = new(); send.send(1u8).unwrap(); send2.send(1u8).unwrap(); let select = Select::new(); select.add(&recv); select.add(&recv2); assert!(select.wait(&mut [0, 0]).len() == 2); } #[test] fn wait_two() { let (send, recv) = new(); let (send2, recv2) = new(); thread::spawn(move || { ms_sleep(100); send.send(1u8).unwrap(); }); thread::spawn(move || { ms_sleep(200); send2.send(1u8).unwrap(); }); let select = Select::new(); select.add(&recv); select.add(&recv2); let mut saw1 = false; 'outer: loop { let mut buf = [0, 0]; for &mut id in select.wait(&mut buf) { if id == recv.id() && recv.recv_sync().is_err() { saw1 = true; } if id == recv2.id() && recv2.recv_sync().is_err()
} } assert!(saw1); } #[test] fn select_wrong_thread() { // Check that cross thread selecting works. let (send1, recv1) = new(); let (send2, recv2) = new(); let id1 = recv1.id(); let id2 = recv2.id(); let select1 = Arc::new(Select::new()); let select2 = select1.clone(); let thread = thread::scoped(move || { select2.add(&recv2); send2.send(1u8).unwrap(); ms_sleep(100); // clear the second channel so that wait below will remove it from the ready list recv2.recv_sync().unwrap(); assert_eq!(select2.wait(&mut [0, 0]), &mut [id1][..]); }); select1.add(&recv1); assert_eq!(select1.wait(&mut [0, 0]), &mut [id2][..]); send1.send(2u8).unwrap(); // make sure that we wait for the other thread before dropping anything else drop(thread); } #[test] fn select_chance() { // Check that only one selecting thread wakes up. let counter1 = Arc::new(AtomicUsize::new(0)); let counter2 = counter1.clone(); let counter3 = counter1.clone(); let (send, recv) = new(); let select1 = Arc::new(Select::new()); let select2 = select1.clone(); select1.add(&recv); thread::spawn(move || { select1.wait(&mut []); counter2.fetch_add(1, SeqCst); }); thread::spawn(move || { select2.wait(&mut []); counter3.fetch_add(1, SeqCst); }); ms_sleep(100); send.send(1u8).unwrap(); ms_sleep(100); assert_eq!(counter1.swap(0, SeqCst), 1); }
{ break 'outer; }
conditional_block
test.rs
use std::thread::{self, sleep_ms}; use std::sync::{Arc}; use std::sync::atomic::{AtomicUsize}; use std::sync::atomic::Ordering::{SeqCst}; use spsc::unbounded::{new}; use super::{Select, Selectable}; fn ms_sleep(ms: i64) { sleep_ms(ms as u32); } #[test] fn no_wait_one() { let (send, recv) = new(); send.send(1u8).unwrap(); let select = Select::new(); select.add(&recv); assert!(select.wait(&mut [0]).len() == 1); } #[test] fn wait_one() { let (send, recv) = new(); thread::spawn(move || { ms_sleep(100); send.send(1u8).unwrap(); }); let select = Select::new(); select.add(&recv); assert!(select.wait(&mut [0]) == &mut [recv.id()][..]); } #[test] fn ready_list_one() { let (send, recv) = new(); let select = Select::new(); select.add(&recv); send.send(1u8).unwrap(); assert!(select.wait_timeout(&mut [0], None) == Some(&mut [recv.id()][..]));
fn no_wait_two() { let (send, recv) = new(); let (send2, recv2) = new(); send.send(1u8).unwrap(); send2.send(1u8).unwrap(); let select = Select::new(); select.add(&recv); select.add(&recv2); assert!(select.wait(&mut [0, 0]).len() == 2); } #[test] fn wait_two() { let (send, recv) = new(); let (send2, recv2) = new(); thread::spawn(move || { ms_sleep(100); send.send(1u8).unwrap(); }); thread::spawn(move || { ms_sleep(200); send2.send(1u8).unwrap(); }); let select = Select::new(); select.add(&recv); select.add(&recv2); let mut saw1 = false; 'outer: loop { let mut buf = [0, 0]; for &mut id in select.wait(&mut buf) { if id == recv.id() && recv.recv_sync().is_err() { saw1 = true; } if id == recv2.id() && recv2.recv_sync().is_err() { break 'outer; } } } assert!(saw1); } #[test] fn select_wrong_thread() { // Check that cross thread selecting works. let (send1, recv1) = new(); let (send2, recv2) = new(); let id1 = recv1.id(); let id2 = recv2.id(); let select1 = Arc::new(Select::new()); let select2 = select1.clone(); let thread = thread::scoped(move || { select2.add(&recv2); send2.send(1u8).unwrap(); ms_sleep(100); // clear the second channel so that wait below will remove it from the ready list recv2.recv_sync().unwrap(); assert_eq!(select2.wait(&mut [0, 0]), &mut [id1][..]); }); select1.add(&recv1); assert_eq!(select1.wait(&mut [0, 0]), &mut [id2][..]); send1.send(2u8).unwrap(); // make sure that we wait for the other thread before dropping anything else drop(thread); } #[test] fn select_chance() { // Check that only one selecting thread wakes up. let counter1 = Arc::new(AtomicUsize::new(0)); let counter2 = counter1.clone(); let counter3 = counter1.clone(); let (send, recv) = new(); let select1 = Arc::new(Select::new()); let select2 = select1.clone(); select1.add(&recv); thread::spawn(move || { select1.wait(&mut []); counter2.fetch_add(1, SeqCst); }); thread::spawn(move || { select2.wait(&mut []); counter3.fetch_add(1, SeqCst); }); ms_sleep(100); send.send(1u8).unwrap(); ms_sleep(100); assert_eq!(counter1.swap(0, SeqCst), 1); }
} #[test]
random_line_split
test.rs
use std::thread::{self, sleep_ms}; use std::sync::{Arc}; use std::sync::atomic::{AtomicUsize}; use std::sync::atomic::Ordering::{SeqCst}; use spsc::unbounded::{new}; use super::{Select, Selectable}; fn
(ms: i64) { sleep_ms(ms as u32); } #[test] fn no_wait_one() { let (send, recv) = new(); send.send(1u8).unwrap(); let select = Select::new(); select.add(&recv); assert!(select.wait(&mut [0]).len() == 1); } #[test] fn wait_one() { let (send, recv) = new(); thread::spawn(move || { ms_sleep(100); send.send(1u8).unwrap(); }); let select = Select::new(); select.add(&recv); assert!(select.wait(&mut [0]) == &mut [recv.id()][..]); } #[test] fn ready_list_one() { let (send, recv) = new(); let select = Select::new(); select.add(&recv); send.send(1u8).unwrap(); assert!(select.wait_timeout(&mut [0], None) == Some(&mut [recv.id()][..])); } #[test] fn no_wait_two() { let (send, recv) = new(); let (send2, recv2) = new(); send.send(1u8).unwrap(); send2.send(1u8).unwrap(); let select = Select::new(); select.add(&recv); select.add(&recv2); assert!(select.wait(&mut [0, 0]).len() == 2); } #[test] fn wait_two() { let (send, recv) = new(); let (send2, recv2) = new(); thread::spawn(move || { ms_sleep(100); send.send(1u8).unwrap(); }); thread::spawn(move || { ms_sleep(200); send2.send(1u8).unwrap(); }); let select = Select::new(); select.add(&recv); select.add(&recv2); let mut saw1 = false; 'outer: loop { let mut buf = [0, 0]; for &mut id in select.wait(&mut buf) { if id == recv.id() && recv.recv_sync().is_err() { saw1 = true; } if id == recv2.id() && recv2.recv_sync().is_err() { break 'outer; } } } assert!(saw1); } #[test] fn select_wrong_thread() { // Check that cross thread selecting works. let (send1, recv1) = new(); let (send2, recv2) = new(); let id1 = recv1.id(); let id2 = recv2.id(); let select1 = Arc::new(Select::new()); let select2 = select1.clone(); let thread = thread::scoped(move || { select2.add(&recv2); send2.send(1u8).unwrap(); ms_sleep(100); // clear the second channel so that wait below will remove it from the ready list recv2.recv_sync().unwrap(); assert_eq!(select2.wait(&mut [0, 0]), &mut [id1][..]); }); select1.add(&recv1); assert_eq!(select1.wait(&mut [0, 0]), &mut [id2][..]); send1.send(2u8).unwrap(); // make sure that we wait for the other thread before dropping anything else drop(thread); } #[test] fn select_chance() { // Check that only one selecting thread wakes up. let counter1 = Arc::new(AtomicUsize::new(0)); let counter2 = counter1.clone(); let counter3 = counter1.clone(); let (send, recv) = new(); let select1 = Arc::new(Select::new()); let select2 = select1.clone(); select1.add(&recv); thread::spawn(move || { select1.wait(&mut []); counter2.fetch_add(1, SeqCst); }); thread::spawn(move || { select2.wait(&mut []); counter3.fetch_add(1, SeqCst); }); ms_sleep(100); send.send(1u8).unwrap(); ms_sleep(100); assert_eq!(counter1.swap(0, SeqCst), 1); }
ms_sleep
identifier_name
util.rs
//! Module for utility functions. /// Verifies equality between an array of length 16 and a slice of unknown length. pub fn verify_16(x: &[u8; 16], y: &[u8]) -> bool
#[inline(never)] pub(crate) fn verify_inner(x: &impl AsRef<[u8]>, y: &[u8]) -> u8 { let x = x.as_ref(); assert_eq!(x.len(), y.len()); x.iter().zip(y).fold(0, |acc, (x, y)| acc | (x ^ y)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_verify_16() { assert!(verify_16(b"abcdefghijklmnop", b"abcdefghijklmnop")); assert!(verify_16(&[0xff; 16], &[0xff; 16])); assert!(verify_16(&[0x80; 16], &[0x80; 16])); assert!(!verify_16(b"abcdefghijklmnop", b"ponmlkjihgfedcba")); assert!(!verify_16(b"abcdefghijklmnop", b"")); assert!(!verify_16(b"abcdefghijklmnop", b"abcd")); assert!(!verify_16(&[0xff; 16], &[0x80; 16])); assert!(!verify_16(&[0xff; 16], &[0x80; 4])); assert!(!verify_16(&[0x80; 16], &[0xff; 16])); assert!(!verify_16(&[0x80; 16], &[0xff; 4])); } #[test] fn test_verify_inner() { assert_eq!(0, verify_inner(b"", b"")); assert_eq!(0, verify_inner(b"Hello!", b"Hello!")); assert_eq!(0, verify_inner(&[0x80, 0xff], &[0x80, 0xff])); assert_ne!(0, verify_inner(b"ok", b"ko")); assert_ne!(0, verify_inner(&[0x80, 0xff], &[0xff, 0x80])); } }
{ x.len() == y.len() && verify_inner(x, y) == 0 }
identifier_body
util.rs
//! Module for utility functions. /// Verifies equality between an array of length 16 and a slice of unknown length. pub fn verify_16(x: &[u8; 16], y: &[u8]) -> bool { x.len() == y.len() && verify_inner(x, y) == 0 } #[inline(never)] pub(crate) fn verify_inner(x: &impl AsRef<[u8]>, y: &[u8]) -> u8 { let x = x.as_ref(); assert_eq!(x.len(), y.len()); x.iter().zip(y).fold(0, |acc, (x, y)| acc | (x ^ y)) } #[cfg(test)] mod tests { use super::*; #[test] fn
() { assert!(verify_16(b"abcdefghijklmnop", b"abcdefghijklmnop")); assert!(verify_16(&[0xff; 16], &[0xff; 16])); assert!(verify_16(&[0x80; 16], &[0x80; 16])); assert!(!verify_16(b"abcdefghijklmnop", b"ponmlkjihgfedcba")); assert!(!verify_16(b"abcdefghijklmnop", b"")); assert!(!verify_16(b"abcdefghijklmnop", b"abcd")); assert!(!verify_16(&[0xff; 16], &[0x80; 16])); assert!(!verify_16(&[0xff; 16], &[0x80; 4])); assert!(!verify_16(&[0x80; 16], &[0xff; 16])); assert!(!verify_16(&[0x80; 16], &[0xff; 4])); } #[test] fn test_verify_inner() { assert_eq!(0, verify_inner(b"", b"")); assert_eq!(0, verify_inner(b"Hello!", b"Hello!")); assert_eq!(0, verify_inner(&[0x80, 0xff], &[0x80, 0xff])); assert_ne!(0, verify_inner(b"ok", b"ko")); assert_ne!(0, verify_inner(&[0x80, 0xff], &[0xff, 0x80])); } }
test_verify_16
identifier_name
util.rs
//! Module for utility functions. /// Verifies equality between an array of length 16 and a slice of unknown length. pub fn verify_16(x: &[u8; 16], y: &[u8]) -> bool { x.len() == y.len() && verify_inner(x, y) == 0 } #[inline(never)] pub(crate) fn verify_inner(x: &impl AsRef<[u8]>, y: &[u8]) -> u8 { let x = x.as_ref(); assert_eq!(x.len(), y.len()); x.iter().zip(y).fold(0, |acc, (x, y)| acc | (x ^ y)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_verify_16() { assert!(verify_16(b"abcdefghijklmnop", b"abcdefghijklmnop")); assert!(verify_16(&[0xff; 16], &[0xff; 16])); assert!(verify_16(&[0x80; 16], &[0x80; 16])); assert!(!verify_16(b"abcdefghijklmnop", b"ponmlkjihgfedcba")); assert!(!verify_16(b"abcdefghijklmnop", b"")); assert!(!verify_16(b"abcdefghijklmnop", b"abcd")); assert!(!verify_16(&[0xff; 16], &[0x80; 16])); assert!(!verify_16(&[0xff; 16], &[0x80; 4])); assert!(!verify_16(&[0x80; 16], &[0xff; 16])); assert!(!verify_16(&[0x80; 16], &[0xff; 4])); } #[test]
fn test_verify_inner() { assert_eq!(0, verify_inner(b"", b"")); assert_eq!(0, verify_inner(b"Hello!", b"Hello!")); assert_eq!(0, verify_inner(&[0x80, 0xff], &[0x80, 0xff])); assert_ne!(0, verify_inner(b"ok", b"ko")); assert_ne!(0, verify_inner(&[0x80, 0xff], &[0xff, 0x80])); } }
random_line_split
cell.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. //! Shareable mutable containers. //! //! Values of the `Cell` and `RefCell` types may be mutated through //! shared references (i.e. the common `&T` type), whereas most Rust //! types can only be mutated through unique (`&mut T`) references. We //! say that `Cell` and `RefCell` provide *interior mutability*, in //! contrast with typical Rust types that exhibit *inherited //! mutability*. //! //! Cell types come in two flavors: `Cell` and `RefCell`. `Cell` //! provides `get` and `set` methods that change the //! interior value with a single method call. `Cell` though is only //! compatible with types that implement `Copy`. For other types, //! one must use the `RefCell` type, acquiring a write lock before //! mutating. //! //! `RefCell` uses Rust's lifetimes to implement *dynamic borrowing*, //! a process whereby one can claim temporary, exclusive, mutable //! access to the inner value. Borrows for `RefCell`s are tracked *at //! runtime*, unlike Rust's native reference types which are entirely //! tracked statically, at compile time. Because `RefCell` borrows are //! dynamic it is possible to attempt to borrow a value that is //! already mutably borrowed; when this happens it results in task //! failure. //! //! # When to choose interior mutability //! //! The more common inherited mutability, where one must have unique //! access to mutate a value, is one of the key language elements that //! enables Rust to reason strongly about pointer aliasing, statically //! preventing crash bugs. Because of that, inherited mutability is //! preferred, and interior mutability is something of a last //! resort. Since cell types enable mutation where it would otherwise //! be disallowed though, there are occasions when interior //! mutability might be appropriate, or even *must* be used, e.g. //! //! * Introducing inherited mutability roots to shared types. //! * Implementation details of logically-immutable methods. //! * Mutating implementations of `clone`. //! //! ## Introducing inherited mutability roots to shared types //! //! Shared smart pointer types, including `Rc` and `Arc`, provide //! containers that can be cloned and shared between multiple parties. //! Because the contained values may be multiply-aliased, they can //! only be borrowed as shared references, not mutable references. //! Without cells it would be impossible to mutate data inside of //! shared boxes at all! //! //! It's very common then to put a `RefCell` inside shared pointer //! types to reintroduce mutability: //! //! ``` //! use std::collections::HashMap; //! use std::cell::RefCell; //! use std::rc::Rc; //! //! fn main() { //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new())); //! shared_map.borrow_mut().insert("africa", 92388i); //! shared_map.borrow_mut().insert("kyoto", 11837i); //! shared_map.borrow_mut().insert("piccadilly", 11826i); //! shared_map.borrow_mut().insert("marbles", 38i); //! } //! ``` //! //! ## Implementation details of logically-immutable methods //! //! Occasionally it may be desirable not to expose in an API that //! there is mutation happening "under the hood". This may be because //! logically the operation is immutable, but e.g. caching forces the //! implementation to perform mutation; or because you must employ //! mutation to implement a trait method that was originally defined //! to take `&self`. //! //! ``` //! use std::cell::RefCell; //! //! struct Graph { //! edges: Vec<(uint, uint)>, //! span_tree_cache: RefCell<Option<Vec<(uint, uint)>>> //! } //! //! impl Graph { //! fn minimum_spanning_tree(&self) -> Vec<(uint, uint)> { //! // Create a new scope to contain the lifetime of the //! // dynamic borrow //! { //! // Take a reference to the inside of cache cell //! let mut cache = self.span_tree_cache.borrow_mut(); //! if cache.is_some() { //! return cache.get_ref().clone(); //! } //! //! let span_tree = self.calc_span_tree(); //! *cache = Some(span_tree); //! } //! //! // Recursive call to return the just-cached value. //! // Note that if we had not let the previous borrow //! // of the cache fall out of scope then the subsequent //! // recursive borrow would cause a dynamic task failure. //! // This is the major hazard of using `RefCell`. //! self.minimum_spanning_tree() //! } //! # fn calc_span_tree(&self) -> Vec<(uint, uint)> { vec![] } //! } //! # fn main() { } //! ``` //! //! ## Mutating implementations of `clone` //! //! This is simply a special - but common - case of the previous: //! hiding mutability for operations that appear to be immutable. //! The `clone` method is expected to not change the source value, and //! is declared to take `&self`, not `&mut self`. Therefore any //! mutation that happens in the `clone` method must use cell //! types. For example, `Rc` maintains its reference counts within a //! `Cell`. //! //! ``` //! use std::cell::Cell; //! //! struct Rc<T> { //! ptr: *mut RcBox<T> //! } //! //! struct RcBox<T> { //! value: T, //! refcount: Cell<uint> //! } //! //! impl<T> Clone for Rc<T> { //! fn clone(&self) -> Rc<T> { //! unsafe { //! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1); //! Rc { ptr: self.ptr } //! } //! } //! } //! ``` //! // FIXME: Explain difference between Cell and RefCell // FIXME: Downsides to interior mutability // FIXME: Can't be shared between threads. Dynamic borrows // FIXME: Relationship to Atomic types and RWLock use clone::Clone; use cmp::PartialEq; use kinds::{marker, Copy}; use ops::{Deref, DerefMut, Drop}; use option::{None, Option, Some}; /// A mutable memory location that admits only `Copy` data. #[unstable = "likely to be renamed; otherwise stable"] pub struct Cell<T> { value: UnsafeCell<T>, noshare: marker::NoSync, } #[stable] impl<T:Copy> Cell<T> { /// Creates a new `Cell` containing the given value. pub fn new(value: T) -> Cell<T> { Cell { value: UnsafeCell::new(value), noshare: marker::NoSync, } } /// Returns a copy of the contained value. #[inline] pub fn get(&self) -> T { unsafe{ *self.value.get() } } /// Sets the contained value. #[inline] pub fn set(&self, value: T) { unsafe { *self.value.get() = value; } } } #[unstable = "waiting for `Clone` trait to become stable"] impl<T:Copy> Clone for Cell<T> { fn clone(&self) -> Cell<T> { Cell::new(self.get()) } } #[unstable = "waiting for `PartialEq` trait to become stable"] impl<T:PartialEq + Copy> PartialEq for Cell<T> { fn eq(&self, other: &Cell<T>) -> bool { self.get() == other.get() } } /// A mutable memory location with dynamically checked borrow rules #[unstable = "likely to be renamed; otherwise stable"] pub struct RefCell<T> { value: UnsafeCell<T>, borrow: Cell<BorrowFlag>, nocopy: marker::NoCopy, noshare: marker::NoSync, } // Values [1, MAX-1] represent the number of `Ref` active // (will not outgrow its range since `uint` is the size of the address space) type BorrowFlag = uint; static UNUSED: BorrowFlag = 0; static WRITING: BorrowFlag = -1; impl<T> RefCell<T> { /// Create a new `RefCell` containing `value` #[stable] pub fn new(value: T) -> RefCell<T> { RefCell { value: UnsafeCell::new(value), borrow: Cell::new(UNUSED), nocopy: marker::NoCopy, noshare: marker::NoSync, } } /// Consumes the `RefCell`, returning the wrapped value. #[unstable = "may be renamed, depending on global conventions"] pub fn unwrap(self) -> T { debug_assert!(self.borrow.get() == UNUSED); unsafe{self.value.unwrap()} } /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// Returns `None` if the value is currently mutably borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> { match self.borrow.get() { WRITING => None, borrow =>
} } /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// # Failure /// /// Fails if the value is currently mutably borrowed. #[unstable] pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match self.try_borrow() { Some(ptr) => ptr, None => fail!("RefCell<T> already mutably borrowed") } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// Returns `None` if the value is currently borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> { match self.borrow.get() { UNUSED => { self.borrow.set(WRITING); Some(RefMut { _parent: self }) }, _ => None } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// # Failure /// /// Fails if the value is currently borrowed. #[unstable] pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { match self.try_borrow_mut() { Some(ptr) => ptr, None => fail!("RefCell<T> already borrowed") } } } #[unstable = "waiting for `Clone` to become stable"] impl<T: Clone> Clone for RefCell<T> { fn clone(&self) -> RefCell<T> { RefCell::new(self.borrow().clone()) } } #[unstable = "waiting for `PartialEq` to become stable"] impl<T: PartialEq> PartialEq for RefCell<T> { fn eq(&self, other: &RefCell<T>) -> bool { *self.borrow() == *other.borrow() } } /// Wraps a borrowed reference to a value in a `RefCell` box. #[unstable] pub struct Ref<'b, T> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _parent: &'b RefCell<T> } #[unsafe_destructor] #[unstable] impl<'b, T> Drop for Ref<'b, T> { fn drop(&mut self) { let borrow = self._parent.borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._parent.borrow.set(borrow - 1); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for Ref<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { unsafe { &*self._parent.value.get() } } } /// Copy a `Ref`. /// /// The `RefCell` is already immutably borrowed, so this cannot fail. /// /// A `Clone` implementation would interfere with the widespread /// use of `r.borrow().clone()` to clone the contents of a `RefCell`. #[experimental = "likely to be moved to a method, pending language changes"] pub fn clone_ref<'b, T>(orig: &Ref<'b, T>) -> Ref<'b, T> { // Since this Ref exists, we know the borrow flag // is not set to WRITING. let borrow = orig._parent.borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); orig._parent.borrow.set(borrow + 1); Ref { _parent: orig._parent, } } /// Wraps a mutable borrowed reference to a value in a `RefCell` box. #[unstable] pub struct RefMut<'b, T> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _parent: &'b RefCell<T> } #[unsafe_destructor] #[unstable] impl<'b, T> Drop for RefMut<'b, T> { fn drop(&mut self) { let borrow = self._parent.borrow.get(); debug_assert!(borrow == WRITING); self._parent.borrow.set(UNUSED); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for RefMut<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { unsafe { &*self._parent.value.get() } } } #[unstable = "waiting for `DerefMut` to become stable"] impl<'b, T> DerefMut<T> for RefMut<'b, T> { #[inline] fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *self._parent.value.get() } } } /// The core primitive for interior mutability in Rust. /// /// `UnsafeCell` type that wraps a type T and indicates unsafe interior /// operations on the wrapped type. Types with an `UnsafeCell<T>` field are /// considered to have an *unsafe interior*. The `UnsafeCell` type is the only /// legal way to obtain aliasable data that is considered mutable. In general, /// transmuting an &T type into an &mut T is considered undefined behavior. /// /// Although it is possible to put an `UnsafeCell<T>` into static item, it is /// not permitted to take the address of the static item if the item is not /// declared as mutable. This rule exists because immutable static items are /// stored in read-only memory, and thus any attempt to mutate their interior /// can cause segfaults. Immutable static items containing `UnsafeCell<T>` /// instances are still useful as read-only initializers, however, so we do not /// forbid them altogether. /// /// Types like `Cell` and `RefCell` use this type to wrap their internal data. /// /// `UnsafeCell` doesn't opt-out from any kind, instead, types with an /// `UnsafeCell` interior are expected to opt-out from kinds themselves. /// /// # Example: /// /// ```rust /// use std::cell::UnsafeCell; /// use std::kinds::marker; /// /// struct NotThreadSafe<T> { /// value: UnsafeCell<T>, /// marker: marker::NoSync /// } /// ``` /// /// **NOTE:** `UnsafeCell<T>` fields are public to allow static initializers. It /// is not recommended to access its fields directly, `get` should be used /// instead. #[lang="unsafe"] #[unstable = "this type may be renamed in the future"] pub struct UnsafeCell<T> { /// Wrapped value /// /// This field should not be accessed directly, it is made public for static /// initializers. #[unstable] pub value: T, } impl<T> UnsafeCell<T> { /// Construct a new instance of `UnsafeCell` which will wrap the specified /// value. /// /// All access to the inner value through methods is `unsafe`, and it is /// highly discouraged to access the fields directly. #[stable] pub fn new(value: T) -> UnsafeCell<T> { UnsafeCell { value: value } } /// Gets a mutable pointer to the wrapped value. /// /// This function is unsafe as the pointer returned is an unsafe pointer and /// no guarantees are made about the aliasing of the pointers being handed /// out in this or other tasks. #[inline] #[unstable = "conventions around acquiring an inner reference are still \ under development"] pub unsafe fn get(&self) -> *mut T { &self.value as *const T as *mut T } /// Unwraps the value /// /// This function is unsafe because there is no guarantee that this or other /// tasks are currently inspecting the inner value. #[inline] #[unstable = "conventions around the name `unwrap` are still under \ development"] pub unsafe fn unwrap(self) -> T { self.value } }
{ self.borrow.set(borrow + 1); Some(Ref { _parent: self }) }
conditional_block
cell.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. //! Shareable mutable containers. //! //! Values of the `Cell` and `RefCell` types may be mutated through //! shared references (i.e. the common `&T` type), whereas most Rust //! types can only be mutated through unique (`&mut T`) references. We //! say that `Cell` and `RefCell` provide *interior mutability*, in //! contrast with typical Rust types that exhibit *inherited //! mutability*. //! //! Cell types come in two flavors: `Cell` and `RefCell`. `Cell` //! provides `get` and `set` methods that change the //! interior value with a single method call. `Cell` though is only //! compatible with types that implement `Copy`. For other types, //! one must use the `RefCell` type, acquiring a write lock before //! mutating. //! //! `RefCell` uses Rust's lifetimes to implement *dynamic borrowing*, //! a process whereby one can claim temporary, exclusive, mutable //! access to the inner value. Borrows for `RefCell`s are tracked *at //! runtime*, unlike Rust's native reference types which are entirely //! tracked statically, at compile time. Because `RefCell` borrows are //! dynamic it is possible to attempt to borrow a value that is //! already mutably borrowed; when this happens it results in task //! failure. //! //! # When to choose interior mutability //! //! The more common inherited mutability, where one must have unique //! access to mutate a value, is one of the key language elements that //! enables Rust to reason strongly about pointer aliasing, statically //! preventing crash bugs. Because of that, inherited mutability is //! preferred, and interior mutability is something of a last //! resort. Since cell types enable mutation where it would otherwise //! be disallowed though, there are occasions when interior //! mutability might be appropriate, or even *must* be used, e.g. //! //! * Introducing inherited mutability roots to shared types. //! * Implementation details of logically-immutable methods. //! * Mutating implementations of `clone`. //! //! ## Introducing inherited mutability roots to shared types //! //! Shared smart pointer types, including `Rc` and `Arc`, provide //! containers that can be cloned and shared between multiple parties. //! Because the contained values may be multiply-aliased, they can //! only be borrowed as shared references, not mutable references. //! Without cells it would be impossible to mutate data inside of //! shared boxes at all! //! //! It's very common then to put a `RefCell` inside shared pointer //! types to reintroduce mutability: //! //! ``` //! use std::collections::HashMap; //! use std::cell::RefCell; //! use std::rc::Rc; //! //! fn main() { //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new())); //! shared_map.borrow_mut().insert("africa", 92388i); //! shared_map.borrow_mut().insert("kyoto", 11837i); //! shared_map.borrow_mut().insert("piccadilly", 11826i); //! shared_map.borrow_mut().insert("marbles", 38i); //! } //! ``` //! //! ## Implementation details of logically-immutable methods //! //! Occasionally it may be desirable not to expose in an API that //! there is mutation happening "under the hood". This may be because //! logically the operation is immutable, but e.g. caching forces the //! implementation to perform mutation; or because you must employ //! mutation to implement a trait method that was originally defined //! to take `&self`. //! //! ``` //! use std::cell::RefCell; //! //! struct Graph { //! edges: Vec<(uint, uint)>, //! span_tree_cache: RefCell<Option<Vec<(uint, uint)>>> //! } //! //! impl Graph { //! fn minimum_spanning_tree(&self) -> Vec<(uint, uint)> { //! // Create a new scope to contain the lifetime of the //! // dynamic borrow //! { //! // Take a reference to the inside of cache cell //! let mut cache = self.span_tree_cache.borrow_mut(); //! if cache.is_some() { //! return cache.get_ref().clone(); //! } //! //! let span_tree = self.calc_span_tree(); //! *cache = Some(span_tree); //! } //! //! // Recursive call to return the just-cached value. //! // Note that if we had not let the previous borrow //! // of the cache fall out of scope then the subsequent //! // recursive borrow would cause a dynamic task failure. //! // This is the major hazard of using `RefCell`. //! self.minimum_spanning_tree() //! } //! # fn calc_span_tree(&self) -> Vec<(uint, uint)> { vec![] } //! } //! # fn main() { } //! ``` //! //! ## Mutating implementations of `clone` //! //! This is simply a special - but common - case of the previous: //! hiding mutability for operations that appear to be immutable. //! The `clone` method is expected to not change the source value, and //! is declared to take `&self`, not `&mut self`. Therefore any //! mutation that happens in the `clone` method must use cell //! types. For example, `Rc` maintains its reference counts within a //! `Cell`. //! //! ``` //! use std::cell::Cell; //! //! struct Rc<T> { //! ptr: *mut RcBox<T> //! } //! //! struct RcBox<T> { //! value: T, //! refcount: Cell<uint> //! } //! //! impl<T> Clone for Rc<T> { //! fn clone(&self) -> Rc<T> { //! unsafe { //! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1); //! Rc { ptr: self.ptr } //! } //! } //! } //! ``` //! // FIXME: Explain difference between Cell and RefCell // FIXME: Downsides to interior mutability // FIXME: Can't be shared between threads. Dynamic borrows // FIXME: Relationship to Atomic types and RWLock use clone::Clone; use cmp::PartialEq; use kinds::{marker, Copy}; use ops::{Deref, DerefMut, Drop}; use option::{None, Option, Some}; /// A mutable memory location that admits only `Copy` data. #[unstable = "likely to be renamed; otherwise stable"] pub struct Cell<T> { value: UnsafeCell<T>, noshare: marker::NoSync, } #[stable] impl<T:Copy> Cell<T> { /// Creates a new `Cell` containing the given value. pub fn new(value: T) -> Cell<T> { Cell { value: UnsafeCell::new(value), noshare: marker::NoSync, } } /// Returns a copy of the contained value. #[inline] pub fn get(&self) -> T { unsafe{ *self.value.get() } } /// Sets the contained value. #[inline] pub fn set(&self, value: T) { unsafe { *self.value.get() = value; } } } #[unstable = "waiting for `Clone` trait to become stable"] impl<T:Copy> Clone for Cell<T> { fn clone(&self) -> Cell<T> { Cell::new(self.get()) } } #[unstable = "waiting for `PartialEq` trait to become stable"] impl<T:PartialEq + Copy> PartialEq for Cell<T> { fn eq(&self, other: &Cell<T>) -> bool { self.get() == other.get() } } /// A mutable memory location with dynamically checked borrow rules #[unstable = "likely to be renamed; otherwise stable"] pub struct RefCell<T> { value: UnsafeCell<T>, borrow: Cell<BorrowFlag>, nocopy: marker::NoCopy, noshare: marker::NoSync, } // Values [1, MAX-1] represent the number of `Ref` active // (will not outgrow its range since `uint` is the size of the address space) type BorrowFlag = uint; static UNUSED: BorrowFlag = 0; static WRITING: BorrowFlag = -1; impl<T> RefCell<T> { /// Create a new `RefCell` containing `value` #[stable] pub fn new(value: T) -> RefCell<T> { RefCell { value: UnsafeCell::new(value), borrow: Cell::new(UNUSED), nocopy: marker::NoCopy, noshare: marker::NoSync, } } /// Consumes the `RefCell`, returning the wrapped value. #[unstable = "may be renamed, depending on global conventions"] pub fn unwrap(self) -> T { debug_assert!(self.borrow.get() == UNUSED); unsafe{self.value.unwrap()} } /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// Returns `None` if the value is currently mutably borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> { match self.borrow.get() { WRITING => None, borrow => { self.borrow.set(borrow + 1); Some(Ref { _parent: self }) } } } /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// # Failure /// /// Fails if the value is currently mutably borrowed. #[unstable] pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match self.try_borrow() { Some(ptr) => ptr, None => fail!("RefCell<T> already mutably borrowed") } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// Returns `None` if the value is currently borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> { match self.borrow.get() { UNUSED => { self.borrow.set(WRITING); Some(RefMut { _parent: self }) }, _ => None } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// # Failure /// /// Fails if the value is currently borrowed. #[unstable] pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { match self.try_borrow_mut() { Some(ptr) => ptr, None => fail!("RefCell<T> already borrowed") } } } #[unstable = "waiting for `Clone` to become stable"] impl<T: Clone> Clone for RefCell<T> { fn clone(&self) -> RefCell<T> { RefCell::new(self.borrow().clone()) } } #[unstable = "waiting for `PartialEq` to become stable"] impl<T: PartialEq> PartialEq for RefCell<T> { fn eq(&self, other: &RefCell<T>) -> bool { *self.borrow() == *other.borrow() } } /// Wraps a borrowed reference to a value in a `RefCell` box. #[unstable] pub struct Ref<'b, T> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _parent: &'b RefCell<T> } #[unsafe_destructor] #[unstable] impl<'b, T> Drop for Ref<'b, T> { fn drop(&mut self) { let borrow = self._parent.borrow.get();
debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._parent.borrow.set(borrow - 1); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for Ref<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { unsafe { &*self._parent.value.get() } } } /// Copy a `Ref`. /// /// The `RefCell` is already immutably borrowed, so this cannot fail. /// /// A `Clone` implementation would interfere with the widespread /// use of `r.borrow().clone()` to clone the contents of a `RefCell`. #[experimental = "likely to be moved to a method, pending language changes"] pub fn clone_ref<'b, T>(orig: &Ref<'b, T>) -> Ref<'b, T> { // Since this Ref exists, we know the borrow flag // is not set to WRITING. let borrow = orig._parent.borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); orig._parent.borrow.set(borrow + 1); Ref { _parent: orig._parent, } } /// Wraps a mutable borrowed reference to a value in a `RefCell` box. #[unstable] pub struct RefMut<'b, T> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _parent: &'b RefCell<T> } #[unsafe_destructor] #[unstable] impl<'b, T> Drop for RefMut<'b, T> { fn drop(&mut self) { let borrow = self._parent.borrow.get(); debug_assert!(borrow == WRITING); self._parent.borrow.set(UNUSED); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for RefMut<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { unsafe { &*self._parent.value.get() } } } #[unstable = "waiting for `DerefMut` to become stable"] impl<'b, T> DerefMut<T> for RefMut<'b, T> { #[inline] fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *self._parent.value.get() } } } /// The core primitive for interior mutability in Rust. /// /// `UnsafeCell` type that wraps a type T and indicates unsafe interior /// operations on the wrapped type. Types with an `UnsafeCell<T>` field are /// considered to have an *unsafe interior*. The `UnsafeCell` type is the only /// legal way to obtain aliasable data that is considered mutable. In general, /// transmuting an &T type into an &mut T is considered undefined behavior. /// /// Although it is possible to put an `UnsafeCell<T>` into static item, it is /// not permitted to take the address of the static item if the item is not /// declared as mutable. This rule exists because immutable static items are /// stored in read-only memory, and thus any attempt to mutate their interior /// can cause segfaults. Immutable static items containing `UnsafeCell<T>` /// instances are still useful as read-only initializers, however, so we do not /// forbid them altogether. /// /// Types like `Cell` and `RefCell` use this type to wrap their internal data. /// /// `UnsafeCell` doesn't opt-out from any kind, instead, types with an /// `UnsafeCell` interior are expected to opt-out from kinds themselves. /// /// # Example: /// /// ```rust /// use std::cell::UnsafeCell; /// use std::kinds::marker; /// /// struct NotThreadSafe<T> { /// value: UnsafeCell<T>, /// marker: marker::NoSync /// } /// ``` /// /// **NOTE:** `UnsafeCell<T>` fields are public to allow static initializers. It /// is not recommended to access its fields directly, `get` should be used /// instead. #[lang="unsafe"] #[unstable = "this type may be renamed in the future"] pub struct UnsafeCell<T> { /// Wrapped value /// /// This field should not be accessed directly, it is made public for static /// initializers. #[unstable] pub value: T, } impl<T> UnsafeCell<T> { /// Construct a new instance of `UnsafeCell` which will wrap the specified /// value. /// /// All access to the inner value through methods is `unsafe`, and it is /// highly discouraged to access the fields directly. #[stable] pub fn new(value: T) -> UnsafeCell<T> { UnsafeCell { value: value } } /// Gets a mutable pointer to the wrapped value. /// /// This function is unsafe as the pointer returned is an unsafe pointer and /// no guarantees are made about the aliasing of the pointers being handed /// out in this or other tasks. #[inline] #[unstable = "conventions around acquiring an inner reference are still \ under development"] pub unsafe fn get(&self) -> *mut T { &self.value as *const T as *mut T } /// Unwraps the value /// /// This function is unsafe because there is no guarantee that this or other /// tasks are currently inspecting the inner value. #[inline] #[unstable = "conventions around the name `unwrap` are still under \ development"] pub unsafe fn unwrap(self) -> T { self.value } }
random_line_split
cell.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. //! Shareable mutable containers. //! //! Values of the `Cell` and `RefCell` types may be mutated through //! shared references (i.e. the common `&T` type), whereas most Rust //! types can only be mutated through unique (`&mut T`) references. We //! say that `Cell` and `RefCell` provide *interior mutability*, in //! contrast with typical Rust types that exhibit *inherited //! mutability*. //! //! Cell types come in two flavors: `Cell` and `RefCell`. `Cell` //! provides `get` and `set` methods that change the //! interior value with a single method call. `Cell` though is only //! compatible with types that implement `Copy`. For other types, //! one must use the `RefCell` type, acquiring a write lock before //! mutating. //! //! `RefCell` uses Rust's lifetimes to implement *dynamic borrowing*, //! a process whereby one can claim temporary, exclusive, mutable //! access to the inner value. Borrows for `RefCell`s are tracked *at //! runtime*, unlike Rust's native reference types which are entirely //! tracked statically, at compile time. Because `RefCell` borrows are //! dynamic it is possible to attempt to borrow a value that is //! already mutably borrowed; when this happens it results in task //! failure. //! //! # When to choose interior mutability //! //! The more common inherited mutability, where one must have unique //! access to mutate a value, is one of the key language elements that //! enables Rust to reason strongly about pointer aliasing, statically //! preventing crash bugs. Because of that, inherited mutability is //! preferred, and interior mutability is something of a last //! resort. Since cell types enable mutation where it would otherwise //! be disallowed though, there are occasions when interior //! mutability might be appropriate, or even *must* be used, e.g. //! //! * Introducing inherited mutability roots to shared types. //! * Implementation details of logically-immutable methods. //! * Mutating implementations of `clone`. //! //! ## Introducing inherited mutability roots to shared types //! //! Shared smart pointer types, including `Rc` and `Arc`, provide //! containers that can be cloned and shared between multiple parties. //! Because the contained values may be multiply-aliased, they can //! only be borrowed as shared references, not mutable references. //! Without cells it would be impossible to mutate data inside of //! shared boxes at all! //! //! It's very common then to put a `RefCell` inside shared pointer //! types to reintroduce mutability: //! //! ``` //! use std::collections::HashMap; //! use std::cell::RefCell; //! use std::rc::Rc; //! //! fn main() { //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new())); //! shared_map.borrow_mut().insert("africa", 92388i); //! shared_map.borrow_mut().insert("kyoto", 11837i); //! shared_map.borrow_mut().insert("piccadilly", 11826i); //! shared_map.borrow_mut().insert("marbles", 38i); //! } //! ``` //! //! ## Implementation details of logically-immutable methods //! //! Occasionally it may be desirable not to expose in an API that //! there is mutation happening "under the hood". This may be because //! logically the operation is immutable, but e.g. caching forces the //! implementation to perform mutation; or because you must employ //! mutation to implement a trait method that was originally defined //! to take `&self`. //! //! ``` //! use std::cell::RefCell; //! //! struct Graph { //! edges: Vec<(uint, uint)>, //! span_tree_cache: RefCell<Option<Vec<(uint, uint)>>> //! } //! //! impl Graph { //! fn minimum_spanning_tree(&self) -> Vec<(uint, uint)> { //! // Create a new scope to contain the lifetime of the //! // dynamic borrow //! { //! // Take a reference to the inside of cache cell //! let mut cache = self.span_tree_cache.borrow_mut(); //! if cache.is_some() { //! return cache.get_ref().clone(); //! } //! //! let span_tree = self.calc_span_tree(); //! *cache = Some(span_tree); //! } //! //! // Recursive call to return the just-cached value. //! // Note that if we had not let the previous borrow //! // of the cache fall out of scope then the subsequent //! // recursive borrow would cause a dynamic task failure. //! // This is the major hazard of using `RefCell`. //! self.minimum_spanning_tree() //! } //! # fn calc_span_tree(&self) -> Vec<(uint, uint)> { vec![] } //! } //! # fn main() { } //! ``` //! //! ## Mutating implementations of `clone` //! //! This is simply a special - but common - case of the previous: //! hiding mutability for operations that appear to be immutable. //! The `clone` method is expected to not change the source value, and //! is declared to take `&self`, not `&mut self`. Therefore any //! mutation that happens in the `clone` method must use cell //! types. For example, `Rc` maintains its reference counts within a //! `Cell`. //! //! ``` //! use std::cell::Cell; //! //! struct Rc<T> { //! ptr: *mut RcBox<T> //! } //! //! struct RcBox<T> { //! value: T, //! refcount: Cell<uint> //! } //! //! impl<T> Clone for Rc<T> { //! fn clone(&self) -> Rc<T> { //! unsafe { //! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1); //! Rc { ptr: self.ptr } //! } //! } //! } //! ``` //! // FIXME: Explain difference between Cell and RefCell // FIXME: Downsides to interior mutability // FIXME: Can't be shared between threads. Dynamic borrows // FIXME: Relationship to Atomic types and RWLock use clone::Clone; use cmp::PartialEq; use kinds::{marker, Copy}; use ops::{Deref, DerefMut, Drop}; use option::{None, Option, Some}; /// A mutable memory location that admits only `Copy` data. #[unstable = "likely to be renamed; otherwise stable"] pub struct Cell<T> { value: UnsafeCell<T>, noshare: marker::NoSync, } #[stable] impl<T:Copy> Cell<T> { /// Creates a new `Cell` containing the given value. pub fn new(value: T) -> Cell<T> { Cell { value: UnsafeCell::new(value), noshare: marker::NoSync, } } /// Returns a copy of the contained value. #[inline] pub fn get(&self) -> T { unsafe{ *self.value.get() } } /// Sets the contained value. #[inline] pub fn set(&self, value: T) { unsafe { *self.value.get() = value; } } } #[unstable = "waiting for `Clone` trait to become stable"] impl<T:Copy> Clone for Cell<T> { fn clone(&self) -> Cell<T> { Cell::new(self.get()) } } #[unstable = "waiting for `PartialEq` trait to become stable"] impl<T:PartialEq + Copy> PartialEq for Cell<T> { fn eq(&self, other: &Cell<T>) -> bool { self.get() == other.get() } } /// A mutable memory location with dynamically checked borrow rules #[unstable = "likely to be renamed; otherwise stable"] pub struct RefCell<T> { value: UnsafeCell<T>, borrow: Cell<BorrowFlag>, nocopy: marker::NoCopy, noshare: marker::NoSync, } // Values [1, MAX-1] represent the number of `Ref` active // (will not outgrow its range since `uint` is the size of the address space) type BorrowFlag = uint; static UNUSED: BorrowFlag = 0; static WRITING: BorrowFlag = -1; impl<T> RefCell<T> { /// Create a new `RefCell` containing `value` #[stable] pub fn new(value: T) -> RefCell<T> { RefCell { value: UnsafeCell::new(value), borrow: Cell::new(UNUSED), nocopy: marker::NoCopy, noshare: marker::NoSync, } } /// Consumes the `RefCell`, returning the wrapped value. #[unstable = "may be renamed, depending on global conventions"] pub fn unwrap(self) -> T { debug_assert!(self.borrow.get() == UNUSED); unsafe{self.value.unwrap()} } /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// Returns `None` if the value is currently mutably borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> { match self.borrow.get() { WRITING => None, borrow => { self.borrow.set(borrow + 1); Some(Ref { _parent: self }) } } } /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// # Failure /// /// Fails if the value is currently mutably borrowed. #[unstable] pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match self.try_borrow() { Some(ptr) => ptr, None => fail!("RefCell<T> already mutably borrowed") } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// Returns `None` if the value is currently borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> { match self.borrow.get() { UNUSED => { self.borrow.set(WRITING); Some(RefMut { _parent: self }) }, _ => None } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// # Failure /// /// Fails if the value is currently borrowed. #[unstable] pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { match self.try_borrow_mut() { Some(ptr) => ptr, None => fail!("RefCell<T> already borrowed") } } } #[unstable = "waiting for `Clone` to become stable"] impl<T: Clone> Clone for RefCell<T> { fn clone(&self) -> RefCell<T> { RefCell::new(self.borrow().clone()) } } #[unstable = "waiting for `PartialEq` to become stable"] impl<T: PartialEq> PartialEq for RefCell<T> { fn eq(&self, other: &RefCell<T>) -> bool { *self.borrow() == *other.borrow() } } /// Wraps a borrowed reference to a value in a `RefCell` box. #[unstable] pub struct Ref<'b, T> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _parent: &'b RefCell<T> } #[unsafe_destructor] #[unstable] impl<'b, T> Drop for Ref<'b, T> { fn
(&mut self) { let borrow = self._parent.borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._parent.borrow.set(borrow - 1); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for Ref<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { unsafe { &*self._parent.value.get() } } } /// Copy a `Ref`. /// /// The `RefCell` is already immutably borrowed, so this cannot fail. /// /// A `Clone` implementation would interfere with the widespread /// use of `r.borrow().clone()` to clone the contents of a `RefCell`. #[experimental = "likely to be moved to a method, pending language changes"] pub fn clone_ref<'b, T>(orig: &Ref<'b, T>) -> Ref<'b, T> { // Since this Ref exists, we know the borrow flag // is not set to WRITING. let borrow = orig._parent.borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); orig._parent.borrow.set(borrow + 1); Ref { _parent: orig._parent, } } /// Wraps a mutable borrowed reference to a value in a `RefCell` box. #[unstable] pub struct RefMut<'b, T> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _parent: &'b RefCell<T> } #[unsafe_destructor] #[unstable] impl<'b, T> Drop for RefMut<'b, T> { fn drop(&mut self) { let borrow = self._parent.borrow.get(); debug_assert!(borrow == WRITING); self._parent.borrow.set(UNUSED); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for RefMut<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { unsafe { &*self._parent.value.get() } } } #[unstable = "waiting for `DerefMut` to become stable"] impl<'b, T> DerefMut<T> for RefMut<'b, T> { #[inline] fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *self._parent.value.get() } } } /// The core primitive for interior mutability in Rust. /// /// `UnsafeCell` type that wraps a type T and indicates unsafe interior /// operations on the wrapped type. Types with an `UnsafeCell<T>` field are /// considered to have an *unsafe interior*. The `UnsafeCell` type is the only /// legal way to obtain aliasable data that is considered mutable. In general, /// transmuting an &T type into an &mut T is considered undefined behavior. /// /// Although it is possible to put an `UnsafeCell<T>` into static item, it is /// not permitted to take the address of the static item if the item is not /// declared as mutable. This rule exists because immutable static items are /// stored in read-only memory, and thus any attempt to mutate their interior /// can cause segfaults. Immutable static items containing `UnsafeCell<T>` /// instances are still useful as read-only initializers, however, so we do not /// forbid them altogether. /// /// Types like `Cell` and `RefCell` use this type to wrap their internal data. /// /// `UnsafeCell` doesn't opt-out from any kind, instead, types with an /// `UnsafeCell` interior are expected to opt-out from kinds themselves. /// /// # Example: /// /// ```rust /// use std::cell::UnsafeCell; /// use std::kinds::marker; /// /// struct NotThreadSafe<T> { /// value: UnsafeCell<T>, /// marker: marker::NoSync /// } /// ``` /// /// **NOTE:** `UnsafeCell<T>` fields are public to allow static initializers. It /// is not recommended to access its fields directly, `get` should be used /// instead. #[lang="unsafe"] #[unstable = "this type may be renamed in the future"] pub struct UnsafeCell<T> { /// Wrapped value /// /// This field should not be accessed directly, it is made public for static /// initializers. #[unstable] pub value: T, } impl<T> UnsafeCell<T> { /// Construct a new instance of `UnsafeCell` which will wrap the specified /// value. /// /// All access to the inner value through methods is `unsafe`, and it is /// highly discouraged to access the fields directly. #[stable] pub fn new(value: T) -> UnsafeCell<T> { UnsafeCell { value: value } } /// Gets a mutable pointer to the wrapped value. /// /// This function is unsafe as the pointer returned is an unsafe pointer and /// no guarantees are made about the aliasing of the pointers being handed /// out in this or other tasks. #[inline] #[unstable = "conventions around acquiring an inner reference are still \ under development"] pub unsafe fn get(&self) -> *mut T { &self.value as *const T as *mut T } /// Unwraps the value /// /// This function is unsafe because there is no guarantee that this or other /// tasks are currently inspecting the inner value. #[inline] #[unstable = "conventions around the name `unwrap` are still under \ development"] pub unsafe fn unwrap(self) -> T { self.value } }
drop
identifier_name
util.rs
// Small functions of utility use core::SearchType::{self, ExactMatch, StartsWith}; use core::Session; use std::cmp; use std::path::Path; pub fn getline(filepath: &Path, linenum: usize, session: &Session) -> String { let src = session.load_file(filepath); src.code.lines().nth(linenum - 1).unwrap_or("not found").to_string() } pub fn is_pattern_char(c: char) -> bool { c.is_alphanumeric() || c.is_whitespace() || (c == '_') || (c == ':') || (c == '.') } pub fn is_search_expr_char(c: char) -> bool { c.is_alphanumeric() || (c == '_') || (c == ':') || (c == '.') } pub fn is_ident_char(c: char) -> bool { c.is_alphanumeric() || (c == '_') || (c == '!') } pub fn txt_matches(stype: SearchType, needle: &str, haystack: &str) -> bool { match stype { ExactMatch => { let n_len = needle.len(); let h_len = haystack.len(); if n_len == 0 { return true; } // PD: switch to use.match_indices() when that stabilizes let mut n=0; while let Some(n1) = haystack[n..].find(needle) { n += n1; if (n == 0 ||!is_ident_char(char_at(haystack, n-1))) && (n+n_len == h_len ||!is_ident_char(char_at(haystack, n+n_len))) { return true; } n += 1; } false }, StartsWith => { if needle.is_empty() { return true; } // PD: switch to use.match_indices() when that stabilizes let mut n=0; while let Some(n1) = haystack[n..].find(needle) { n += n1; if n == 0 ||!is_ident_char(char_at(haystack, n-1)) { return true; } n += 1; } false } } }
match stype { ExactMatch => searchstr == candidate, StartsWith => candidate.starts_with(searchstr) } } // pub fn get_backtrace() -> String { // let mut m = std::old_io::MemWriter::new(); // let s = std::rt::backtrace::write(&mut m) // .ok().map_or("NO backtrace".to_string(), // |_| String::from_utf8_lossy(m.get_ref()).to_string()); // return s; // } pub fn is_double_dot(msrc: &str, i: usize) -> bool { (i > 1) && &msrc[i-1..i+1] == ".." } #[test] fn txt_matches_matches_stuff() { assert_eq!(true, txt_matches(ExactMatch, "Vec","Vec")); assert_eq!(true, txt_matches(StartsWith, "Vec","Vector")); assert_eq!(false, txt_matches(ExactMatch, "Vec","use Vector")); assert_eq!(true, txt_matches(StartsWith, "Vec","use Vector")); assert_eq!(false, txt_matches(StartsWith, "Vec","use aVector")); assert_eq!(true, txt_matches(ExactMatch, "Vec","use Vec")); } pub fn expand_ident(s: &str, pos: usize) -> (usize, usize) { // TODO: Would this better be an assertion? Why are out-of-bound values getting here? // They are coming from the command-line, question is, if they should be handled beforehand // clamp pos into allowed range let pos = cmp::min(s.len(), pos); let sb = &s[..pos]; let mut start = pos; // backtrack to find start of word for (i, c) in sb.char_indices().rev() { if!is_ident_char(c) { break; } start = i; } (start, pos) } pub fn find_ident_end(s: &str, pos: usize) -> usize { // find end of word let sa = &s[pos..]; for (i, c) in sa.char_indices() { if!is_ident_char(c) { return pos + i; } } s.len() } #[test] fn find_ident_end_ascii() { assert_eq!(5, find_ident_end("ident", 0)); assert_eq!(6, find_ident_end("(ident)", 1)); assert_eq!(17, find_ident_end("let an_identifier = 100;", 4)); } #[test] fn find_ident_end_unicode() { assert_eq!(7, find_ident_end("num_µs", 0)); assert_eq!(10, find_ident_end("ends_in_µ", 0)); } // PD: short term replacement for.char_at() function. Should be replaced once // that stabilizes pub fn char_at(src: &str, i: usize) -> char { src[i..].chars().next().unwrap() }
pub fn symbol_matches(stype: SearchType, searchstr: &str, candidate: &str) -> bool {
random_line_split
util.rs
// Small functions of utility use core::SearchType::{self, ExactMatch, StartsWith}; use core::Session; use std::cmp; use std::path::Path; pub fn getline(filepath: &Path, linenum: usize, session: &Session) -> String { let src = session.load_file(filepath); src.code.lines().nth(linenum - 1).unwrap_or("not found").to_string() } pub fn is_pattern_char(c: char) -> bool { c.is_alphanumeric() || c.is_whitespace() || (c == '_') || (c == ':') || (c == '.') } pub fn is_search_expr_char(c: char) -> bool
pub fn is_ident_char(c: char) -> bool { c.is_alphanumeric() || (c == '_') || (c == '!') } pub fn txt_matches(stype: SearchType, needle: &str, haystack: &str) -> bool { match stype { ExactMatch => { let n_len = needle.len(); let h_len = haystack.len(); if n_len == 0 { return true; } // PD: switch to use.match_indices() when that stabilizes let mut n=0; while let Some(n1) = haystack[n..].find(needle) { n += n1; if (n == 0 ||!is_ident_char(char_at(haystack, n-1))) && (n+n_len == h_len ||!is_ident_char(char_at(haystack, n+n_len))) { return true; } n += 1; } false }, StartsWith => { if needle.is_empty() { return true; } // PD: switch to use.match_indices() when that stabilizes let mut n=0; while let Some(n1) = haystack[n..].find(needle) { n += n1; if n == 0 ||!is_ident_char(char_at(haystack, n-1)) { return true; } n += 1; } false } } } pub fn symbol_matches(stype: SearchType, searchstr: &str, candidate: &str) -> bool { match stype { ExactMatch => searchstr == candidate, StartsWith => candidate.starts_with(searchstr) } } // pub fn get_backtrace() -> String { // let mut m = std::old_io::MemWriter::new(); // let s = std::rt::backtrace::write(&mut m) // .ok().map_or("NO backtrace".to_string(), // |_| String::from_utf8_lossy(m.get_ref()).to_string()); // return s; // } pub fn is_double_dot(msrc: &str, i: usize) -> bool { (i > 1) && &msrc[i-1..i+1] == ".." } #[test] fn txt_matches_matches_stuff() { assert_eq!(true, txt_matches(ExactMatch, "Vec","Vec")); assert_eq!(true, txt_matches(StartsWith, "Vec","Vector")); assert_eq!(false, txt_matches(ExactMatch, "Vec","use Vector")); assert_eq!(true, txt_matches(StartsWith, "Vec","use Vector")); assert_eq!(false, txt_matches(StartsWith, "Vec","use aVector")); assert_eq!(true, txt_matches(ExactMatch, "Vec","use Vec")); } pub fn expand_ident(s: &str, pos: usize) -> (usize, usize) { // TODO: Would this better be an assertion? Why are out-of-bound values getting here? // They are coming from the command-line, question is, if they should be handled beforehand // clamp pos into allowed range let pos = cmp::min(s.len(), pos); let sb = &s[..pos]; let mut start = pos; // backtrack to find start of word for (i, c) in sb.char_indices().rev() { if!is_ident_char(c) { break; } start = i; } (start, pos) } pub fn find_ident_end(s: &str, pos: usize) -> usize { // find end of word let sa = &s[pos..]; for (i, c) in sa.char_indices() { if!is_ident_char(c) { return pos + i; } } s.len() } #[test] fn find_ident_end_ascii() { assert_eq!(5, find_ident_end("ident", 0)); assert_eq!(6, find_ident_end("(ident)", 1)); assert_eq!(17, find_ident_end("let an_identifier = 100;", 4)); } #[test] fn find_ident_end_unicode() { assert_eq!(7, find_ident_end("num_µs", 0)); assert_eq!(10, find_ident_end("ends_in_µ", 0)); } // PD: short term replacement for.char_at() function. Should be replaced once // that stabilizes pub fn char_at(src: &str, i: usize) -> char { src[i..].chars().next().unwrap() }
{ c.is_alphanumeric() || (c == '_') || (c == ':') || (c == '.') }
identifier_body
util.rs
// Small functions of utility use core::SearchType::{self, ExactMatch, StartsWith}; use core::Session; use std::cmp; use std::path::Path; pub fn
(filepath: &Path, linenum: usize, session: &Session) -> String { let src = session.load_file(filepath); src.code.lines().nth(linenum - 1).unwrap_or("not found").to_string() } pub fn is_pattern_char(c: char) -> bool { c.is_alphanumeric() || c.is_whitespace() || (c == '_') || (c == ':') || (c == '.') } pub fn is_search_expr_char(c: char) -> bool { c.is_alphanumeric() || (c == '_') || (c == ':') || (c == '.') } pub fn is_ident_char(c: char) -> bool { c.is_alphanumeric() || (c == '_') || (c == '!') } pub fn txt_matches(stype: SearchType, needle: &str, haystack: &str) -> bool { match stype { ExactMatch => { let n_len = needle.len(); let h_len = haystack.len(); if n_len == 0 { return true; } // PD: switch to use.match_indices() when that stabilizes let mut n=0; while let Some(n1) = haystack[n..].find(needle) { n += n1; if (n == 0 ||!is_ident_char(char_at(haystack, n-1))) && (n+n_len == h_len ||!is_ident_char(char_at(haystack, n+n_len))) { return true; } n += 1; } false }, StartsWith => { if needle.is_empty() { return true; } // PD: switch to use.match_indices() when that stabilizes let mut n=0; while let Some(n1) = haystack[n..].find(needle) { n += n1; if n == 0 ||!is_ident_char(char_at(haystack, n-1)) { return true; } n += 1; } false } } } pub fn symbol_matches(stype: SearchType, searchstr: &str, candidate: &str) -> bool { match stype { ExactMatch => searchstr == candidate, StartsWith => candidate.starts_with(searchstr) } } // pub fn get_backtrace() -> String { // let mut m = std::old_io::MemWriter::new(); // let s = std::rt::backtrace::write(&mut m) // .ok().map_or("NO backtrace".to_string(), // |_| String::from_utf8_lossy(m.get_ref()).to_string()); // return s; // } pub fn is_double_dot(msrc: &str, i: usize) -> bool { (i > 1) && &msrc[i-1..i+1] == ".." } #[test] fn txt_matches_matches_stuff() { assert_eq!(true, txt_matches(ExactMatch, "Vec","Vec")); assert_eq!(true, txt_matches(StartsWith, "Vec","Vector")); assert_eq!(false, txt_matches(ExactMatch, "Vec","use Vector")); assert_eq!(true, txt_matches(StartsWith, "Vec","use Vector")); assert_eq!(false, txt_matches(StartsWith, "Vec","use aVector")); assert_eq!(true, txt_matches(ExactMatch, "Vec","use Vec")); } pub fn expand_ident(s: &str, pos: usize) -> (usize, usize) { // TODO: Would this better be an assertion? Why are out-of-bound values getting here? // They are coming from the command-line, question is, if they should be handled beforehand // clamp pos into allowed range let pos = cmp::min(s.len(), pos); let sb = &s[..pos]; let mut start = pos; // backtrack to find start of word for (i, c) in sb.char_indices().rev() { if!is_ident_char(c) { break; } start = i; } (start, pos) } pub fn find_ident_end(s: &str, pos: usize) -> usize { // find end of word let sa = &s[pos..]; for (i, c) in sa.char_indices() { if!is_ident_char(c) { return pos + i; } } s.len() } #[test] fn find_ident_end_ascii() { assert_eq!(5, find_ident_end("ident", 0)); assert_eq!(6, find_ident_end("(ident)", 1)); assert_eq!(17, find_ident_end("let an_identifier = 100;", 4)); } #[test] fn find_ident_end_unicode() { assert_eq!(7, find_ident_end("num_µs", 0)); assert_eq!(10, find_ident_end("ends_in_µ", 0)); } // PD: short term replacement for.char_at() function. Should be replaced once // that stabilizes pub fn char_at(src: &str, i: usize) -> char { src[i..].chars().next().unwrap() }
getline
identifier_name
urls.rs
/* vim: set et: */ use url; use hyper; use types::FolderId; use types::ProgramId; use std::fmt; pub enum EVUrl { Login, Folder(FolderId), Program(ProgramId), Move(ProgramId, FolderId) } impl hyper::client::IntoUrl for EVUrl { fn into_url(self) -> Result<url::Url, url::ParseError> { // TODO: Implement Into<String> for EVUrl let s: String = self.to_string(); url::Url::parse(&s)
} impl fmt::Display for EVUrl { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { EVUrl::Login => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/login.sl"), EVUrl::Folder(ref id) => match *id { FolderId::Root => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true"), ref id => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/ready.sl?folderid={}&ppos=0&ajax=true", id), }, EVUrl::Program(ref id) => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/program.sl?programid={}&ppos=0&ajax=true", id), EVUrl::Move(ref pid, ref fid) => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true&move=true&destination={}&programviewid={}", fid, pid) } } } #[cfg(test)] mod tests { use super::EVUrl; use types::FolderId; use types::ProgramId; #[test] fn show_login_url() { let url = EVUrl::Login; assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/login.sl"); } #[test] fn show_root_folder_url() { let url = EVUrl::Folder(FolderId::Root); assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true"); } #[test] fn show_non_root_folder_url() { let url = EVUrl::Folder(FolderId::FolderId(123)); assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/ready.sl?folderid=123&ppos=0&ajax=true"); } #[test] fn show_program_url() { let url = EVUrl::Program(ProgramId::ProgramId(123)); assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/program.sl?programid=123&ppos=0&ajax=true"); } #[test] fn show_move_url() { let url = EVUrl::Move(ProgramId::ProgramId(123), FolderId::FolderId(321)); assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true&move=true&destination=321&programviewid=123"); } }
}
random_line_split
urls.rs
/* vim: set et: */ use url; use hyper; use types::FolderId; use types::ProgramId; use std::fmt; pub enum EVUrl { Login, Folder(FolderId), Program(ProgramId), Move(ProgramId, FolderId) } impl hyper::client::IntoUrl for EVUrl { fn into_url(self) -> Result<url::Url, url::ParseError> { // TODO: Implement Into<String> for EVUrl let s: String = self.to_string(); url::Url::parse(&s) } } impl fmt::Display for EVUrl { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result
} #[cfg(test)] mod tests { use super::EVUrl; use types::FolderId; use types::ProgramId; #[test] fn show_login_url() { let url = EVUrl::Login; assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/login.sl"); } #[test] fn show_root_folder_url() { let url = EVUrl::Folder(FolderId::Root); assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true"); } #[test] fn show_non_root_folder_url() { let url = EVUrl::Folder(FolderId::FolderId(123)); assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/ready.sl?folderid=123&ppos=0&ajax=true"); } #[test] fn show_program_url() { let url = EVUrl::Program(ProgramId::ProgramId(123)); assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/program.sl?programid=123&ppos=0&ajax=true"); } #[test] fn show_move_url() { let url = EVUrl::Move(ProgramId::ProgramId(123), FolderId::FolderId(321)); assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true&move=true&destination=321&programviewid=123"); } }
{ match *self { EVUrl::Login => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/login.sl"), EVUrl::Folder(ref id) => match *id { FolderId::Root => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true"), ref id => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/ready.sl?folderid={}&ppos=0&ajax=true", id), }, EVUrl::Program(ref id) => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/program.sl?programid={}&ppos=0&ajax=true", id), EVUrl::Move(ref pid, ref fid) => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true&move=true&destination={}&programviewid={}", fid, pid) } }
identifier_body
urls.rs
/* vim: set et: */ use url; use hyper; use types::FolderId; use types::ProgramId; use std::fmt; pub enum EVUrl { Login, Folder(FolderId), Program(ProgramId), Move(ProgramId, FolderId) } impl hyper::client::IntoUrl for EVUrl { fn into_url(self) -> Result<url::Url, url::ParseError> { // TODO: Implement Into<String> for EVUrl let s: String = self.to_string(); url::Url::parse(&s) } } impl fmt::Display for EVUrl { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { EVUrl::Login => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/login.sl"), EVUrl::Folder(ref id) => match *id { FolderId::Root => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true"), ref id => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/ready.sl?folderid={}&ppos=0&ajax=true", id), }, EVUrl::Program(ref id) => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/program.sl?programid={}&ppos=0&ajax=true", id), EVUrl::Move(ref pid, ref fid) => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true&move=true&destination={}&programviewid={}", fid, pid) } } } #[cfg(test)] mod tests { use super::EVUrl; use types::FolderId; use types::ProgramId; #[test] fn
() { let url = EVUrl::Login; assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/login.sl"); } #[test] fn show_root_folder_url() { let url = EVUrl::Folder(FolderId::Root); assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true"); } #[test] fn show_non_root_folder_url() { let url = EVUrl::Folder(FolderId::FolderId(123)); assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/ready.sl?folderid=123&ppos=0&ajax=true"); } #[test] fn show_program_url() { let url = EVUrl::Program(ProgramId::ProgramId(123)); assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/program.sl?programid=123&ppos=0&ajax=true"); } #[test] fn show_move_url() { let url = EVUrl::Move(ProgramId::ProgramId(123), FolderId::FolderId(321)); assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true&move=true&destination=321&programviewid=123"); } }
show_login_url
identifier_name
store.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. */ use crate::ErrorKind; use async_trait::async_trait; use bookmarks::BookmarkName; use bytes::Bytes; use changeset_info::ChangesetInfo; use context::CoreContext; use mononoke_types::{ChangesetId, ContentId, MPath}; use std::collections::HashMap; #[async_trait] pub trait FileContentManager: Send + Sync { async fn get_file_size<'a>( &'a self, ctx: &'a CoreContext, id: ContentId, ) -> Result<u64, ErrorKind>; async fn get_file_text<'a>( &'a self, ctx: &'a CoreContext, id: ContentId, ) -> Result<Option<Bytes>, ErrorKind>; async fn find_content<'a>( &'a self, ctx: &'a CoreContext, bookmark: BookmarkName, paths: Vec<MPath>, ) -> Result<HashMap<MPath, PathContent>, ErrorKind>; async fn file_changes<'a>( &'a self, ctx: &'a CoreContext, new_cs_id: ChangesetId, old_cs_id: ChangesetId, ) -> Result<Vec<(MPath, FileChange)>, ErrorKind>; async fn latest_changes<'a>( &'a self, ctx: &'a CoreContext, bookmark: BookmarkName, paths: Vec<MPath>, ) -> Result<HashMap<MPath, ChangesetInfo>, ErrorKind>; } #[derive(Clone, Debug)] pub enum
{ Directory, File(ContentId), } #[derive(Clone, Debug)] pub enum FileChange { Added(ContentId), Changed(ContentId, ContentId), Removed, }
PathContent
identifier_name
store.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. */ use crate::ErrorKind; use async_trait::async_trait; use bookmarks::BookmarkName; use bytes::Bytes; use changeset_info::ChangesetInfo; use context::CoreContext; use mononoke_types::{ChangesetId, ContentId, MPath}; use std::collections::HashMap; #[async_trait] pub trait FileContentManager: Send + Sync { async fn get_file_size<'a>( &'a self, ctx: &'a CoreContext, id: ContentId, ) -> Result<u64, ErrorKind>; async fn get_file_text<'a>( &'a self, ctx: &'a CoreContext, id: ContentId, ) -> Result<Option<Bytes>, ErrorKind>; async fn find_content<'a>(
ctx: &'a CoreContext, bookmark: BookmarkName, paths: Vec<MPath>, ) -> Result<HashMap<MPath, PathContent>, ErrorKind>; async fn file_changes<'a>( &'a self, ctx: &'a CoreContext, new_cs_id: ChangesetId, old_cs_id: ChangesetId, ) -> Result<Vec<(MPath, FileChange)>, ErrorKind>; async fn latest_changes<'a>( &'a self, ctx: &'a CoreContext, bookmark: BookmarkName, paths: Vec<MPath>, ) -> Result<HashMap<MPath, ChangesetInfo>, ErrorKind>; } #[derive(Clone, Debug)] pub enum PathContent { Directory, File(ContentId), } #[derive(Clone, Debug)] pub enum FileChange { Added(ContentId), Changed(ContentId, ContentId), Removed, }
&'a self,
random_line_split
draw.rs
use specs::{ReadExpect, ReadStorage, System, WriteStorage}; use crate::animation::SpriteData; use crate::combat::components::{AnimationState, Draw, State, UnitType}; pub struct UpdateImage; impl<'a> System<'a> for UpdateImage { type SystemData = ( ReadExpect<'a, SpriteData>, WriteStorage<'a, Draw>, ReadStorage<'a, AnimationState>, ReadStorage<'a, UnitType>, WriteStorage<'a, State>, ); fn run( &mut self, (sprite_data, mut draw, animation_state, unit_type, mut state): Self::SystemData, ) { use specs::Join; let sprites = &sprite_data.sprites; for (draw, animation_state, unit_type, state) in (&mut draw, &animation_state, &unit_type, &mut state).join()
let animation = draw.animation.as_str(); let sprite_resource = sprites.get(&unit_type.name); if let Some(sprite) = sprite_resource { let animation = sprite .animations .get(animation) .unwrap_or_else(|| panic!("{} not found in yaml", animation)); match &animation.order { None => { draw.frame = animation.frames[animation_state.frame_number as usize].clone(); draw.direction = state.direction; state.length = animation.frames.len() as u32; } Some(order) => { let frame_num: usize = order[animation_state.frame_number as usize] as usize; draw.frame = animation.frames[frame_num].clone(); draw.direction = state.direction; state.length = order.len() as u32; } } } } } }
{
random_line_split
draw.rs
use specs::{ReadExpect, ReadStorage, System, WriteStorage}; use crate::animation::SpriteData; use crate::combat::components::{AnimationState, Draw, State, UnitType}; pub struct
; impl<'a> System<'a> for UpdateImage { type SystemData = ( ReadExpect<'a, SpriteData>, WriteStorage<'a, Draw>, ReadStorage<'a, AnimationState>, ReadStorage<'a, UnitType>, WriteStorage<'a, State>, ); fn run( &mut self, (sprite_data, mut draw, animation_state, unit_type, mut state): Self::SystemData, ) { use specs::Join; let sprites = &sprite_data.sprites; for (draw, animation_state, unit_type, state) in (&mut draw, &animation_state, &unit_type, &mut state).join() { let animation = draw.animation.as_str(); let sprite_resource = sprites.get(&unit_type.name); if let Some(sprite) = sprite_resource { let animation = sprite .animations .get(animation) .unwrap_or_else(|| panic!("{} not found in yaml", animation)); match &animation.order { None => { draw.frame = animation.frames[animation_state.frame_number as usize].clone(); draw.direction = state.direction; state.length = animation.frames.len() as u32; } Some(order) => { let frame_num: usize = order[animation_state.frame_number as usize] as usize; draw.frame = animation.frames[frame_num].clone(); draw.direction = state.direction; state.length = order.len() as u32; } } } } } }
UpdateImage
identifier_name
draw.rs
use specs::{ReadExpect, ReadStorage, System, WriteStorage}; use crate::animation::SpriteData; use crate::combat::components::{AnimationState, Draw, State, UnitType}; pub struct UpdateImage; impl<'a> System<'a> for UpdateImage { type SystemData = ( ReadExpect<'a, SpriteData>, WriteStorage<'a, Draw>, ReadStorage<'a, AnimationState>, ReadStorage<'a, UnitType>, WriteStorage<'a, State>, ); fn run( &mut self, (sprite_data, mut draw, animation_state, unit_type, mut state): Self::SystemData, ) { use specs::Join; let sprites = &sprite_data.sprites; for (draw, animation_state, unit_type, state) in (&mut draw, &animation_state, &unit_type, &mut state).join() { let animation = draw.animation.as_str(); let sprite_resource = sprites.get(&unit_type.name); if let Some(sprite) = sprite_resource
} } } }
{ let animation = sprite .animations .get(animation) .unwrap_or_else(|| panic!("{} not found in yaml", animation)); match &animation.order { None => { draw.frame = animation.frames[animation_state.frame_number as usize].clone(); draw.direction = state.direction; state.length = animation.frames.len() as u32; } Some(order) => { let frame_num: usize = order[animation_state.frame_number as usize] as usize; draw.frame = animation.frames[frame_num].clone(); draw.direction = state.direction; state.length = order.len() as u32; } }
conditional_block
default.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. use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use std::gc::Gc; pub fn expand_deriving_default(cx: &mut ExtCtxt, span: Span, mitem: Gc<MetaItem>, item: Gc<Item>, push: |Gc<Item>|) { let inline = cx.meta_word(span, InternedString::new("inline")); let attrs = vec!(cx.attribute(span, inline)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: Path::new(vec!("std", "default", "Default")), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!( MethodDef { name: "default", generics: LifetimeBounds::empty(), explicit_self: None, args: Vec::new(), ret_ty: Self, attributes: attrs, const_nonmatching: false, combine_substructure: combine_substructure(|a, b, c| { default_substructure(a, b, c) }) }) }; trait_def.expand(cx, mitem, item, push) } fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> Gc<Expr>
Named(ref fields) => { let default_fields = fields.iter().map(|&(ident, span)| { cx.field_imm(span, ident, default_call(span)) }).collect(); cx.expr_struct_ident(trait_span, substr.type_ident, default_fields) } } } StaticEnum(..) => { cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs"); // let compilation continue cx.expr_uint(trait_span, 0) } _ => cx.span_bug(trait_span, "Non-static method in `deriving(Default)`") }; }
{ let default_ident = vec!( cx.ident_of("std"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ); let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new()); return match *substr.fields { StaticStruct(_, ref summary) => { match *summary { Unnamed(ref fields) => { if fields.is_empty() { cx.expr_ident(trait_span, substr.type_ident) } else { let exprs = fields.iter().map(|sp| default_call(*sp)).collect(); cx.expr_call_ident(trait_span, substr.type_ident, exprs) } }
identifier_body
default.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. use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use std::gc::Gc; pub fn expand_deriving_default(cx: &mut ExtCtxt, span: Span, mitem: Gc<MetaItem>, item: Gc<Item>, push: |Gc<Item>|) { let inline = cx.meta_word(span, InternedString::new("inline")); let attrs = vec!(cx.attribute(span, inline)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: Path::new(vec!("std", "default", "Default")), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!( MethodDef { name: "default", generics: LifetimeBounds::empty(), explicit_self: None, args: Vec::new(), ret_ty: Self, attributes: attrs, const_nonmatching: false, combine_substructure: combine_substructure(|a, b, c| { default_substructure(a, b, c) }) }) }; trait_def.expand(cx, mitem, item, push) } fn
(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> Gc<Expr> { let default_ident = vec!( cx.ident_of("std"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ); let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new()); return match *substr.fields { StaticStruct(_, ref summary) => { match *summary { Unnamed(ref fields) => { if fields.is_empty() { cx.expr_ident(trait_span, substr.type_ident) } else { let exprs = fields.iter().map(|sp| default_call(*sp)).collect(); cx.expr_call_ident(trait_span, substr.type_ident, exprs) } } Named(ref fields) => { let default_fields = fields.iter().map(|&(ident, span)| { cx.field_imm(span, ident, default_call(span)) }).collect(); cx.expr_struct_ident(trait_span, substr.type_ident, default_fields) } } } StaticEnum(..) => { cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs"); // let compilation continue cx.expr_uint(trait_span, 0) } _ => cx.span_bug(trait_span, "Non-static method in `deriving(Default)`") }; }
default_substructure
identifier_name
default.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. use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use std::gc::Gc; pub fn expand_deriving_default(cx: &mut ExtCtxt, span: Span, mitem: Gc<MetaItem>, item: Gc<Item>, push: |Gc<Item>|) { let inline = cx.meta_word(span, InternedString::new("inline")); let attrs = vec!(cx.attribute(span, inline)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: Path::new(vec!("std", "default", "Default")), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!( MethodDef { name: "default", generics: LifetimeBounds::empty(), explicit_self: None, args: Vec::new(), ret_ty: Self, attributes: attrs, const_nonmatching: false, combine_substructure: combine_substructure(|a, b, c| { default_substructure(a, b, c) }) }) }; trait_def.expand(cx, mitem, item, push) } fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> Gc<Expr> { let default_ident = vec!( cx.ident_of("std"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ); let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new()); return match *substr.fields { StaticStruct(_, ref summary) => { match *summary { Unnamed(ref fields) => { if fields.is_empty() { cx.expr_ident(trait_span, substr.type_ident) } else { let exprs = fields.iter().map(|sp| default_call(*sp)).collect(); cx.expr_call_ident(trait_span, substr.type_ident, exprs) } } Named(ref fields) => {
}).collect(); cx.expr_struct_ident(trait_span, substr.type_ident, default_fields) } } } StaticEnum(..) => { cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs"); // let compilation continue cx.expr_uint(trait_span, 0) } _ => cx.span_bug(trait_span, "Non-static method in `deriving(Default)`") }; }
let default_fields = fields.iter().map(|&(ident, span)| { cx.field_imm(span, ident, default_call(span))
random_line_split
facebook.rs
use hyper; use hyper::net::NetworkListener; use hyper::server::Request; use hyper::server::Response; use hyper::uri::RequestUri; use hyper::header::AccessControlAllowOrigin; use rand::{self, Rng}; use serde_json; use std::collections::BTreeMap; use std::io::Read; use std::sync::{mpsc, Mutex}; use url; use protocol::authentication::AuthenticationType; use authentication::Credentials; use ::spotilocal::ssl_context; struct ServerHandler { token_tx: Mutex<mpsc::Sender<String>>, csrf: String, } impl ServerHandler { fn handle_login(&self, params: &BTreeMap<String, String>) -> hyper::status::StatusCode { let token = params.get("access_token").unwrap(); let csrf = params.get("csrf").unwrap(); if *csrf == self.csrf { self.token_tx.lock().unwrap().send(token.to_owned()).unwrap(); hyper::status::StatusCode::Ok } else { hyper::status::StatusCode::Forbidden } } } impl hyper::server::Handler for ServerHandler { fn handle<'a, 'k>(&'a self, request: Request<'a, 'k>, mut response: Response<'a, hyper::net::Fresh>) { response.headers_mut().set(AccessControlAllowOrigin::Value("https://login.spotify.com".to_owned())); *response.status_mut() = if let RequestUri::AbsolutePath(path) = request.uri { let (path, query, _) = url::parse_path(&path).unwrap(); let params = query.map_or(vec![], |q| url::form_urlencoded::parse(q.as_bytes())) .into_iter().collect::<BTreeMap<_,_>>(); debug!("{:?} {:?} {:?}", request.method, path, params); if request.method == hyper::method::Method::Get && path == vec!["login", "facebook_login_sso.json"] { self.handle_login(&params) } else { hyper::status::StatusCode::NotFound } } else { hyper::status::StatusCode::NotFound } } } fn facebook_get_me_id(token: &str) -> Result<String, ()>
pub fn facebook_login() -> Result<Credentials, ()> { let (tx, rx) = mpsc::channel(); let csrf = rand::thread_rng().gen_ascii_chars().take(32).collect::<String>(); let handler = ServerHandler { token_tx: Mutex::new(tx), csrf: csrf.clone() }; let ssl = ssl_context().unwrap(); let mut listener = hyper::net::HttpsListener::new("127.0.0.1:0", ssl).unwrap(); let port = listener.local_addr().unwrap().port(); let mut server = hyper::Server::new(listener).handle(handler).unwrap(); println!("Logging in using Facebook, please visit https://login.spotify.com/login-facebook-sso/?csrf={}&port={} in your browser.", csrf, port); let token = rx.recv().unwrap(); let user_id = facebook_get_me_id(&token).unwrap(); let cred = Credentials { username: user_id, auth_type: AuthenticationType::AUTHENTICATION_FACEBOOK_TOKEN, auth_data: token.as_bytes().to_owned(), }; server.close().unwrap(); Ok(cred) }
{ let url = format!("https://graph.facebook.com/me?fields=id&access_token={}", token); let client = hyper::Client::new(); let mut response = client.get(&url).send().unwrap(); let mut body = String::new(); response.read_to_string(&mut body).unwrap(); let mut result : BTreeMap<String, String> = serde_json::from_str(&body).unwrap(); Ok(result.remove("id").unwrap()) }
identifier_body
facebook.rs
use hyper; use hyper::net::NetworkListener; use hyper::server::Request; use hyper::server::Response; use hyper::uri::RequestUri; use hyper::header::AccessControlAllowOrigin; use rand::{self, Rng}; use serde_json; use std::collections::BTreeMap; use std::io::Read; use std::sync::{mpsc, Mutex}; use url; use protocol::authentication::AuthenticationType; use authentication::Credentials; use ::spotilocal::ssl_context; struct ServerHandler { token_tx: Mutex<mpsc::Sender<String>>, csrf: String, } impl ServerHandler { fn handle_login(&self, params: &BTreeMap<String, String>) -> hyper::status::StatusCode { let token = params.get("access_token").unwrap(); let csrf = params.get("csrf").unwrap(); if *csrf == self.csrf { self.token_tx.lock().unwrap().send(token.to_owned()).unwrap(); hyper::status::StatusCode::Ok } else { hyper::status::StatusCode::Forbidden } } } impl hyper::server::Handler for ServerHandler { fn handle<'a, 'k>(&'a self, request: Request<'a, 'k>, mut response: Response<'a, hyper::net::Fresh>) { response.headers_mut().set(AccessControlAllowOrigin::Value("https://login.spotify.com".to_owned())); *response.status_mut() = if let RequestUri::AbsolutePath(path) = request.uri { let (path, query, _) = url::parse_path(&path).unwrap(); let params = query.map_or(vec![], |q| url::form_urlencoded::parse(q.as_bytes())) .into_iter().collect::<BTreeMap<_,_>>(); debug!("{:?} {:?} {:?}", request.method, path, params); if request.method == hyper::method::Method::Get && path == vec!["login", "facebook_login_sso.json"] { self.handle_login(&params) } else
} else { hyper::status::StatusCode::NotFound } } } fn facebook_get_me_id(token: &str) -> Result<String, ()> { let url = format!("https://graph.facebook.com/me?fields=id&access_token={}", token); let client = hyper::Client::new(); let mut response = client.get(&url).send().unwrap(); let mut body = String::new(); response.read_to_string(&mut body).unwrap(); let mut result : BTreeMap<String, String> = serde_json::from_str(&body).unwrap(); Ok(result.remove("id").unwrap()) } pub fn facebook_login() -> Result<Credentials, ()> { let (tx, rx) = mpsc::channel(); let csrf = rand::thread_rng().gen_ascii_chars().take(32).collect::<String>(); let handler = ServerHandler { token_tx: Mutex::new(tx), csrf: csrf.clone() }; let ssl = ssl_context().unwrap(); let mut listener = hyper::net::HttpsListener::new("127.0.0.1:0", ssl).unwrap(); let port = listener.local_addr().unwrap().port(); let mut server = hyper::Server::new(listener).handle(handler).unwrap(); println!("Logging in using Facebook, please visit https://login.spotify.com/login-facebook-sso/?csrf={}&port={} in your browser.", csrf, port); let token = rx.recv().unwrap(); let user_id = facebook_get_me_id(&token).unwrap(); let cred = Credentials { username: user_id, auth_type: AuthenticationType::AUTHENTICATION_FACEBOOK_TOKEN, auth_data: token.as_bytes().to_owned(), }; server.close().unwrap(); Ok(cred) }
{ hyper::status::StatusCode::NotFound }
conditional_block
facebook.rs
use hyper; use hyper::net::NetworkListener; use hyper::server::Request; use hyper::server::Response; use hyper::uri::RequestUri; use hyper::header::AccessControlAllowOrigin; use rand::{self, Rng}; use serde_json; use std::collections::BTreeMap; use std::io::Read; use std::sync::{mpsc, Mutex}; use url; use protocol::authentication::AuthenticationType; use authentication::Credentials; use ::spotilocal::ssl_context; struct ServerHandler { token_tx: Mutex<mpsc::Sender<String>>, csrf: String, } impl ServerHandler { fn handle_login(&self, params: &BTreeMap<String, String>) -> hyper::status::StatusCode { let token = params.get("access_token").unwrap(); let csrf = params.get("csrf").unwrap(); if *csrf == self.csrf { self.token_tx.lock().unwrap().send(token.to_owned()).unwrap(); hyper::status::StatusCode::Ok } else { hyper::status::StatusCode::Forbidden } } } impl hyper::server::Handler for ServerHandler { fn handle<'a, 'k>(&'a self, request: Request<'a, 'k>, mut response: Response<'a, hyper::net::Fresh>) { response.headers_mut().set(AccessControlAllowOrigin::Value("https://login.spotify.com".to_owned())); *response.status_mut() = if let RequestUri::AbsolutePath(path) = request.uri { let (path, query, _) = url::parse_path(&path).unwrap(); let params = query.map_or(vec![], |q| url::form_urlencoded::parse(q.as_bytes())) .into_iter().collect::<BTreeMap<_,_>>(); debug!("{:?} {:?} {:?}", request.method, path, params); if request.method == hyper::method::Method::Get && path == vec!["login", "facebook_login_sso.json"] { self.handle_login(&params) } else { hyper::status::StatusCode::NotFound } } else { hyper::status::StatusCode::NotFound } } } fn facebook_get_me_id(token: &str) -> Result<String, ()> { let url = format!("https://graph.facebook.com/me?fields=id&access_token={}", token); let client = hyper::Client::new(); let mut response = client.get(&url).send().unwrap(); let mut body = String::new(); response.read_to_string(&mut body).unwrap(); let mut result : BTreeMap<String, String> = serde_json::from_str(&body).unwrap(); Ok(result.remove("id").unwrap()) } pub fn facebook_login() -> Result<Credentials, ()> { let (tx, rx) = mpsc::channel(); let csrf = rand::thread_rng().gen_ascii_chars().take(32).collect::<String>(); let handler = ServerHandler { token_tx: Mutex::new(tx), csrf: csrf.clone() }; let ssl = ssl_context().unwrap(); let mut listener = hyper::net::HttpsListener::new("127.0.0.1:0", ssl).unwrap(); let port = listener.local_addr().unwrap().port();
let mut server = hyper::Server::new(listener).handle(handler).unwrap(); println!("Logging in using Facebook, please visit https://login.spotify.com/login-facebook-sso/?csrf={}&port={} in your browser.", csrf, port); let token = rx.recv().unwrap(); let user_id = facebook_get_me_id(&token).unwrap(); let cred = Credentials { username: user_id, auth_type: AuthenticationType::AUTHENTICATION_FACEBOOK_TOKEN, auth_data: token.as_bytes().to_owned(), }; server.close().unwrap(); Ok(cred) }
random_line_split
facebook.rs
use hyper; use hyper::net::NetworkListener; use hyper::server::Request; use hyper::server::Response; use hyper::uri::RequestUri; use hyper::header::AccessControlAllowOrigin; use rand::{self, Rng}; use serde_json; use std::collections::BTreeMap; use std::io::Read; use std::sync::{mpsc, Mutex}; use url; use protocol::authentication::AuthenticationType; use authentication::Credentials; use ::spotilocal::ssl_context; struct ServerHandler { token_tx: Mutex<mpsc::Sender<String>>, csrf: String, } impl ServerHandler { fn
(&self, params: &BTreeMap<String, String>) -> hyper::status::StatusCode { let token = params.get("access_token").unwrap(); let csrf = params.get("csrf").unwrap(); if *csrf == self.csrf { self.token_tx.lock().unwrap().send(token.to_owned()).unwrap(); hyper::status::StatusCode::Ok } else { hyper::status::StatusCode::Forbidden } } } impl hyper::server::Handler for ServerHandler { fn handle<'a, 'k>(&'a self, request: Request<'a, 'k>, mut response: Response<'a, hyper::net::Fresh>) { response.headers_mut().set(AccessControlAllowOrigin::Value("https://login.spotify.com".to_owned())); *response.status_mut() = if let RequestUri::AbsolutePath(path) = request.uri { let (path, query, _) = url::parse_path(&path).unwrap(); let params = query.map_or(vec![], |q| url::form_urlencoded::parse(q.as_bytes())) .into_iter().collect::<BTreeMap<_,_>>(); debug!("{:?} {:?} {:?}", request.method, path, params); if request.method == hyper::method::Method::Get && path == vec!["login", "facebook_login_sso.json"] { self.handle_login(&params) } else { hyper::status::StatusCode::NotFound } } else { hyper::status::StatusCode::NotFound } } } fn facebook_get_me_id(token: &str) -> Result<String, ()> { let url = format!("https://graph.facebook.com/me?fields=id&access_token={}", token); let client = hyper::Client::new(); let mut response = client.get(&url).send().unwrap(); let mut body = String::new(); response.read_to_string(&mut body).unwrap(); let mut result : BTreeMap<String, String> = serde_json::from_str(&body).unwrap(); Ok(result.remove("id").unwrap()) } pub fn facebook_login() -> Result<Credentials, ()> { let (tx, rx) = mpsc::channel(); let csrf = rand::thread_rng().gen_ascii_chars().take(32).collect::<String>(); let handler = ServerHandler { token_tx: Mutex::new(tx), csrf: csrf.clone() }; let ssl = ssl_context().unwrap(); let mut listener = hyper::net::HttpsListener::new("127.0.0.1:0", ssl).unwrap(); let port = listener.local_addr().unwrap().port(); let mut server = hyper::Server::new(listener).handle(handler).unwrap(); println!("Logging in using Facebook, please visit https://login.spotify.com/login-facebook-sso/?csrf={}&port={} in your browser.", csrf, port); let token = rx.recv().unwrap(); let user_id = facebook_get_me_id(&token).unwrap(); let cred = Credentials { username: user_id, auth_type: AuthenticationType::AUTHENTICATION_FACEBOOK_TOKEN, auth_data: token.as_bytes().to_owned(), }; server.close().unwrap(); Ok(cred) }
handle_login
identifier_name
scell_seal_string_echo.rs
// Copyright 2019 (c) rust-themis 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. use std::process::exit;
use themis::secure_cell::SecureCell; fn main() { let matches = clap_app!(scell_seal_string_echo => (version: env!("CARGO_PKG_VERSION")) (about: "Secure Cell echo testing tool (sealing mode).") (@arg mode: +required "<enc|dec>") (@arg key: +required "master key") (@arg message: +required "message to encrypt or decrypt") (@arg context: "user context") ) .get_matches(); let mode = matches.value_of("mode").unwrap(); let key = matches.value_of("key").unwrap(); let message = matches.value_of("message").unwrap(); let context = matches.value_of("context").unwrap_or_default(); let cell = SecureCell::with_key(&key) .unwrap_or_else(|_| { eprintln!("invalid parameters: empty master key"); exit(1); }) .seal(); match mode { "enc" => { let encrypted = cell .encrypt_with_context(&message, &context) .unwrap_or_else(|error| { eprintln!("failed to encrypt message: {}", error); exit(1); }); println!("{}", base64::encode(&encrypted)); } "dec" => { let decoded_message = base64::decode(&message).unwrap_or_else(|error| { eprintln!("failed to decode message: {}", error); exit(1); }); let decrypted = cell .decrypt_with_context(&decoded_message, &context) .unwrap_or_else(|error| { eprintln!("failed to decrypt message: {}", error); exit(1); }); println!("{}", std::str::from_utf8(&decrypted).expect("UTF-8 string")); } other => { eprintln!("invalid mode {}, use \"enc\" or \"dec\"", other); exit(1); } } }
use clap::clap_app;
random_line_split
scell_seal_string_echo.rs
// Copyright 2019 (c) rust-themis 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. use std::process::exit; use clap::clap_app; use themis::secure_cell::SecureCell; fn
() { let matches = clap_app!(scell_seal_string_echo => (version: env!("CARGO_PKG_VERSION")) (about: "Secure Cell echo testing tool (sealing mode).") (@arg mode: +required "<enc|dec>") (@arg key: +required "master key") (@arg message: +required "message to encrypt or decrypt") (@arg context: "user context") ) .get_matches(); let mode = matches.value_of("mode").unwrap(); let key = matches.value_of("key").unwrap(); let message = matches.value_of("message").unwrap(); let context = matches.value_of("context").unwrap_or_default(); let cell = SecureCell::with_key(&key) .unwrap_or_else(|_| { eprintln!("invalid parameters: empty master key"); exit(1); }) .seal(); match mode { "enc" => { let encrypted = cell .encrypt_with_context(&message, &context) .unwrap_or_else(|error| { eprintln!("failed to encrypt message: {}", error); exit(1); }); println!("{}", base64::encode(&encrypted)); } "dec" => { let decoded_message = base64::decode(&message).unwrap_or_else(|error| { eprintln!("failed to decode message: {}", error); exit(1); }); let decrypted = cell .decrypt_with_context(&decoded_message, &context) .unwrap_or_else(|error| { eprintln!("failed to decrypt message: {}", error); exit(1); }); println!("{}", std::str::from_utf8(&decrypted).expect("UTF-8 string")); } other => { eprintln!("invalid mode {}, use \"enc\" or \"dec\"", other); exit(1); } } }
main
identifier_name
scell_seal_string_echo.rs
// Copyright 2019 (c) rust-themis 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. use std::process::exit; use clap::clap_app; use themis::secure_cell::SecureCell; fn main()
}) .seal(); match mode { "enc" => { let encrypted = cell .encrypt_with_context(&message, &context) .unwrap_or_else(|error| { eprintln!("failed to encrypt message: {}", error); exit(1); }); println!("{}", base64::encode(&encrypted)); } "dec" => { let decoded_message = base64::decode(&message).unwrap_or_else(|error| { eprintln!("failed to decode message: {}", error); exit(1); }); let decrypted = cell .decrypt_with_context(&decoded_message, &context) .unwrap_or_else(|error| { eprintln!("failed to decrypt message: {}", error); exit(1); }); println!("{}", std::str::from_utf8(&decrypted).expect("UTF-8 string")); } other => { eprintln!("invalid mode {}, use \"enc\" or \"dec\"", other); exit(1); } } }
{ let matches = clap_app!(scell_seal_string_echo => (version: env!("CARGO_PKG_VERSION")) (about: "Secure Cell echo testing tool (sealing mode).") (@arg mode: +required "<enc|dec>") (@arg key: +required "master key") (@arg message: +required "message to encrypt or decrypt") (@arg context: "user context") ) .get_matches(); let mode = matches.value_of("mode").unwrap(); let key = matches.value_of("key").unwrap(); let message = matches.value_of("message").unwrap(); let context = matches.value_of("context").unwrap_or_default(); let cell = SecureCell::with_key(&key) .unwrap_or_else(|_| { eprintln!("invalid parameters: empty master key"); exit(1);
identifier_body
user.rs
use std::convert::From; use crypto; use diesel; use errors::Error; use diesel::prelude::*; use data::schema::users; use data::users::{User as ModelUser, NewUser as ModelNewUser}; #[derive(Serialize, Deserialize)] pub struct
{ pub id: Uuid, pub email: String, #[serde(skip_serializing, skip_deserializing)] pub password: Vec<u8>, } impl From<ModelUser> for User { fn from(user: ModelUser) -> User { User { id: user.id, email: user.email, password: user.password, } } } impl User { pub fn verify_password(&self, plaintext: &str) -> bool { crypto::verify(&self.password, plaintext.as_bytes()).unwrap(); } } pub struct NewUser<'a> { pub email: &'a str, pub password: Vec<u8>, } pub fn create_user<'a>(user: &'a NewUser, conn: &'a PgConnection) -> Result<User, Error> { let new_user = ModelUser { email: &user.email.to_lowercase(), password: crypto::hash(user.password.as_ref(), crypto::generate_salt(16).unwrap()), }; // get database result and insert new user into users table diesel::insert(&new_user) .into(users::table) .get_result::<ModelUser>(conn) .and_then(|user| Ok(user.into())) }
User
identifier_name
user.rs
use std::convert::From; use crypto; use diesel; use errors::Error; use diesel::prelude::*; use data::schema::users; use data::users::{User as ModelUser, NewUser as ModelNewUser}; #[derive(Serialize, Deserialize)] pub struct User { pub id: Uuid, pub email: String, #[serde(skip_serializing, skip_deserializing)] pub password: Vec<u8>, } impl From<ModelUser> for User { fn from(user: ModelUser) -> User { User { id: user.id, email: user.email, password: user.password, } } } impl User { pub fn verify_password(&self, plaintext: &str) -> bool
} pub struct NewUser<'a> { pub email: &'a str, pub password: Vec<u8>, } pub fn create_user<'a>(user: &'a NewUser, conn: &'a PgConnection) -> Result<User, Error> { let new_user = ModelUser { email: &user.email.to_lowercase(), password: crypto::hash(user.password.as_ref(), crypto::generate_salt(16).unwrap()), }; // get database result and insert new user into users table diesel::insert(&new_user) .into(users::table) .get_result::<ModelUser>(conn) .and_then(|user| Ok(user.into())) }
{ crypto::verify(&self.password, plaintext.as_bytes()).unwrap(); }
identifier_body
user.rs
use std::convert::From; use crypto; use diesel; use errors::Error; use diesel::prelude::*; use data::schema::users; use data::users::{User as ModelUser, NewUser as ModelNewUser}; #[derive(Serialize, Deserialize)] pub struct User { pub id: Uuid, pub email: String, #[serde(skip_serializing, skip_deserializing)] pub password: Vec<u8>, }
email: user.email, password: user.password, } } } impl User { pub fn verify_password(&self, plaintext: &str) -> bool { crypto::verify(&self.password, plaintext.as_bytes()).unwrap(); } } pub struct NewUser<'a> { pub email: &'a str, pub password: Vec<u8>, } pub fn create_user<'a>(user: &'a NewUser, conn: &'a PgConnection) -> Result<User, Error> { let new_user = ModelUser { email: &user.email.to_lowercase(), password: crypto::hash(user.password.as_ref(), crypto::generate_salt(16).unwrap()), }; // get database result and insert new user into users table diesel::insert(&new_user) .into(users::table) .get_result::<ModelUser>(conn) .and_then(|user| Ok(user.into())) }
impl From<ModelUser> for User { fn from(user: ModelUser) -> User { User { id: user.id,
random_line_split
super.rs
fn function() { println!("called `function()`"); } mod cool { pub fn
() { println!("called `cool::function()`"); } } mod my { fn function() { println!("called `my::function()`"); } mod cool { pub fn function() { println!("called `my::cool::function()`"); } } pub fn indirect_call() { // Let's access all the functions named `function` from this scope! print!("called `my::indirect_call()`, that\n> "); // The `self` keyword refers to the current module scope - in this case `my`. // Calling `self::function()` and calling `function()` directly both give // the same result, because they refer to the same function. self::function(); function(); // We can also use `self` to access another module inside `my`: self::cool::function(); // The `super` keyword refers to the parent scope (outside the `my` module). super::function(); // This will bind to the `cool::function` in the *crate* scope. // In this case the crate scope is the outermost scope. { use cool::function as root_function; root_function(); } } } fn main() { my::indirect_call(); }
function
identifier_name
super.rs
fn function() { println!("called `function()`"); } mod cool { pub fn function() { println!("called `cool::function()`"); } } mod my { fn function() { println!("called `my::function()`"); } mod cool { pub fn function()
} pub fn indirect_call() { // Let's access all the functions named `function` from this scope! print!("called `my::indirect_call()`, that\n> "); // The `self` keyword refers to the current module scope - in this case `my`. // Calling `self::function()` and calling `function()` directly both give // the same result, because they refer to the same function. self::function(); function(); // We can also use `self` to access another module inside `my`: self::cool::function(); // The `super` keyword refers to the parent scope (outside the `my` module). super::function(); // This will bind to the `cool::function` in the *crate* scope. // In this case the crate scope is the outermost scope. { use cool::function as root_function; root_function(); } } } fn main() { my::indirect_call(); }
{ println!("called `my::cool::function()`"); }
identifier_body
super.rs
fn function() { println!("called `function()`"); } mod cool { pub fn function() { println!("called `cool::function()`"); } } mod my { fn function() { println!("called `my::function()`"); } mod cool { pub fn function() { println!("called `my::cool::function()`"); } } pub fn indirect_call() { // Let's access all the functions named `function` from this scope! print!("called `my::indirect_call()`, that\n> ");
// the same result, because they refer to the same function. self::function(); function(); // We can also use `self` to access another module inside `my`: self::cool::function(); // The `super` keyword refers to the parent scope (outside the `my` module). super::function(); // This will bind to the `cool::function` in the *crate* scope. // In this case the crate scope is the outermost scope. { use cool::function as root_function; root_function(); } } } fn main() { my::indirect_call(); }
// The `self` keyword refers to the current module scope - in this case `my`. // Calling `self::function()` and calling `function()` directly both give
random_line_split
hamming_numbers.rs
// http://rosettacode.org/wiki/Hamming_numbers extern crate num; use num::bigint::{BigUint, ToBigUint}; use std::cmp::min; use std::num::{One, one}; use std::collections::{RingBuf, Deque}; // needed because hamming_numbers_alt uses this as a library #[allow(dead_code)] #[cfg(not(test))] fn main() { // capacity of the queue currently needs to be a power of 2 because of a bug with RingBuf let hamming : Hamming<BigUint> = Hamming::new(128); for (idx, h) in hamming.enumerate().take(1_000_000) { match idx + 1 { 1..20 => print!("{} ", h.to_biguint().unwrap()), i @ 1691 | i @ 1000000 => println!("\n{}th number: {}", i, h.to_biguint().unwrap()), _ => continue } } } //representing a Hamming number as a BigUint impl HammingNumber for BigUint { // returns the multipliers 2, 3 and 5 in the representation for the HammingNumber fn multipliers()-> (BigUint, BigUint, BigUint) { (2u.to_biguint().unwrap(), 3u.to_biguint().unwrap(), 5u.to_biguint().unwrap()) } } /// representation of a Hamming number /// allows to abstract on how the hamming number is stored /// i.e. as BigUint directly or just as the powers of 2, 3 and 5 used to build it pub trait HammingNumber : Eq + Ord + ToBigUint + Mul<Self, Self> + One { fn multipliers() -> (Self, Self, Self); } /// Hamming numbers are multiples of 2, 3 or 5. /// /// We keep them on three queues and extract the lowest (leftmost) value from /// the three queues at each iteration. pub struct Hamming<T> { // Using a RingBuf as a queue, push to the back, pop from the front q2: RingBuf<T>, q3: RingBuf<T>, q5: RingBuf<T> } impl<T: HammingNumber> Hamming<T> { /// Static constructor method /// `n` initializes the capacity of the queues pub fn new(n: uint) -> Hamming<T> { let mut h = Hamming { q2: RingBuf::with_capacity(n), q3: RingBuf::with_capacity(n), q5: RingBuf::with_capacity(n) };
h } /// Pushes the next multiple of `n` (x2, x3, x5) to the queues pub fn enqueue(&mut self, n: &T) { let (two, three, five) = HammingNumber::multipliers(); self.q2.push(*n * two); self.q3.push(*n * three); self.q5.push(*n * five); } } // Implements the `Iterator` trait, so we can generate Hamming numbers lazily impl<T: HammingNumber> Iterator<T> for Hamming<T> { // The core of the work is done in the `next` method. // We check which of the 3 queues has the lowest candidate and extract it // as the next Hamming number. fn next(&mut self) -> Option<T> { // Return `pop_targets` so the borrow from `front()` will be finished let (two, three, five) = match (self.q2.front(), self.q3.front(), self.q5.front()) { (Some(head2), Some(head3), Some(head5)) => { let n = min(head2, min(head3, head5)); (head2 == n, head3 == n, head5 == n) }, _ => unreachable!() }; let h2 = if two { self.q2.pop_front() } else { None }; let h3 = if three { self.q3.pop_front() } else { None }; let h5 = if five { self.q5.pop_front() } else { None }; match h2.or(h3).or(h5) { Some(n) => { self.enqueue(&n); Some(n) } None => unreachable!() } } } #[test] fn create() { let mut h = Hamming::<BigUint>::new(5); h.q2.push(one::<BigUint>()); h.q2.push(one::<BigUint>() * 3u.to_biguint().unwrap()); assert_eq!(h.q2.pop_front().unwrap(), one::<BigUint>()); } #[test] fn try_enqueue() { let mut h = Hamming::<BigUint>::new(5); let (two, three, five) = HammingNumber::multipliers(); h.enqueue(&one::<BigUint>()); h.enqueue(&(&one::<BigUint>() * two)); assert!(h.q2.pop_front().unwrap() == one::<BigUint>()); assert!(h.q3.pop_front().unwrap() == one::<BigUint>()); assert!(h.q5.pop_front().unwrap() == one::<BigUint>()); assert!(h.q2.pop_front().unwrap() == one::<BigUint>() * two); assert!(h.q3.pop_front().unwrap() == one::<BigUint>() * three); assert!(h.q5.pop_front().unwrap() == one::<BigUint>() * five); } #[test] fn hamming_iter() { let mut hamming = Hamming::<BigUint>::new(20); assert!(hamming.nth(19).unwrap().to_biguint() == 36u.to_biguint()); } #[test] fn hamming_iter_1million() { let mut hamming = Hamming::<BigUint>::new(128); // one-million-th hamming number has index 999_999 because indexes are zero-based assert_eq!(hamming.nth(999_999).unwrap().to_biguint(), from_str( "519312780448388736089589843750000000000000000000000000000000000000000000000000000000") ); }
h.q2.push(one()); h.q3.push(one()); h.q5.push(one());
random_line_split
hamming_numbers.rs
// http://rosettacode.org/wiki/Hamming_numbers extern crate num; use num::bigint::{BigUint, ToBigUint}; use std::cmp::min; use std::num::{One, one}; use std::collections::{RingBuf, Deque}; // needed because hamming_numbers_alt uses this as a library #[allow(dead_code)] #[cfg(not(test))] fn main() { // capacity of the queue currently needs to be a power of 2 because of a bug with RingBuf let hamming : Hamming<BigUint> = Hamming::new(128); for (idx, h) in hamming.enumerate().take(1_000_000) { match idx + 1 { 1..20 => print!("{} ", h.to_biguint().unwrap()), i @ 1691 | i @ 1000000 => println!("\n{}th number: {}", i, h.to_biguint().unwrap()), _ => continue } } } //representing a Hamming number as a BigUint impl HammingNumber for BigUint { // returns the multipliers 2, 3 and 5 in the representation for the HammingNumber fn multipliers()-> (BigUint, BigUint, BigUint) { (2u.to_biguint().unwrap(), 3u.to_biguint().unwrap(), 5u.to_biguint().unwrap()) } } /// representation of a Hamming number /// allows to abstract on how the hamming number is stored /// i.e. as BigUint directly or just as the powers of 2, 3 and 5 used to build it pub trait HammingNumber : Eq + Ord + ToBigUint + Mul<Self, Self> + One { fn multipliers() -> (Self, Self, Self); } /// Hamming numbers are multiples of 2, 3 or 5. /// /// We keep them on three queues and extract the lowest (leftmost) value from /// the three queues at each iteration. pub struct Hamming<T> { // Using a RingBuf as a queue, push to the back, pop from the front q2: RingBuf<T>, q3: RingBuf<T>, q5: RingBuf<T> } impl<T: HammingNumber> Hamming<T> { /// Static constructor method /// `n` initializes the capacity of the queues pub fn new(n: uint) -> Hamming<T> { let mut h = Hamming { q2: RingBuf::with_capacity(n), q3: RingBuf::with_capacity(n), q5: RingBuf::with_capacity(n) }; h.q2.push(one()); h.q3.push(one()); h.q5.push(one()); h } /// Pushes the next multiple of `n` (x2, x3, x5) to the queues pub fn enqueue(&mut self, n: &T) { let (two, three, five) = HammingNumber::multipliers(); self.q2.push(*n * two); self.q3.push(*n * three); self.q5.push(*n * five); } } // Implements the `Iterator` trait, so we can generate Hamming numbers lazily impl<T: HammingNumber> Iterator<T> for Hamming<T> { // The core of the work is done in the `next` method. // We check which of the 3 queues has the lowest candidate and extract it // as the next Hamming number. fn next(&mut self) -> Option<T> { // Return `pop_targets` so the borrow from `front()` will be finished let (two, three, five) = match (self.q2.front(), self.q3.front(), self.q5.front()) { (Some(head2), Some(head3), Some(head5)) => { let n = min(head2, min(head3, head5)); (head2 == n, head3 == n, head5 == n) }, _ => unreachable!() }; let h2 = if two { self.q2.pop_front() } else { None }; let h3 = if three { self.q3.pop_front() } else { None }; let h5 = if five { self.q5.pop_front() } else { None }; match h2.or(h3).or(h5) { Some(n) => { self.enqueue(&n); Some(n) } None => unreachable!() } } } #[test] fn create() { let mut h = Hamming::<BigUint>::new(5); h.q2.push(one::<BigUint>()); h.q2.push(one::<BigUint>() * 3u.to_biguint().unwrap()); assert_eq!(h.q2.pop_front().unwrap(), one::<BigUint>()); } #[test] fn try_enqueue() { let mut h = Hamming::<BigUint>::new(5); let (two, three, five) = HammingNumber::multipliers(); h.enqueue(&one::<BigUint>()); h.enqueue(&(&one::<BigUint>() * two)); assert!(h.q2.pop_front().unwrap() == one::<BigUint>()); assert!(h.q3.pop_front().unwrap() == one::<BigUint>()); assert!(h.q5.pop_front().unwrap() == one::<BigUint>()); assert!(h.q2.pop_front().unwrap() == one::<BigUint>() * two); assert!(h.q3.pop_front().unwrap() == one::<BigUint>() * three); assert!(h.q5.pop_front().unwrap() == one::<BigUint>() * five); } #[test] fn
() { let mut hamming = Hamming::<BigUint>::new(20); assert!(hamming.nth(19).unwrap().to_biguint() == 36u.to_biguint()); } #[test] fn hamming_iter_1million() { let mut hamming = Hamming::<BigUint>::new(128); // one-million-th hamming number has index 999_999 because indexes are zero-based assert_eq!(hamming.nth(999_999).unwrap().to_biguint(), from_str( "519312780448388736089589843750000000000000000000000000000000000000000000000000000000") ); }
hamming_iter
identifier_name
hamming_numbers.rs
// http://rosettacode.org/wiki/Hamming_numbers extern crate num; use num::bigint::{BigUint, ToBigUint}; use std::cmp::min; use std::num::{One, one}; use std::collections::{RingBuf, Deque}; // needed because hamming_numbers_alt uses this as a library #[allow(dead_code)] #[cfg(not(test))] fn main() { // capacity of the queue currently needs to be a power of 2 because of a bug with RingBuf let hamming : Hamming<BigUint> = Hamming::new(128); for (idx, h) in hamming.enumerate().take(1_000_000) { match idx + 1 { 1..20 => print!("{} ", h.to_biguint().unwrap()), i @ 1691 | i @ 1000000 => println!("\n{}th number: {}", i, h.to_biguint().unwrap()), _ => continue } } } //representing a Hamming number as a BigUint impl HammingNumber for BigUint { // returns the multipliers 2, 3 and 5 in the representation for the HammingNumber fn multipliers()-> (BigUint, BigUint, BigUint) { (2u.to_biguint().unwrap(), 3u.to_biguint().unwrap(), 5u.to_biguint().unwrap()) } } /// representation of a Hamming number /// allows to abstract on how the hamming number is stored /// i.e. as BigUint directly or just as the powers of 2, 3 and 5 used to build it pub trait HammingNumber : Eq + Ord + ToBigUint + Mul<Self, Self> + One { fn multipliers() -> (Self, Self, Self); } /// Hamming numbers are multiples of 2, 3 or 5. /// /// We keep them on three queues and extract the lowest (leftmost) value from /// the three queues at each iteration. pub struct Hamming<T> { // Using a RingBuf as a queue, push to the back, pop from the front q2: RingBuf<T>, q3: RingBuf<T>, q5: RingBuf<T> } impl<T: HammingNumber> Hamming<T> { /// Static constructor method /// `n` initializes the capacity of the queues pub fn new(n: uint) -> Hamming<T> { let mut h = Hamming { q2: RingBuf::with_capacity(n), q3: RingBuf::with_capacity(n), q5: RingBuf::with_capacity(n) }; h.q2.push(one()); h.q3.push(one()); h.q5.push(one()); h } /// Pushes the next multiple of `n` (x2, x3, x5) to the queues pub fn enqueue(&mut self, n: &T) { let (two, three, five) = HammingNumber::multipliers(); self.q2.push(*n * two); self.q3.push(*n * three); self.q5.push(*n * five); } } // Implements the `Iterator` trait, so we can generate Hamming numbers lazily impl<T: HammingNumber> Iterator<T> for Hamming<T> { // The core of the work is done in the `next` method. // We check which of the 3 queues has the lowest candidate and extract it // as the next Hamming number. fn next(&mut self) -> Option<T> { // Return `pop_targets` so the borrow from `front()` will be finished let (two, three, five) = match (self.q2.front(), self.q3.front(), self.q5.front()) { (Some(head2), Some(head3), Some(head5)) => { let n = min(head2, min(head3, head5)); (head2 == n, head3 == n, head5 == n) }, _ => unreachable!() }; let h2 = if two { self.q2.pop_front() } else { None }; let h3 = if three { self.q3.pop_front() } else
; let h5 = if five { self.q5.pop_front() } else { None }; match h2.or(h3).or(h5) { Some(n) => { self.enqueue(&n); Some(n) } None => unreachable!() } } } #[test] fn create() { let mut h = Hamming::<BigUint>::new(5); h.q2.push(one::<BigUint>()); h.q2.push(one::<BigUint>() * 3u.to_biguint().unwrap()); assert_eq!(h.q2.pop_front().unwrap(), one::<BigUint>()); } #[test] fn try_enqueue() { let mut h = Hamming::<BigUint>::new(5); let (two, three, five) = HammingNumber::multipliers(); h.enqueue(&one::<BigUint>()); h.enqueue(&(&one::<BigUint>() * two)); assert!(h.q2.pop_front().unwrap() == one::<BigUint>()); assert!(h.q3.pop_front().unwrap() == one::<BigUint>()); assert!(h.q5.pop_front().unwrap() == one::<BigUint>()); assert!(h.q2.pop_front().unwrap() == one::<BigUint>() * two); assert!(h.q3.pop_front().unwrap() == one::<BigUint>() * three); assert!(h.q5.pop_front().unwrap() == one::<BigUint>() * five); } #[test] fn hamming_iter() { let mut hamming = Hamming::<BigUint>::new(20); assert!(hamming.nth(19).unwrap().to_biguint() == 36u.to_biguint()); } #[test] fn hamming_iter_1million() { let mut hamming = Hamming::<BigUint>::new(128); // one-million-th hamming number has index 999_999 because indexes are zero-based assert_eq!(hamming.nth(999_999).unwrap().to_biguint(), from_str( "519312780448388736089589843750000000000000000000000000000000000000000000000000000000") ); }
{ None }
conditional_block
lib.rs
#![allow(non_snake_case)] mod counter; use counter::Counter; use std::mem::transmute; #[no_mangle] pub extern fn createCounter(val: u32) -> *mut Counter { let _counter = unsafe { transmute(Box::new(Counter::new(val))) }; _counter } #[no_mangle] pub extern fn getCounterValue(ptr: *mut Counter) -> u32 { let mut _counter = unsafe { &mut *ptr };
#[no_mangle] pub extern fn incrementCounterBy(ptr: *mut Counter, bys_ptr: *const u32, bys_len: usize) -> u32 { let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) }; _counter.incr(bys) } #[no_mangle] pub extern fn decrementCounterBy(ptr: *mut Counter, bys_ptr: *const u32, bys_len: usize) -> u32 { let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) }; _counter.decr(bys) } #[no_mangle] pub extern fn destroyCounter(ptr: *mut Counter) { let _counter: Box<Counter> = unsafe{ transmute(ptr) }; // Drop }
_counter.get() }
random_line_split
lib.rs
#![allow(non_snake_case)] mod counter; use counter::Counter; use std::mem::transmute; #[no_mangle] pub extern fn createCounter(val: u32) -> *mut Counter { let _counter = unsafe { transmute(Box::new(Counter::new(val))) }; _counter } #[no_mangle] pub extern fn getCounterValue(ptr: *mut Counter) -> u32 { let mut _counter = unsafe { &mut *ptr }; _counter.get() } #[no_mangle] pub extern fn incrementCounterBy(ptr: *mut Counter, bys_ptr: *const u32, bys_len: usize) -> u32
#[no_mangle] pub extern fn decrementCounterBy(ptr: *mut Counter, bys_ptr: *const u32, bys_len: usize) -> u32 { let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) }; _counter.decr(bys) } #[no_mangle] pub extern fn destroyCounter(ptr: *mut Counter) { let _counter: Box<Counter> = unsafe{ transmute(ptr) }; // Drop }
{ let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) }; _counter.incr(bys) }
identifier_body
lib.rs
#![allow(non_snake_case)] mod counter; use counter::Counter; use std::mem::transmute; #[no_mangle] pub extern fn createCounter(val: u32) -> *mut Counter { let _counter = unsafe { transmute(Box::new(Counter::new(val))) }; _counter } #[no_mangle] pub extern fn
(ptr: *mut Counter) -> u32 { let mut _counter = unsafe { &mut *ptr }; _counter.get() } #[no_mangle] pub extern fn incrementCounterBy(ptr: *mut Counter, bys_ptr: *const u32, bys_len: usize) -> u32 { let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) }; _counter.incr(bys) } #[no_mangle] pub extern fn decrementCounterBy(ptr: *mut Counter, bys_ptr: *const u32, bys_len: usize) -> u32 { let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) }; _counter.decr(bys) } #[no_mangle] pub extern fn destroyCounter(ptr: *mut Counter) { let _counter: Box<Counter> = unsafe{ transmute(ptr) }; // Drop }
getCounterValue
identifier_name
associated-types-in-impl-generics.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. // pretty-expanded FIXME #23616 trait Get { type Value; fn get(&self) -> &<Self as Get>::Value; } struct Struct { x: isize, } impl Get for Struct { type Value = isize; fn
(&self) -> &isize { &self.x } } trait Grab { type U; fn grab(&self) -> &<Self as Grab>::U; } impl<T:Get> Grab for T { type U = <T as Get>::Value; fn grab(&self) -> &<T as Get>::Value { self.get() } } fn main() { let s = Struct { x: 100, }; assert_eq!(*s.grab(), 100); }
get
identifier_name
associated-types-in-impl-generics.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. // pretty-expanded FIXME #23616 trait Get { type Value; fn get(&self) -> &<Self as Get>::Value; } struct Struct { x: isize, } impl Get for Struct { type Value = isize; fn get(&self) -> &isize
} trait Grab { type U; fn grab(&self) -> &<Self as Grab>::U; } impl<T:Get> Grab for T { type U = <T as Get>::Value; fn grab(&self) -> &<T as Get>::Value { self.get() } } fn main() { let s = Struct { x: 100, }; assert_eq!(*s.grab(), 100); }
{ &self.x }
identifier_body
associated-types-in-impl-generics.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. // pretty-expanded FIXME #23616
} struct Struct { x: isize, } impl Get for Struct { type Value = isize; fn get(&self) -> &isize { &self.x } } trait Grab { type U; fn grab(&self) -> &<Self as Grab>::U; } impl<T:Get> Grab for T { type U = <T as Get>::Value; fn grab(&self) -> &<T as Get>::Value { self.get() } } fn main() { let s = Struct { x: 100, }; assert_eq!(*s.grab(), 100); }
trait Get { type Value; fn get(&self) -> &<Self as Get>::Value;
random_line_split
merge_intervals.rs
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut intervals = intervals; intervals.sort_by(|a, b| a[0].cmp(&b[0])); let mut merged: Vec<Vec<i32>> = Vec::new(); for interval in intervals { // 如果是第一个,或和最后一个不相交,就放到 merged 中 if merged.is_empty() || merged.last().unwrap()[1] < interval[0] { merged.push(interval); } else { // 和最后一个相交,两个取并集 merged .last_mut() .map(|last| last[1] = last[1].max(interval[1])); } } merged } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let r = merge(vec![vec![1, 3], vec![2, 6], vec![8, 10], vec![15, 18]]); let expect = vec![vec![1, 6], vec![8, 10], vec![15, 18]]; assert_eq!(r, expect); let r = merge(vec![vec![1, 4], vec![4, 5]]); let expect = vec![vec![1, 5]]; assert_eq!(r, expect);
} }
random_line_split
merge_intervals.rs
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut intervals = intervals; intervals.sort_by(|a, b| a[0].cmp(&b[0])); let mut merged: Vec<Vec<i32>> = Vec::new(); for interval in intervals { // 如果是第一个,或和最后一个不相交,就放到 merged 中 if merged.is_empty() || merged.last().unwrap()[1] < interval[0] { merged.push(interval);
merged .last_mut() .map(|last| last[1] = last[1].max(interval[1])); } } merged } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let r = merge(vec![vec![1, 3], vec![2, 6], vec![8, 10], vec![15, 18]]); let expect = vec![vec![1, 6], vec![8, 10], vec![15, 18]]; assert_eq!(r, expect); let r = merge(vec![vec![1, 4], vec![4, 5]]); let expect = vec![vec![1, 5]]; assert_eq!(r, expect); } }
} else { // 和最后一个相交,两个取并集
conditional_block
merge_intervals.rs
pub fn
(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut intervals = intervals; intervals.sort_by(|a, b| a[0].cmp(&b[0])); let mut merged: Vec<Vec<i32>> = Vec::new(); for interval in intervals { // 如果是第一个,或和最后一个不相交,就放到 merged 中 if merged.is_empty() || merged.last().unwrap()[1] < interval[0] { merged.push(interval); } else { // 和最后一个相交,两个取并集 merged .last_mut() .map(|last| last[1] = last[1].max(interval[1])); } } merged } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let r = merge(vec![vec![1, 3], vec![2, 6], vec![8, 10], vec![15, 18]]); let expect = vec![vec![1, 6], vec![8, 10], vec![15, 18]]; assert_eq!(r, expect); let r = merge(vec![vec![1, 4], vec![4, 5]]); let expect = vec![vec![1, 5]]; assert_eq!(r, expect); } }
merge
identifier_name
merge_intervals.rs
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut intervals = intervals; intervals.sort_by(|a, b| a[0].cmp(&b[0])); let mut merged: Vec<Vec<i32>> = Vec::new(); for interval in intervals { // 如果是第一个,或和最后一个不相交,就放到 merged 中 if merged.is_empty() || merged.last().unwrap()[1] < interval[0] { merged.push(interval); } else { // 和最后一个相交,两个取并集 merged .last_mut() .map(|last| last[1] = last[1].max(interval[1])); } } merged } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let r = merge(vec![vec![1, 3], vec![2, 6], vec![8, 10], ve
c![15, 18]]); let expect = vec![vec![1, 6], vec![8, 10], vec![15, 18]]; assert_eq!(r, expect); let r = merge(vec![vec![1, 4], vec![4, 5]]); let expect = vec![vec![1, 5]]; assert_eq!(r, expect); } }
identifier_body
unbind_3pid.rs
//! `POST /_matrix/client/*/account/3pid/unbind` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3account3pidunbind use ruma_common::{api::ruma_api, thirdparty::Medium}; use crate::account::ThirdPartyIdRemovalStatus; ruma_api! { metadata: { description: "Unbind a 3PID from a user's account on an identity server.", method: POST, name: "unbind_3pid", r0_path: "/_matrix/client/r0/account/3pid/unbind", stable_path: "/_matrix/client/v3/account/3pid/unbind", rate_limited: false, authentication: AccessToken, added: 1.0, } request: { /// Identity server to unbind from. #[serde(skip_serializing_if = "Option::is_none")] pub id_server: Option<&'a str>, /// Medium of the 3PID to be removed. pub medium: Medium, /// Third-party address being removed. pub address: &'a str, } response: { /// Result of unbind operation. pub id_server_unbind_result: ThirdPartyIdRemovalStatus, } error: crate::Error } impl<'a> Request<'a> { /// Creates a new `Request` with the given medium and third-party address. pub fn new(medium: Medium, address: &'a str) -> Self { Self { id_server: None, medium, address } } } impl Response { /// Creates a new `Response` with the given unbind result. pub fn
(id_server_unbind_result: ThirdPartyIdRemovalStatus) -> Self { Self { id_server_unbind_result } } } }
new
identifier_name
unbind_3pid.rs
//! `POST /_matrix/client/*/account/3pid/unbind` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3account3pidunbind use ruma_common::{api::ruma_api, thirdparty::Medium}; use crate::account::ThirdPartyIdRemovalStatus; ruma_api! { metadata: { description: "Unbind a 3PID from a user's account on an identity server.", method: POST, name: "unbind_3pid", r0_path: "/_matrix/client/r0/account/3pid/unbind", stable_path: "/_matrix/client/v3/account/3pid/unbind", rate_limited: false, authentication: AccessToken, added: 1.0, } request: { /// Identity server to unbind from. #[serde(skip_serializing_if = "Option::is_none")] pub id_server: Option<&'a str>, /// Medium of the 3PID to be removed. pub medium: Medium, /// Third-party address being removed. pub address: &'a str, }
pub id_server_unbind_result: ThirdPartyIdRemovalStatus, } error: crate::Error } impl<'a> Request<'a> { /// Creates a new `Request` with the given medium and third-party address. pub fn new(medium: Medium, address: &'a str) -> Self { Self { id_server: None, medium, address } } } impl Response { /// Creates a new `Response` with the given unbind result. pub fn new(id_server_unbind_result: ThirdPartyIdRemovalStatus) -> Self { Self { id_server_unbind_result } } } }
response: { /// Result of unbind operation.
random_line_split
unbind_3pid.rs
//! `POST /_matrix/client/*/account/3pid/unbind` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3account3pidunbind use ruma_common::{api::ruma_api, thirdparty::Medium}; use crate::account::ThirdPartyIdRemovalStatus; ruma_api! { metadata: { description: "Unbind a 3PID from a user's account on an identity server.", method: POST, name: "unbind_3pid", r0_path: "/_matrix/client/r0/account/3pid/unbind", stable_path: "/_matrix/client/v3/account/3pid/unbind", rate_limited: false, authentication: AccessToken, added: 1.0, } request: { /// Identity server to unbind from. #[serde(skip_serializing_if = "Option::is_none")] pub id_server: Option<&'a str>, /// Medium of the 3PID to be removed. pub medium: Medium, /// Third-party address being removed. pub address: &'a str, } response: { /// Result of unbind operation. pub id_server_unbind_result: ThirdPartyIdRemovalStatus, } error: crate::Error } impl<'a> Request<'a> { /// Creates a new `Request` with the given medium and third-party address. pub fn new(medium: Medium, address: &'a str) -> Self { Self { id_server: None, medium, address } } } impl Response { /// Creates a new `Response` with the given unbind result. pub fn new(id_server_unbind_result: ThirdPartyIdRemovalStatus) -> Self
} }
{ Self { id_server_unbind_result } }
identifier_body
error.rs
//! error provides newtypes and Error's for sqlib. use escaping::unescape; use std::convert::From; use std::error::{self, Error as Err}; use std::fmt::{self, Display}; use std::io; use std::net::AddrParseError; use std::result; use std::sync::PoisonError; /// The standart result type of sqlib. pub type Result<T> = result::Result<T, Error>; /// A SQError contains a TS3 Server Query error. /// /// # Example /// ``` /// use sqlib::error::SQError; /// /// let line = "error id=0 msg=ok".to_string(); /// /// let err_option = SQError::parse(&line); /// let err = match err_option { /// Some(err) => err, /// None => { panic!("no error found"); }, /// }; /// assert_eq!(0, err.id()); /// ``` #[derive(Debug)] pub struct SQError { id: u32, msg: String, full_msg: String, } // helping function for SQError::parse fn is_seperator(c: char) -> bool { c == '=' || c.is_whitespace() } impl SQError { pub fn
(id: u32, msg: String) -> SQError { let full_msg_str = format!("error id={} msg={}", id, &msg); SQError { id, msg, full_msg: full_msg_str, } } /// Creates an OK error. pub fn ok() -> SQError { SQError::new(0, "ok".to_string()) } /// This function tries to parse a string into an Error. /// /// # Return values /// /// - If it fails to parse it returns Ok(false). /// - If it parses the string as an OK error it returns Ok(true). /// - If it parses the string as another error it returns Err(error). /// /// # Example /// ``` /// use sqlib::error::{Error, SQError}; /// /// let ok_str = "error id=0 msg=ok"; /// let no_err_str = "this is no error"; /// let err_str = "error id=1 msg=test"; /// /// let test_err = SQError::new(1, "test".to_string()); /// let to_test_error = match SQError::parse_is_ok(err_str).unwrap_err() { /// Error::SQ(e) => e, /// _ => SQError::ok(), /// }; /// /// assert_eq!(SQError::parse_is_ok(ok_str).unwrap(), true); /// assert_eq!(SQError::parse_is_ok(no_err_str).unwrap(), false); /// assert_eq!(to_test_error, test_err); /// ``` pub fn parse_is_ok(s: &str) -> Result<bool> { let err = match SQError::parse(s) { None => { return Ok(false); } Some(err) => err, }; if err == SQError::ok() { Ok(true) } else { Err(Error::from(err)) } } /// try to parse a String to a SQError pub fn parse(s: &str) -> Option<SQError> { // the str shouldn't be trimmed, because a real error is without // whitespace in the beginning let parts: Vec<&str> = s.splitn(6, is_seperator).collect(); if parts.len() < 5 { return None; } if parts[0]!= "error" { return None; } if parts[1]!= "id" { return None; } let id_result = parts[2].parse::<u32>(); let id = match id_result { Err(_) => { return None; } Ok(val) => val, }; if parts[3]!= "msg" { return None; } let msg = parts[4].to_string().clone(); Some(SQError::new(id, unescape(&msg))) } pub fn id(&self) -> u32 { self.id } pub fn msg(&self) -> String { self.msg.clone() } } impl PartialEq for SQError { fn eq(&self, other: &Self) -> bool { self.id == other.id } } impl Eq for SQError {} impl Display for SQError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.full_msg) } } impl error::Error for SQError { fn description(&self) -> &str { &self.full_msg } } /// Error is a custom Error type for the sqlib. #[derive(Debug)] pub enum Error { /// wraps io::Error Io(io::Error), /// server query error messages SQ(SQError), /// other errors Other(String), } impl Error { pub fn is_io(&self) -> bool { match *self { Error::Io(_) => true, _ => false, } } pub fn is_sq(&self) -> bool { match *self { Error::SQ(_) => true, _ => false, } } pub fn is_other(&self) -> bool { match *self { Error::Other(_) => true, _ => false, } } } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::Io(ref err) => err.description(), Error::SQ(ref err) => err.description(), Error::Other(ref s) => s, } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl<'a> From<&'a str> for Error { fn from(err: &'a str) -> Error { Error::Other(err.to_string()) } } impl From<String> for Error { fn from(err: String) -> Error { Error::Other(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl From<SQError> for Error { fn from(err: SQError) -> Error { Error::SQ(err) } } impl From<AddrParseError> for Error { fn from(err: AddrParseError) -> Error { Error::Other(err.description().to_string()) } } impl<T> From<PoisonError<T>> for Error { fn from(err: PoisonError<T>) -> Error { Error::Other(format!("{}", err)) } }
new
identifier_name
error.rs
//! error provides newtypes and Error's for sqlib. use escaping::unescape; use std::convert::From; use std::error::{self, Error as Err}; use std::fmt::{self, Display}; use std::io; use std::net::AddrParseError; use std::result; use std::sync::PoisonError; /// The standart result type of sqlib. pub type Result<T> = result::Result<T, Error>; /// A SQError contains a TS3 Server Query error. /// /// # Example /// ``` /// use sqlib::error::SQError; /// /// let line = "error id=0 msg=ok".to_string(); /// /// let err_option = SQError::parse(&line); /// let err = match err_option { /// Some(err) => err, /// None => { panic!("no error found"); }, /// }; /// assert_eq!(0, err.id()); /// ``` #[derive(Debug)] pub struct SQError { id: u32, msg: String, full_msg: String, } // helping function for SQError::parse fn is_seperator(c: char) -> bool { c == '=' || c.is_whitespace() } impl SQError { pub fn new(id: u32, msg: String) -> SQError { let full_msg_str = format!("error id={} msg={}", id, &msg); SQError { id, msg, full_msg: full_msg_str, } } /// Creates an OK error. pub fn ok() -> SQError { SQError::new(0, "ok".to_string()) } /// This function tries to parse a string into an Error. /// /// # Return values /// /// - If it fails to parse it returns Ok(false). /// - If it parses the string as an OK error it returns Ok(true). /// - If it parses the string as another error it returns Err(error). /// /// # Example /// ``` /// use sqlib::error::{Error, SQError}; /// /// let ok_str = "error id=0 msg=ok"; /// let no_err_str = "this is no error"; /// let err_str = "error id=1 msg=test"; /// /// let test_err = SQError::new(1, "test".to_string()); /// let to_test_error = match SQError::parse_is_ok(err_str).unwrap_err() { /// Error::SQ(e) => e, /// _ => SQError::ok(), /// }; /// /// assert_eq!(SQError::parse_is_ok(ok_str).unwrap(), true); /// assert_eq!(SQError::parse_is_ok(no_err_str).unwrap(), false); /// assert_eq!(to_test_error, test_err); /// ``` pub fn parse_is_ok(s: &str) -> Result<bool> { let err = match SQError::parse(s) { None => { return Ok(false); } Some(err) => err, }; if err == SQError::ok() { Ok(true) } else { Err(Error::from(err)) } } /// try to parse a String to a SQError pub fn parse(s: &str) -> Option<SQError> { // the str shouldn't be trimmed, because a real error is without // whitespace in the beginning let parts: Vec<&str> = s.splitn(6, is_seperator).collect(); if parts.len() < 5 { return None; } if parts[0]!= "error" { return None; } if parts[1]!= "id" { return None; } let id_result = parts[2].parse::<u32>(); let id = match id_result { Err(_) => { return None; } Ok(val) => val, }; if parts[3]!= "msg" { return None; } let msg = parts[4].to_string().clone(); Some(SQError::new(id, unescape(&msg))) } pub fn id(&self) -> u32 { self.id } pub fn msg(&self) -> String { self.msg.clone() } } impl PartialEq for SQError { fn eq(&self, other: &Self) -> bool { self.id == other.id } } impl Eq for SQError {} impl Display for SQError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.full_msg) } } impl error::Error for SQError { fn description(&self) -> &str { &self.full_msg } } /// Error is a custom Error type for the sqlib. #[derive(Debug)] pub enum Error { /// wraps io::Error Io(io::Error), /// server query error messages SQ(SQError), /// other errors Other(String), } impl Error { pub fn is_io(&self) -> bool { match *self { Error::Io(_) => true, _ => false,
} } pub fn is_sq(&self) -> bool { match *self { Error::SQ(_) => true, _ => false, } } pub fn is_other(&self) -> bool { match *self { Error::Other(_) => true, _ => false, } } } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::Io(ref err) => err.description(), Error::SQ(ref err) => err.description(), Error::Other(ref s) => s, } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl<'a> From<&'a str> for Error { fn from(err: &'a str) -> Error { Error::Other(err.to_string()) } } impl From<String> for Error { fn from(err: String) -> Error { Error::Other(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl From<SQError> for Error { fn from(err: SQError) -> Error { Error::SQ(err) } } impl From<AddrParseError> for Error { fn from(err: AddrParseError) -> Error { Error::Other(err.description().to_string()) } } impl<T> From<PoisonError<T>> for Error { fn from(err: PoisonError<T>) -> Error { Error::Other(format!("{}", err)) } }
random_line_split
error.rs
//! error provides newtypes and Error's for sqlib. use escaping::unescape; use std::convert::From; use std::error::{self, Error as Err}; use std::fmt::{self, Display}; use std::io; use std::net::AddrParseError; use std::result; use std::sync::PoisonError; /// The standart result type of sqlib. pub type Result<T> = result::Result<T, Error>; /// A SQError contains a TS3 Server Query error. /// /// # Example /// ``` /// use sqlib::error::SQError; /// /// let line = "error id=0 msg=ok".to_string(); /// /// let err_option = SQError::parse(&line); /// let err = match err_option { /// Some(err) => err, /// None => { panic!("no error found"); }, /// }; /// assert_eq!(0, err.id()); /// ``` #[derive(Debug)] pub struct SQError { id: u32, msg: String, full_msg: String, } // helping function for SQError::parse fn is_seperator(c: char) -> bool { c == '=' || c.is_whitespace() } impl SQError { pub fn new(id: u32, msg: String) -> SQError { let full_msg_str = format!("error id={} msg={}", id, &msg); SQError { id, msg, full_msg: full_msg_str, } } /// Creates an OK error. pub fn ok() -> SQError { SQError::new(0, "ok".to_string()) } /// This function tries to parse a string into an Error. /// /// # Return values /// /// - If it fails to parse it returns Ok(false). /// - If it parses the string as an OK error it returns Ok(true). /// - If it parses the string as another error it returns Err(error). /// /// # Example /// ``` /// use sqlib::error::{Error, SQError}; /// /// let ok_str = "error id=0 msg=ok"; /// let no_err_str = "this is no error"; /// let err_str = "error id=1 msg=test"; /// /// let test_err = SQError::new(1, "test".to_string()); /// let to_test_error = match SQError::parse_is_ok(err_str).unwrap_err() { /// Error::SQ(e) => e, /// _ => SQError::ok(), /// }; /// /// assert_eq!(SQError::parse_is_ok(ok_str).unwrap(), true); /// assert_eq!(SQError::parse_is_ok(no_err_str).unwrap(), false); /// assert_eq!(to_test_error, test_err); /// ``` pub fn parse_is_ok(s: &str) -> Result<bool> { let err = match SQError::parse(s) { None => { return Ok(false); } Some(err) => err, }; if err == SQError::ok() { Ok(true) } else { Err(Error::from(err)) } } /// try to parse a String to a SQError pub fn parse(s: &str) -> Option<SQError> { // the str shouldn't be trimmed, because a real error is without // whitespace in the beginning let parts: Vec<&str> = s.splitn(6, is_seperator).collect(); if parts.len() < 5 { return None; } if parts[0]!= "error" { return None; } if parts[1]!= "id" { return None; } let id_result = parts[2].parse::<u32>(); let id = match id_result { Err(_) => { return None; } Ok(val) => val, }; if parts[3]!= "msg" { return None; } let msg = parts[4].to_string().clone(); Some(SQError::new(id, unescape(&msg))) } pub fn id(&self) -> u32 { self.id } pub fn msg(&self) -> String { self.msg.clone() } } impl PartialEq for SQError { fn eq(&self, other: &Self) -> bool { self.id == other.id } } impl Eq for SQError {} impl Display for SQError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.full_msg) } } impl error::Error for SQError { fn description(&self) -> &str { &self.full_msg } } /// Error is a custom Error type for the sqlib. #[derive(Debug)] pub enum Error { /// wraps io::Error Io(io::Error), /// server query error messages SQ(SQError), /// other errors Other(String), } impl Error { pub fn is_io(&self) -> bool { match *self { Error::Io(_) => true, _ => false, } } pub fn is_sq(&self) -> bool { match *self { Error::SQ(_) => true, _ => false, } } pub fn is_other(&self) -> bool { match *self { Error::Other(_) => true, _ => false, } } } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::Io(ref err) => err.description(), Error::SQ(ref err) => err.description(), Error::Other(ref s) => s, } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl<'a> From<&'a str> for Error { fn from(err: &'a str) -> Error { Error::Other(err.to_string()) } } impl From<String> for Error { fn from(err: String) -> Error { Error::Other(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error
} impl From<SQError> for Error { fn from(err: SQError) -> Error { Error::SQ(err) } } impl From<AddrParseError> for Error { fn from(err: AddrParseError) -> Error { Error::Other(err.description().to_string()) } } impl<T> From<PoisonError<T>> for Error { fn from(err: PoisonError<T>) -> Error { Error::Other(format!("{}", err)) } }
{ Error::Io(err) }
identifier_body
error.rs
//! error provides newtypes and Error's for sqlib. use escaping::unescape; use std::convert::From; use std::error::{self, Error as Err}; use std::fmt::{self, Display}; use std::io; use std::net::AddrParseError; use std::result; use std::sync::PoisonError; /// The standart result type of sqlib. pub type Result<T> = result::Result<T, Error>; /// A SQError contains a TS3 Server Query error. /// /// # Example /// ``` /// use sqlib::error::SQError; /// /// let line = "error id=0 msg=ok".to_string(); /// /// let err_option = SQError::parse(&line); /// let err = match err_option { /// Some(err) => err, /// None => { panic!("no error found"); }, /// }; /// assert_eq!(0, err.id()); /// ``` #[derive(Debug)] pub struct SQError { id: u32, msg: String, full_msg: String, } // helping function for SQError::parse fn is_seperator(c: char) -> bool { c == '=' || c.is_whitespace() } impl SQError { pub fn new(id: u32, msg: String) -> SQError { let full_msg_str = format!("error id={} msg={}", id, &msg); SQError { id, msg, full_msg: full_msg_str, } } /// Creates an OK error. pub fn ok() -> SQError { SQError::new(0, "ok".to_string()) } /// This function tries to parse a string into an Error. /// /// # Return values /// /// - If it fails to parse it returns Ok(false). /// - If it parses the string as an OK error it returns Ok(true). /// - If it parses the string as another error it returns Err(error). /// /// # Example /// ``` /// use sqlib::error::{Error, SQError}; /// /// let ok_str = "error id=0 msg=ok"; /// let no_err_str = "this is no error"; /// let err_str = "error id=1 msg=test"; /// /// let test_err = SQError::new(1, "test".to_string()); /// let to_test_error = match SQError::parse_is_ok(err_str).unwrap_err() { /// Error::SQ(e) => e, /// _ => SQError::ok(), /// }; /// /// assert_eq!(SQError::parse_is_ok(ok_str).unwrap(), true); /// assert_eq!(SQError::parse_is_ok(no_err_str).unwrap(), false); /// assert_eq!(to_test_error, test_err); /// ``` pub fn parse_is_ok(s: &str) -> Result<bool> { let err = match SQError::parse(s) { None => { return Ok(false); } Some(err) => err, }; if err == SQError::ok() { Ok(true) } else { Err(Error::from(err)) } } /// try to parse a String to a SQError pub fn parse(s: &str) -> Option<SQError> { // the str shouldn't be trimmed, because a real error is without // whitespace in the beginning let parts: Vec<&str> = s.splitn(6, is_seperator).collect(); if parts.len() < 5 { return None; } if parts[0]!= "error" { return None; } if parts[1]!= "id" { return None; } let id_result = parts[2].parse::<u32>(); let id = match id_result { Err(_) =>
Ok(val) => val, }; if parts[3]!= "msg" { return None; } let msg = parts[4].to_string().clone(); Some(SQError::new(id, unescape(&msg))) } pub fn id(&self) -> u32 { self.id } pub fn msg(&self) -> String { self.msg.clone() } } impl PartialEq for SQError { fn eq(&self, other: &Self) -> bool { self.id == other.id } } impl Eq for SQError {} impl Display for SQError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.full_msg) } } impl error::Error for SQError { fn description(&self) -> &str { &self.full_msg } } /// Error is a custom Error type for the sqlib. #[derive(Debug)] pub enum Error { /// wraps io::Error Io(io::Error), /// server query error messages SQ(SQError), /// other errors Other(String), } impl Error { pub fn is_io(&self) -> bool { match *self { Error::Io(_) => true, _ => false, } } pub fn is_sq(&self) -> bool { match *self { Error::SQ(_) => true, _ => false, } } pub fn is_other(&self) -> bool { match *self { Error::Other(_) => true, _ => false, } } } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::Io(ref err) => err.description(), Error::SQ(ref err) => err.description(), Error::Other(ref s) => s, } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl<'a> From<&'a str> for Error { fn from(err: &'a str) -> Error { Error::Other(err.to_string()) } } impl From<String> for Error { fn from(err: String) -> Error { Error::Other(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl From<SQError> for Error { fn from(err: SQError) -> Error { Error::SQ(err) } } impl From<AddrParseError> for Error { fn from(err: AddrParseError) -> Error { Error::Other(err.description().to_string()) } } impl<T> From<PoisonError<T>> for Error { fn from(err: PoisonError<T>) -> Error { Error::Other(format!("{}", err)) } }
{ return None; }
conditional_block
mod.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] pub fn
() { // strings are implemented as a collection of bytes plus some methods to provide useful // functionality when those bytes are interpreted as text. // the'str' type represents a string slice, and is usually seen in its borrowed form &str // str is a type in the langugage itself // String type is provided by the standard library // Both String and string slices are UTF-8 encoded. let mut s = String::from("foo bar"); { let slice: &str = &mut s[0..4]; // Can't do the following?? // slice[2] = 'x'; } println!("new string: {}", s); // 2 ways of creating String objects from string literals are equivalent let s = "foo bar".to_string(); let s = String::from("foo bar"); // Since strings are utf-8, the following are all valid let hello = "السلام عليكم"; let hello = "Dobrý den"; let hello = "Hello"; let hello = "שָׁלוֹם"; let hello = "नमस्ते"; let hello = "こんにちは"; let hello = "안녕하세요"; let hello = "你好"; let hello = "Olá"; let hello = "Здравствуйте"; let hello = "Hola"; // When taking string slices, we only read the bytes specified by the range. If the range of // bytes is cannot be decoded to UTF-8 code points, an attemp to do so might result in an // error. let hello = "नमस्ते"; let s = &hello[..3]; // This will only print न instead of नमस्. println!("I say: {}", s); // If we instead give the range of [0..2], the programs panics with the error: // 'byte index 2 is not a char boundary; it is inside 'न' (bytes 0..3) of `नमस्ते' // let s = &hello[..2]; // println!("{}", s); // String mutations // Push a string slice let mut hello = String::from("hello"); hello.push_str("foo"); // Push a character (unicode code point) let mut hello = "hol".to_string(); hello.push('न'); println!("hol is now: {}", hello); // Concat strings let hello = "hello,".to_string(); let world = String::from(" world!"); let hello_world = hello /* moved */ + &world; // We can't add 2 string values. The + operator takes a string reference as its argument. // Does this lead to new space allocation to store the new string? // hello = hello + world; is not allowed // CAn only add a &str to a String. &String gets coerced into a &str using deref coercion // (something like converting &s to &s[..]. println!("{}", hello_world); // Concatenating multiple strings let s1 = String::from("tic"); let s2 = String::from("tac"); let s3 = String::from("toe"); // format! macro is similar to println. Does not take ownership of its arguments let s = format!("{}-{}-{}", s1, s2, s3); // When doing simple addition, the first argument is moved. Does the str reference type not // implement the + operator? let s = s1 + "-" + &s2 + "-" + &s3; // println!("{}", s1); s1 has been moved! println!("{}", s2); println!("{}", s3); // We can't index into a string due to UTF-8 encoding and resulting ambiguity in what is really // desired fromt he index // Also, the expectation with indexing is O(1) access, whereas thay might not be possible for // Strings, due to the UTF-8 encoding of characters. let hello = "Здравствуйте"; // Not allowed: // let answer = &hello[0]; // // Instead, rust supports getting a string slice by specifying the byte range let s: &str = &hello[..2]; // index out-of-range will not be detected at compile time println!("{}", s); // In rust, we can think of strings in 3 ways: // 1. Sequence of bytes (vec[u8]) // 2. Unicode scalar values (these are what the'char' type in rust would have) // 3. Grapheme Clusters // e.g., the string "नमस्ते" can be: // 1. [224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135] // 2. ['न', 'म', 'स', '्', 'त', 'े'] // Note that the 4th and 6th elements in this array are not // really characters, but instead diatrics which do not make sense in isolation. // 3. ["न", "म", "स्", "ते"] // // Apart from string slicing, rust also provides a way to iterator over the bytes or the // characters. Iteration over grapheme clusters is not provided through the standard library. // let hello = "नमस्ते"; for b in hello.bytes() { println!("{}", b); } for c in hello.chars() { println!("{}", c); } }
foo
identifier_name
mod.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] pub fn foo()
// Since strings are utf-8, the following are all valid let hello = "السلام عليكم"; let hello = "Dobrý den"; let hello = "Hello"; let hello = "שָׁלוֹם"; let hello = "नमस्ते"; let hello = "こんにちは"; let hello = "안녕하세요"; let hello = "你好"; let hello = "Olá"; let hello = "Здравствуйте"; let hello = "Hola"; // When taking string slices, we only read the bytes specified by the range. If the range of // bytes is cannot be decoded to UTF-8 code points, an attemp to do so might result in an // error. let hello = "नमस्ते"; let s = &hello[..3]; // This will only print न instead of नमस्. println!("I say: {}", s); // If we instead give the range of [0..2], the programs panics with the error: // 'byte index 2 is not a char boundary; it is inside 'न' (bytes 0..3) of `नमस्ते' // let s = &hello[..2]; // println!("{}", s); // String mutations // Push a string slice let mut hello = String::from("hello"); hello.push_str("foo"); // Push a character (unicode code point) let mut hello = "hol".to_string(); hello.push('न'); println!("hol is now: {}", hello); // Concat strings let hello = "hello,".to_string(); let world = String::from(" world!"); let hello_world = hello /* moved */ + &world; // We can't add 2 string values. The + operator takes a string reference as its argument. // Does this lead to new space allocation to store the new string? // hello = hello + world; is not allowed // CAn only add a &str to a String. &String gets coerced into a &str using deref coercion // (something like converting &s to &s[..]. println!("{}", hello_world); // Concatenating multiple strings let s1 = String::from("tic"); let s2 = String::from("tac"); let s3 = String::from("toe"); // format! macro is similar to println. Does not take ownership of its arguments let s = format!("{}-{}-{}", s1, s2, s3); // When doing simple addition, the first argument is moved. Does the str reference type not // implement the + operator? let s = s1 + "-" + &s2 + "-" + &s3; // println!("{}", s1); s1 has been moved! println!("{}", s2); println!("{}", s3); // We can't index into a string due to UTF-8 encoding and resulting ambiguity in what is really // desired fromt he index // Also, the expectation with indexing is O(1) access, whereas thay might not be possible for // Strings, due to the UTF-8 encoding of characters. let hello = "Здравствуйте"; // Not allowed: // let answer = &hello[0]; // // Instead, rust supports getting a string slice by specifying the byte range let s: &str = &hello[..2]; // index out-of-range will not be detected at compile time println!("{}", s); // In rust, we can think of strings in 3 ways: // 1. Sequence of bytes (vec[u8]) // 2. Unicode scalar values (these are what the'char' type in rust would have) // 3. Grapheme Clusters // e.g., the string "नमस्ते" can be: // 1. [224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135] // 2. ['न', 'म', 'स', '्', 'त', 'े'] // Note that the 4th and 6th elements in this array are not // really characters, but instead diatrics which do not make sense in isolation. // 3. ["न", "म", "स्", "ते"] // // Apart from string slicing, rust also provides a way to iterator over the bytes or the // characters. Iteration over grapheme clusters is not provided through the standard library. // let hello = "नमस्ते"; for b in hello.bytes() { println!("{}", b); } for c in hello.chars() { println!("{}", c); } }
{ // strings are implemented as a collection of bytes plus some methods to provide useful // functionality when those bytes are interpreted as text. // the 'str' type represents a string slice, and is usually seen in its borrowed form &str // str is a type in the langugage itself // String type is provided by the standard library // Both String and string slices are UTF-8 encoded. let mut s = String::from("foo bar"); { let slice: &str = &mut s[0..4]; // Can't do the following?? // slice[2] = 'x'; } println!("new string: {}", s); // 2 ways of creating String objects from string literals are equivalent let s = "foo bar".to_string(); let s = String::from("foo bar");
identifier_body
mod.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] pub fn foo() { // strings are implemented as a collection of bytes plus some methods to provide useful // functionality when those bytes are interpreted as text. // the'str' type represents a string slice, and is usually seen in its borrowed form &str // str is a type in the langugage itself // String type is provided by the standard library // Both String and string slices are UTF-8 encoded. let mut s = String::from("foo bar"); { let slice: &str = &mut s[0..4]; // Can't do the following?? // slice[2] = 'x'; } println!("new string: {}", s); // 2 ways of creating String objects from string literals are equivalent let s = "foo bar".to_string(); let s = String::from("foo bar");
// Since strings are utf-8, the following are all valid let hello = "السلام عليكم"; let hello = "Dobrý den"; let hello = "Hello"; let hello = "שָׁלוֹם"; let hello = "नमस्ते"; let hello = "こんにちは"; let hello = "안녕하세요"; let hello = "你好"; let hello = "Olá"; let hello = "Здравствуйте"; let hello = "Hola"; // When taking string slices, we only read the bytes specified by the range. If the range of // bytes is cannot be decoded to UTF-8 code points, an attemp to do so might result in an // error. let hello = "नमस्ते"; let s = &hello[..3]; // This will only print न instead of नमस्. println!("I say: {}", s); // If we instead give the range of [0..2], the programs panics with the error: // 'byte index 2 is not a char boundary; it is inside 'न' (bytes 0..3) of `नमस्ते' // let s = &hello[..2]; // println!("{}", s); // String mutations // Push a string slice let mut hello = String::from("hello"); hello.push_str("foo"); // Push a character (unicode code point) let mut hello = "hol".to_string(); hello.push('न'); println!("hol is now: {}", hello); // Concat strings let hello = "hello,".to_string(); let world = String::from(" world!"); let hello_world = hello /* moved */ + &world; // We can't add 2 string values. The + operator takes a string reference as its argument. // Does this lead to new space allocation to store the new string? // hello = hello + world; is not allowed // CAn only add a &str to a String. &String gets coerced into a &str using deref coercion // (something like converting &s to &s[..]. println!("{}", hello_world); // Concatenating multiple strings let s1 = String::from("tic"); let s2 = String::from("tac"); let s3 = String::from("toe"); // format! macro is similar to println. Does not take ownership of its arguments let s = format!("{}-{}-{}", s1, s2, s3); // When doing simple addition, the first argument is moved. Does the str reference type not // implement the + operator? let s = s1 + "-" + &s2 + "-" + &s3; // println!("{}", s1); s1 has been moved! println!("{}", s2); println!("{}", s3); // We can't index into a string due to UTF-8 encoding and resulting ambiguity in what is really // desired fromt he index // Also, the expectation with indexing is O(1) access, whereas thay might not be possible for // Strings, due to the UTF-8 encoding of characters. let hello = "Здравствуйте"; // Not allowed: // let answer = &hello[0]; // // Instead, rust supports getting a string slice by specifying the byte range let s: &str = &hello[..2]; // index out-of-range will not be detected at compile time println!("{}", s); // In rust, we can think of strings in 3 ways: // 1. Sequence of bytes (vec[u8]) // 2. Unicode scalar values (these are what the'char' type in rust would have) // 3. Grapheme Clusters // e.g., the string "नमस्ते" can be: // 1. [224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135] // 2. ['न', 'म', 'स', '्', 'त', 'े'] // Note that the 4th and 6th elements in this array are not // really characters, but instead diatrics which do not make sense in isolation. // 3. ["न", "म", "स्", "ते"] // // Apart from string slicing, rust also provides a way to iterator over the bytes or the // characters. Iteration over grapheme clusters is not provided through the standard library. // let hello = "नमस्ते"; for b in hello.bytes() { println!("{}", b); } for c in hello.chars() { println!("{}", c); } }
random_line_split
main.rs
#![allow(clippy::unnecessary_fold)] fn
() { let numbers = [1, 2, 3, 4, 5]; let sum = numbers.iter().fold(0, |a, n| a + n); println!("{}", sum); let product = numbers.iter().fold(1, |a, n| a * n); println!("{}", product); } #[cfg(test)] mod tests { #[test] fn test_sum() { let sum = [1, 2, 3, 4, 5].iter().fold(0, |a, n| a + n); assert_eq!(sum, 15); } #[test] fn test_product() { let product = [1, 2, 3, 4, 5].iter().fold(1, |a, n| a * n); assert_eq!(product, 120); } }
main
identifier_name
main.rs
#![allow(clippy::unnecessary_fold)] fn main()
#[cfg(test)] mod tests { #[test] fn test_sum() { let sum = [1, 2, 3, 4, 5].iter().fold(0, |a, n| a + n); assert_eq!(sum, 15); } #[test] fn test_product() { let product = [1, 2, 3, 4, 5].iter().fold(1, |a, n| a * n); assert_eq!(product, 120); } }
{ let numbers = [1, 2, 3, 4, 5]; let sum = numbers.iter().fold(0, |a, n| a + n); println!("{}", sum); let product = numbers.iter().fold(1, |a, n| a * n); println!("{}", product); }
identifier_body
main.rs
#![allow(clippy::unnecessary_fold)]
let sum = numbers.iter().fold(0, |a, n| a + n); println!("{}", sum); let product = numbers.iter().fold(1, |a, n| a * n); println!("{}", product); } #[cfg(test)] mod tests { #[test] fn test_sum() { let sum = [1, 2, 3, 4, 5].iter().fold(0, |a, n| a + n); assert_eq!(sum, 15); } #[test] fn test_product() { let product = [1, 2, 3, 4, 5].iter().fold(1, |a, n| a * n); assert_eq!(product, 120); } }
fn main() { let numbers = [1, 2, 3, 4, 5];
random_line_split
sliceobject.rs
use libc::c_int; use pyport::Py_ssize_t; use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { static mut _Py_EllipsisObject: PyObject; } #[inline(always)] pub unsafe fn Py_Ellipsis() -> *mut PyObject { &mut _Py_EllipsisObject } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub static mut PySlice_Type: PyTypeObject; pub static mut PyEllipsis_Type: PyTypeObject; } #[inline(always)] pub unsafe fn
(op: *mut PyObject) -> c_int { (Py_TYPE(op) == &mut PySlice_Type) as c_int } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub fn PySlice_New(start: *mut PyObject, stop: *mut PyObject, step: *mut PyObject) -> *mut PyObject; pub fn PySlice_GetIndices(r: *mut PyObject, length: Py_ssize_t, start: *mut Py_ssize_t, stop: *mut Py_ssize_t, step: *mut Py_ssize_t) -> c_int; pub fn PySlice_GetIndicesEx(r: *mut PyObject, length: Py_ssize_t, start: *mut Py_ssize_t, stop: *mut Py_ssize_t, step: *mut Py_ssize_t, slicelength: *mut Py_ssize_t) -> c_int; }
PySlice_Check
identifier_name
sliceobject.rs
use libc::c_int; use pyport::Py_ssize_t; use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { static mut _Py_EllipsisObject: PyObject; } #[inline(always)] pub unsafe fn Py_Ellipsis() -> *mut PyObject { &mut _Py_EllipsisObject } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub static mut PySlice_Type: PyTypeObject; pub static mut PyEllipsis_Type: PyTypeObject; } #[inline(always)] pub unsafe fn PySlice_Check(op: *mut PyObject) -> c_int
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub fn PySlice_New(start: *mut PyObject, stop: *mut PyObject, step: *mut PyObject) -> *mut PyObject; pub fn PySlice_GetIndices(r: *mut PyObject, length: Py_ssize_t, start: *mut Py_ssize_t, stop: *mut Py_ssize_t, step: *mut Py_ssize_t) -> c_int; pub fn PySlice_GetIndicesEx(r: *mut PyObject, length: Py_ssize_t, start: *mut Py_ssize_t, stop: *mut Py_ssize_t, step: *mut Py_ssize_t, slicelength: *mut Py_ssize_t) -> c_int; }
{ (Py_TYPE(op) == &mut PySlice_Type) as c_int }
identifier_body
sliceobject.rs
use libc::c_int; use pyport::Py_ssize_t;
static mut _Py_EllipsisObject: PyObject; } #[inline(always)] pub unsafe fn Py_Ellipsis() -> *mut PyObject { &mut _Py_EllipsisObject } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub static mut PySlice_Type: PyTypeObject; pub static mut PyEllipsis_Type: PyTypeObject; } #[inline(always)] pub unsafe fn PySlice_Check(op: *mut PyObject) -> c_int { (Py_TYPE(op) == &mut PySlice_Type) as c_int } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub fn PySlice_New(start: *mut PyObject, stop: *mut PyObject, step: *mut PyObject) -> *mut PyObject; pub fn PySlice_GetIndices(r: *mut PyObject, length: Py_ssize_t, start: *mut Py_ssize_t, stop: *mut Py_ssize_t, step: *mut Py_ssize_t) -> c_int; pub fn PySlice_GetIndicesEx(r: *mut PyObject, length: Py_ssize_t, start: *mut Py_ssize_t, stop: *mut Py_ssize_t, step: *mut Py_ssize_t, slicelength: *mut Py_ssize_t) -> c_int; }
use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
random_line_split
from_repr.rs
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{Data, DeriveInput, PathArguments, Type, TypeParen}; use crate::helpers::{non_enum_error, HasStrumVariantProperties}; pub fn from_repr_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.generics; let (impl_generics, ty_generics, where_clause) = gen.split_for_impl(); let vis = &ast.vis; let attrs = &ast.attrs; let mut discriminant_type: Type = syn::parse("usize".parse().unwrap()).unwrap(); for attr in attrs { let path = &attr.path; let tokens = &attr.tokens; if path.leading_colon.is_some() { continue; } if path.segments.len()!= 1 { continue; } let segment = path.segments.first().unwrap(); if segment.ident!= "repr" { continue; } if segment.arguments!= PathArguments::None { continue; } let typ_paren = match syn::parse2::<Type>(tokens.clone()) { Ok(Type::Paren(TypeParen { elem,.. })) => *elem, _ => continue, }; let inner_path = match &typ_paren { Type::Path(t) => t, _ => continue, }; if let Some(seg) = inner_path.path.segments.last() { for t in &[ "u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize", ] { if seg.ident == t { discriminant_type = typ_paren; break; } } } } if gen.lifetimes().count() > 0 { return Err(syn::Error::new( Span::call_site(), "This macro doesn't support enums with lifetimes. \ The resulting enums would be unbounded.", )); } let variants = match &ast.data { Data::Enum(v) => &v.variants, _ => return Err(non_enum_error()), }; let mut arms = Vec::new(); let mut constant_defs = Vec::new(); let mut has_additional_data = false; let mut prev_const_var_ident = None; for variant in variants { use syn::Fields::*; if variant.get_variant_properties()?.disabled.is_some() { continue; } let ident = &variant.ident; let params = match &variant.fields { Unit => quote! {}, Unnamed(fields) => { has_additional_data = true; let defaults = ::std::iter::repeat(quote!(::core::default::Default::default())) .take(fields.unnamed.len()); quote! { (#(#defaults),*) } } Named(fields) => { has_additional_data = true; let fields = fields .named .iter() .map(|field| field.ident.as_ref().unwrap()); quote! { {#(#fields: ::core::default::Default::default()),*} } } }; use heck::ShoutySnakeCase; let const_var_str = format!("{}_DISCRIMINANT", variant.ident).to_shouty_snake_case(); let const_var_ident = format_ident!("{}", const_var_str); let const_val_expr = match &variant.discriminant { Some((_, expr)) => quote! { #expr }, None => match &prev_const_var_ident { Some(prev) => quote! { #prev + 1 }, None => quote! { 0 }, }, }; constant_defs.push(quote! {const #const_var_ident: #discriminant_type = #const_val_expr;}); arms.push(quote! {v if v == #const_var_ident => ::core::option::Option::Some(#name::#ident #params)}); prev_const_var_ident = Some(const_var_ident); } arms.push(quote! { _ => ::core::option::Option::None }); let const_if_possible = if has_additional_data { quote! {} } else { #[rustversion::before(1.46)] fn filter_by_rust_version(s: TokenStream) -> TokenStream { quote! {} }
}; Ok(quote! { impl #impl_generics #name #ty_generics #where_clause { #vis #const_if_possible fn from_repr(discriminant: #discriminant_type) -> Option<#name #ty_generics> { #(#constant_defs)* match discriminant { #(#arms),* } } } }) }
#[rustversion::since(1.46)] fn filter_by_rust_version(s: TokenStream) -> TokenStream { s } filter_by_rust_version(quote! { const })
random_line_split
from_repr.rs
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{Data, DeriveInput, PathArguments, Type, TypeParen}; use crate::helpers::{non_enum_error, HasStrumVariantProperties}; pub fn
(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.generics; let (impl_generics, ty_generics, where_clause) = gen.split_for_impl(); let vis = &ast.vis; let attrs = &ast.attrs; let mut discriminant_type: Type = syn::parse("usize".parse().unwrap()).unwrap(); for attr in attrs { let path = &attr.path; let tokens = &attr.tokens; if path.leading_colon.is_some() { continue; } if path.segments.len()!= 1 { continue; } let segment = path.segments.first().unwrap(); if segment.ident!= "repr" { continue; } if segment.arguments!= PathArguments::None { continue; } let typ_paren = match syn::parse2::<Type>(tokens.clone()) { Ok(Type::Paren(TypeParen { elem,.. })) => *elem, _ => continue, }; let inner_path = match &typ_paren { Type::Path(t) => t, _ => continue, }; if let Some(seg) = inner_path.path.segments.last() { for t in &[ "u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize", ] { if seg.ident == t { discriminant_type = typ_paren; break; } } } } if gen.lifetimes().count() > 0 { return Err(syn::Error::new( Span::call_site(), "This macro doesn't support enums with lifetimes. \ The resulting enums would be unbounded.", )); } let variants = match &ast.data { Data::Enum(v) => &v.variants, _ => return Err(non_enum_error()), }; let mut arms = Vec::new(); let mut constant_defs = Vec::new(); let mut has_additional_data = false; let mut prev_const_var_ident = None; for variant in variants { use syn::Fields::*; if variant.get_variant_properties()?.disabled.is_some() { continue; } let ident = &variant.ident; let params = match &variant.fields { Unit => quote! {}, Unnamed(fields) => { has_additional_data = true; let defaults = ::std::iter::repeat(quote!(::core::default::Default::default())) .take(fields.unnamed.len()); quote! { (#(#defaults),*) } } Named(fields) => { has_additional_data = true; let fields = fields .named .iter() .map(|field| field.ident.as_ref().unwrap()); quote! { {#(#fields: ::core::default::Default::default()),*} } } }; use heck::ShoutySnakeCase; let const_var_str = format!("{}_DISCRIMINANT", variant.ident).to_shouty_snake_case(); let const_var_ident = format_ident!("{}", const_var_str); let const_val_expr = match &variant.discriminant { Some((_, expr)) => quote! { #expr }, None => match &prev_const_var_ident { Some(prev) => quote! { #prev + 1 }, None => quote! { 0 }, }, }; constant_defs.push(quote! {const #const_var_ident: #discriminant_type = #const_val_expr;}); arms.push(quote! {v if v == #const_var_ident => ::core::option::Option::Some(#name::#ident #params)}); prev_const_var_ident = Some(const_var_ident); } arms.push(quote! { _ => ::core::option::Option::None }); let const_if_possible = if has_additional_data { quote! {} } else { #[rustversion::before(1.46)] fn filter_by_rust_version(s: TokenStream) -> TokenStream { quote! {} } #[rustversion::since(1.46)] fn filter_by_rust_version(s: TokenStream) -> TokenStream { s } filter_by_rust_version(quote! { const }) }; Ok(quote! { impl #impl_generics #name #ty_generics #where_clause { #vis #const_if_possible fn from_repr(discriminant: #discriminant_type) -> Option<#name #ty_generics> { #(#constant_defs)* match discriminant { #(#arms),* } } } }) }
from_repr_inner
identifier_name
from_repr.rs
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{Data, DeriveInput, PathArguments, Type, TypeParen}; use crate::helpers::{non_enum_error, HasStrumVariantProperties}; pub fn from_repr_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.generics; let (impl_generics, ty_generics, where_clause) = gen.split_for_impl(); let vis = &ast.vis; let attrs = &ast.attrs; let mut discriminant_type: Type = syn::parse("usize".parse().unwrap()).unwrap(); for attr in attrs { let path = &attr.path; let tokens = &attr.tokens; if path.leading_colon.is_some() { continue; } if path.segments.len()!= 1 { continue; } let segment = path.segments.first().unwrap(); if segment.ident!= "repr" { continue; } if segment.arguments!= PathArguments::None
let typ_paren = match syn::parse2::<Type>(tokens.clone()) { Ok(Type::Paren(TypeParen { elem,.. })) => *elem, _ => continue, }; let inner_path = match &typ_paren { Type::Path(t) => t, _ => continue, }; if let Some(seg) = inner_path.path.segments.last() { for t in &[ "u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize", ] { if seg.ident == t { discriminant_type = typ_paren; break; } } } } if gen.lifetimes().count() > 0 { return Err(syn::Error::new( Span::call_site(), "This macro doesn't support enums with lifetimes. \ The resulting enums would be unbounded.", )); } let variants = match &ast.data { Data::Enum(v) => &v.variants, _ => return Err(non_enum_error()), }; let mut arms = Vec::new(); let mut constant_defs = Vec::new(); let mut has_additional_data = false; let mut prev_const_var_ident = None; for variant in variants { use syn::Fields::*; if variant.get_variant_properties()?.disabled.is_some() { continue; } let ident = &variant.ident; let params = match &variant.fields { Unit => quote! {}, Unnamed(fields) => { has_additional_data = true; let defaults = ::std::iter::repeat(quote!(::core::default::Default::default())) .take(fields.unnamed.len()); quote! { (#(#defaults),*) } } Named(fields) => { has_additional_data = true; let fields = fields .named .iter() .map(|field| field.ident.as_ref().unwrap()); quote! { {#(#fields: ::core::default::Default::default()),*} } } }; use heck::ShoutySnakeCase; let const_var_str = format!("{}_DISCRIMINANT", variant.ident).to_shouty_snake_case(); let const_var_ident = format_ident!("{}", const_var_str); let const_val_expr = match &variant.discriminant { Some((_, expr)) => quote! { #expr }, None => match &prev_const_var_ident { Some(prev) => quote! { #prev + 1 }, None => quote! { 0 }, }, }; constant_defs.push(quote! {const #const_var_ident: #discriminant_type = #const_val_expr;}); arms.push(quote! {v if v == #const_var_ident => ::core::option::Option::Some(#name::#ident #params)}); prev_const_var_ident = Some(const_var_ident); } arms.push(quote! { _ => ::core::option::Option::None }); let const_if_possible = if has_additional_data { quote! {} } else { #[rustversion::before(1.46)] fn filter_by_rust_version(s: TokenStream) -> TokenStream { quote! {} } #[rustversion::since(1.46)] fn filter_by_rust_version(s: TokenStream) -> TokenStream { s } filter_by_rust_version(quote! { const }) }; Ok(quote! { impl #impl_generics #name #ty_generics #where_clause { #vis #const_if_possible fn from_repr(discriminant: #discriminant_type) -> Option<#name #ty_generics> { #(#constant_defs)* match discriminant { #(#arms),* } } } }) }
{ continue; }
conditional_block
from_repr.rs
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{Data, DeriveInput, PathArguments, Type, TypeParen}; use crate::helpers::{non_enum_error, HasStrumVariantProperties}; pub fn from_repr_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.generics; let (impl_generics, ty_generics, where_clause) = gen.split_for_impl(); let vis = &ast.vis; let attrs = &ast.attrs; let mut discriminant_type: Type = syn::parse("usize".parse().unwrap()).unwrap(); for attr in attrs { let path = &attr.path; let tokens = &attr.tokens; if path.leading_colon.is_some() { continue; } if path.segments.len()!= 1 { continue; } let segment = path.segments.first().unwrap(); if segment.ident!= "repr" { continue; } if segment.arguments!= PathArguments::None { continue; } let typ_paren = match syn::parse2::<Type>(tokens.clone()) { Ok(Type::Paren(TypeParen { elem,.. })) => *elem, _ => continue, }; let inner_path = match &typ_paren { Type::Path(t) => t, _ => continue, }; if let Some(seg) = inner_path.path.segments.last() { for t in &[ "u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize", ] { if seg.ident == t { discriminant_type = typ_paren; break; } } } } if gen.lifetimes().count() > 0 { return Err(syn::Error::new( Span::call_site(), "This macro doesn't support enums with lifetimes. \ The resulting enums would be unbounded.", )); } let variants = match &ast.data { Data::Enum(v) => &v.variants, _ => return Err(non_enum_error()), }; let mut arms = Vec::new(); let mut constant_defs = Vec::new(); let mut has_additional_data = false; let mut prev_const_var_ident = None; for variant in variants { use syn::Fields::*; if variant.get_variant_properties()?.disabled.is_some() { continue; } let ident = &variant.ident; let params = match &variant.fields { Unit => quote! {}, Unnamed(fields) => { has_additional_data = true; let defaults = ::std::iter::repeat(quote!(::core::default::Default::default())) .take(fields.unnamed.len()); quote! { (#(#defaults),*) } } Named(fields) => { has_additional_data = true; let fields = fields .named .iter() .map(|field| field.ident.as_ref().unwrap()); quote! { {#(#fields: ::core::default::Default::default()),*} } } }; use heck::ShoutySnakeCase; let const_var_str = format!("{}_DISCRIMINANT", variant.ident).to_shouty_snake_case(); let const_var_ident = format_ident!("{}", const_var_str); let const_val_expr = match &variant.discriminant { Some((_, expr)) => quote! { #expr }, None => match &prev_const_var_ident { Some(prev) => quote! { #prev + 1 }, None => quote! { 0 }, }, }; constant_defs.push(quote! {const #const_var_ident: #discriminant_type = #const_val_expr;}); arms.push(quote! {v if v == #const_var_ident => ::core::option::Option::Some(#name::#ident #params)}); prev_const_var_ident = Some(const_var_ident); } arms.push(quote! { _ => ::core::option::Option::None }); let const_if_possible = if has_additional_data { quote! {} } else { #[rustversion::before(1.46)] fn filter_by_rust_version(s: TokenStream) -> TokenStream
#[rustversion::since(1.46)] fn filter_by_rust_version(s: TokenStream) -> TokenStream { s } filter_by_rust_version(quote! { const }) }; Ok(quote! { impl #impl_generics #name #ty_generics #where_clause { #vis #const_if_possible fn from_repr(discriminant: #discriminant_type) -> Option<#name #ty_generics> { #(#constant_defs)* match discriminant { #(#arms),* } } } }) }
{ quote! {} }
identifier_body
lib.rs
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Terminal formatting library. //! //! This crate provides the `Terminal` trait, which abstracts over an [ANSI //! Terminal][ansi] to provide color printing, among other things. There are two //! implementations, the `TerminfoTerminal`, which uses control characters from //! a [terminfo][ti] database, and `WinConsole`, which uses the [Win32 Console //! API][win]. //! //! # Usage //! //! This crate is [on crates.io](https://crates.io/crates/term) and can be //! used by adding `term` to the dependencies in your project's `Cargo.toml`. //! //! ```toml //! [dependencies] //! //! term = "0.2" //! ``` //! //! and this to your crate root: //! //! ```rust //! extern crate term; //! ``` //! //! # Examples //! //! ```no_run //! extern crate term; //! use std::io::prelude::*; //! //! fn main() { //! let mut t = term::stdout().unwrap(); //! //! t.fg(term::color::GREEN).unwrap(); //! (write!(t, "hello, ")).unwrap(); //! //! t.fg(term::color::RED).unwrap(); //! (writeln!(t, "world!")).unwrap(); //! //! assert!(t.reset().unwrap()); //! } //! ``` //! //! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code //! [win]: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682010%28v=vs.85%29.aspx //! [ti]: https://en.wikipedia.org/wiki/Terminfo #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![deny(missing_docs)] #![cfg_attr(test, deny(warnings))] #![cfg_attr(rust_build, feature(staged_api))] #![cfg_attr(rust_build, staged_api)] #![cfg_attr(rust_build, unstable(feature = "rustc_private", reason = "use the crates.io `term` library instead"))] use std::io::prelude::*; pub use terminfo::TerminfoTerminal; #[cfg(windows)] pub use win::WinConsole; use std::io::{self, Stdout, Stderr}; pub mod terminfo; #[cfg(windows)] mod win; /// Alias for stdout terminals. pub type StdoutTerminal = Terminal<Output=Stdout> + Send; /// Alias for stderr terminals. pub type StderrTerminal = Terminal<Output=Stderr> + Send; #[cfg(not(windows))] /// Return a Terminal wrapping stdout, or None if a terminal couldn't be /// opened. pub fn stdout() -> Option<Box<StdoutTerminal>> { TerminfoTerminal::new(io::stdout()).map(|t| { Box::new(t) as Box<StdoutTerminal> }) } #[cfg(windows)] /// Return a Terminal wrapping stdout, or None if a terminal couldn't be /// opened. pub fn stdout() -> Option<Box<StdoutTerminal>>
#[cfg(not(windows))] /// Return a Terminal wrapping stderr, or None if a terminal couldn't be /// opened. pub fn stderr() -> Option<Box<StderrTerminal>> { TerminfoTerminal::new(io::stderr()).map(|t| { Box::new(t) as Box<StderrTerminal> }) } #[cfg(windows)] /// Return a Terminal wrapping stderr, or None if a terminal couldn't be /// opened. pub fn stderr() -> Option<Box<StderrTerminal>> { TerminfoTerminal::new(io::stderr()).map(|t| { Box::new(t) as Box<StderrTerminal> }).or_else(|| WinConsole::new(io::stderr()).ok().map(|t| { Box::new(t) as Box<StderrTerminal> })) } /// Terminal color definitions #[allow(missing_docs)] pub mod color { /// Number for a terminal color pub type Color = u16; pub const BLACK: Color = 0; pub const RED: Color = 1; pub const GREEN: Color = 2; pub const YELLOW: Color = 3; pub const BLUE: Color = 4; pub const MAGENTA: Color = 5; pub const CYAN: Color = 6; pub const WHITE: Color = 7; pub const BRIGHT_BLACK: Color = 8; pub const BRIGHT_RED: Color = 9; pub const BRIGHT_GREEN: Color = 10; pub const BRIGHT_YELLOW: Color = 11; pub const BRIGHT_BLUE: Color = 12; pub const BRIGHT_MAGENTA: Color = 13; pub const BRIGHT_CYAN: Color = 14; pub const BRIGHT_WHITE: Color = 15; } /// Terminal attributes for use with term.attr(). /// /// Most attributes can only be turned on and must be turned off with term.reset(). /// The ones that can be turned off explicitly take a boolean value. /// Color is also represented as an attribute for convenience. #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum Attr { /// Bold (or possibly bright) mode Bold, /// Dim mode, also called faint or half-bright. Often not supported Dim, /// Italics mode. Often not supported Italic(bool), /// Underline mode Underline(bool), /// Blink mode Blink, /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold Standout(bool), /// Reverse mode, inverts the foreground and background colors Reverse, /// Secure mode, also called invis mode. Hides the printed text Secure, /// Convenience attribute to set the foreground color ForegroundColor(color::Color), /// Convenience attribute to set the background color BackgroundColor(color::Color) } /// A terminal with similar capabilities to an ANSI Terminal /// (foreground/background colors etc). pub trait Terminal: Write { /// The terminal's output writer type. type Output: Write; /// Sets the foreground color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn fg(&mut self, color: color::Color) -> io::Result<bool>; /// Sets the background color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn bg(&mut self, color: color::Color) -> io::Result<bool>; /// Sets the given terminal attribute, if supported. Returns `Ok(true)` /// if the attribute was supported, `Ok(false)` otherwise, and `Err(e)` if /// there was an I/O error. fn attr(&mut self, attr: Attr) -> io::Result<bool>; /// Returns whether the given terminal attribute is supported. fn supports_attr(&self, attr: Attr) -> bool; /// Resets all terminal attributes and color to the default. /// /// Returns `Ok(true)` if the terminal was reset, `Ok(false)` otherwise, and `Err(e)` if there /// was an I/O error. fn reset(&mut self) -> io::Result<bool>; /// Moves the cursor up one line. /// /// Returns `Ok(true)` if the cursor was moved, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn cursor_up(&mut self) -> io::Result<bool>; /// Deletes the text from the cursor location to the end of the line. /// /// Returns `Ok(true)` if the text was deleted, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn delete_line(&mut self) -> io::Result<bool>; /// Moves the cursor to the left edge of the current line. /// /// Returns `Ok(true)` if the text was deleted, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn carriage_return(&mut self) -> io::Result<bool>; /// Gets an immutable reference to the stream inside fn get_ref<'a>(&'a self) -> &'a Self::Output; /// Gets a mutable reference to the stream inside fn get_mut<'a>(&'a mut self) -> &'a mut Self::Output; /// Returns the contained stream, destroying the `Terminal` fn into_inner(self) -> Self::Output where Self: Sized; }
{ TerminfoTerminal::new(io::stdout()).map(|t| { Box::new(t) as Box<StdoutTerminal> }).or_else(|| WinConsole::new(io::stdout()).ok().map(|t| { Box::new(t) as Box<StdoutTerminal> })) }
identifier_body
lib.rs
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Terminal formatting library. //! //! This crate provides the `Terminal` trait, which abstracts over an [ANSI //! Terminal][ansi] to provide color printing, among other things. There are two //! implementations, the `TerminfoTerminal`, which uses control characters from //! a [terminfo][ti] database, and `WinConsole`, which uses the [Win32 Console //! API][win]. //! //! # Usage //! //! This crate is [on crates.io](https://crates.io/crates/term) and can be //! used by adding `term` to the dependencies in your project's `Cargo.toml`. //! //! ```toml //! [dependencies] //! //! term = "0.2" //! ``` //! //! and this to your crate root: //! //! ```rust //! extern crate term; //! ``` //! //! # Examples //! //! ```no_run //! extern crate term; //! use std::io::prelude::*; //! //! fn main() { //! let mut t = term::stdout().unwrap(); //! //! t.fg(term::color::GREEN).unwrap(); //! (write!(t, "hello, ")).unwrap(); //! //! t.fg(term::color::RED).unwrap(); //! (writeln!(t, "world!")).unwrap(); //! //! assert!(t.reset().unwrap()); //! } //! ``` //! //! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code //! [win]: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682010%28v=vs.85%29.aspx //! [ti]: https://en.wikipedia.org/wiki/Terminfo #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![deny(missing_docs)] #![cfg_attr(test, deny(warnings))] #![cfg_attr(rust_build, feature(staged_api))] #![cfg_attr(rust_build, staged_api)] #![cfg_attr(rust_build, unstable(feature = "rustc_private", reason = "use the crates.io `term` library instead"))] use std::io::prelude::*; pub use terminfo::TerminfoTerminal; #[cfg(windows)] pub use win::WinConsole; use std::io::{self, Stdout, Stderr}; pub mod terminfo; #[cfg(windows)] mod win; /// Alias for stdout terminals. pub type StdoutTerminal = Terminal<Output=Stdout> + Send; /// Alias for stderr terminals. pub type StderrTerminal = Terminal<Output=Stderr> + Send; #[cfg(not(windows))] /// Return a Terminal wrapping stdout, or None if a terminal couldn't be /// opened. pub fn stdout() -> Option<Box<StdoutTerminal>> { TerminfoTerminal::new(io::stdout()).map(|t| { Box::new(t) as Box<StdoutTerminal> }) } #[cfg(windows)] /// Return a Terminal wrapping stdout, or None if a terminal couldn't be /// opened. pub fn stdout() -> Option<Box<StdoutTerminal>> { TerminfoTerminal::new(io::stdout()).map(|t| { Box::new(t) as Box<StdoutTerminal> }).or_else(|| WinConsole::new(io::stdout()).ok().map(|t| { Box::new(t) as Box<StdoutTerminal> })) } #[cfg(not(windows))] /// Return a Terminal wrapping stderr, or None if a terminal couldn't be /// opened. pub fn stderr() -> Option<Box<StderrTerminal>> { TerminfoTerminal::new(io::stderr()).map(|t| { Box::new(t) as Box<StderrTerminal> }) } #[cfg(windows)] /// Return a Terminal wrapping stderr, or None if a terminal couldn't be /// opened. pub fn stderr() -> Option<Box<StderrTerminal>> { TerminfoTerminal::new(io::stderr()).map(|t| { Box::new(t) as Box<StderrTerminal> }).or_else(|| WinConsole::new(io::stderr()).ok().map(|t| { Box::new(t) as Box<StderrTerminal> })) } /// Terminal color definitions #[allow(missing_docs)] pub mod color { /// Number for a terminal color pub type Color = u16; pub const BLACK: Color = 0; pub const RED: Color = 1; pub const GREEN: Color = 2; pub const YELLOW: Color = 3; pub const BLUE: Color = 4; pub const MAGENTA: Color = 5; pub const CYAN: Color = 6; pub const WHITE: Color = 7; pub const BRIGHT_BLACK: Color = 8; pub const BRIGHT_RED: Color = 9; pub const BRIGHT_GREEN: Color = 10; pub const BRIGHT_YELLOW: Color = 11; pub const BRIGHT_BLUE: Color = 12; pub const BRIGHT_MAGENTA: Color = 13; pub const BRIGHT_CYAN: Color = 14; pub const BRIGHT_WHITE: Color = 15; } /// Terminal attributes for use with term.attr(). /// /// Most attributes can only be turned on and must be turned off with term.reset(). /// The ones that can be turned off explicitly take a boolean value. /// Color is also represented as an attribute for convenience. #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum
{ /// Bold (or possibly bright) mode Bold, /// Dim mode, also called faint or half-bright. Often not supported Dim, /// Italics mode. Often not supported Italic(bool), /// Underline mode Underline(bool), /// Blink mode Blink, /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold Standout(bool), /// Reverse mode, inverts the foreground and background colors Reverse, /// Secure mode, also called invis mode. Hides the printed text Secure, /// Convenience attribute to set the foreground color ForegroundColor(color::Color), /// Convenience attribute to set the background color BackgroundColor(color::Color) } /// A terminal with similar capabilities to an ANSI Terminal /// (foreground/background colors etc). pub trait Terminal: Write { /// The terminal's output writer type. type Output: Write; /// Sets the foreground color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn fg(&mut self, color: color::Color) -> io::Result<bool>; /// Sets the background color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn bg(&mut self, color: color::Color) -> io::Result<bool>; /// Sets the given terminal attribute, if supported. Returns `Ok(true)` /// if the attribute was supported, `Ok(false)` otherwise, and `Err(e)` if /// there was an I/O error. fn attr(&mut self, attr: Attr) -> io::Result<bool>; /// Returns whether the given terminal attribute is supported. fn supports_attr(&self, attr: Attr) -> bool; /// Resets all terminal attributes and color to the default. /// /// Returns `Ok(true)` if the terminal was reset, `Ok(false)` otherwise, and `Err(e)` if there /// was an I/O error. fn reset(&mut self) -> io::Result<bool>; /// Moves the cursor up one line. /// /// Returns `Ok(true)` if the cursor was moved, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn cursor_up(&mut self) -> io::Result<bool>; /// Deletes the text from the cursor location to the end of the line. /// /// Returns `Ok(true)` if the text was deleted, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn delete_line(&mut self) -> io::Result<bool>; /// Moves the cursor to the left edge of the current line. /// /// Returns `Ok(true)` if the text was deleted, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn carriage_return(&mut self) -> io::Result<bool>; /// Gets an immutable reference to the stream inside fn get_ref<'a>(&'a self) -> &'a Self::Output; /// Gets a mutable reference to the stream inside fn get_mut<'a>(&'a mut self) -> &'a mut Self::Output; /// Returns the contained stream, destroying the `Terminal` fn into_inner(self) -> Self::Output where Self: Sized; }
Attr
identifier_name
lib.rs
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Terminal formatting library. //! //! This crate provides the `Terminal` trait, which abstracts over an [ANSI //! Terminal][ansi] to provide color printing, among other things. There are two //! implementations, the `TerminfoTerminal`, which uses control characters from //! a [terminfo][ti] database, and `WinConsole`, which uses the [Win32 Console //! API][win]. //! //! # Usage //! //! This crate is [on crates.io](https://crates.io/crates/term) and can be //! used by adding `term` to the dependencies in your project's `Cargo.toml`. //! //! ```toml //! [dependencies] //! //! term = "0.2" //! ``` //! //! and this to your crate root: //! //! ```rust //! extern crate term; //! ``` //! //! # Examples //! //! ```no_run //! extern crate term; //! use std::io::prelude::*; //! //! fn main() { //! let mut t = term::stdout().unwrap(); //! //! t.fg(term::color::GREEN).unwrap(); //! (write!(t, "hello, ")).unwrap(); //! //! t.fg(term::color::RED).unwrap(); //! (writeln!(t, "world!")).unwrap(); //! //! assert!(t.reset().unwrap()); //! } //! ``` //! //! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code //! [win]: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682010%28v=vs.85%29.aspx //! [ti]: https://en.wikipedia.org/wiki/Terminfo #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![deny(missing_docs)] #![cfg_attr(test, deny(warnings))] #![cfg_attr(rust_build, feature(staged_api))] #![cfg_attr(rust_build, staged_api)] #![cfg_attr(rust_build, unstable(feature = "rustc_private", reason = "use the crates.io `term` library instead"))] use std::io::prelude::*; pub use terminfo::TerminfoTerminal; #[cfg(windows)] pub use win::WinConsole; use std::io::{self, Stdout, Stderr}; pub mod terminfo; #[cfg(windows)] mod win; /// Alias for stdout terminals. pub type StdoutTerminal = Terminal<Output=Stdout> + Send; /// Alias for stderr terminals. pub type StderrTerminal = Terminal<Output=Stderr> + Send; #[cfg(not(windows))] /// Return a Terminal wrapping stdout, or None if a terminal couldn't be /// opened. pub fn stdout() -> Option<Box<StdoutTerminal>> { TerminfoTerminal::new(io::stdout()).map(|t| { Box::new(t) as Box<StdoutTerminal> }) } #[cfg(windows)] /// Return a Terminal wrapping stdout, or None if a terminal couldn't be /// opened. pub fn stdout() -> Option<Box<StdoutTerminal>> { TerminfoTerminal::new(io::stdout()).map(|t| { Box::new(t) as Box<StdoutTerminal> }).or_else(|| WinConsole::new(io::stdout()).ok().map(|t| { Box::new(t) as Box<StdoutTerminal> })) } #[cfg(not(windows))] /// Return a Terminal wrapping stderr, or None if a terminal couldn't be /// opened. pub fn stderr() -> Option<Box<StderrTerminal>> { TerminfoTerminal::new(io::stderr()).map(|t| { Box::new(t) as Box<StderrTerminal> }) } #[cfg(windows)] /// Return a Terminal wrapping stderr, or None if a terminal couldn't be /// opened. pub fn stderr() -> Option<Box<StderrTerminal>> { TerminfoTerminal::new(io::stderr()).map(|t| { Box::new(t) as Box<StderrTerminal> }).or_else(|| WinConsole::new(io::stderr()).ok().map(|t| { Box::new(t) as Box<StderrTerminal> })) } /// Terminal color definitions #[allow(missing_docs)] pub mod color { /// Number for a terminal color pub type Color = u16; pub const BLACK: Color = 0; pub const RED: Color = 1; pub const GREEN: Color = 2; pub const YELLOW: Color = 3; pub const BLUE: Color = 4; pub const MAGENTA: Color = 5; pub const CYAN: Color = 6; pub const WHITE: Color = 7; pub const BRIGHT_BLACK: Color = 8; pub const BRIGHT_RED: Color = 9; pub const BRIGHT_GREEN: Color = 10; pub const BRIGHT_YELLOW: Color = 11; pub const BRIGHT_BLUE: Color = 12; pub const BRIGHT_MAGENTA: Color = 13; pub const BRIGHT_CYAN: Color = 14; pub const BRIGHT_WHITE: Color = 15; } /// Terminal attributes for use with term.attr(). /// /// Most attributes can only be turned on and must be turned off with term.reset(). /// The ones that can be turned off explicitly take a boolean value. /// Color is also represented as an attribute for convenience. #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum Attr { /// Bold (or possibly bright) mode Bold, /// Dim mode, also called faint or half-bright. Often not supported Dim, /// Italics mode. Often not supported Italic(bool), /// Underline mode Underline(bool), /// Blink mode Blink, /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold Standout(bool), /// Reverse mode, inverts the foreground and background colors Reverse, /// Secure mode, also called invis mode. Hides the printed text Secure, /// Convenience attribute to set the foreground color ForegroundColor(color::Color), /// Convenience attribute to set the background color BackgroundColor(color::Color) } /// A terminal with similar capabilities to an ANSI Terminal /// (foreground/background colors etc). pub trait Terminal: Write { /// The terminal's output writer type. type Output: Write; /// Sets the foreground color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn fg(&mut self, color: color::Color) -> io::Result<bool>; /// Sets the background color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn bg(&mut self, color: color::Color) -> io::Result<bool>; /// Sets the given terminal attribute, if supported. Returns `Ok(true)` /// if the attribute was supported, `Ok(false)` otherwise, and `Err(e)` if /// there was an I/O error. fn attr(&mut self, attr: Attr) -> io::Result<bool>; /// Returns whether the given terminal attribute is supported. fn supports_attr(&self, attr: Attr) -> bool; /// Resets all terminal attributes and color to the default. /// /// Returns `Ok(true)` if the terminal was reset, `Ok(false)` otherwise, and `Err(e)` if there /// was an I/O error. fn reset(&mut self) -> io::Result<bool>; /// Moves the cursor up one line. /// /// Returns `Ok(true)` if the cursor was moved, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn cursor_up(&mut self) -> io::Result<bool>; /// Deletes the text from the cursor location to the end of the line. /// /// Returns `Ok(true)` if the text was deleted, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn delete_line(&mut self) -> io::Result<bool>;
/// Gets an immutable reference to the stream inside fn get_ref<'a>(&'a self) -> &'a Self::Output; /// Gets a mutable reference to the stream inside fn get_mut<'a>(&'a mut self) -> &'a mut Self::Output; /// Returns the contained stream, destroying the `Terminal` fn into_inner(self) -> Self::Output where Self: Sized; }
/// Moves the cursor to the left edge of the current line. /// /// Returns `Ok(true)` if the text was deleted, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn carriage_return(&mut self) -> io::Result<bool>;
random_line_split
p017.rs
use solutions::Solution; pub fn solve() -> Solution { let mut sum = 0; for n in 1..1001 { sum += wordify(n).len(); } Solution::new(&format!("{}", sum)) } /// Turns the given number (in the range [1,1000]) into a string with no spaces or dashes fn wordify(n: usize) -> String { let numbers = vec!["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]; let tens = vec!["", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; // Treat 1000 as a special case (don't worry about higher numbers) if n == 1000 { return "onethousand".to_string(); } let mut n = n; let mut s = String::new();
if n % 100 < 20 { s += numbers[n % 100]; n /= 100; } else { // Otherwise, the construction of numbers is regular s += numbers[n % 10]; n /= 10; s = tens[n % 10].to_string() + &s; n /= 10; } if n!= 0 { // Add "and" between hundreds and whatever comes after if!s.is_empty() { s = "and".to_string() + &s; } s = numbers[n % 10].to_string() + "hundred" + &s; } s }
// Need to account for special number names below 20
random_line_split
p017.rs
use solutions::Solution; pub fn solve() -> Solution { let mut sum = 0; for n in 1..1001 { sum += wordify(n).len(); } Solution::new(&format!("{}", sum)) } /// Turns the given number (in the range [1,1000]) into a string with no spaces or dashes fn wordify(n: usize) -> String { let numbers = vec!["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]; let tens = vec!["", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; // Treat 1000 as a special case (don't worry about higher numbers) if n == 1000
let mut n = n; let mut s = String::new(); // Need to account for special number names below 20 if n % 100 < 20 { s += numbers[n % 100]; n /= 100; } else { // Otherwise, the construction of numbers is regular s += numbers[n % 10]; n /= 10; s = tens[n % 10].to_string() + &s; n /= 10; } if n!= 0 { // Add "and" between hundreds and whatever comes after if!s.is_empty() { s = "and".to_string() + &s; } s = numbers[n % 10].to_string() + "hundred" + &s; } s }
{ return "onethousand".to_string(); }
conditional_block
p017.rs
use solutions::Solution; pub fn solve() -> Solution { let mut sum = 0; for n in 1..1001 { sum += wordify(n).len(); } Solution::new(&format!("{}", sum)) } /// Turns the given number (in the range [1,1000]) into a string with no spaces or dashes fn
(n: usize) -> String { let numbers = vec!["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]; let tens = vec!["", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; // Treat 1000 as a special case (don't worry about higher numbers) if n == 1000 { return "onethousand".to_string(); } let mut n = n; let mut s = String::new(); // Need to account for special number names below 20 if n % 100 < 20 { s += numbers[n % 100]; n /= 100; } else { // Otherwise, the construction of numbers is regular s += numbers[n % 10]; n /= 10; s = tens[n % 10].to_string() + &s; n /= 10; } if n!= 0 { // Add "and" between hundreds and whatever comes after if!s.is_empty() { s = "and".to_string() + &s; } s = numbers[n % 10].to_string() + "hundred" + &s; } s }
wordify
identifier_name
p017.rs
use solutions::Solution; pub fn solve() -> Solution
/// Turns the given number (in the range [1,1000]) into a string with no spaces or dashes fn wordify(n: usize) -> String { let numbers = vec!["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]; let tens = vec!["", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; // Treat 1000 as a special case (don't worry about higher numbers) if n == 1000 { return "onethousand".to_string(); } let mut n = n; let mut s = String::new(); // Need to account for special number names below 20 if n % 100 < 20 { s += numbers[n % 100]; n /= 100; } else { // Otherwise, the construction of numbers is regular s += numbers[n % 10]; n /= 10; s = tens[n % 10].to_string() + &s; n /= 10; } if n!= 0 { // Add "and" between hundreds and whatever comes after if!s.is_empty() { s = "and".to_string() + &s; } s = numbers[n % 10].to_string() + "hundred" + &s; } s }
{ let mut sum = 0; for n in 1..1001 { sum += wordify(n).len(); } Solution::new(&format!("{}", sum)) }
identifier_body
lib.rs
#[feature(macro_rules)]; #[crate_id = "diagrus#0.1"]; #[crate_type = "lib"]; #[crate_type = "dylib"]; #[comment = "Utilities to make using JSON easier"]; #[license = "MIT"]; extern mod extra; use std::fmt; pub use self::fromjson::FromJson; pub use self::jsonutil::JsonLike; pub mod macros; pub mod jsonutil;
pub enum ErrorTy { Conversion, Value } /// These error codes describe the actual error specifically. #[deriving(Clone, Encodable, Decodable, Eq, ToStr)] pub enum ErrorCode { NotString, NotNumber, NotInteger, NotBoolean, NotList, NotObject, NotEither, NoSuchKey, IdxOutOfBounds } /// This structure fully describes any errors resulting from use of the library. /// This structure implements `std::fmt::Default`, and `std::to_str::ToStr`, and /// can therefore be converted into a more descriptive string. #[deriving(Clone, Encodable, Decodable, Eq)] pub struct Error { /// Error category category: ErrorTy, /// Code indicating the specific error. code: ErrorCode } impl Error { pub fn new(ty: ErrorTy, code: ErrorCode) -> Error { Error { category: ty, code: code } } } impl fmt::Default for Error { fn fmt(e: &Error, f: &mut fmt::Formatter) { let msg = match e.code { NotString => ~"Not a JSON string", NotNumber => ~"Not a JSON number", NotInteger => ~"JSON number is not an integer", NotBoolean => ~"Not a JSON boolean", NotList => ~"Not a JSON list", NotObject => ~"Not a JSON Object", NotEither => ~"Could not be interpreted as either type", NoSuchKey => ~"No such JSON attribute", IdxOutOfBounds => ~"List index out of bounds" }; write!(f.buf, r#""{}" Error: "{}""#, e.category.to_str(), msg); } } impl ToStr for Error { fn to_str(&self) -> ~str { format!("{}", *self) } } /// Convenience function for errors fn error<T>(ty: ErrorTy, code: ErrorCode) -> Result<T, Error> { Err(Error::new(ty, code)) }
pub mod fromjson; /// This enum indicates if the error is due to a conversion failure, /// or from mishandling the JSON value #[deriving(Clone, Encodable, Decodable, Eq, ToStr)]
random_line_split
lib.rs
#[feature(macro_rules)]; #[crate_id = "diagrus#0.1"]; #[crate_type = "lib"]; #[crate_type = "dylib"]; #[comment = "Utilities to make using JSON easier"]; #[license = "MIT"]; extern mod extra; use std::fmt; pub use self::fromjson::FromJson; pub use self::jsonutil::JsonLike; pub mod macros; pub mod jsonutil; pub mod fromjson; /// This enum indicates if the error is due to a conversion failure, /// or from mishandling the JSON value #[deriving(Clone, Encodable, Decodable, Eq, ToStr)] pub enum ErrorTy { Conversion, Value } /// These error codes describe the actual error specifically. #[deriving(Clone, Encodable, Decodable, Eq, ToStr)] pub enum ErrorCode { NotString, NotNumber, NotInteger, NotBoolean, NotList, NotObject, NotEither, NoSuchKey, IdxOutOfBounds } /// This structure fully describes any errors resulting from use of the library. /// This structure implements `std::fmt::Default`, and `std::to_str::ToStr`, and /// can therefore be converted into a more descriptive string. #[deriving(Clone, Encodable, Decodable, Eq)] pub struct Error { /// Error category category: ErrorTy, /// Code indicating the specific error. code: ErrorCode } impl Error { pub fn new(ty: ErrorTy, code: ErrorCode) -> Error { Error { category: ty, code: code } } } impl fmt::Default for Error { fn fmt(e: &Error, f: &mut fmt::Formatter)
} impl ToStr for Error { fn to_str(&self) -> ~str { format!("{}", *self) } } /// Convenience function for errors fn error<T>(ty: ErrorTy, code: ErrorCode) -> Result<T, Error> { Err(Error::new(ty, code)) }
{ let msg = match e.code { NotString => ~"Not a JSON string", NotNumber => ~"Not a JSON number", NotInteger => ~"JSON number is not an integer", NotBoolean => ~"Not a JSON boolean", NotList => ~"Not a JSON list", NotObject => ~"Not a JSON Object", NotEither => ~"Could not be interpreted as either type", NoSuchKey => ~"No such JSON attribute", IdxOutOfBounds => ~"List index out of bounds" }; write!(f.buf, r#""{}" Error: "{}""#, e.category.to_str(), msg); }
identifier_body
lib.rs
#[feature(macro_rules)]; #[crate_id = "diagrus#0.1"]; #[crate_type = "lib"]; #[crate_type = "dylib"]; #[comment = "Utilities to make using JSON easier"]; #[license = "MIT"]; extern mod extra; use std::fmt; pub use self::fromjson::FromJson; pub use self::jsonutil::JsonLike; pub mod macros; pub mod jsonutil; pub mod fromjson; /// This enum indicates if the error is due to a conversion failure, /// or from mishandling the JSON value #[deriving(Clone, Encodable, Decodable, Eq, ToStr)] pub enum ErrorTy { Conversion, Value } /// These error codes describe the actual error specifically. #[deriving(Clone, Encodable, Decodable, Eq, ToStr)] pub enum ErrorCode { NotString, NotNumber, NotInteger, NotBoolean, NotList, NotObject, NotEither, NoSuchKey, IdxOutOfBounds } /// This structure fully describes any errors resulting from use of the library. /// This structure implements `std::fmt::Default`, and `std::to_str::ToStr`, and /// can therefore be converted into a more descriptive string. #[deriving(Clone, Encodable, Decodable, Eq)] pub struct
{ /// Error category category: ErrorTy, /// Code indicating the specific error. code: ErrorCode } impl Error { pub fn new(ty: ErrorTy, code: ErrorCode) -> Error { Error { category: ty, code: code } } } impl fmt::Default for Error { fn fmt(e: &Error, f: &mut fmt::Formatter) { let msg = match e.code { NotString => ~"Not a JSON string", NotNumber => ~"Not a JSON number", NotInteger => ~"JSON number is not an integer", NotBoolean => ~"Not a JSON boolean", NotList => ~"Not a JSON list", NotObject => ~"Not a JSON Object", NotEither => ~"Could not be interpreted as either type", NoSuchKey => ~"No such JSON attribute", IdxOutOfBounds => ~"List index out of bounds" }; write!(f.buf, r#""{}" Error: "{}""#, e.category.to_str(), msg); } } impl ToStr for Error { fn to_str(&self) -> ~str { format!("{}", *self) } } /// Convenience function for errors fn error<T>(ty: ErrorTy, code: ErrorCode) -> Result<T, Error> { Err(Error::new(ty, code)) }
Error
identifier_name