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
command.rs
use std::error; use clap; use crate::config; use super::executer::{Executer, ExecuterOptions}; pub struct Command<'c> { config: &'c config::command::Config, name: Option<&'c str>, no_wait: bool, all: bool, } impl<'c> Command<'c> { pub fn from_args(config: &'c config::command::Config, args: &'c clap::ArgMatches<'c>) -> Self
pub fn new( config: &'c config::command::Config, name: Option<&'c str>, no_wait: bool, all: bool, ) -> Self { trace!("command::service::deploy::Command::new"); Command { config: config, name: name, no_wait: no_wait, all: all, } } pub async fn run(&self) -> Result<(), Box<dyn error::Error>> { trace!("command::service::deploy::Command::run"); if let Some(service_config_group) = self.config.service.as_ref() { for service_config in service_config_group { let mut runnable: bool = false; if let Some(name) = self.name { if name == service_config.name { runnable = true; } } if self.all { runnable = true; } if!runnable { continue; } let options = ExecuterOptions { no_wait: self.no_wait, }; let ecs_deploy_cmd = Executer::from_config(&service_config, &options); ecs_deploy_cmd.run().await?; } } Ok(()) } }
{ trace!("command::service::deploy::Command::from_args"); Command { config: config, name: args.value_of("NAME"), no_wait: args.is_present("NO_WAIT"), all: args.is_present("ALL"), } }
identifier_body
command.rs
use std::error; use clap; use crate::config; use super::executer::{Executer, ExecuterOptions}; pub struct Command<'c> { config: &'c config::command::Config, name: Option<&'c str>,
} impl<'c> Command<'c> { pub fn from_args(config: &'c config::command::Config, args: &'c clap::ArgMatches<'c>) -> Self { trace!("command::service::deploy::Command::from_args"); Command { config: config, name: args.value_of("NAME"), no_wait: args.is_present("NO_WAIT"), all: args.is_present("ALL"), } } pub fn new( config: &'c config::command::Config, name: Option<&'c str>, no_wait: bool, all: bool, ) -> Self { trace!("command::service::deploy::Command::new"); Command { config: config, name: name, no_wait: no_wait, all: all, } } pub async fn run(&self) -> Result<(), Box<dyn error::Error>> { trace!("command::service::deploy::Command::run"); if let Some(service_config_group) = self.config.service.as_ref() { for service_config in service_config_group { let mut runnable: bool = false; if let Some(name) = self.name { if name == service_config.name { runnable = true; } } if self.all { runnable = true; } if!runnable { continue; } let options = ExecuterOptions { no_wait: self.no_wait, }; let ecs_deploy_cmd = Executer::from_config(&service_config, &options); ecs_deploy_cmd.run().await?; } } Ok(()) } }
no_wait: bool, all: bool,
random_line_split
command.rs
use std::error; use clap; use crate::config; use super::executer::{Executer, ExecuterOptions}; pub struct Command<'c> { config: &'c config::command::Config, name: Option<&'c str>, no_wait: bool, all: bool, } impl<'c> Command<'c> { pub fn
(config: &'c config::command::Config, args: &'c clap::ArgMatches<'c>) -> Self { trace!("command::service::deploy::Command::from_args"); Command { config: config, name: args.value_of("NAME"), no_wait: args.is_present("NO_WAIT"), all: args.is_present("ALL"), } } pub fn new( config: &'c config::command::Config, name: Option<&'c str>, no_wait: bool, all: bool, ) -> Self { trace!("command::service::deploy::Command::new"); Command { config: config, name: name, no_wait: no_wait, all: all, } } pub async fn run(&self) -> Result<(), Box<dyn error::Error>> { trace!("command::service::deploy::Command::run"); if let Some(service_config_group) = self.config.service.as_ref() { for service_config in service_config_group { let mut runnable: bool = false; if let Some(name) = self.name { if name == service_config.name { runnable = true; } } if self.all { runnable = true; } if!runnable { continue; } let options = ExecuterOptions { no_wait: self.no_wait, }; let ecs_deploy_cmd = Executer::from_config(&service_config, &options); ecs_deploy_cmd.run().await?; } } Ok(()) } }
from_args
identifier_name
command.rs
use std::error; use clap; use crate::config; use super::executer::{Executer, ExecuterOptions}; pub struct Command<'c> { config: &'c config::command::Config, name: Option<&'c str>, no_wait: bool, all: bool, } impl<'c> Command<'c> { pub fn from_args(config: &'c config::command::Config, args: &'c clap::ArgMatches<'c>) -> Self { trace!("command::service::deploy::Command::from_args"); Command { config: config, name: args.value_of("NAME"), no_wait: args.is_present("NO_WAIT"), all: args.is_present("ALL"), } } pub fn new( config: &'c config::command::Config, name: Option<&'c str>, no_wait: bool, all: bool, ) -> Self { trace!("command::service::deploy::Command::new"); Command { config: config, name: name, no_wait: no_wait, all: all, } } pub async fn run(&self) -> Result<(), Box<dyn error::Error>> { trace!("command::service::deploy::Command::run"); if let Some(service_config_group) = self.config.service.as_ref()
} } Ok(()) } }
{ for service_config in service_config_group { let mut runnable: bool = false; if let Some(name) = self.name { if name == service_config.name { runnable = true; } } if self.all { runnable = true; } if !runnable { continue; } let options = ExecuterOptions { no_wait: self.no_wait, }; let ecs_deploy_cmd = Executer::from_config(&service_config, &options); ecs_deploy_cmd.run().await?;
conditional_block
regions-proc-bound-capture.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. // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. fn borrowed_proc<'a>(x: &'a isize) -> Box<FnMut()->(isize) + 'a> { // This is legal, because the region bound on `proc` // states that it captures `x`. Box::new(move|| { *x }) } fn static_proc(x: &isize) -> Box<FnMut()->(isize) +'static> { // This is illegal, because the region bound on `proc` is'static. Box::new(move|| { *x }) //~ ERROR captured variable `x` does not outlive the enclosing closure }
fn main() { }
random_line_split
regions-proc-bound-capture.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. // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. fn borrowed_proc<'a>(x: &'a isize) -> Box<FnMut()->(isize) + 'a>
fn static_proc(x: &isize) -> Box<FnMut()->(isize) +'static> { // This is illegal, because the region bound on `proc` is'static. Box::new(move|| { *x }) //~ ERROR captured variable `x` does not outlive the enclosing closure } fn main() { }
{ // This is legal, because the region bound on `proc` // states that it captures `x`. Box::new(move|| { *x }) }
identifier_body
regions-proc-bound-capture.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. // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. fn
<'a>(x: &'a isize) -> Box<FnMut()->(isize) + 'a> { // This is legal, because the region bound on `proc` // states that it captures `x`. Box::new(move|| { *x }) } fn static_proc(x: &isize) -> Box<FnMut()->(isize) +'static> { // This is illegal, because the region bound on `proc` is'static. Box::new(move|| { *x }) //~ ERROR captured variable `x` does not outlive the enclosing closure } fn main() { }
borrowed_proc
identifier_name
html-literals.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. #![allow(non_camel_case_types)] // A test of the macro system. Can we do HTML literals? /* This is an HTML parser written as a macro. It's all CPS, and we have to carry around a bunch of state. The arguments to macros all look like this: { tag_stack* # expr* # tokens } The stack keeps track of where we are in the tree. The expr is a list of children of the current node. The tokens are everything that's left. */ use HTMLFragment::{tag, text}; macro_rules! html { ( $($body:tt)* ) => ( parse_node!( []; []; $($body)* ) ) } macro_rules! parse_node { ( [:$head:ident ($(:$head_nodes:expr),*) $(:$tags:ident ($(:$tag_nodes:expr),*))*]; [$(:$nodes:expr),*]; </$tag:ident> $($rest:tt)* ) => ( parse_node!(
) ); ( [$(:$tags:ident ($(:$tag_nodes:expr),*) )*]; [$(:$nodes:expr),*]; <$tag:ident> $($rest:tt)* ) => ( parse_node!( [:$tag ($(:$nodes)*) $(: $tags ($(:$tag_nodes),*) )*]; []; $($rest)* ) ); ( [$(:$tags:ident ($(:$tag_nodes:expr),*) )*]; [$(:$nodes:expr),*]; . $($rest:tt)* ) => ( parse_node!( [$(: $tags ($(:$tag_nodes),*))*]; [$(:$nodes,)* :text(".".to_string())]; $($rest)* ) ); ( [$(:$tags:ident ($(:$tag_nodes:expr),*) )*]; [$(:$nodes:expr),*]; $word:ident $($rest:tt)* ) => ( parse_node!( [$(: $tags ($(:$tag_nodes),*))*]; [$(:$nodes,)* :text(stringify!($word).to_string())]; $($rest)* ) ); ( []; [:$e:expr]; ) => ( $e ); } pub fn main() { let _page = html! ( <html> <head><title>This is the title.</title></head> <body> <p>This is some text</p> </body> </html> ); } enum HTMLFragment { tag(String, Vec<HTMLFragment> ), text(String), }
[$(: $tags ($(:$tag_nodes),*))*]; [$(:$head_nodes,)* :tag(stringify!($head).to_string(), vec![$($nodes),*])]; $($rest)*
random_line_split
html-literals.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. #![allow(non_camel_case_types)] // A test of the macro system. Can we do HTML literals? /* This is an HTML parser written as a macro. It's all CPS, and we have to carry around a bunch of state. The arguments to macros all look like this: { tag_stack* # expr* # tokens } The stack keeps track of where we are in the tree. The expr is a list of children of the current node. The tokens are everything that's left. */ use HTMLFragment::{tag, text}; macro_rules! html { ( $($body:tt)* ) => ( parse_node!( []; []; $($body)* ) ) } macro_rules! parse_node { ( [:$head:ident ($(:$head_nodes:expr),*) $(:$tags:ident ($(:$tag_nodes:expr),*))*]; [$(:$nodes:expr),*]; </$tag:ident> $($rest:tt)* ) => ( parse_node!( [$(: $tags ($(:$tag_nodes),*))*]; [$(:$head_nodes,)* :tag(stringify!($head).to_string(), vec![$($nodes),*])]; $($rest)* ) ); ( [$(:$tags:ident ($(:$tag_nodes:expr),*) )*]; [$(:$nodes:expr),*]; <$tag:ident> $($rest:tt)* ) => ( parse_node!( [:$tag ($(:$nodes)*) $(: $tags ($(:$tag_nodes),*) )*]; []; $($rest)* ) ); ( [$(:$tags:ident ($(:$tag_nodes:expr),*) )*]; [$(:$nodes:expr),*]; . $($rest:tt)* ) => ( parse_node!( [$(: $tags ($(:$tag_nodes),*))*]; [$(:$nodes,)* :text(".".to_string())]; $($rest)* ) ); ( [$(:$tags:ident ($(:$tag_nodes:expr),*) )*]; [$(:$nodes:expr),*]; $word:ident $($rest:tt)* ) => ( parse_node!( [$(: $tags ($(:$tag_nodes),*))*]; [$(:$nodes,)* :text(stringify!($word).to_string())]; $($rest)* ) ); ( []; [:$e:expr]; ) => ( $e ); } pub fn
() { let _page = html! ( <html> <head><title>This is the title.</title></head> <body> <p>This is some text</p> </body> </html> ); } enum HTMLFragment { tag(String, Vec<HTMLFragment> ), text(String), }
main
identifier_name
list_devices.rs
extern crate libudev; use std::io; fn main() { let context = libudev::Context::new().unwrap(); list_devices(&context).unwrap(); } fn list_devices(context: &libudev::Context) -> io::Result<()>
println!(" parent: None"); } println!(" [properties]"); for property in device.properties() { println!(" - {:?} {:?}", property.name(), property.value()); } println!(" [attributes]"); for attribute in device.attributes() { println!(" - {:?} {:?}", attribute.name(), attribute.value()); } } Ok(()) }
{ let mut enumerator = try!(libudev::Enumerator::new(&context)); for device in try!(enumerator.scan_devices()) { println!(""); println!("initialized: {:?}", device.is_initialized()); println!(" devnum: {:?}", device.devnum()); println!(" syspath: {:?}", device.syspath()); println!(" devpath: {:?}", device.devpath()); println!(" subsystem: {:?}", device.subsystem()); println!(" sysname: {:?}", device.sysname()); println!(" sysnum: {:?}", device.sysnum()); println!(" devtype: {:?}", device.devtype()); println!(" driver: {:?}", device.driver()); println!(" devnode: {:?}", device.devnode()); if let Some(parent) = device.parent() { println!(" parent: {:?}", parent.syspath()); } else {
identifier_body
list_devices.rs
extern crate libudev; use std::io; fn
() { let context = libudev::Context::new().unwrap(); list_devices(&context).unwrap(); } fn list_devices(context: &libudev::Context) -> io::Result<()> { let mut enumerator = try!(libudev::Enumerator::new(&context)); for device in try!(enumerator.scan_devices()) { println!(""); println!("initialized: {:?}", device.is_initialized()); println!(" devnum: {:?}", device.devnum()); println!(" syspath: {:?}", device.syspath()); println!(" devpath: {:?}", device.devpath()); println!(" subsystem: {:?}", device.subsystem()); println!(" sysname: {:?}", device.sysname()); println!(" sysnum: {:?}", device.sysnum()); println!(" devtype: {:?}", device.devtype()); println!(" driver: {:?}", device.driver()); println!(" devnode: {:?}", device.devnode()); if let Some(parent) = device.parent() { println!(" parent: {:?}", parent.syspath()); } else { println!(" parent: None"); } println!(" [properties]"); for property in device.properties() { println!(" - {:?} {:?}", property.name(), property.value()); } println!(" [attributes]"); for attribute in device.attributes() { println!(" - {:?} {:?}", attribute.name(), attribute.value()); } } Ok(()) }
main
identifier_name
list_devices.rs
extern crate libudev; use std::io; fn main() { let context = libudev::Context::new().unwrap(); list_devices(&context).unwrap(); } fn list_devices(context: &libudev::Context) -> io::Result<()> { let mut enumerator = try!(libudev::Enumerator::new(&context)); for device in try!(enumerator.scan_devices()) { println!(""); println!("initialized: {:?}", device.is_initialized()); println!(" devnum: {:?}", device.devnum()); println!(" syspath: {:?}", device.syspath()); println!(" devpath: {:?}", device.devpath()); println!(" subsystem: {:?}", device.subsystem()); println!(" sysname: {:?}", device.sysname()); println!(" sysnum: {:?}", device.sysnum()); println!(" devtype: {:?}", device.devtype()); println!(" driver: {:?}", device.driver()); println!(" devnode: {:?}", device.devnode()); if let Some(parent) = device.parent() { println!(" parent: {:?}", parent.syspath()); } else
println!(" [properties]"); for property in device.properties() { println!(" - {:?} {:?}", property.name(), property.value()); } println!(" [attributes]"); for attribute in device.attributes() { println!(" - {:?} {:?}", attribute.name(), attribute.value()); } } Ok(()) }
{ println!(" parent: None"); }
conditional_block
list_devices.rs
extern crate libudev; use std::io; fn main() { let context = libudev::Context::new().unwrap(); list_devices(&context).unwrap(); } fn list_devices(context: &libudev::Context) -> io::Result<()> { let mut enumerator = try!(libudev::Enumerator::new(&context)); for device in try!(enumerator.scan_devices()) { println!(""); println!("initialized: {:?}", device.is_initialized()); println!(" devnum: {:?}", device.devnum());
println!(" sysnum: {:?}", device.sysnum()); println!(" devtype: {:?}", device.devtype()); println!(" driver: {:?}", device.driver()); println!(" devnode: {:?}", device.devnode()); if let Some(parent) = device.parent() { println!(" parent: {:?}", parent.syspath()); } else { println!(" parent: None"); } println!(" [properties]"); for property in device.properties() { println!(" - {:?} {:?}", property.name(), property.value()); } println!(" [attributes]"); for attribute in device.attributes() { println!(" - {:?} {:?}", attribute.name(), attribute.value()); } } Ok(()) }
println!(" syspath: {:?}", device.syspath()); println!(" devpath: {:?}", device.devpath()); println!(" subsystem: {:?}", device.subsystem()); println!(" sysname: {:?}", device.sysname());
random_line_split
mod.rs
use std::str::Chars; use std::iter::Peekable; /// The input stream operates on an input string and provides character-wise access. pub struct InputStream<'a> { /// The input string. input: &'a str, /// The position of the next character in the input string.
pos: usize, /// The iterator over the input string. iterator: Peekable<Chars<'a>> } impl<'a> InputStream<'a> { /// Generates a new InputStream instance. pub fn new(input: &'a str) -> InputStream<'a> { InputStream{input: input, pos: 0, iterator: input.chars().peekable()} } /// Returns the character of the next position of the stream without discarding it from the stream. pub fn peek(& mut self) -> Option<char> { self.iterator.peek().map(|x| *x) } /// Returns the character of the next position of the stream and advances the stream position. pub fn next(& mut self) -> Option<char> { match self.iterator.next() { Some(x) => { self.pos += 1; Some(x) }, None => None } } /// Returns true if there are no more characters to read. Returns false otherwise. pub fn eof(& mut self) -> bool { self.iterator.peek().is_none() } /// Returns the current position of the input string. pub fn get_pos(& self) -> usize { self.pos } /// Returns the input string. pub fn get_input(& self) -> & str { & self.input } }
random_line_split
mod.rs
use std::str::Chars; use std::iter::Peekable; /// The input stream operates on an input string and provides character-wise access. pub struct InputStream<'a> { /// The input string. input: &'a str, /// The position of the next character in the input string. pos: usize, /// The iterator over the input string. iterator: Peekable<Chars<'a>> } impl<'a> InputStream<'a> { /// Generates a new InputStream instance. pub fn new(input: &'a str) -> InputStream<'a> { InputStream{input: input, pos: 0, iterator: input.chars().peekable()} } /// Returns the character of the next position of the stream without discarding it from the stream. pub fn peek(& mut self) -> Option<char> { self.iterator.peek().map(|x| *x) } /// Returns the character of the next position of the stream and advances the stream position. pub fn next(& mut self) -> Option<char> { match self.iterator.next() { Some(x) => { self.pos += 1; Some(x) }, None => None } } /// Returns true if there are no more characters to read. Returns false otherwise. pub fn
(& mut self) -> bool { self.iterator.peek().is_none() } /// Returns the current position of the input string. pub fn get_pos(& self) -> usize { self.pos } /// Returns the input string. pub fn get_input(& self) -> & str { & self.input } }
eof
identifier_name
mod.rs
use std::str::Chars; use std::iter::Peekable; /// The input stream operates on an input string and provides character-wise access. pub struct InputStream<'a> { /// The input string. input: &'a str, /// The position of the next character in the input string. pos: usize, /// The iterator over the input string. iterator: Peekable<Chars<'a>> } impl<'a> InputStream<'a> { /// Generates a new InputStream instance. pub fn new(input: &'a str) -> InputStream<'a> { InputStream{input: input, pos: 0, iterator: input.chars().peekable()} } /// Returns the character of the next position of the stream without discarding it from the stream. pub fn peek(& mut self) -> Option<char>
/// Returns the character of the next position of the stream and advances the stream position. pub fn next(& mut self) -> Option<char> { match self.iterator.next() { Some(x) => { self.pos += 1; Some(x) }, None => None } } /// Returns true if there are no more characters to read. Returns false otherwise. pub fn eof(& mut self) -> bool { self.iterator.peek().is_none() } /// Returns the current position of the input string. pub fn get_pos(& self) -> usize { self.pos } /// Returns the input string. pub fn get_input(& self) -> & str { & self.input } }
{ self.iterator.peek().map(|x| *x) }
identifier_body
batch.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::pin::Pin; use std::ptr::null_mut; use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use crossbeam::channel::{ self, RecvError, RecvTimeoutError, SendError, TryRecvError, TrySendError, }; use futures::stream::Stream; use futures::task::{Context, Poll, Waker}; struct State { // If the receiver can't get any messages temporarily in `poll` context, it will put its // current task here. recv_task: AtomicPtr<Waker>, notify_size: usize, // How many messages are sent without notify. pending: AtomicUsize, notifier_registered: AtomicBool, } impl State { fn new(notify_size: usize) -> State { State { // Any pointer that is put into `recv_task` must be a valid and owned // pointer (it must not be dropped). When a pointer is retrieved from // `recv_task`, the user is responsible for its proper destruction. recv_task: AtomicPtr::new(null_mut()), notify_size, pending: AtomicUsize::new(0), notifier_registered: AtomicBool::new(false), } } #[inline] fn try_notify_post_send(&self) { let old_pending = self.pending.fetch_add(1, Ordering::AcqRel); if old_pending >= self.notify_size - 1 { self.notify(); } } #[inline] fn notify(&self) { let t = self.recv_task.swap(null_mut(), Ordering::AcqRel); if!t.is_null() { self.pending.store(0, Ordering::Release); // Safety: see comment on `recv_task`. let t = unsafe { Box::from_raw(t) }; t.wake(); } } /// When the `Receiver` that holds the `State` is running on an `Executor`, /// the `Receiver` calls this to yield from the current `poll` context, /// and puts the current task handle to `recv_task`, so that the `Sender` /// respectively can notify it after sending some messages into the channel. #[inline] fn yield_poll(&self, waker: Waker) -> bool { let t = Box::into_raw(Box::new(waker)); let origin = self.recv_task.swap(t, Ordering::AcqRel); if!origin.is_null() { // Safety: see comment on `recv_task`. unsafe { drop(Box::from_raw(origin)) }; return true; } false } } impl Drop for State { fn drop(&mut self) { let t = self.recv_task.swap(null_mut(), Ordering::AcqRel); if!t.is_null() { // Safety: see comment on `recv_task`. unsafe { drop(Box::from_raw(t)) }; } } } /// `Notifier` is used to notify receiver whenever you want. pub struct Notifier(Arc<State>); impl Notifier { #[inline] pub fn notify(self) { drop(self); } } impl Drop for Notifier { #[inline] fn drop(&mut self) { let notifier_registered = &self.0.notifier_registered; if notifier_registered .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire) .is_err() { unreachable!("notifier_registered must be true"); } self.0.notify(); } } pub struct Sender<T> { sender: Option<channel::Sender<T>>, state: Arc<State>, } impl<T> Clone for Sender<T> { #[inline] fn clone(&self) -> Sender<T> { Sender { sender: self.sender.clone(), state: Arc::clone(&self.state), } } } impl<T> Drop for Sender<T> { #[inline] fn drop(&mut self) { drop(self.sender.take()); self.state.notify(); } } pub struct Receiver<T> { receiver: channel::Receiver<T>, state: Arc<State>, } impl<T> Sender<T> { pub fn is_empty(&self) -> bool { // When there is no sender references, it can't be known whether // it's empty or not. self.sender.as_ref().map_or(false, |s| s.is_empty()) } #[inline] pub fn send(&self, t: T) -> Result<(), SendError<T>> { self.sender.as_ref().unwrap().send(t)?; self.state.try_notify_post_send(); Ok(()) } #[inline] pub fn send_and_notify(&self, t: T) -> Result<(), SendError<T>> { self.sender.as_ref().unwrap().send(t)?; self.state.notify(); Ok(()) } #[inline] pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> { self.sender.as_ref().unwrap().try_send(t)?; self.state.try_notify_post_send(); Ok(()) } #[inline] pub fn get_notifier(&self) -> Option<Notifier> { let notifier_registered = &self.state.notifier_registered; if notifier_registered .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .is_ok() { return Some(Notifier(Arc::clone(&self.state))); } None } } impl<T> Receiver<T> { #[inline] pub fn recv(&self) -> Result<T, RecvError> { self.receiver.recv() } #[inline] pub fn try_recv(&self) -> Result<T, TryRecvError>
#[inline] pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvTimeoutError> { self.receiver.recv_timeout(timeout) } } /// Creates a unbounded channel with a given `notify_size`, which means if there are more pending /// messages in the channel than `notify_size`, the `Sender` will auto notify the `Receiver`. /// /// # Panics /// if `notify_size` equals to 0. #[inline] pub fn unbounded<T>(notify_size: usize) -> (Sender<T>, Receiver<T>) { assert!(notify_size > 0); let state = Arc::new(State::new(notify_size)); let (sender, receiver) = channel::unbounded(); ( Sender { sender: Some(sender), state: state.clone(), }, Receiver { receiver, state }, ) } /// Creates a bounded channel with a given `notify_size`, which means if there are more pending /// messages in the channel than `notify_size`, the `Sender` will auto notify the `Receiver`. /// /// # Panics /// if `notify_size` equals to 0. #[inline] pub fn bounded<T>(cap: usize, notify_size: usize) -> (Sender<T>, Receiver<T>) { assert!(notify_size > 0); let state = Arc::new(State::new(notify_size)); let (sender, receiver) = channel::bounded(cap); ( Sender { sender: Some(sender), state: state.clone(), }, Receiver { receiver, state }, ) } impl<T> Stream for Receiver<T> { type Item = T; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { match self.try_recv() { Ok(m) => Poll::Ready(Some(m)), Err(TryRecvError::Empty) => { if self.state.yield_poll(cx.waker().clone()) { Poll::Pending } else { // For the case that all senders are dropped before the current task is saved. self.poll_next(cx) } } Err(TryRecvError::Disconnected) => Poll::Ready(None), } } } /// A Collector Used in `BatchReceiver`. pub trait BatchCollector<Collection, Elem> { /// If `elem` is collected into `collection` successfully, return `None`. /// Otherwise return `elem` back, and `collection` should be spilled out. fn collect(&mut self, collection: &mut Collection, elem: Elem) -> Option<Elem>; } pub struct VecCollector; impl<E> BatchCollector<Vec<E>, E> for VecCollector { fn collect(&mut self, v: &mut Vec<E>, e: E) -> Option<E> { v.push(e); None } } /// `BatchReceiver` is a `futures::Stream`, which returns a batched type. pub struct BatchReceiver<T, E, I, C> { rx: Receiver<T>, max_batch_size: usize, elem: Option<E>, initializer: I, collector: C, } impl<T, E, I, C> BatchReceiver<T, E, I, C> where T: Unpin, E: Unpin, I: Fn() -> E + Unpin, C: BatchCollector<E, T> + Unpin, { /// Creates a new `BatchReceiver` with given `initializer` and `collector`. `initializer` is /// used to generate a initial value, and `collector` will collect every (at most /// `max_batch_size`) raw items into the batched value. pub fn new(rx: Receiver<T>, max_batch_size: usize, initializer: I, collector: C) -> Self { BatchReceiver { rx, max_batch_size, elem: None, initializer, collector, } } } impl<T, E, I, C> Stream for BatchReceiver<T, E, I, C> where T: Unpin, E: Unpin, I: Fn() -> E + Unpin, C: BatchCollector<E, T> + Unpin, { type Item = E; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let ctx = self.get_mut(); let (mut count, mut received) = (0, None); let finished = loop { match ctx.rx.try_recv() { Ok(m) => { let collection = ctx.elem.get_or_insert_with(&ctx.initializer); if let Some(m) = ctx.collector.collect(collection, m) { received = Some(m); break false; } count += 1; if count >= ctx.max_batch_size { break false; } } Err(TryRecvError::Disconnected) => break true, Err(TryRecvError::Empty) => { if ctx.rx.state.yield_poll(cx.waker().clone()) { break false; } } } }; if ctx.elem.is_none() && finished { return Poll::Ready(None); } else if ctx.elem.is_none() { return Poll::Pending; } let elem = ctx.elem.take(); if let Some(m) = received { let collection = ctx.elem.get_or_insert_with(&ctx.initializer); let _received = ctx.collector.collect(collection, m); debug_assert!(_received.is_none()); } Poll::Ready(elem) } } #[cfg(test)] mod tests { use std::sync::{mpsc, Mutex}; use std::{thread, time}; use futures::future::{self, BoxFuture, FutureExt}; use futures::stream::{self, StreamExt}; use futures::task::{self, ArcWake, Poll}; use tokio::runtime::Builder; use super::*; #[test] fn test_receiver() { let (tx, rx) = unbounded::<u64>(4); let msg_counter = Arc::new(AtomicUsize::new(0)); let msg_counter1 = Arc::clone(&msg_counter); let pool = Builder::new() .threaded_scheduler() .core_threads(1) .build() .unwrap(); let _res = pool.spawn(rx.for_each(move |_| { msg_counter1.fetch_add(1, Ordering::AcqRel); future::ready(()) })); // Wait until the receiver is suspended. loop { thread::sleep(time::Duration::from_millis(10)); if!tx.state.recv_task.load(Ordering::SeqCst).is_null() { break; } } // Send without notify, the receiver can't get batched messages. assert!(tx.send(0).is_ok()); thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 0); // Send with notify. let notifier = tx.get_notifier().unwrap(); assert!(tx.get_notifier().is_none()); notifier.notify(); thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 1); // Auto notify with more sendings. for _ in 0..4 { assert!(tx.send(0).is_ok()); } thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 5); } #[test] fn test_batch_receiver() { let (tx, rx) = unbounded::<u64>(4); let rx = BatchReceiver::new(rx, 8, || Vec::with_capacity(4), VecCollector); let msg_counter = Arc::new(AtomicUsize::new(0)); let msg_counter_spawned = Arc::clone(&msg_counter); let (nty, polled) = mpsc::sync_channel(1); let pool = Builder::new() .threaded_scheduler() .core_threads(1) .build() .unwrap(); let _res = pool.spawn( stream::select( rx, stream::poll_fn(move |_| -> Poll<Option<Vec<u64>>> { nty.send(()).unwrap(); Poll::Ready(None) }), ) .for_each(move |v| { let len = v.len(); assert!(len <= 8); msg_counter_spawned.fetch_add(len, Ordering::AcqRel); future::ready(()) }), ); // Wait until the receiver has been polled in the spawned thread. polled.recv().unwrap(); // Send without notify, the receiver can't get batched messages. assert!(tx.send(0).is_ok()); thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 0); // Send with notify. let notifier = tx.get_notifier().unwrap(); assert!(tx.get_notifier().is_none()); notifier.notify(); thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 1); // Auto notify with more sendings. for _ in 0..16 { assert!(tx.send(0).is_ok()); } thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 17); } #[test] fn test_switch_between_sender_and_receiver() { let (tx, mut rx) = unbounded::<i32>(4); let future = async move { rx.next().await }; let task = Task { future: Arc::new(Mutex::new(Some(future.boxed()))), }; // Receiver has not received any messages, so the future is not be finished // in this tick. task.tick(); assert!(task.future.lock().unwrap().is_some()); // After sender is dropped, the task will be waked and then it tick self // again to advance the progress. drop(tx); assert!(task.future.lock().unwrap().is_none()); } #[derive(Clone)] struct Task { future: Arc<Mutex<Option<BoxFuture<'static, Option<i32>>>>>, } impl Task { fn tick(&self) { let task = Arc::new(self.clone()); let mut future_slot = self.future.lock().unwrap(); if let Some(mut future) = future_slot.take() { let waker = task::waker_ref(&task); let cx = &mut Context::from_waker(&*waker); match future.as_mut().poll(cx) { Poll::Pending => { *future_slot = Some(future); } Poll::Ready(None) => {} _ => unimplemented!(), } } } } impl ArcWake for Task { fn wake_by_ref(arc_self: &Arc<Self>) { arc_self.tick(); } } }
{ self.receiver.try_recv() }
identifier_body
batch.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::pin::Pin; use std::ptr::null_mut; use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use crossbeam::channel::{ self, RecvError, RecvTimeoutError, SendError, TryRecvError, TrySendError, }; use futures::stream::Stream; use futures::task::{Context, Poll, Waker}; struct State { // If the receiver can't get any messages temporarily in `poll` context, it will put its // current task here. recv_task: AtomicPtr<Waker>, notify_size: usize, // How many messages are sent without notify. pending: AtomicUsize, notifier_registered: AtomicBool, } impl State { fn new(notify_size: usize) -> State { State { // Any pointer that is put into `recv_task` must be a valid and owned // pointer (it must not be dropped). When a pointer is retrieved from // `recv_task`, the user is responsible for its proper destruction. recv_task: AtomicPtr::new(null_mut()), notify_size, pending: AtomicUsize::new(0), notifier_registered: AtomicBool::new(false), } } #[inline] fn try_notify_post_send(&self) { let old_pending = self.pending.fetch_add(1, Ordering::AcqRel); if old_pending >= self.notify_size - 1 { self.notify(); } } #[inline] fn notify(&self) { let t = self.recv_task.swap(null_mut(), Ordering::AcqRel); if!t.is_null() { self.pending.store(0, Ordering::Release); // Safety: see comment on `recv_task`. let t = unsafe { Box::from_raw(t) }; t.wake(); } } /// When the `Receiver` that holds the `State` is running on an `Executor`, /// the `Receiver` calls this to yield from the current `poll` context, /// and puts the current task handle to `recv_task`, so that the `Sender` /// respectively can notify it after sending some messages into the channel. #[inline] fn yield_poll(&self, waker: Waker) -> bool { let t = Box::into_raw(Box::new(waker)); let origin = self.recv_task.swap(t, Ordering::AcqRel); if!origin.is_null() { // Safety: see comment on `recv_task`. unsafe { drop(Box::from_raw(origin)) }; return true; } false } } impl Drop for State { fn drop(&mut self) { let t = self.recv_task.swap(null_mut(), Ordering::AcqRel); if!t.is_null() { // Safety: see comment on `recv_task`. unsafe { drop(Box::from_raw(t)) }; } } } /// `Notifier` is used to notify receiver whenever you want. pub struct Notifier(Arc<State>); impl Notifier { #[inline] pub fn notify(self) { drop(self); } } impl Drop for Notifier { #[inline] fn drop(&mut self) { let notifier_registered = &self.0.notifier_registered; if notifier_registered .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire) .is_err() { unreachable!("notifier_registered must be true"); } self.0.notify(); } } pub struct Sender<T> { sender: Option<channel::Sender<T>>, state: Arc<State>, } impl<T> Clone for Sender<T> { #[inline] fn clone(&self) -> Sender<T> { Sender { sender: self.sender.clone(), state: Arc::clone(&self.state), } } } impl<T> Drop for Sender<T> { #[inline] fn drop(&mut self) { drop(self.sender.take()); self.state.notify(); } } pub struct Receiver<T> { receiver: channel::Receiver<T>, state: Arc<State>, } impl<T> Sender<T> { pub fn is_empty(&self) -> bool { // When there is no sender references, it can't be known whether // it's empty or not. self.sender.as_ref().map_or(false, |s| s.is_empty()) } #[inline] pub fn send(&self, t: T) -> Result<(), SendError<T>> { self.sender.as_ref().unwrap().send(t)?; self.state.try_notify_post_send(); Ok(()) } #[inline] pub fn send_and_notify(&self, t: T) -> Result<(), SendError<T>> { self.sender.as_ref().unwrap().send(t)?; self.state.notify(); Ok(()) } #[inline] pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> { self.sender.as_ref().unwrap().try_send(t)?; self.state.try_notify_post_send(); Ok(()) } #[inline] pub fn get_notifier(&self) -> Option<Notifier> { let notifier_registered = &self.state.notifier_registered; if notifier_registered .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .is_ok() { return Some(Notifier(Arc::clone(&self.state))); } None } } impl<T> Receiver<T> { #[inline] pub fn recv(&self) -> Result<T, RecvError> { self.receiver.recv() } #[inline] pub fn try_recv(&self) -> Result<T, TryRecvError> { self.receiver.try_recv() } #[inline] pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvTimeoutError> { self.receiver.recv_timeout(timeout) } } /// Creates a unbounded channel with a given `notify_size`, which means if there are more pending /// messages in the channel than `notify_size`, the `Sender` will auto notify the `Receiver`. /// /// # Panics /// if `notify_size` equals to 0. #[inline] pub fn unbounded<T>(notify_size: usize) -> (Sender<T>, Receiver<T>) { assert!(notify_size > 0); let state = Arc::new(State::new(notify_size)); let (sender, receiver) = channel::unbounded(); ( Sender { sender: Some(sender), state: state.clone(), }, Receiver { receiver, state }, ) } /// Creates a bounded channel with a given `notify_size`, which means if there are more pending /// messages in the channel than `notify_size`, the `Sender` will auto notify the `Receiver`. /// /// # Panics /// if `notify_size` equals to 0. #[inline] pub fn bounded<T>(cap: usize, notify_size: usize) -> (Sender<T>, Receiver<T>) { assert!(notify_size > 0); let state = Arc::new(State::new(notify_size)); let (sender, receiver) = channel::bounded(cap); ( Sender { sender: Some(sender), state: state.clone(), }, Receiver { receiver, state }, ) } impl<T> Stream for Receiver<T> { type Item = T; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { match self.try_recv() { Ok(m) => Poll::Ready(Some(m)), Err(TryRecvError::Empty) => { if self.state.yield_poll(cx.waker().clone()) { Poll::Pending } else { // For the case that all senders are dropped before the current task is saved. self.poll_next(cx) } } Err(TryRecvError::Disconnected) => Poll::Ready(None), } } } /// A Collector Used in `BatchReceiver`. pub trait BatchCollector<Collection, Elem> { /// If `elem` is collected into `collection` successfully, return `None`. /// Otherwise return `elem` back, and `collection` should be spilled out. fn collect(&mut self, collection: &mut Collection, elem: Elem) -> Option<Elem>; } pub struct VecCollector; impl<E> BatchCollector<Vec<E>, E> for VecCollector { fn collect(&mut self, v: &mut Vec<E>, e: E) -> Option<E> { v.push(e); None } } /// `BatchReceiver` is a `futures::Stream`, which returns a batched type. pub struct BatchReceiver<T, E, I, C> { rx: Receiver<T>, max_batch_size: usize, elem: Option<E>, initializer: I, collector: C, } impl<T, E, I, C> BatchReceiver<T, E, I, C>
I: Fn() -> E + Unpin, C: BatchCollector<E, T> + Unpin, { /// Creates a new `BatchReceiver` with given `initializer` and `collector`. `initializer` is /// used to generate a initial value, and `collector` will collect every (at most /// `max_batch_size`) raw items into the batched value. pub fn new(rx: Receiver<T>, max_batch_size: usize, initializer: I, collector: C) -> Self { BatchReceiver { rx, max_batch_size, elem: None, initializer, collector, } } } impl<T, E, I, C> Stream for BatchReceiver<T, E, I, C> where T: Unpin, E: Unpin, I: Fn() -> E + Unpin, C: BatchCollector<E, T> + Unpin, { type Item = E; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let ctx = self.get_mut(); let (mut count, mut received) = (0, None); let finished = loop { match ctx.rx.try_recv() { Ok(m) => { let collection = ctx.elem.get_or_insert_with(&ctx.initializer); if let Some(m) = ctx.collector.collect(collection, m) { received = Some(m); break false; } count += 1; if count >= ctx.max_batch_size { break false; } } Err(TryRecvError::Disconnected) => break true, Err(TryRecvError::Empty) => { if ctx.rx.state.yield_poll(cx.waker().clone()) { break false; } } } }; if ctx.elem.is_none() && finished { return Poll::Ready(None); } else if ctx.elem.is_none() { return Poll::Pending; } let elem = ctx.elem.take(); if let Some(m) = received { let collection = ctx.elem.get_or_insert_with(&ctx.initializer); let _received = ctx.collector.collect(collection, m); debug_assert!(_received.is_none()); } Poll::Ready(elem) } } #[cfg(test)] mod tests { use std::sync::{mpsc, Mutex}; use std::{thread, time}; use futures::future::{self, BoxFuture, FutureExt}; use futures::stream::{self, StreamExt}; use futures::task::{self, ArcWake, Poll}; use tokio::runtime::Builder; use super::*; #[test] fn test_receiver() { let (tx, rx) = unbounded::<u64>(4); let msg_counter = Arc::new(AtomicUsize::new(0)); let msg_counter1 = Arc::clone(&msg_counter); let pool = Builder::new() .threaded_scheduler() .core_threads(1) .build() .unwrap(); let _res = pool.spawn(rx.for_each(move |_| { msg_counter1.fetch_add(1, Ordering::AcqRel); future::ready(()) })); // Wait until the receiver is suspended. loop { thread::sleep(time::Duration::from_millis(10)); if!tx.state.recv_task.load(Ordering::SeqCst).is_null() { break; } } // Send without notify, the receiver can't get batched messages. assert!(tx.send(0).is_ok()); thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 0); // Send with notify. let notifier = tx.get_notifier().unwrap(); assert!(tx.get_notifier().is_none()); notifier.notify(); thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 1); // Auto notify with more sendings. for _ in 0..4 { assert!(tx.send(0).is_ok()); } thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 5); } #[test] fn test_batch_receiver() { let (tx, rx) = unbounded::<u64>(4); let rx = BatchReceiver::new(rx, 8, || Vec::with_capacity(4), VecCollector); let msg_counter = Arc::new(AtomicUsize::new(0)); let msg_counter_spawned = Arc::clone(&msg_counter); let (nty, polled) = mpsc::sync_channel(1); let pool = Builder::new() .threaded_scheduler() .core_threads(1) .build() .unwrap(); let _res = pool.spawn( stream::select( rx, stream::poll_fn(move |_| -> Poll<Option<Vec<u64>>> { nty.send(()).unwrap(); Poll::Ready(None) }), ) .for_each(move |v| { let len = v.len(); assert!(len <= 8); msg_counter_spawned.fetch_add(len, Ordering::AcqRel); future::ready(()) }), ); // Wait until the receiver has been polled in the spawned thread. polled.recv().unwrap(); // Send without notify, the receiver can't get batched messages. assert!(tx.send(0).is_ok()); thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 0); // Send with notify. let notifier = tx.get_notifier().unwrap(); assert!(tx.get_notifier().is_none()); notifier.notify(); thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 1); // Auto notify with more sendings. for _ in 0..16 { assert!(tx.send(0).is_ok()); } thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 17); } #[test] fn test_switch_between_sender_and_receiver() { let (tx, mut rx) = unbounded::<i32>(4); let future = async move { rx.next().await }; let task = Task { future: Arc::new(Mutex::new(Some(future.boxed()))), }; // Receiver has not received any messages, so the future is not be finished // in this tick. task.tick(); assert!(task.future.lock().unwrap().is_some()); // After sender is dropped, the task will be waked and then it tick self // again to advance the progress. drop(tx); assert!(task.future.lock().unwrap().is_none()); } #[derive(Clone)] struct Task { future: Arc<Mutex<Option<BoxFuture<'static, Option<i32>>>>>, } impl Task { fn tick(&self) { let task = Arc::new(self.clone()); let mut future_slot = self.future.lock().unwrap(); if let Some(mut future) = future_slot.take() { let waker = task::waker_ref(&task); let cx = &mut Context::from_waker(&*waker); match future.as_mut().poll(cx) { Poll::Pending => { *future_slot = Some(future); } Poll::Ready(None) => {} _ => unimplemented!(), } } } } impl ArcWake for Task { fn wake_by_ref(arc_self: &Arc<Self>) { arc_self.tick(); } } }
where T: Unpin, E: Unpin,
random_line_split
batch.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::pin::Pin; use std::ptr::null_mut; use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use crossbeam::channel::{ self, RecvError, RecvTimeoutError, SendError, TryRecvError, TrySendError, }; use futures::stream::Stream; use futures::task::{Context, Poll, Waker}; struct State { // If the receiver can't get any messages temporarily in `poll` context, it will put its // current task here. recv_task: AtomicPtr<Waker>, notify_size: usize, // How many messages are sent without notify. pending: AtomicUsize, notifier_registered: AtomicBool, } impl State { fn new(notify_size: usize) -> State { State { // Any pointer that is put into `recv_task` must be a valid and owned // pointer (it must not be dropped). When a pointer is retrieved from // `recv_task`, the user is responsible for its proper destruction. recv_task: AtomicPtr::new(null_mut()), notify_size, pending: AtomicUsize::new(0), notifier_registered: AtomicBool::new(false), } } #[inline] fn try_notify_post_send(&self) { let old_pending = self.pending.fetch_add(1, Ordering::AcqRel); if old_pending >= self.notify_size - 1 { self.notify(); } } #[inline] fn notify(&self) { let t = self.recv_task.swap(null_mut(), Ordering::AcqRel); if!t.is_null() { self.pending.store(0, Ordering::Release); // Safety: see comment on `recv_task`. let t = unsafe { Box::from_raw(t) }; t.wake(); } } /// When the `Receiver` that holds the `State` is running on an `Executor`, /// the `Receiver` calls this to yield from the current `poll` context, /// and puts the current task handle to `recv_task`, so that the `Sender` /// respectively can notify it after sending some messages into the channel. #[inline] fn yield_poll(&self, waker: Waker) -> bool { let t = Box::into_raw(Box::new(waker)); let origin = self.recv_task.swap(t, Ordering::AcqRel); if!origin.is_null() { // Safety: see comment on `recv_task`. unsafe { drop(Box::from_raw(origin)) }; return true; } false } } impl Drop for State { fn drop(&mut self) { let t = self.recv_task.swap(null_mut(), Ordering::AcqRel); if!t.is_null() { // Safety: see comment on `recv_task`. unsafe { drop(Box::from_raw(t)) }; } } } /// `Notifier` is used to notify receiver whenever you want. pub struct Notifier(Arc<State>); impl Notifier { #[inline] pub fn notify(self) { drop(self); } } impl Drop for Notifier { #[inline] fn drop(&mut self) { let notifier_registered = &self.0.notifier_registered; if notifier_registered .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire) .is_err() { unreachable!("notifier_registered must be true"); } self.0.notify(); } } pub struct Sender<T> { sender: Option<channel::Sender<T>>, state: Arc<State>, } impl<T> Clone for Sender<T> { #[inline] fn clone(&self) -> Sender<T> { Sender { sender: self.sender.clone(), state: Arc::clone(&self.state), } } } impl<T> Drop for Sender<T> { #[inline] fn drop(&mut self) { drop(self.sender.take()); self.state.notify(); } } pub struct Receiver<T> { receiver: channel::Receiver<T>, state: Arc<State>, } impl<T> Sender<T> { pub fn is_empty(&self) -> bool { // When there is no sender references, it can't be known whether // it's empty or not. self.sender.as_ref().map_or(false, |s| s.is_empty()) } #[inline] pub fn send(&self, t: T) -> Result<(), SendError<T>> { self.sender.as_ref().unwrap().send(t)?; self.state.try_notify_post_send(); Ok(()) } #[inline] pub fn send_and_notify(&self, t: T) -> Result<(), SendError<T>> { self.sender.as_ref().unwrap().send(t)?; self.state.notify(); Ok(()) } #[inline] pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> { self.sender.as_ref().unwrap().try_send(t)?; self.state.try_notify_post_send(); Ok(()) } #[inline] pub fn get_notifier(&self) -> Option<Notifier> { let notifier_registered = &self.state.notifier_registered; if notifier_registered .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .is_ok() { return Some(Notifier(Arc::clone(&self.state))); } None } } impl<T> Receiver<T> { #[inline] pub fn recv(&self) -> Result<T, RecvError> { self.receiver.recv() } #[inline] pub fn try_recv(&self) -> Result<T, TryRecvError> { self.receiver.try_recv() } #[inline] pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvTimeoutError> { self.receiver.recv_timeout(timeout) } } /// Creates a unbounded channel with a given `notify_size`, which means if there are more pending /// messages in the channel than `notify_size`, the `Sender` will auto notify the `Receiver`. /// /// # Panics /// if `notify_size` equals to 0. #[inline] pub fn unbounded<T>(notify_size: usize) -> (Sender<T>, Receiver<T>) { assert!(notify_size > 0); let state = Arc::new(State::new(notify_size)); let (sender, receiver) = channel::unbounded(); ( Sender { sender: Some(sender), state: state.clone(), }, Receiver { receiver, state }, ) } /// Creates a bounded channel with a given `notify_size`, which means if there are more pending /// messages in the channel than `notify_size`, the `Sender` will auto notify the `Receiver`. /// /// # Panics /// if `notify_size` equals to 0. #[inline] pub fn bounded<T>(cap: usize, notify_size: usize) -> (Sender<T>, Receiver<T>) { assert!(notify_size > 0); let state = Arc::new(State::new(notify_size)); let (sender, receiver) = channel::bounded(cap); ( Sender { sender: Some(sender), state: state.clone(), }, Receiver { receiver, state }, ) } impl<T> Stream for Receiver<T> { type Item = T; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { match self.try_recv() { Ok(m) => Poll::Ready(Some(m)), Err(TryRecvError::Empty) => { if self.state.yield_poll(cx.waker().clone()) { Poll::Pending } else { // For the case that all senders are dropped before the current task is saved. self.poll_next(cx) } } Err(TryRecvError::Disconnected) => Poll::Ready(None), } } } /// A Collector Used in `BatchReceiver`. pub trait BatchCollector<Collection, Elem> { /// If `elem` is collected into `collection` successfully, return `None`. /// Otherwise return `elem` back, and `collection` should be spilled out. fn collect(&mut self, collection: &mut Collection, elem: Elem) -> Option<Elem>; } pub struct VecCollector; impl<E> BatchCollector<Vec<E>, E> for VecCollector { fn collect(&mut self, v: &mut Vec<E>, e: E) -> Option<E> { v.push(e); None } } /// `BatchReceiver` is a `futures::Stream`, which returns a batched type. pub struct BatchReceiver<T, E, I, C> { rx: Receiver<T>, max_batch_size: usize, elem: Option<E>, initializer: I, collector: C, } impl<T, E, I, C> BatchReceiver<T, E, I, C> where T: Unpin, E: Unpin, I: Fn() -> E + Unpin, C: BatchCollector<E, T> + Unpin, { /// Creates a new `BatchReceiver` with given `initializer` and `collector`. `initializer` is /// used to generate a initial value, and `collector` will collect every (at most /// `max_batch_size`) raw items into the batched value. pub fn new(rx: Receiver<T>, max_batch_size: usize, initializer: I, collector: C) -> Self { BatchReceiver { rx, max_batch_size, elem: None, initializer, collector, } } } impl<T, E, I, C> Stream for BatchReceiver<T, E, I, C> where T: Unpin, E: Unpin, I: Fn() -> E + Unpin, C: BatchCollector<E, T> + Unpin, { type Item = E; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let ctx = self.get_mut(); let (mut count, mut received) = (0, None); let finished = loop { match ctx.rx.try_recv() { Ok(m) => { let collection = ctx.elem.get_or_insert_with(&ctx.initializer); if let Some(m) = ctx.collector.collect(collection, m) { received = Some(m); break false; } count += 1; if count >= ctx.max_batch_size { break false; } } Err(TryRecvError::Disconnected) => break true, Err(TryRecvError::Empty) => { if ctx.rx.state.yield_poll(cx.waker().clone()) { break false; } } } }; if ctx.elem.is_none() && finished { return Poll::Ready(None); } else if ctx.elem.is_none() { return Poll::Pending; } let elem = ctx.elem.take(); if let Some(m) = received { let collection = ctx.elem.get_or_insert_with(&ctx.initializer); let _received = ctx.collector.collect(collection, m); debug_assert!(_received.is_none()); } Poll::Ready(elem) } } #[cfg(test)] mod tests { use std::sync::{mpsc, Mutex}; use std::{thread, time}; use futures::future::{self, BoxFuture, FutureExt}; use futures::stream::{self, StreamExt}; use futures::task::{self, ArcWake, Poll}; use tokio::runtime::Builder; use super::*; #[test] fn test_receiver() { let (tx, rx) = unbounded::<u64>(4); let msg_counter = Arc::new(AtomicUsize::new(0)); let msg_counter1 = Arc::clone(&msg_counter); let pool = Builder::new() .threaded_scheduler() .core_threads(1) .build() .unwrap(); let _res = pool.spawn(rx.for_each(move |_| { msg_counter1.fetch_add(1, Ordering::AcqRel); future::ready(()) })); // Wait until the receiver is suspended. loop { thread::sleep(time::Duration::from_millis(10)); if!tx.state.recv_task.load(Ordering::SeqCst).is_null() { break; } } // Send without notify, the receiver can't get batched messages. assert!(tx.send(0).is_ok()); thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 0); // Send with notify. let notifier = tx.get_notifier().unwrap(); assert!(tx.get_notifier().is_none()); notifier.notify(); thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 1); // Auto notify with more sendings. for _ in 0..4 { assert!(tx.send(0).is_ok()); } thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 5); } #[test] fn test_batch_receiver() { let (tx, rx) = unbounded::<u64>(4); let rx = BatchReceiver::new(rx, 8, || Vec::with_capacity(4), VecCollector); let msg_counter = Arc::new(AtomicUsize::new(0)); let msg_counter_spawned = Arc::clone(&msg_counter); let (nty, polled) = mpsc::sync_channel(1); let pool = Builder::new() .threaded_scheduler() .core_threads(1) .build() .unwrap(); let _res = pool.spawn( stream::select( rx, stream::poll_fn(move |_| -> Poll<Option<Vec<u64>>> { nty.send(()).unwrap(); Poll::Ready(None) }), ) .for_each(move |v| { let len = v.len(); assert!(len <= 8); msg_counter_spawned.fetch_add(len, Ordering::AcqRel); future::ready(()) }), ); // Wait until the receiver has been polled in the spawned thread. polled.recv().unwrap(); // Send without notify, the receiver can't get batched messages. assert!(tx.send(0).is_ok()); thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 0); // Send with notify. let notifier = tx.get_notifier().unwrap(); assert!(tx.get_notifier().is_none()); notifier.notify(); thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 1); // Auto notify with more sendings. for _ in 0..16 { assert!(tx.send(0).is_ok()); } thread::sleep(time::Duration::from_millis(10)); assert_eq!(msg_counter.load(Ordering::Acquire), 17); } #[test] fn test_switch_between_sender_and_receiver() { let (tx, mut rx) = unbounded::<i32>(4); let future = async move { rx.next().await }; let task = Task { future: Arc::new(Mutex::new(Some(future.boxed()))), }; // Receiver has not received any messages, so the future is not be finished // in this tick. task.tick(); assert!(task.future.lock().unwrap().is_some()); // After sender is dropped, the task will be waked and then it tick self // again to advance the progress. drop(tx); assert!(task.future.lock().unwrap().is_none()); } #[derive(Clone)] struct Task { future: Arc<Mutex<Option<BoxFuture<'static, Option<i32>>>>>, } impl Task { fn
(&self) { let task = Arc::new(self.clone()); let mut future_slot = self.future.lock().unwrap(); if let Some(mut future) = future_slot.take() { let waker = task::waker_ref(&task); let cx = &mut Context::from_waker(&*waker); match future.as_mut().poll(cx) { Poll::Pending => { *future_slot = Some(future); } Poll::Ready(None) => {} _ => unimplemented!(), } } } } impl ArcWake for Task { fn wake_by_ref(arc_self: &Arc<Self>) { arc_self.tick(); } } }
tick
identifier_name
alignment-gep-tup-like-1.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 pair<A,B> { a: A, b: B } trait Invokable<A> { fn f(&self) -> (A, u16); } struct Invoker<A> { a: A, b: u16, } impl<A:Clone> Invokable<A> for Invoker<A> { fn
(&self) -> (A, u16) { (self.a.clone(), self.b) } } fn f<A:Clone +'static>(a: A, b: u16) -> Box<Invokable<A>+'static> { box Invoker { a: a, b: b, } as (Box<Invokable<A>+'static>) } pub fn main() { let (a, b) = f(22_u64, 44u16).f(); println!("a={} b={}", a, b); assert_eq!(a, 22u64); assert_eq!(b, 44u16); }
f
identifier_name
alignment-gep-tup-like-1.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 pair<A,B> { a: A, b: B } trait Invokable<A> { fn f(&self) -> (A, u16); } struct Invoker<A> { a: A, b: u16, } impl<A:Clone> Invokable<A> for Invoker<A> { fn f(&self) -> (A, u16) { (self.a.clone(), self.b) } } fn f<A:Clone +'static>(a: A, b: u16) -> Box<Invokable<A>+'static> { box Invoker { a: a, b: b, } as (Box<Invokable<A>+'static>) } pub fn main()
{ let (a, b) = f(22_u64, 44u16).f(); println!("a={} b={}", a, b); assert_eq!(a, 22u64); assert_eq!(b, 44u16); }
identifier_body
alignment-gep-tup-like-1.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. //
// except according to those terms. struct pair<A,B> { a: A, b: B } trait Invokable<A> { fn f(&self) -> (A, u16); } struct Invoker<A> { a: A, b: u16, } impl<A:Clone> Invokable<A> for Invoker<A> { fn f(&self) -> (A, u16) { (self.a.clone(), self.b) } } fn f<A:Clone +'static>(a: A, b: u16) -> Box<Invokable<A>+'static> { box Invoker { a: a, b: b, } as (Box<Invokable<A>+'static>) } pub fn main() { let (a, b) = f(22_u64, 44u16).f(); println!("a={} b={}", a, b); assert_eq!(a, 22u64); assert_eq!(b, 44u16); }
// 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
random_line_split
generator.rs
#![feature(generators, generator_trait)] use std::ops::{Generator, GeneratorState}; use std::pin::Pin; // The following implementation of a function called from a `yield` statement // (apparently requiring the Result and the `String` type or constructor) // creates conditions where the `generator::StateTransform` MIR transform will // drop all `Counter` `Coverage` statements from a MIR. `simplify.rs` has logic // to handle this condition, and still report dead block coverage. fn get_u32(val: bool) -> Result<u32, String> { if val { Ok(1) } else { Err(String::from("some error")) } } fn main()
{ let is_true = std::env::args().len() == 1; let mut generator = || { yield get_u32(is_true); return "foo"; }; match Pin::new(&mut generator).resume(()) { GeneratorState::Yielded(Ok(1)) => {} _ => panic!("unexpected return from resume"), } match Pin::new(&mut generator).resume(()) { GeneratorState::Complete("foo") => {} _ => panic!("unexpected return from resume"), } }
identifier_body
generator.rs
#![feature(generators, generator_trait)] use std::ops::{Generator, GeneratorState}; use std::pin::Pin; // The following implementation of a function called from a `yield` statement // (apparently requiring the Result and the `String` type or constructor) // creates conditions where the `generator::StateTransform` MIR transform will // drop all `Counter` `Coverage` statements from a MIR. `simplify.rs` has logic // to handle this condition, and still report dead block coverage. fn get_u32(val: bool) -> Result<u32, String> { if val { Ok(1) } else { Err(String::from("some error")) } } fn
() { let is_true = std::env::args().len() == 1; let mut generator = || { yield get_u32(is_true); return "foo"; }; match Pin::new(&mut generator).resume(()) { GeneratorState::Yielded(Ok(1)) => {} _ => panic!("unexpected return from resume"), } match Pin::new(&mut generator).resume(()) { GeneratorState::Complete("foo") => {} _ => panic!("unexpected return from resume"), } }
main
identifier_name
generator.rs
#![feature(generators, generator_trait)] use std::ops::{Generator, GeneratorState}; use std::pin::Pin;
// creates conditions where the `generator::StateTransform` MIR transform will // drop all `Counter` `Coverage` statements from a MIR. `simplify.rs` has logic // to handle this condition, and still report dead block coverage. fn get_u32(val: bool) -> Result<u32, String> { if val { Ok(1) } else { Err(String::from("some error")) } } fn main() { let is_true = std::env::args().len() == 1; let mut generator = || { yield get_u32(is_true); return "foo"; }; match Pin::new(&mut generator).resume(()) { GeneratorState::Yielded(Ok(1)) => {} _ => panic!("unexpected return from resume"), } match Pin::new(&mut generator).resume(()) { GeneratorState::Complete("foo") => {} _ => panic!("unexpected return from resume"), } }
// The following implementation of a function called from a `yield` statement // (apparently requiring the Result and the `String` type or constructor)
random_line_split
_6_2_coordinate_systems_depth.rs
#![allow(non_upper_case_globals)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::sync::mpsc::Receiver; use std::ptr; use std::mem; use std::os::raw::c_void; use std::path::Path; use std::ffi::CStr; use shader::Shader; use image; use image::GenericImage; use cgmath::{Matrix4, vec3, Deg, Rad, perspective}; use cgmath::prelude::*; // settings const SCR_WIDTH: u32 = 800; const SCR_HEIGHT: u32 = 600; #[allow(non_snake_case)] pub fn main_1_6_2()
gl::load_with(|symbol| window.get_proc_address(symbol) as *const _); let (ourShader, VBO, VAO, texture1, texture2) = unsafe { // configure global opengl state // ----------------------------- gl::Enable(gl::DEPTH_TEST); // build and compile our shader program // ------------------------------------ let ourShader = Shader::new( "src/_1_getting_started/shaders/6.2.coordinate_systems.vs", "src/_1_getting_started/shaders/6.2.coordinate_systems.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ let vertices: [f32; 180] = [ -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, -0.5, 1.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, 0.5, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0 ]; let (mut VBO, mut VAO) = (0, 0); gl::GenVertexArrays(1, &mut VAO); gl::GenBuffers(1, &mut VBO); gl::BindVertexArray(VAO); gl::BindBuffer(gl::ARRAY_BUFFER, VBO); gl::BufferData(gl::ARRAY_BUFFER, (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &vertices[0] as *const f32 as *const c_void, gl::STATIC_DRAW); let stride = 5 * mem::size_of::<GLfloat>() as GLsizei; // position attribute gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null()); gl::EnableVertexAttribArray(0); // texture coord attribute gl::VertexAttribPointer(1, 2, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void); gl::EnableVertexAttribArray(1); // load and create a texture // ------------------------- let (mut texture1, mut texture2) = (0, 0); // texture 1 // --------- gl::GenTextures(1, &mut texture1); gl::BindTexture(gl::TEXTURE_2D, texture1); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/container.jpg")).expect("Failed to load texture"); let data = img.raw_pixels(); gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGB, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // texture 2 // --------- gl::GenTextures(1, &mut texture2); gl::BindTexture(gl::TEXTURE_2D, texture2); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/awesomeface.png")).expect("Failed to load texture"); let img = img.flipv(); // flip loaded texture on the y-axis. let data = img.raw_pixels(); // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGBA, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.useProgram(); ourShader.setInt(c_str!("texture1"), 0); ourShader.setInt(c_str!("texture2"), 1); (ourShader, VBO, VAO, texture1, texture2) }; // render loop // ----------- while!window.should_close() { // events // ----- process_events(&mut window, &events); // render // ------ unsafe { gl::ClearColor(0.2, 0.3, 0.3, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); // bind textures on corresponding texture units gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, texture1); gl::ActiveTexture(gl::TEXTURE1); gl::BindTexture(gl::TEXTURE_2D, texture2); // activate shader ourShader.useProgram(); // create transformations // NOTE: cgmath requires axis vectors to be normalized! let model: Matrix4<f32> = Matrix4::from_axis_angle(vec3(0.5, 1.0, 0.0).normalize(), Rad(glfw.get_time() as f32)); let view: Matrix4<f32> = Matrix4::from_translation(vec3(0., 0., -3.)); let projection: Matrix4<f32> = perspective(Deg(45.0), SCR_WIDTH as f32 / SCR_HEIGHT as f32, 0.1, 100.0); // retrieve the matrix uniform locations let modelLoc = gl::GetUniformLocation(ourShader.ID, c_str!("model").as_ptr()); let viewLoc = gl::GetUniformLocation(ourShader.ID, c_str!("view").as_ptr()); // pass them to the shaders (3 different ways) gl::UniformMatrix4fv(modelLoc, 1, gl::FALSE, model.as_ptr()); gl::UniformMatrix4fv(viewLoc, 1, gl::FALSE, &view[0][0]); // note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once. ourShader.setMat4(c_str!("projection"), &projection); // render container gl::BindVertexArray(VAO); gl::DrawArrays(gl::TRIANGLES, 0, 36); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- window.swap_buffers(); glfw.poll_events(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ unsafe { gl::DeleteVertexArrays(1, &VAO); gl::DeleteBuffers(1, &VBO); } } fn process_events(window: &mut glfw::Window, events: &Receiver<(f64, glfw::WindowEvent)>) { for (_, event) in glfw::flush_messages(events) { match event { glfw::WindowEvent::FramebufferSize(width, height) => { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. unsafe { gl::Viewport(0, 0, width, height) } } glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => window.set_should_close(true), _ => {} } } }
{ // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos")] glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // glfw window creation // -------------------- let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window"); window.make_current(); window.set_key_polling(true); window.set_framebuffer_size_polling(true); // gl: load all OpenGL function pointers // ---------------------------------------
identifier_body
_6_2_coordinate_systems_depth.rs
#![allow(non_upper_case_globals)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::sync::mpsc::Receiver; use std::ptr; use std::mem; use std::os::raw::c_void; use std::path::Path; use std::ffi::CStr; use shader::Shader; use image; use image::GenericImage; use cgmath::{Matrix4, vec3, Deg, Rad, perspective}; use cgmath::prelude::*; // settings const SCR_WIDTH: u32 = 800; const SCR_HEIGHT: u32 = 600; #[allow(non_snake_case)] pub fn main_1_6_2() { // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos")] glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // glfw window creation // -------------------- let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window"); window.make_current(); window.set_key_polling(true); window.set_framebuffer_size_polling(true); // gl: load all OpenGL function pointers // --------------------------------------- gl::load_with(|symbol| window.get_proc_address(symbol) as *const _); let (ourShader, VBO, VAO, texture1, texture2) = unsafe { // configure global opengl state // ----------------------------- gl::Enable(gl::DEPTH_TEST); // build and compile our shader program // ------------------------------------ let ourShader = Shader::new( "src/_1_getting_started/shaders/6.2.coordinate_systems.vs", "src/_1_getting_started/shaders/6.2.coordinate_systems.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ let vertices: [f32; 180] = [ -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, -0.5, 1.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, 0.5, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0 ]; let (mut VBO, mut VAO) = (0, 0); gl::GenVertexArrays(1, &mut VAO); gl::GenBuffers(1, &mut VBO); gl::BindVertexArray(VAO); gl::BindBuffer(gl::ARRAY_BUFFER, VBO); gl::BufferData(gl::ARRAY_BUFFER, (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &vertices[0] as *const f32 as *const c_void, gl::STATIC_DRAW); let stride = 5 * mem::size_of::<GLfloat>() as GLsizei; // position attribute gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null()); gl::EnableVertexAttribArray(0); // texture coord attribute gl::VertexAttribPointer(1, 2, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void); gl::EnableVertexAttribArray(1); // load and create a texture // ------------------------- let (mut texture1, mut texture2) = (0, 0); // texture 1 // --------- gl::GenTextures(1, &mut texture1); gl::BindTexture(gl::TEXTURE_2D, texture1); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/container.jpg")).expect("Failed to load texture"); let data = img.raw_pixels(); gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGB, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // texture 2 // --------- gl::GenTextures(1, &mut texture2); gl::BindTexture(gl::TEXTURE_2D, texture2); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/awesomeface.png")).expect("Failed to load texture"); let img = img.flipv(); // flip loaded texture on the y-axis. let data = img.raw_pixels(); // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGBA, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.useProgram(); ourShader.setInt(c_str!("texture1"), 0); ourShader.setInt(c_str!("texture2"), 1); (ourShader, VBO, VAO, texture1, texture2) }; // render loop // ----------- while!window.should_close() { // events // ----- process_events(&mut window, &events); // render // ------ unsafe { gl::ClearColor(0.2, 0.3, 0.3, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); // bind textures on corresponding texture units gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, texture1); gl::ActiveTexture(gl::TEXTURE1); gl::BindTexture(gl::TEXTURE_2D, texture2); // activate shader ourShader.useProgram(); // create transformations // NOTE: cgmath requires axis vectors to be normalized! let model: Matrix4<f32> = Matrix4::from_axis_angle(vec3(0.5, 1.0, 0.0).normalize(), Rad(glfw.get_time() as f32)); let view: Matrix4<f32> = Matrix4::from_translation(vec3(0., 0., -3.)); let projection: Matrix4<f32> = perspective(Deg(45.0), SCR_WIDTH as f32 / SCR_HEIGHT as f32, 0.1, 100.0); // retrieve the matrix uniform locations let modelLoc = gl::GetUniformLocation(ourShader.ID, c_str!("model").as_ptr()); let viewLoc = gl::GetUniformLocation(ourShader.ID, c_str!("view").as_ptr()); // pass them to the shaders (3 different ways) gl::UniformMatrix4fv(modelLoc, 1, gl::FALSE, model.as_ptr()); gl::UniformMatrix4fv(viewLoc, 1, gl::FALSE, &view[0][0]); // note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once. ourShader.setMat4(c_str!("projection"), &projection); // render container gl::BindVertexArray(VAO); gl::DrawArrays(gl::TRIANGLES, 0, 36); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- window.swap_buffers(); glfw.poll_events(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ unsafe { gl::DeleteVertexArrays(1, &VAO); gl::DeleteBuffers(1, &VBO); } } fn process_events(window: &mut glfw::Window, events: &Receiver<(f64, glfw::WindowEvent)>) { for (_, event) in glfw::flush_messages(events) { match event { glfw::WindowEvent::FramebufferSize(width, height) => { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. unsafe { gl::Viewport(0, 0, width, height) } } glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => window.set_should_close(true), _ =>
} } }
{}
conditional_block
_6_2_coordinate_systems_depth.rs
#![allow(non_upper_case_globals)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl;
use std::sync::mpsc::Receiver; use std::ptr; use std::mem; use std::os::raw::c_void; use std::path::Path; use std::ffi::CStr; use shader::Shader; use image; use image::GenericImage; use cgmath::{Matrix4, vec3, Deg, Rad, perspective}; use cgmath::prelude::*; // settings const SCR_WIDTH: u32 = 800; const SCR_HEIGHT: u32 = 600; #[allow(non_snake_case)] pub fn main_1_6_2() { // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos")] glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // glfw window creation // -------------------- let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window"); window.make_current(); window.set_key_polling(true); window.set_framebuffer_size_polling(true); // gl: load all OpenGL function pointers // --------------------------------------- gl::load_with(|symbol| window.get_proc_address(symbol) as *const _); let (ourShader, VBO, VAO, texture1, texture2) = unsafe { // configure global opengl state // ----------------------------- gl::Enable(gl::DEPTH_TEST); // build and compile our shader program // ------------------------------------ let ourShader = Shader::new( "src/_1_getting_started/shaders/6.2.coordinate_systems.vs", "src/_1_getting_started/shaders/6.2.coordinate_systems.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ let vertices: [f32; 180] = [ -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, -0.5, 1.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, 0.5, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0 ]; let (mut VBO, mut VAO) = (0, 0); gl::GenVertexArrays(1, &mut VAO); gl::GenBuffers(1, &mut VBO); gl::BindVertexArray(VAO); gl::BindBuffer(gl::ARRAY_BUFFER, VBO); gl::BufferData(gl::ARRAY_BUFFER, (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &vertices[0] as *const f32 as *const c_void, gl::STATIC_DRAW); let stride = 5 * mem::size_of::<GLfloat>() as GLsizei; // position attribute gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null()); gl::EnableVertexAttribArray(0); // texture coord attribute gl::VertexAttribPointer(1, 2, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void); gl::EnableVertexAttribArray(1); // load and create a texture // ------------------------- let (mut texture1, mut texture2) = (0, 0); // texture 1 // --------- gl::GenTextures(1, &mut texture1); gl::BindTexture(gl::TEXTURE_2D, texture1); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/container.jpg")).expect("Failed to load texture"); let data = img.raw_pixels(); gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGB, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // texture 2 // --------- gl::GenTextures(1, &mut texture2); gl::BindTexture(gl::TEXTURE_2D, texture2); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/awesomeface.png")).expect("Failed to load texture"); let img = img.flipv(); // flip loaded texture on the y-axis. let data = img.raw_pixels(); // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGBA, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.useProgram(); ourShader.setInt(c_str!("texture1"), 0); ourShader.setInt(c_str!("texture2"), 1); (ourShader, VBO, VAO, texture1, texture2) }; // render loop // ----------- while!window.should_close() { // events // ----- process_events(&mut window, &events); // render // ------ unsafe { gl::ClearColor(0.2, 0.3, 0.3, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); // bind textures on corresponding texture units gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, texture1); gl::ActiveTexture(gl::TEXTURE1); gl::BindTexture(gl::TEXTURE_2D, texture2); // activate shader ourShader.useProgram(); // create transformations // NOTE: cgmath requires axis vectors to be normalized! let model: Matrix4<f32> = Matrix4::from_axis_angle(vec3(0.5, 1.0, 0.0).normalize(), Rad(glfw.get_time() as f32)); let view: Matrix4<f32> = Matrix4::from_translation(vec3(0., 0., -3.)); let projection: Matrix4<f32> = perspective(Deg(45.0), SCR_WIDTH as f32 / SCR_HEIGHT as f32, 0.1, 100.0); // retrieve the matrix uniform locations let modelLoc = gl::GetUniformLocation(ourShader.ID, c_str!("model").as_ptr()); let viewLoc = gl::GetUniformLocation(ourShader.ID, c_str!("view").as_ptr()); // pass them to the shaders (3 different ways) gl::UniformMatrix4fv(modelLoc, 1, gl::FALSE, model.as_ptr()); gl::UniformMatrix4fv(viewLoc, 1, gl::FALSE, &view[0][0]); // note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once. ourShader.setMat4(c_str!("projection"), &projection); // render container gl::BindVertexArray(VAO); gl::DrawArrays(gl::TRIANGLES, 0, 36); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- window.swap_buffers(); glfw.poll_events(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ unsafe { gl::DeleteVertexArrays(1, &VAO); gl::DeleteBuffers(1, &VBO); } } fn process_events(window: &mut glfw::Window, events: &Receiver<(f64, glfw::WindowEvent)>) { for (_, event) in glfw::flush_messages(events) { match event { glfw::WindowEvent::FramebufferSize(width, height) => { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. unsafe { gl::Viewport(0, 0, width, height) } } glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => window.set_should_close(true), _ => {} } } }
use self::gl::types::*;
random_line_split
_6_2_coordinate_systems_depth.rs
#![allow(non_upper_case_globals)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::sync::mpsc::Receiver; use std::ptr; use std::mem; use std::os::raw::c_void; use std::path::Path; use std::ffi::CStr; use shader::Shader; use image; use image::GenericImage; use cgmath::{Matrix4, vec3, Deg, Rad, perspective}; use cgmath::prelude::*; // settings const SCR_WIDTH: u32 = 800; const SCR_HEIGHT: u32 = 600; #[allow(non_snake_case)] pub fn
() { // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos")] glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // glfw window creation // -------------------- let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window"); window.make_current(); window.set_key_polling(true); window.set_framebuffer_size_polling(true); // gl: load all OpenGL function pointers // --------------------------------------- gl::load_with(|symbol| window.get_proc_address(symbol) as *const _); let (ourShader, VBO, VAO, texture1, texture2) = unsafe { // configure global opengl state // ----------------------------- gl::Enable(gl::DEPTH_TEST); // build and compile our shader program // ------------------------------------ let ourShader = Shader::new( "src/_1_getting_started/shaders/6.2.coordinate_systems.vs", "src/_1_getting_started/shaders/6.2.coordinate_systems.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ let vertices: [f32; 180] = [ -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, -0.5, 1.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, 0.5, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0 ]; let (mut VBO, mut VAO) = (0, 0); gl::GenVertexArrays(1, &mut VAO); gl::GenBuffers(1, &mut VBO); gl::BindVertexArray(VAO); gl::BindBuffer(gl::ARRAY_BUFFER, VBO); gl::BufferData(gl::ARRAY_BUFFER, (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &vertices[0] as *const f32 as *const c_void, gl::STATIC_DRAW); let stride = 5 * mem::size_of::<GLfloat>() as GLsizei; // position attribute gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null()); gl::EnableVertexAttribArray(0); // texture coord attribute gl::VertexAttribPointer(1, 2, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void); gl::EnableVertexAttribArray(1); // load and create a texture // ------------------------- let (mut texture1, mut texture2) = (0, 0); // texture 1 // --------- gl::GenTextures(1, &mut texture1); gl::BindTexture(gl::TEXTURE_2D, texture1); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/container.jpg")).expect("Failed to load texture"); let data = img.raw_pixels(); gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGB, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // texture 2 // --------- gl::GenTextures(1, &mut texture2); gl::BindTexture(gl::TEXTURE_2D, texture2); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/awesomeface.png")).expect("Failed to load texture"); let img = img.flipv(); // flip loaded texture on the y-axis. let data = img.raw_pixels(); // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGBA, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.useProgram(); ourShader.setInt(c_str!("texture1"), 0); ourShader.setInt(c_str!("texture2"), 1); (ourShader, VBO, VAO, texture1, texture2) }; // render loop // ----------- while!window.should_close() { // events // ----- process_events(&mut window, &events); // render // ------ unsafe { gl::ClearColor(0.2, 0.3, 0.3, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); // bind textures on corresponding texture units gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, texture1); gl::ActiveTexture(gl::TEXTURE1); gl::BindTexture(gl::TEXTURE_2D, texture2); // activate shader ourShader.useProgram(); // create transformations // NOTE: cgmath requires axis vectors to be normalized! let model: Matrix4<f32> = Matrix4::from_axis_angle(vec3(0.5, 1.0, 0.0).normalize(), Rad(glfw.get_time() as f32)); let view: Matrix4<f32> = Matrix4::from_translation(vec3(0., 0., -3.)); let projection: Matrix4<f32> = perspective(Deg(45.0), SCR_WIDTH as f32 / SCR_HEIGHT as f32, 0.1, 100.0); // retrieve the matrix uniform locations let modelLoc = gl::GetUniformLocation(ourShader.ID, c_str!("model").as_ptr()); let viewLoc = gl::GetUniformLocation(ourShader.ID, c_str!("view").as_ptr()); // pass them to the shaders (3 different ways) gl::UniformMatrix4fv(modelLoc, 1, gl::FALSE, model.as_ptr()); gl::UniformMatrix4fv(viewLoc, 1, gl::FALSE, &view[0][0]); // note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once. ourShader.setMat4(c_str!("projection"), &projection); // render container gl::BindVertexArray(VAO); gl::DrawArrays(gl::TRIANGLES, 0, 36); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- window.swap_buffers(); glfw.poll_events(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ unsafe { gl::DeleteVertexArrays(1, &VAO); gl::DeleteBuffers(1, &VBO); } } fn process_events(window: &mut glfw::Window, events: &Receiver<(f64, glfw::WindowEvent)>) { for (_, event) in glfw::flush_messages(events) { match event { glfw::WindowEvent::FramebufferSize(width, height) => { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. unsafe { gl::Viewport(0, 0, width, height) } } glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => window.set_should_close(true), _ => {} } } }
main_1_6_2
identifier_name
turtle.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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 super::FractalAnimation; use fractal_lib::geometry::{Point, Vector, ViewAreaTransformer}; use fractal_lib::turtle::{Turtle, TurtleCollectToNextForwardIterator, TurtleProgram, TurtleState}; use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement}; /// Constructs a ViewAreaTransformer for converting between a canvas pixel-coordinate and the /// coordinate system used by Turtle curves. /// /// The Turtle curves expect a view area that has positive values going up and to the right, and /// that center on both (0.0, 0.0) and (1.0, 0.0). to achieve this, the we need a view area from /// -0.5 to 1.5 on the X axis, and -0.75 and 0.75 on the Y axis. fn turtle_vat(canvas: &HtmlCanvasElement) -> ViewAreaTransformer { let screen_width = f64::from(canvas.width()); let screen_height = f64::from(canvas.height()); ViewAreaTransformer::new( [screen_width, screen_height], Point { x: -0.5, y: -0.75 }, Point { x: 1.5, y: 0.75 }, ) } /// A turtle that can draw to an HTML Canvas. struct CanvasTurtle { state: TurtleState, pub ctx: CanvasRenderingContext2d, } impl CanvasTurtle { pub fn new(state: TurtleState, ctx: CanvasRenderingContext2d) -> CanvasTurtle { CanvasTurtle { state, ctx } } } impl Turtle for CanvasTurtle { fn forward(&mut self, distance: f64) { let old_pos = self.state.position; let new_pos = self.state.position.point_at(Vector { direction: self.state.angle, magnitude: distance, }); if self.state.down { let turtle_vat = turtle_vat(&self.ctx.canvas().unwrap()); let old_coords = turtle_vat.map_point_to_pixel(old_pos); let new_coords = turtle_vat.map_point_to_pixel(new_pos); // log::debug!("Line to {}, {}", new_pos.x, new_pos.y); // log::debug!( // "old coords", // old_coords[0], // old_coords[1], // ); // log::debug!( // "new coords", // &new_coords[0], // &new_coords[1], // ); self.ctx.set_line_width(1.0f64); self.ctx.begin_path(); self.ctx.move_to(old_coords[0], old_coords[1]); self.ctx.line_to(new_coords[0], new_coords[1]); self.ctx.stroke(); } self.state.position = new_pos; } fn set_pos(&mut self, new_pos: Point) { self.state.position = new_pos; } fn set_rad(&mut self, new_rad: f64) { self.state.angle = new_rad; } fn turn_rad(&mut self, radians: f64) { use std::f64::consts::PI; self.state.angle = (self.state.angle + radians) % (2.0 * PI); } fn down(&mut self) { self.state.down = true; } fn up(&mut self) { self.state.down = false; } } /// Represents everything needed to render a turtle a piece at a time to a canvas. /// /// It holds onto a turtle program, which is then used to eventually initialize an iterator over
} impl TurtleAnimation { /// Build a TurtleAnimation from a canvas element and a boxed turtle program. /// /// The TurtleProgram is copied and boxed (via its `turtle_program_iter`) to to avoid /// TurtleAnimation being generic. pub fn new(ctx: CanvasRenderingContext2d, program: &dyn TurtleProgram) -> TurtleAnimation { let mut turtle = CanvasTurtle::new(TurtleState::new(), ctx); let init_turtle_steps = program.init_turtle(); for action in init_turtle_steps { turtle.perform(action) } let iter = program.turtle_program_iter().collect_to_next_forward(); TurtleAnimation { turtle, iter } } } impl FractalAnimation for TurtleAnimation { /// Returns true if there are more moves to make, and false if it can no longer perform a move. fn draw_one_frame(&mut self) -> bool { if let Some(one_move) = self.iter.next() { log::debug!("Rendering one move"); for action in one_move { self.turtle.perform(action); } true } else { log::debug!("No more moves"); self.turtle.up(); false } } /// Translates a pixel-coordinate on the Canvas into the coordinate system used by the turtle /// curves. /// /// See turtle::turtle_vat for more information on the coordinate system for turtle curves. fn pixel_to_coordinate(&self, x: f64, y: f64) -> [f64; 2] { let canvas = self.turtle.ctx.canvas().unwrap(); let pos_point = turtle_vat(&canvas).map_pixel_to_point([x, y]); pos_point.into() } fn zoom(&mut self, _x1: f64, _y1: f64, _x2: f64, _y2: f64) -> bool { false } }
/// that program. pub struct TurtleAnimation { turtle: CanvasTurtle, iter: TurtleCollectToNextForwardIterator,
random_line_split
turtle.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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 super::FractalAnimation; use fractal_lib::geometry::{Point, Vector, ViewAreaTransformer}; use fractal_lib::turtle::{Turtle, TurtleCollectToNextForwardIterator, TurtleProgram, TurtleState}; use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement}; /// Constructs a ViewAreaTransformer for converting between a canvas pixel-coordinate and the /// coordinate system used by Turtle curves. /// /// The Turtle curves expect a view area that has positive values going up and to the right, and /// that center on both (0.0, 0.0) and (1.0, 0.0). to achieve this, the we need a view area from /// -0.5 to 1.5 on the X axis, and -0.75 and 0.75 on the Y axis. fn turtle_vat(canvas: &HtmlCanvasElement) -> ViewAreaTransformer { let screen_width = f64::from(canvas.width()); let screen_height = f64::from(canvas.height()); ViewAreaTransformer::new( [screen_width, screen_height], Point { x: -0.5, y: -0.75 }, Point { x: 1.5, y: 0.75 }, ) } /// A turtle that can draw to an HTML Canvas. struct CanvasTurtle { state: TurtleState, pub ctx: CanvasRenderingContext2d, } impl CanvasTurtle { pub fn new(state: TurtleState, ctx: CanvasRenderingContext2d) -> CanvasTurtle { CanvasTurtle { state, ctx } } } impl Turtle for CanvasTurtle { fn forward(&mut self, distance: f64) { let old_pos = self.state.position; let new_pos = self.state.position.point_at(Vector { direction: self.state.angle, magnitude: distance, }); if self.state.down { let turtle_vat = turtle_vat(&self.ctx.canvas().unwrap()); let old_coords = turtle_vat.map_point_to_pixel(old_pos); let new_coords = turtle_vat.map_point_to_pixel(new_pos); // log::debug!("Line to {}, {}", new_pos.x, new_pos.y); // log::debug!( // "old coords", // old_coords[0], // old_coords[1], // ); // log::debug!( // "new coords", // &new_coords[0], // &new_coords[1], // ); self.ctx.set_line_width(1.0f64); self.ctx.begin_path(); self.ctx.move_to(old_coords[0], old_coords[1]); self.ctx.line_to(new_coords[0], new_coords[1]); self.ctx.stroke(); } self.state.position = new_pos; } fn set_pos(&mut self, new_pos: Point) { self.state.position = new_pos; } fn set_rad(&mut self, new_rad: f64) { self.state.angle = new_rad; } fn turn_rad(&mut self, radians: f64) { use std::f64::consts::PI; self.state.angle = (self.state.angle + radians) % (2.0 * PI); } fn down(&mut self) { self.state.down = true; } fn up(&mut self) { self.state.down = false; } } /// Represents everything needed to render a turtle a piece at a time to a canvas. /// /// It holds onto a turtle program, which is then used to eventually initialize an iterator over /// that program. pub struct TurtleAnimation { turtle: CanvasTurtle, iter: TurtleCollectToNextForwardIterator, } impl TurtleAnimation { /// Build a TurtleAnimation from a canvas element and a boxed turtle program. /// /// The TurtleProgram is copied and boxed (via its `turtle_program_iter`) to to avoid /// TurtleAnimation being generic. pub fn new(ctx: CanvasRenderingContext2d, program: &dyn TurtleProgram) -> TurtleAnimation { let mut turtle = CanvasTurtle::new(TurtleState::new(), ctx); let init_turtle_steps = program.init_turtle(); for action in init_turtle_steps { turtle.perform(action) } let iter = program.turtle_program_iter().collect_to_next_forward(); TurtleAnimation { turtle, iter } } } impl FractalAnimation for TurtleAnimation { /// Returns true if there are more moves to make, and false if it can no longer perform a move. fn draw_one_frame(&mut self) -> bool { if let Some(one_move) = self.iter.next() { log::debug!("Rendering one move"); for action in one_move { self.turtle.perform(action); } true } else { log::debug!("No more moves"); self.turtle.up(); false } } /// Translates a pixel-coordinate on the Canvas into the coordinate system used by the turtle /// curves. /// /// See turtle::turtle_vat for more information on the coordinate system for turtle curves. fn pixel_to_coordinate(&self, x: f64, y: f64) -> [f64; 2] { let canvas = self.turtle.ctx.canvas().unwrap(); let pos_point = turtle_vat(&canvas).map_pixel_to_point([x, y]); pos_point.into() } fn
(&mut self, _x1: f64, _y1: f64, _x2: f64, _y2: f64) -> bool { false } }
zoom
identifier_name
turtle.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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 super::FractalAnimation; use fractal_lib::geometry::{Point, Vector, ViewAreaTransformer}; use fractal_lib::turtle::{Turtle, TurtleCollectToNextForwardIterator, TurtleProgram, TurtleState}; use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement}; /// Constructs a ViewAreaTransformer for converting between a canvas pixel-coordinate and the /// coordinate system used by Turtle curves. /// /// The Turtle curves expect a view area that has positive values going up and to the right, and /// that center on both (0.0, 0.0) and (1.0, 0.0). to achieve this, the we need a view area from /// -0.5 to 1.5 on the X axis, and -0.75 and 0.75 on the Y axis. fn turtle_vat(canvas: &HtmlCanvasElement) -> ViewAreaTransformer { let screen_width = f64::from(canvas.width()); let screen_height = f64::from(canvas.height()); ViewAreaTransformer::new( [screen_width, screen_height], Point { x: -0.5, y: -0.75 }, Point { x: 1.5, y: 0.75 }, ) } /// A turtle that can draw to an HTML Canvas. struct CanvasTurtle { state: TurtleState, pub ctx: CanvasRenderingContext2d, } impl CanvasTurtle { pub fn new(state: TurtleState, ctx: CanvasRenderingContext2d) -> CanvasTurtle { CanvasTurtle { state, ctx } } } impl Turtle for CanvasTurtle { fn forward(&mut self, distance: f64) { let old_pos = self.state.position; let new_pos = self.state.position.point_at(Vector { direction: self.state.angle, magnitude: distance, }); if self.state.down { let turtle_vat = turtle_vat(&self.ctx.canvas().unwrap()); let old_coords = turtle_vat.map_point_to_pixel(old_pos); let new_coords = turtle_vat.map_point_to_pixel(new_pos); // log::debug!("Line to {}, {}", new_pos.x, new_pos.y); // log::debug!( // "old coords", // old_coords[0], // old_coords[1], // ); // log::debug!( // "new coords", // &new_coords[0], // &new_coords[1], // ); self.ctx.set_line_width(1.0f64); self.ctx.begin_path(); self.ctx.move_to(old_coords[0], old_coords[1]); self.ctx.line_to(new_coords[0], new_coords[1]); self.ctx.stroke(); } self.state.position = new_pos; } fn set_pos(&mut self, new_pos: Point) { self.state.position = new_pos; } fn set_rad(&mut self, new_rad: f64) { self.state.angle = new_rad; } fn turn_rad(&mut self, radians: f64) { use std::f64::consts::PI; self.state.angle = (self.state.angle + radians) % (2.0 * PI); } fn down(&mut self) { self.state.down = true; } fn up(&mut self) { self.state.down = false; } } /// Represents everything needed to render a turtle a piece at a time to a canvas. /// /// It holds onto a turtle program, which is then used to eventually initialize an iterator over /// that program. pub struct TurtleAnimation { turtle: CanvasTurtle, iter: TurtleCollectToNextForwardIterator, } impl TurtleAnimation { /// Build a TurtleAnimation from a canvas element and a boxed turtle program. /// /// The TurtleProgram is copied and boxed (via its `turtle_program_iter`) to to avoid /// TurtleAnimation being generic. pub fn new(ctx: CanvasRenderingContext2d, program: &dyn TurtleProgram) -> TurtleAnimation { let mut turtle = CanvasTurtle::new(TurtleState::new(), ctx); let init_turtle_steps = program.init_turtle(); for action in init_turtle_steps { turtle.perform(action) } let iter = program.turtle_program_iter().collect_to_next_forward(); TurtleAnimation { turtle, iter } } } impl FractalAnimation for TurtleAnimation { /// Returns true if there are more moves to make, and false if it can no longer perform a move. fn draw_one_frame(&mut self) -> bool { if let Some(one_move) = self.iter.next()
else { log::debug!("No more moves"); self.turtle.up(); false } } /// Translates a pixel-coordinate on the Canvas into the coordinate system used by the turtle /// curves. /// /// See turtle::turtle_vat for more information on the coordinate system for turtle curves. fn pixel_to_coordinate(&self, x: f64, y: f64) -> [f64; 2] { let canvas = self.turtle.ctx.canvas().unwrap(); let pos_point = turtle_vat(&canvas).map_pixel_to_point([x, y]); pos_point.into() } fn zoom(&mut self, _x1: f64, _y1: f64, _x2: f64, _y2: f64) -> bool { false } }
{ log::debug!("Rendering one move"); for action in one_move { self.turtle.perform(action); } true }
conditional_block
turtle.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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 super::FractalAnimation; use fractal_lib::geometry::{Point, Vector, ViewAreaTransformer}; use fractal_lib::turtle::{Turtle, TurtleCollectToNextForwardIterator, TurtleProgram, TurtleState}; use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement}; /// Constructs a ViewAreaTransformer for converting between a canvas pixel-coordinate and the /// coordinate system used by Turtle curves. /// /// The Turtle curves expect a view area that has positive values going up and to the right, and /// that center on both (0.0, 0.0) and (1.0, 0.0). to achieve this, the we need a view area from /// -0.5 to 1.5 on the X axis, and -0.75 and 0.75 on the Y axis. fn turtle_vat(canvas: &HtmlCanvasElement) -> ViewAreaTransformer { let screen_width = f64::from(canvas.width()); let screen_height = f64::from(canvas.height()); ViewAreaTransformer::new( [screen_width, screen_height], Point { x: -0.5, y: -0.75 }, Point { x: 1.5, y: 0.75 }, ) } /// A turtle that can draw to an HTML Canvas. struct CanvasTurtle { state: TurtleState, pub ctx: CanvasRenderingContext2d, } impl CanvasTurtle { pub fn new(state: TurtleState, ctx: CanvasRenderingContext2d) -> CanvasTurtle { CanvasTurtle { state, ctx } } } impl Turtle for CanvasTurtle { fn forward(&mut self, distance: f64) { let old_pos = self.state.position; let new_pos = self.state.position.point_at(Vector { direction: self.state.angle, magnitude: distance, }); if self.state.down { let turtle_vat = turtle_vat(&self.ctx.canvas().unwrap()); let old_coords = turtle_vat.map_point_to_pixel(old_pos); let new_coords = turtle_vat.map_point_to_pixel(new_pos); // log::debug!("Line to {}, {}", new_pos.x, new_pos.y); // log::debug!( // "old coords", // old_coords[0], // old_coords[1], // ); // log::debug!( // "new coords", // &new_coords[0], // &new_coords[1], // ); self.ctx.set_line_width(1.0f64); self.ctx.begin_path(); self.ctx.move_to(old_coords[0], old_coords[1]); self.ctx.line_to(new_coords[0], new_coords[1]); self.ctx.stroke(); } self.state.position = new_pos; } fn set_pos(&mut self, new_pos: Point) { self.state.position = new_pos; } fn set_rad(&mut self, new_rad: f64) { self.state.angle = new_rad; } fn turn_rad(&mut self, radians: f64) { use std::f64::consts::PI; self.state.angle = (self.state.angle + radians) % (2.0 * PI); } fn down(&mut self)
fn up(&mut self) { self.state.down = false; } } /// Represents everything needed to render a turtle a piece at a time to a canvas. /// /// It holds onto a turtle program, which is then used to eventually initialize an iterator over /// that program. pub struct TurtleAnimation { turtle: CanvasTurtle, iter: TurtleCollectToNextForwardIterator, } impl TurtleAnimation { /// Build a TurtleAnimation from a canvas element and a boxed turtle program. /// /// The TurtleProgram is copied and boxed (via its `turtle_program_iter`) to to avoid /// TurtleAnimation being generic. pub fn new(ctx: CanvasRenderingContext2d, program: &dyn TurtleProgram) -> TurtleAnimation { let mut turtle = CanvasTurtle::new(TurtleState::new(), ctx); let init_turtle_steps = program.init_turtle(); for action in init_turtle_steps { turtle.perform(action) } let iter = program.turtle_program_iter().collect_to_next_forward(); TurtleAnimation { turtle, iter } } } impl FractalAnimation for TurtleAnimation { /// Returns true if there are more moves to make, and false if it can no longer perform a move. fn draw_one_frame(&mut self) -> bool { if let Some(one_move) = self.iter.next() { log::debug!("Rendering one move"); for action in one_move { self.turtle.perform(action); } true } else { log::debug!("No more moves"); self.turtle.up(); false } } /// Translates a pixel-coordinate on the Canvas into the coordinate system used by the turtle /// curves. /// /// See turtle::turtle_vat for more information on the coordinate system for turtle curves. fn pixel_to_coordinate(&self, x: f64, y: f64) -> [f64; 2] { let canvas = self.turtle.ctx.canvas().unwrap(); let pos_point = turtle_vat(&canvas).map_pixel_to_point([x, y]); pos_point.into() } fn zoom(&mut self, _x1: f64, _y1: f64, _x2: f64, _y2: f64) -> bool { false } }
{ self.state.down = true; }
identifier_body
test_life_1_05.rs
extern crate game_of_life_parsers; use std::fs::File; use game_of_life_parsers::GameDescriptor; use game_of_life_parsers::Coord; use game_of_life_parsers::Parser; use game_of_life_parsers::Life105Parser; #[test] fn
() { let file = File::open("tests/life_1_05/glider.life").unwrap(); let mut parser = Life105Parser::new(); let gd: Box<GameDescriptor> = parser.parse(Box::new(file)).unwrap(); assert_eq!(&[2, 3], gd.survival()); assert_eq!(&[1], gd.birth()); assert_eq!(&[ // block 1 Coord { x: 0, y: -1 }, Coord { x: 1, y: 0 }, Coord { x: -1, y: 1 }, Coord { x: 0, y: 1 }, Coord { x: 1, y: 1 }, // block 2 Coord { x: 3, y: 2 }, Coord { x: 4, y: 3 }, Coord { x: 5, y: 4 } ], gd.live_cells()); }
parse_file
identifier_name
test_life_1_05.rs
extern crate game_of_life_parsers; use std::fs::File; use game_of_life_parsers::GameDescriptor; use game_of_life_parsers::Coord; use game_of_life_parsers::Parser; use game_of_life_parsers::Life105Parser; #[test] fn parse_file()
{ let file = File::open("tests/life_1_05/glider.life").unwrap(); let mut parser = Life105Parser::new(); let gd: Box<GameDescriptor> = parser.parse(Box::new(file)).unwrap(); assert_eq!(&[2, 3], gd.survival()); assert_eq!(&[1], gd.birth()); assert_eq!(&[ // block 1 Coord { x: 0, y: -1 }, Coord { x: 1, y: 0 }, Coord { x: -1, y: 1 }, Coord { x: 0, y: 1 }, Coord { x: 1, y: 1 }, // block 2 Coord { x: 3, y: 2 }, Coord { x: 4, y: 3 }, Coord { x: 5, y: 4 } ], gd.live_cells()); }
identifier_body
test_life_1_05.rs
extern crate game_of_life_parsers; use std::fs::File; use game_of_life_parsers::GameDescriptor; use game_of_life_parsers::Coord; use game_of_life_parsers::Parser; use game_of_life_parsers::Life105Parser;
let gd: Box<GameDescriptor> = parser.parse(Box::new(file)).unwrap(); assert_eq!(&[2, 3], gd.survival()); assert_eq!(&[1], gd.birth()); assert_eq!(&[ // block 1 Coord { x: 0, y: -1 }, Coord { x: 1, y: 0 }, Coord { x: -1, y: 1 }, Coord { x: 0, y: 1 }, Coord { x: 1, y: 1 }, // block 2 Coord { x: 3, y: 2 }, Coord { x: 4, y: 3 }, Coord { x: 5, y: 4 } ], gd.live_cells()); }
#[test] fn parse_file() { let file = File::open("tests/life_1_05/glider.life").unwrap(); let mut parser = Life105Parser::new();
random_line_split
socket.rs
use chan; use chan::Sender; use rustc_serialize::{Encodable, json}; use std::io::{BufReader, Read, Write}; use std::net::Shutdown; use std::sync::{Arc, Mutex}; use std::{fs, thread}; use datatype::{Command, DownloadFailed, Error, Event}; use super::{Gateway, Interpret}; use unix_socket::{UnixListener, UnixStream}; /// The `Socket` gateway is used for communication via Unix Domain Sockets. pub struct Socket { pub commands_path: String, pub events_path: String, } impl Gateway for Socket { fn initialize(&mut self, itx: Sender<Interpret>) -> Result<(), String> { let _ = fs::remove_file(&self.commands_path); let commands = match UnixListener::bind(&self.commands_path) { Ok(sock) => sock, Err(err) => return Err(format!("couldn't open commands socket: {}", err)) }; let itx = Arc::new(Mutex::new(itx)); thread::spawn(move || { for conn in commands.incoming() { if let Err(err) = conn { error!("couldn't get commands socket connection: {}", err); continue } let mut stream = conn.unwrap(); let itx = itx.clone(); thread::spawn(move || { let resp = handle_client(&mut stream, itx) .map(|ev| json::encode(&ev).expect("couldn't encode Event").into_bytes()) .unwrap_or_else(|err| format!("{}", err).into_bytes()); stream.write_all(&resp) .unwrap_or_else(|err| error!("couldn't write to commands socket: {}", err)); stream.shutdown(Shutdown::Write) .unwrap_or_else(|err| error!("couldn't close commands socket: {}", err)); }); } }); Ok(info!("Socket listening for commands at {} and sending events to {}.", self.commands_path, self.events_path)) } fn pulse(&self, event: Event) { let output = match event { Event::DownloadComplete(dl) => { json::encode(&EventWrapper { version: "0.1".to_string(), event: "DownloadComplete".to_string(), data: dl }).expect("couldn't encode DownloadComplete event") } Event::DownloadFailed(id, reason) =>
_ => return }; let _ = UnixStream::connect(&self.events_path).map(|mut stream| { stream.write_all(&output.into_bytes()) .unwrap_or_else(|err| error!("couldn't write to events socket: {}", err)); stream.shutdown(Shutdown::Write) .unwrap_or_else(|err| error!("couldn't close events socket: {}", err)); }).map_err(|err| debug!("couldn't open events socket: {}", err)); } } fn handle_client(stream: &mut UnixStream, itx: Arc<Mutex<Sender<Interpret>>>) -> Result<Event, Error> { info!("New domain socket connection"); let mut reader = BufReader::new(stream); let mut input = String::new(); try!(reader.read_to_string(&mut input)); debug!("socket input: {}", input); let cmd = try!(input.parse::<Command>()); let (etx, erx) = chan::async::<Event>(); itx.lock().unwrap().send(Interpret { command: cmd, response_tx: Some(Arc::new(Mutex::new(etx))), }); erx.recv().ok_or(Error::Socket("internal receiver error".to_string())) } // FIXME(PRO-1322): create a proper JSON api #[derive(RustcEncodable, RustcDecodable, PartialEq, Eq, Debug)] pub struct EventWrapper<E: Encodable> { pub version: String, pub event: String, pub data: E } #[cfg(test)] mod tests { use chan; use crossbeam; use rustc_serialize::json; use std::{fs, thread}; use std::io::{Read, Write}; use std::net::Shutdown; use std::time::Duration; use datatype::{Command, DownloadComplete, Event}; use gateway::{Gateway, Interpret}; use super::*; use unix_socket::{UnixListener, UnixStream}; #[test] fn socket_commands_and_events() { let (etx, erx) = chan::sync::<Event>(0); let (itx, irx) = chan::sync::<Interpret>(0); thread::spawn(move || Socket { commands_path: "/tmp/sota-commands.socket".to_string(), events_path: "/tmp/sota-events.socket".to_string(), }.start(itx, erx)); thread::sleep(Duration::from_millis(100)); // wait until socket gateway is created let path = "/tmp/sota-events.socket"; let _ = fs::remove_file(&path); let server = UnixListener::bind(&path).expect("couldn't create events socket for testing"); let send = DownloadComplete { update_id: "1".to_string(), update_image: "/foo/bar".to_string(), signature: "abc".to_string() }; etx.send(Event::DownloadComplete(send.clone())); let (mut stream, _) = server.accept().expect("couldn't read from events socket"); let mut text = String::new(); stream.read_to_string(&mut text).unwrap(); let receive: EventWrapper<DownloadComplete> = json::decode(&text).expect("couldn't decode Event"); assert_eq!(receive.version, "0.1".to_string()); assert_eq!(receive.event, "DownloadComplete".to_string()); assert_eq!(receive.data, send); thread::spawn(move || { let _ = etx; // move into this scope loop { let interpret = irx.recv().expect("gtx is closed"); match interpret.command { Command::StartDownload(id) => { let tx = interpret.response_tx.unwrap(); tx.lock().unwrap().send(Event::FoundSystemInfo(id)); } _ => panic!("expected AcceptUpdates"), } } }); crossbeam::scope(|scope| { for id in 0..10 { scope.spawn(move || { let mut stream = UnixStream::connect("/tmp/sota-commands.socket").expect("couldn't connect to socket"); let _ = stream.write_all(&format!("dl {}", id).into_bytes()).expect("couldn't write to stream"); stream.shutdown(Shutdown::Write).expect("couldn't shut down writing"); let mut resp = String::new(); stream.read_to_string(&mut resp).expect("couldn't read from stream"); let ev: Event = json::decode(&resp).expect("couldn't decode json event"); assert_eq!(ev, Event::FoundSystemInfo(format!("{}", id))); }); } }); } }
{ json::encode(&EventWrapper { version: "0.1".to_string(), event: "DownloadFailed".to_string(), data: DownloadFailed { update_id: id, reason: reason } }).expect("couldn't encode DownloadFailed event") }
conditional_block
socket.rs
use chan; use chan::Sender; use rustc_serialize::{Encodable, json}; use std::io::{BufReader, Read, Write}; use std::net::Shutdown; use std::sync::{Arc, Mutex}; use std::{fs, thread}; use datatype::{Command, DownloadFailed, Error, Event}; use super::{Gateway, Interpret}; use unix_socket::{UnixListener, UnixStream}; /// The `Socket` gateway is used for communication via Unix Domain Sockets. pub struct Socket { pub commands_path: String, pub events_path: String, } impl Gateway for Socket { fn initialize(&mut self, itx: Sender<Interpret>) -> Result<(), String> { let _ = fs::remove_file(&self.commands_path); let commands = match UnixListener::bind(&self.commands_path) { Ok(sock) => sock, Err(err) => return Err(format!("couldn't open commands socket: {}", err)) }; let itx = Arc::new(Mutex::new(itx)); thread::spawn(move || { for conn in commands.incoming() { if let Err(err) = conn { error!("couldn't get commands socket connection: {}", err); continue } let mut stream = conn.unwrap(); let itx = itx.clone(); thread::spawn(move || { let resp = handle_client(&mut stream, itx) .map(|ev| json::encode(&ev).expect("couldn't encode Event").into_bytes()) .unwrap_or_else(|err| format!("{}", err).into_bytes()); stream.write_all(&resp) .unwrap_or_else(|err| error!("couldn't write to commands socket: {}", err)); stream.shutdown(Shutdown::Write) .unwrap_or_else(|err| error!("couldn't close commands socket: {}", err)); }); } }); Ok(info!("Socket listening for commands at {} and sending events to {}.", self.commands_path, self.events_path)) } fn pulse(&self, event: Event) { let output = match event { Event::DownloadComplete(dl) => { json::encode(&EventWrapper { version: "0.1".to_string(), event: "DownloadComplete".to_string(), data: dl }).expect("couldn't encode DownloadComplete event") } Event::DownloadFailed(id, reason) => { json::encode(&EventWrapper { version: "0.1".to_string(), event: "DownloadFailed".to_string(), data: DownloadFailed { update_id: id, reason: reason } }).expect("couldn't encode DownloadFailed event") } _ => return }; let _ = UnixStream::connect(&self.events_path).map(|mut stream| { stream.write_all(&output.into_bytes()) .unwrap_or_else(|err| error!("couldn't write to events socket: {}", err)); stream.shutdown(Shutdown::Write) .unwrap_or_else(|err| error!("couldn't close events socket: {}", err)); }).map_err(|err| debug!("couldn't open events socket: {}", err)); } } fn handle_client(stream: &mut UnixStream, itx: Arc<Mutex<Sender<Interpret>>>) -> Result<Event, Error> { info!("New domain socket connection"); let mut reader = BufReader::new(stream); let mut input = String::new(); try!(reader.read_to_string(&mut input)); debug!("socket input: {}", input); let cmd = try!(input.parse::<Command>()); let (etx, erx) = chan::async::<Event>(); itx.lock().unwrap().send(Interpret { command: cmd, response_tx: Some(Arc::new(Mutex::new(etx))), }); erx.recv().ok_or(Error::Socket("internal receiver error".to_string())) } // FIXME(PRO-1322): create a proper JSON api #[derive(RustcEncodable, RustcDecodable, PartialEq, Eq, Debug)] pub struct
<E: Encodable> { pub version: String, pub event: String, pub data: E } #[cfg(test)] mod tests { use chan; use crossbeam; use rustc_serialize::json; use std::{fs, thread}; use std::io::{Read, Write}; use std::net::Shutdown; use std::time::Duration; use datatype::{Command, DownloadComplete, Event}; use gateway::{Gateway, Interpret}; use super::*; use unix_socket::{UnixListener, UnixStream}; #[test] fn socket_commands_and_events() { let (etx, erx) = chan::sync::<Event>(0); let (itx, irx) = chan::sync::<Interpret>(0); thread::spawn(move || Socket { commands_path: "/tmp/sota-commands.socket".to_string(), events_path: "/tmp/sota-events.socket".to_string(), }.start(itx, erx)); thread::sleep(Duration::from_millis(100)); // wait until socket gateway is created let path = "/tmp/sota-events.socket"; let _ = fs::remove_file(&path); let server = UnixListener::bind(&path).expect("couldn't create events socket for testing"); let send = DownloadComplete { update_id: "1".to_string(), update_image: "/foo/bar".to_string(), signature: "abc".to_string() }; etx.send(Event::DownloadComplete(send.clone())); let (mut stream, _) = server.accept().expect("couldn't read from events socket"); let mut text = String::new(); stream.read_to_string(&mut text).unwrap(); let receive: EventWrapper<DownloadComplete> = json::decode(&text).expect("couldn't decode Event"); assert_eq!(receive.version, "0.1".to_string()); assert_eq!(receive.event, "DownloadComplete".to_string()); assert_eq!(receive.data, send); thread::spawn(move || { let _ = etx; // move into this scope loop { let interpret = irx.recv().expect("gtx is closed"); match interpret.command { Command::StartDownload(id) => { let tx = interpret.response_tx.unwrap(); tx.lock().unwrap().send(Event::FoundSystemInfo(id)); } _ => panic!("expected AcceptUpdates"), } } }); crossbeam::scope(|scope| { for id in 0..10 { scope.spawn(move || { let mut stream = UnixStream::connect("/tmp/sota-commands.socket").expect("couldn't connect to socket"); let _ = stream.write_all(&format!("dl {}", id).into_bytes()).expect("couldn't write to stream"); stream.shutdown(Shutdown::Write).expect("couldn't shut down writing"); let mut resp = String::new(); stream.read_to_string(&mut resp).expect("couldn't read from stream"); let ev: Event = json::decode(&resp).expect("couldn't decode json event"); assert_eq!(ev, Event::FoundSystemInfo(format!("{}", id))); }); } }); } }
EventWrapper
identifier_name
socket.rs
use chan; use chan::Sender; use rustc_serialize::{Encodable, json}; use std::io::{BufReader, Read, Write};
use std::{fs, thread}; use datatype::{Command, DownloadFailed, Error, Event}; use super::{Gateway, Interpret}; use unix_socket::{UnixListener, UnixStream}; /// The `Socket` gateway is used for communication via Unix Domain Sockets. pub struct Socket { pub commands_path: String, pub events_path: String, } impl Gateway for Socket { fn initialize(&mut self, itx: Sender<Interpret>) -> Result<(), String> { let _ = fs::remove_file(&self.commands_path); let commands = match UnixListener::bind(&self.commands_path) { Ok(sock) => sock, Err(err) => return Err(format!("couldn't open commands socket: {}", err)) }; let itx = Arc::new(Mutex::new(itx)); thread::spawn(move || { for conn in commands.incoming() { if let Err(err) = conn { error!("couldn't get commands socket connection: {}", err); continue } let mut stream = conn.unwrap(); let itx = itx.clone(); thread::spawn(move || { let resp = handle_client(&mut stream, itx) .map(|ev| json::encode(&ev).expect("couldn't encode Event").into_bytes()) .unwrap_or_else(|err| format!("{}", err).into_bytes()); stream.write_all(&resp) .unwrap_or_else(|err| error!("couldn't write to commands socket: {}", err)); stream.shutdown(Shutdown::Write) .unwrap_or_else(|err| error!("couldn't close commands socket: {}", err)); }); } }); Ok(info!("Socket listening for commands at {} and sending events to {}.", self.commands_path, self.events_path)) } fn pulse(&self, event: Event) { let output = match event { Event::DownloadComplete(dl) => { json::encode(&EventWrapper { version: "0.1".to_string(), event: "DownloadComplete".to_string(), data: dl }).expect("couldn't encode DownloadComplete event") } Event::DownloadFailed(id, reason) => { json::encode(&EventWrapper { version: "0.1".to_string(), event: "DownloadFailed".to_string(), data: DownloadFailed { update_id: id, reason: reason } }).expect("couldn't encode DownloadFailed event") } _ => return }; let _ = UnixStream::connect(&self.events_path).map(|mut stream| { stream.write_all(&output.into_bytes()) .unwrap_or_else(|err| error!("couldn't write to events socket: {}", err)); stream.shutdown(Shutdown::Write) .unwrap_or_else(|err| error!("couldn't close events socket: {}", err)); }).map_err(|err| debug!("couldn't open events socket: {}", err)); } } fn handle_client(stream: &mut UnixStream, itx: Arc<Mutex<Sender<Interpret>>>) -> Result<Event, Error> { info!("New domain socket connection"); let mut reader = BufReader::new(stream); let mut input = String::new(); try!(reader.read_to_string(&mut input)); debug!("socket input: {}", input); let cmd = try!(input.parse::<Command>()); let (etx, erx) = chan::async::<Event>(); itx.lock().unwrap().send(Interpret { command: cmd, response_tx: Some(Arc::new(Mutex::new(etx))), }); erx.recv().ok_or(Error::Socket("internal receiver error".to_string())) } // FIXME(PRO-1322): create a proper JSON api #[derive(RustcEncodable, RustcDecodable, PartialEq, Eq, Debug)] pub struct EventWrapper<E: Encodable> { pub version: String, pub event: String, pub data: E } #[cfg(test)] mod tests { use chan; use crossbeam; use rustc_serialize::json; use std::{fs, thread}; use std::io::{Read, Write}; use std::net::Shutdown; use std::time::Duration; use datatype::{Command, DownloadComplete, Event}; use gateway::{Gateway, Interpret}; use super::*; use unix_socket::{UnixListener, UnixStream}; #[test] fn socket_commands_and_events() { let (etx, erx) = chan::sync::<Event>(0); let (itx, irx) = chan::sync::<Interpret>(0); thread::spawn(move || Socket { commands_path: "/tmp/sota-commands.socket".to_string(), events_path: "/tmp/sota-events.socket".to_string(), }.start(itx, erx)); thread::sleep(Duration::from_millis(100)); // wait until socket gateway is created let path = "/tmp/sota-events.socket"; let _ = fs::remove_file(&path); let server = UnixListener::bind(&path).expect("couldn't create events socket for testing"); let send = DownloadComplete { update_id: "1".to_string(), update_image: "/foo/bar".to_string(), signature: "abc".to_string() }; etx.send(Event::DownloadComplete(send.clone())); let (mut stream, _) = server.accept().expect("couldn't read from events socket"); let mut text = String::new(); stream.read_to_string(&mut text).unwrap(); let receive: EventWrapper<DownloadComplete> = json::decode(&text).expect("couldn't decode Event"); assert_eq!(receive.version, "0.1".to_string()); assert_eq!(receive.event, "DownloadComplete".to_string()); assert_eq!(receive.data, send); thread::spawn(move || { let _ = etx; // move into this scope loop { let interpret = irx.recv().expect("gtx is closed"); match interpret.command { Command::StartDownload(id) => { let tx = interpret.response_tx.unwrap(); tx.lock().unwrap().send(Event::FoundSystemInfo(id)); } _ => panic!("expected AcceptUpdates"), } } }); crossbeam::scope(|scope| { for id in 0..10 { scope.spawn(move || { let mut stream = UnixStream::connect("/tmp/sota-commands.socket").expect("couldn't connect to socket"); let _ = stream.write_all(&format!("dl {}", id).into_bytes()).expect("couldn't write to stream"); stream.shutdown(Shutdown::Write).expect("couldn't shut down writing"); let mut resp = String::new(); stream.read_to_string(&mut resp).expect("couldn't read from stream"); let ev: Event = json::decode(&resp).expect("couldn't decode json event"); assert_eq!(ev, Event::FoundSystemInfo(format!("{}", id))); }); } }); } }
use std::net::Shutdown; use std::sync::{Arc, Mutex};
random_line_split
socket.rs
use chan; use chan::Sender; use rustc_serialize::{Encodable, json}; use std::io::{BufReader, Read, Write}; use std::net::Shutdown; use std::sync::{Arc, Mutex}; use std::{fs, thread}; use datatype::{Command, DownloadFailed, Error, Event}; use super::{Gateway, Interpret}; use unix_socket::{UnixListener, UnixStream}; /// The `Socket` gateway is used for communication via Unix Domain Sockets. pub struct Socket { pub commands_path: String, pub events_path: String, } impl Gateway for Socket { fn initialize(&mut self, itx: Sender<Interpret>) -> Result<(), String> { let _ = fs::remove_file(&self.commands_path); let commands = match UnixListener::bind(&self.commands_path) { Ok(sock) => sock, Err(err) => return Err(format!("couldn't open commands socket: {}", err)) }; let itx = Arc::new(Mutex::new(itx)); thread::spawn(move || { for conn in commands.incoming() { if let Err(err) = conn { error!("couldn't get commands socket connection: {}", err); continue } let mut stream = conn.unwrap(); let itx = itx.clone(); thread::spawn(move || { let resp = handle_client(&mut stream, itx) .map(|ev| json::encode(&ev).expect("couldn't encode Event").into_bytes()) .unwrap_or_else(|err| format!("{}", err).into_bytes()); stream.write_all(&resp) .unwrap_or_else(|err| error!("couldn't write to commands socket: {}", err)); stream.shutdown(Shutdown::Write) .unwrap_or_else(|err| error!("couldn't close commands socket: {}", err)); }); } }); Ok(info!("Socket listening for commands at {} and sending events to {}.", self.commands_path, self.events_path)) } fn pulse(&self, event: Event)
let _ = UnixStream::connect(&self.events_path).map(|mut stream| { stream.write_all(&output.into_bytes()) .unwrap_or_else(|err| error!("couldn't write to events socket: {}", err)); stream.shutdown(Shutdown::Write) .unwrap_or_else(|err| error!("couldn't close events socket: {}", err)); }).map_err(|err| debug!("couldn't open events socket: {}", err)); } } fn handle_client(stream: &mut UnixStream, itx: Arc<Mutex<Sender<Interpret>>>) -> Result<Event, Error> { info!("New domain socket connection"); let mut reader = BufReader::new(stream); let mut input = String::new(); try!(reader.read_to_string(&mut input)); debug!("socket input: {}", input); let cmd = try!(input.parse::<Command>()); let (etx, erx) = chan::async::<Event>(); itx.lock().unwrap().send(Interpret { command: cmd, response_tx: Some(Arc::new(Mutex::new(etx))), }); erx.recv().ok_or(Error::Socket("internal receiver error".to_string())) } // FIXME(PRO-1322): create a proper JSON api #[derive(RustcEncodable, RustcDecodable, PartialEq, Eq, Debug)] pub struct EventWrapper<E: Encodable> { pub version: String, pub event: String, pub data: E } #[cfg(test)] mod tests { use chan; use crossbeam; use rustc_serialize::json; use std::{fs, thread}; use std::io::{Read, Write}; use std::net::Shutdown; use std::time::Duration; use datatype::{Command, DownloadComplete, Event}; use gateway::{Gateway, Interpret}; use super::*; use unix_socket::{UnixListener, UnixStream}; #[test] fn socket_commands_and_events() { let (etx, erx) = chan::sync::<Event>(0); let (itx, irx) = chan::sync::<Interpret>(0); thread::spawn(move || Socket { commands_path: "/tmp/sota-commands.socket".to_string(), events_path: "/tmp/sota-events.socket".to_string(), }.start(itx, erx)); thread::sleep(Duration::from_millis(100)); // wait until socket gateway is created let path = "/tmp/sota-events.socket"; let _ = fs::remove_file(&path); let server = UnixListener::bind(&path).expect("couldn't create events socket for testing"); let send = DownloadComplete { update_id: "1".to_string(), update_image: "/foo/bar".to_string(), signature: "abc".to_string() }; etx.send(Event::DownloadComplete(send.clone())); let (mut stream, _) = server.accept().expect("couldn't read from events socket"); let mut text = String::new(); stream.read_to_string(&mut text).unwrap(); let receive: EventWrapper<DownloadComplete> = json::decode(&text).expect("couldn't decode Event"); assert_eq!(receive.version, "0.1".to_string()); assert_eq!(receive.event, "DownloadComplete".to_string()); assert_eq!(receive.data, send); thread::spawn(move || { let _ = etx; // move into this scope loop { let interpret = irx.recv().expect("gtx is closed"); match interpret.command { Command::StartDownload(id) => { let tx = interpret.response_tx.unwrap(); tx.lock().unwrap().send(Event::FoundSystemInfo(id)); } _ => panic!("expected AcceptUpdates"), } } }); crossbeam::scope(|scope| { for id in 0..10 { scope.spawn(move || { let mut stream = UnixStream::connect("/tmp/sota-commands.socket").expect("couldn't connect to socket"); let _ = stream.write_all(&format!("dl {}", id).into_bytes()).expect("couldn't write to stream"); stream.shutdown(Shutdown::Write).expect("couldn't shut down writing"); let mut resp = String::new(); stream.read_to_string(&mut resp).expect("couldn't read from stream"); let ev: Event = json::decode(&resp).expect("couldn't decode json event"); assert_eq!(ev, Event::FoundSystemInfo(format!("{}", id))); }); } }); } }
{ let output = match event { Event::DownloadComplete(dl) => { json::encode(&EventWrapper { version: "0.1".to_string(), event: "DownloadComplete".to_string(), data: dl }).expect("couldn't encode DownloadComplete event") } Event::DownloadFailed(id, reason) => { json::encode(&EventWrapper { version: "0.1".to_string(), event: "DownloadFailed".to_string(), data: DownloadFailed { update_id: id, reason: reason } }).expect("couldn't encode DownloadFailed event") } _ => return };
identifier_body
config.rs
use std::collections::BTreeMap; use std::error::Error; use std::io::{self, Read}; use std::fmt; use std::fs::File; use std::path::Path; use serde_json; use cargo; #[derive(Clone, Debug, Deserialize)]
pub protocol_version: String, #[serde(rename = "customDependencies")] pub custom_dependencies: Option<BTreeMap<String, cargo::Dependency>>, #[serde(rename = "customDevDependencies")] pub custom_dev_dependencies: Option<BTreeMap<String, cargo::Dependency>>, #[serde(rename = "baseTypeName")] pub base_type_name: String } impl ServiceConfig { pub fn load_all<P: AsRef<Path>>(config_path: P) -> Result<BTreeMap<String, Self>, io::Error> { let contents = File::open(config_path).and_then(|mut f| { let mut contents = String::new(); f.read_to_string(&mut contents).map(|_| contents) })?; let parsed: BTreeMap<String, ServiceConfig> = serde_json::from_str(&contents).expect("Unable to parse services configuration file."); Ok(parsed) } } #[derive(Debug)] pub enum ConfigError { Io(io::Error), Format(serde_json::Error) } impl From<io::Error> for ConfigError { fn from(err: io::Error) -> Self { ConfigError::Io(err) } } impl From<serde_json::Error> for ConfigError { fn from(err: serde_json::Error) -> Self { ConfigError::Format(err) } } impl fmt::Display for ConfigError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ConfigError::Io(ref e) => e.fmt(f), ConfigError::Format(ref e) => e.fmt(f) } } } impl Error for ConfigError { fn description(&self) -> &str { match *self { ConfigError::Io(ref e) => e.description(), ConfigError::Format(ref e) => e.description() } } fn cause(&self) -> Option<&Error> { match *self { ConfigError::Io(ref e) => Some(e), ConfigError::Format(ref e) => Some(e) } } }
pub struct ServiceConfig { pub version: String, #[serde(rename = "coreVersion")] pub core_version: String, #[serde(rename = "protocolVersion")]
random_line_split
config.rs
use std::collections::BTreeMap; use std::error::Error; use std::io::{self, Read}; use std::fmt; use std::fs::File; use std::path::Path; use serde_json; use cargo; #[derive(Clone, Debug, Deserialize)] pub struct ServiceConfig { pub version: String, #[serde(rename = "coreVersion")] pub core_version: String, #[serde(rename = "protocolVersion")] pub protocol_version: String, #[serde(rename = "customDependencies")] pub custom_dependencies: Option<BTreeMap<String, cargo::Dependency>>, #[serde(rename = "customDevDependencies")] pub custom_dev_dependencies: Option<BTreeMap<String, cargo::Dependency>>, #[serde(rename = "baseTypeName")] pub base_type_name: String } impl ServiceConfig { pub fn load_all<P: AsRef<Path>>(config_path: P) -> Result<BTreeMap<String, Self>, io::Error> { let contents = File::open(config_path).and_then(|mut f| { let mut contents = String::new(); f.read_to_string(&mut contents).map(|_| contents) })?; let parsed: BTreeMap<String, ServiceConfig> = serde_json::from_str(&contents).expect("Unable to parse services configuration file."); Ok(parsed) } } #[derive(Debug)] pub enum ConfigError { Io(io::Error), Format(serde_json::Error) } impl From<io::Error> for ConfigError { fn from(err: io::Error) -> Self { ConfigError::Io(err) } } impl From<serde_json::Error> for ConfigError { fn from(err: serde_json::Error) -> Self { ConfigError::Format(err) } } impl fmt::Display for ConfigError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} impl Error for ConfigError { fn description(&self) -> &str { match *self { ConfigError::Io(ref e) => e.description(), ConfigError::Format(ref e) => e.description() } } fn cause(&self) -> Option<&Error> { match *self { ConfigError::Io(ref e) => Some(e), ConfigError::Format(ref e) => Some(e) } } }
{ match *self { ConfigError::Io(ref e) => e.fmt(f), ConfigError::Format(ref e) => e.fmt(f) } }
identifier_body
config.rs
use std::collections::BTreeMap; use std::error::Error; use std::io::{self, Read}; use std::fmt; use std::fs::File; use std::path::Path; use serde_json; use cargo; #[derive(Clone, Debug, Deserialize)] pub struct ServiceConfig { pub version: String, #[serde(rename = "coreVersion")] pub core_version: String, #[serde(rename = "protocolVersion")] pub protocol_version: String, #[serde(rename = "customDependencies")] pub custom_dependencies: Option<BTreeMap<String, cargo::Dependency>>, #[serde(rename = "customDevDependencies")] pub custom_dev_dependencies: Option<BTreeMap<String, cargo::Dependency>>, #[serde(rename = "baseTypeName")] pub base_type_name: String } impl ServiceConfig { pub fn load_all<P: AsRef<Path>>(config_path: P) -> Result<BTreeMap<String, Self>, io::Error> { let contents = File::open(config_path).and_then(|mut f| { let mut contents = String::new(); f.read_to_string(&mut contents).map(|_| contents) })?; let parsed: BTreeMap<String, ServiceConfig> = serde_json::from_str(&contents).expect("Unable to parse services configuration file."); Ok(parsed) } } #[derive(Debug)] pub enum ConfigError { Io(io::Error), Format(serde_json::Error) } impl From<io::Error> for ConfigError { fn
(err: io::Error) -> Self { ConfigError::Io(err) } } impl From<serde_json::Error> for ConfigError { fn from(err: serde_json::Error) -> Self { ConfigError::Format(err) } } impl fmt::Display for ConfigError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ConfigError::Io(ref e) => e.fmt(f), ConfigError::Format(ref e) => e.fmt(f) } } } impl Error for ConfigError { fn description(&self) -> &str { match *self { ConfigError::Io(ref e) => e.description(), ConfigError::Format(ref e) => e.description() } } fn cause(&self) -> Option<&Error> { match *self { ConfigError::Io(ref e) => Some(e), ConfigError::Format(ref e) => Some(e) } } }
from
identifier_name
main.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern mod glfw; #[link(name="glfw")] extern {} #[start] fn start(argc: int, argv: **u8) -> int { std::rt::start_on_main_thread(argc, argv, main) } fn main() { glfw::set_error_callback(~ErrorContext); do glfw::start { glfw::window_hint::visible(true); let window = glfw::Window::create(640, 480, "Defaults", glfw::Windowed) .expect("Failed to create GLFW window."); window.make_context_current(); let (width, height) = window.get_size(); println!("window size: ({}, {})", width, height); println!("Context version: {:s}", window.get_context_version().to_str()); println!("OpenGL forward compatible: {}", window.is_opengl_forward_compat()); println!("OpenGL debug context: {}", window.is_opengl_debug_context()); println!("OpenGL profile: {}", window.get_opengl_profile()); let gl_params = [ (gl::RED_BITS, None, "red bits" ), (gl::GREEN_BITS, None, "green bits" ), (gl::BLUE_BITS, None, "blue bits" ), (gl::ALPHA_BITS, None, "alpha bits" ), (gl::DEPTH_BITS, None, "depth bits" ), (gl::STENCIL_BITS, None, "stencil bits" ), (gl::ACCUM_RED_BITS, None, "accum red bits" ), (gl::ACCUM_GREEN_BITS, None, "accum green bits" ), (gl::ACCUM_BLUE_BITS, None, "accum blue bits" ), (gl::ACCUM_ALPHA_BITS, None, "accum alpha bits" ), (gl::STEREO, None, "stereo" ), (gl::SAMPLES_ARB, Some("GL_ARB_multisample"), "FSAA samples" ), ]; for &(param, ext, name) in gl_params.iter() { if ext.map_default(true, |s| { glfw::extension_supported(s) })
; } } } struct ErrorContext; impl glfw::ErrorCallback for ErrorContext { fn call(&self, _: glfw::Error, description: ~str) { println!("GLFW Error: {:s}", description); } } mod gl { use std::libc; #[cfg(target_os = "macos")] #[link(name="OpenGL", kind="framework")] extern { } #[cfg(target_os = "linux")] #[link(name="GL")] extern { } pub type GLenum = libc::c_uint; pub type GLint = libc::c_int; pub static RED_BITS : GLenum = 0x0D52; pub static GREEN_BITS : GLenum = 0x0D53; pub static BLUE_BITS : GLenum = 0x0D54; pub static ALPHA_BITS : GLenum = 0x0D55; pub static DEPTH_BITS : GLenum = 0x0D56; pub static STENCIL_BITS : GLenum = 0x0D57; pub static ACCUM_RED_BITS : GLenum = 0x0D58; pub static ACCUM_GREEN_BITS : GLenum = 0x0D59; pub static ACCUM_BLUE_BITS : GLenum = 0x0D5A; pub static ACCUM_ALPHA_BITS : GLenum = 0x0D5B; pub static STEREO : GLenum = 0x0C33; pub static SAMPLES_ARB : GLenum = 0x80A9; #[inline(never)] pub unsafe fn GetIntegerv(pname: GLenum, params: *GLint) { glGetIntegerv(pname, params) } extern "C" { fn glGetIntegerv(pname: GLenum, params: *GLint); } }
{ let value = 0; unsafe { gl::GetIntegerv(param, &value) }; println!("OpenGL {:s}: {}", name, value); }
conditional_block
main.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern mod glfw; #[link(name="glfw")] extern {} #[start] fn start(argc: int, argv: **u8) -> int { std::rt::start_on_main_thread(argc, argv, main) } fn main() { glfw::set_error_callback(~ErrorContext); do glfw::start { glfw::window_hint::visible(true); let window = glfw::Window::create(640, 480, "Defaults", glfw::Windowed) .expect("Failed to create GLFW window."); window.make_context_current(); let (width, height) = window.get_size(); println!("window size: ({}, {})", width, height); println!("Context version: {:s}", window.get_context_version().to_str()); println!("OpenGL forward compatible: {}", window.is_opengl_forward_compat()); println!("OpenGL debug context: {}", window.is_opengl_debug_context()); println!("OpenGL profile: {}", window.get_opengl_profile()); let gl_params = [ (gl::RED_BITS, None, "red bits" ), (gl::GREEN_BITS, None, "green bits" ), (gl::BLUE_BITS, None, "blue bits" ), (gl::ALPHA_BITS, None, "alpha bits" ), (gl::DEPTH_BITS, None, "depth bits" ), (gl::STENCIL_BITS, None, "stencil bits" ), (gl::ACCUM_RED_BITS, None, "accum red bits" ), (gl::ACCUM_GREEN_BITS, None, "accum green bits" ), (gl::ACCUM_BLUE_BITS, None, "accum blue bits" ), (gl::ACCUM_ALPHA_BITS, None, "accum alpha bits" ), (gl::STEREO, None, "stereo" ), (gl::SAMPLES_ARB, Some("GL_ARB_multisample"), "FSAA samples" ), ]; for &(param, ext, name) in gl_params.iter() { if ext.map_default(true, |s| { glfw::extension_supported(s) }) { let value = 0; unsafe { gl::GetIntegerv(param, &value) }; println!("OpenGL {:s}: {}", name, value); }; } } } struct ErrorContext; impl glfw::ErrorCallback for ErrorContext { fn call(&self, _: glfw::Error, description: ~str) { println!("GLFW Error: {:s}", description); } } mod gl { use std::libc; #[cfg(target_os = "macos")] #[link(name="OpenGL", kind="framework")] extern { } #[cfg(target_os = "linux")] #[link(name="GL")] extern { } pub type GLenum = libc::c_uint; pub type GLint = libc::c_int; pub static RED_BITS : GLenum = 0x0D52; pub static GREEN_BITS : GLenum = 0x0D53; pub static BLUE_BITS : GLenum = 0x0D54; pub static ALPHA_BITS : GLenum = 0x0D55; pub static DEPTH_BITS : GLenum = 0x0D56; pub static STENCIL_BITS : GLenum = 0x0D57; pub static ACCUM_RED_BITS : GLenum = 0x0D58; pub static ACCUM_GREEN_BITS : GLenum = 0x0D59; pub static ACCUM_BLUE_BITS : GLenum = 0x0D5A; pub static ACCUM_ALPHA_BITS : GLenum = 0x0D5B; pub static STEREO : GLenum = 0x0C33; pub static SAMPLES_ARB : GLenum = 0x80A9; #[inline(never)] pub unsafe fn GetIntegerv(pname: GLenum, params: *GLint) { glGetIntegerv(pname, params) } extern "C" { fn glGetIntegerv(pname: GLenum, params: *GLint); } }
// Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
main.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern mod glfw; #[link(name="glfw")] extern {} #[start] fn
(argc: int, argv: **u8) -> int { std::rt::start_on_main_thread(argc, argv, main) } fn main() { glfw::set_error_callback(~ErrorContext); do glfw::start { glfw::window_hint::visible(true); let window = glfw::Window::create(640, 480, "Defaults", glfw::Windowed) .expect("Failed to create GLFW window."); window.make_context_current(); let (width, height) = window.get_size(); println!("window size: ({}, {})", width, height); println!("Context version: {:s}", window.get_context_version().to_str()); println!("OpenGL forward compatible: {}", window.is_opengl_forward_compat()); println!("OpenGL debug context: {}", window.is_opengl_debug_context()); println!("OpenGL profile: {}", window.get_opengl_profile()); let gl_params = [ (gl::RED_BITS, None, "red bits" ), (gl::GREEN_BITS, None, "green bits" ), (gl::BLUE_BITS, None, "blue bits" ), (gl::ALPHA_BITS, None, "alpha bits" ), (gl::DEPTH_BITS, None, "depth bits" ), (gl::STENCIL_BITS, None, "stencil bits" ), (gl::ACCUM_RED_BITS, None, "accum red bits" ), (gl::ACCUM_GREEN_BITS, None, "accum green bits" ), (gl::ACCUM_BLUE_BITS, None, "accum blue bits" ), (gl::ACCUM_ALPHA_BITS, None, "accum alpha bits" ), (gl::STEREO, None, "stereo" ), (gl::SAMPLES_ARB, Some("GL_ARB_multisample"), "FSAA samples" ), ]; for &(param, ext, name) in gl_params.iter() { if ext.map_default(true, |s| { glfw::extension_supported(s) }) { let value = 0; unsafe { gl::GetIntegerv(param, &value) }; println!("OpenGL {:s}: {}", name, value); }; } } } struct ErrorContext; impl glfw::ErrorCallback for ErrorContext { fn call(&self, _: glfw::Error, description: ~str) { println!("GLFW Error: {:s}", description); } } mod gl { use std::libc; #[cfg(target_os = "macos")] #[link(name="OpenGL", kind="framework")] extern { } #[cfg(target_os = "linux")] #[link(name="GL")] extern { } pub type GLenum = libc::c_uint; pub type GLint = libc::c_int; pub static RED_BITS : GLenum = 0x0D52; pub static GREEN_BITS : GLenum = 0x0D53; pub static BLUE_BITS : GLenum = 0x0D54; pub static ALPHA_BITS : GLenum = 0x0D55; pub static DEPTH_BITS : GLenum = 0x0D56; pub static STENCIL_BITS : GLenum = 0x0D57; pub static ACCUM_RED_BITS : GLenum = 0x0D58; pub static ACCUM_GREEN_BITS : GLenum = 0x0D59; pub static ACCUM_BLUE_BITS : GLenum = 0x0D5A; pub static ACCUM_ALPHA_BITS : GLenum = 0x0D5B; pub static STEREO : GLenum = 0x0C33; pub static SAMPLES_ARB : GLenum = 0x80A9; #[inline(never)] pub unsafe fn GetIntegerv(pname: GLenum, params: *GLint) { glGetIntegerv(pname, params) } extern "C" { fn glGetIntegerv(pname: GLenum, params: *GLint); } }
start
identifier_name
main.rs
extern crate hkg; extern crate termion; extern crate rustc_serialize; extern crate kuchiki; extern crate chrono; extern crate cancellation; extern crate crossbeam; #[macro_use] extern crate log; extern crate log4rs; use std::io::{stdout, stdin, Write}; use std::io::{self, Read}; use std::sync::mpsc::channel; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, Ordering}; use rustc_serialize::json; use termion::input::TermRead; use termion::raw::IntoRawMode; use hkg::status::*; use hkg::model::IconItem; use hkg::state_manager::*; use hkg::screen_manager::*; use hkg::resources::*; use hkg::web::*; use hkg::responser::*; use std::thread; fn main() { // Initialize log4rs::init_file("config/log4rs.yaml", Default::default()).expect("fail to init log4rs"); info!("app start"); // Clear the screen. hkg::screen::common::clear_screen(); let _stdout = stdout(); // web background services let (tx_req, rx_req) = channel::<ChannelItem>(); let (tx_res, rx_res) = channel::<ChannelItem>(); let (tx_state, rx_state) = channel::<(Status,Status)>(); let working = Arc::new(AtomicBool::new(true)); let control = Arc::downgrade(&working); let mut app = { let stdout = { Box::new(_stdout.lock().into_raw_mode().expect("fail to lock stdout")) }; let icon_collection: Box<Vec<IconItem>> = { let icon_manifest_string = hkg::utility::readfile(String::from("data/icon.manifest.json")); Box::new(json::decode(&icon_manifest_string).expect("fail to lock stdout")) }; hkg::App { index_builder: hkg::builders::index::Index::new(), show_builder: hkg::builders::show::Show::new(), state_manager: StateManager::new(tx_state), screen_manager: ScreenManager::new(), // initialize empty page list_topic_items: Default::default(), show_item: Default::default(), status_bar: hkg::screen::status_bar::StatusBar::new(), index: hkg::screen::index::Index::new(), show: hkg::screen::show::Show::new(icon_collection), image_request_count_lock: Arc::new(Mutex::new(0)), tx_req: &tx_req, rx_res: &rx_res, stdout: stdout, } }; Requester::new(rx_req, tx_res, working.clone()); let respsoner = Responser::new(); let mut index_control = hkg::control::index::Index::new(); let mut show_control = hkg::control::show::Show::new(); // topics request let status_message = list_page(&mut app.state_manager, &tx_req); app.status_bar.append(&app.screen_manager, &status_message); let (tx_in, rx_in) = channel::<::termion::event::Key>(); let working1 = working.clone(); let working2 = working.clone(); thread::spawn(move || { while (*working1).load(Ordering::Relaxed) { let stdin = stdin(); for c in stdin.keys() { // println!("{:?}", c); tx_in.send(c.ok().unwrap()).unwrap(); } } }); while (*working2).load(Ordering::Relaxed) { respsoner.try_recv(&mut app); match rx_in.try_recv() { Ok(c) => { info!("receive input: {:?}", c); info!("current state: {:?}", app.state_manager.get_state() ); match app.state_manager.get_state() { Status::Startup => {} Status::List => { match index_control.handle(c, &mut app) { Some(i) => { if i == 0 { match control.upgrade() { Some(working) => (*working).store(false, Ordering::Relaxed), None => {} } } else { print_screen(&mut app); } } None => error!("index_control handle receive none.") } } Status::Show => { match show_control.handle(c, &mut app) { Some(i) => { if i == 0 { match control.upgrade() { Some(working) => (*working).store(false, Ordering::Relaxed), None => {} } } else { print_screen(&mut app); } } None => error!("show_control handle receive none.") } } } } Err(e) => {} }; if app.state_manager.is_to_print_screen() { print_screen(&mut app); app.state_manager.set_to_print_screen(false); } if app.screen_manager.is_width_changed() || app.screen_manager.is_height_changed() { hkg::screen::common::clear_screen(); print_screen(&mut app); } thread::sleep(std::time::Duration::from_millis(50)); } } fn list_page(state_manager: &mut StateManager, tx_req: &Sender<ChannelItem>) -> String { let ci = ChannelItem { extra: Some(ChannelItemType::Index(Default::default())), result: Default::default() }; let status_message = match tx_req.send(ci) { Ok(()) => { state_manager.set_web_request(true); // *is_web_requesting = true; "SOK".to_string() } Err(e) => format!("{}:{}", "SFAIL", e).to_string(), }; status_message } fn print_screen(app: &mut hkg::App) { match app.state_manager.get_state() { Status::Startup => {} Status::List => { app.index.print(&mut app.stdout, &app.list_topic_items); } Status::Show => { app.show.print(&mut app.stdout, &app.show_item); } } app.status_bar.print(&app.screen_manager);
app.stdout.flush().expect("fail to flush the stdout"); }
random_line_split
main.rs
extern crate hkg; extern crate termion; extern crate rustc_serialize; extern crate kuchiki; extern crate chrono; extern crate cancellation; extern crate crossbeam; #[macro_use] extern crate log; extern crate log4rs; use std::io::{stdout, stdin, Write}; use std::io::{self, Read}; use std::sync::mpsc::channel; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, Ordering}; use rustc_serialize::json; use termion::input::TermRead; use termion::raw::IntoRawMode; use hkg::status::*; use hkg::model::IconItem; use hkg::state_manager::*; use hkg::screen_manager::*; use hkg::resources::*; use hkg::web::*; use hkg::responser::*; use std::thread; fn main()
let mut app = { let stdout = { Box::new(_stdout.lock().into_raw_mode().expect("fail to lock stdout")) }; let icon_collection: Box<Vec<IconItem>> = { let icon_manifest_string = hkg::utility::readfile(String::from("data/icon.manifest.json")); Box::new(json::decode(&icon_manifest_string).expect("fail to lock stdout")) }; hkg::App { index_builder: hkg::builders::index::Index::new(), show_builder: hkg::builders::show::Show::new(), state_manager: StateManager::new(tx_state), screen_manager: ScreenManager::new(), // initialize empty page list_topic_items: Default::default(), show_item: Default::default(), status_bar: hkg::screen::status_bar::StatusBar::new(), index: hkg::screen::index::Index::new(), show: hkg::screen::show::Show::new(icon_collection), image_request_count_lock: Arc::new(Mutex::new(0)), tx_req: &tx_req, rx_res: &rx_res, stdout: stdout, } }; Requester::new(rx_req, tx_res, working.clone()); let respsoner = Responser::new(); let mut index_control = hkg::control::index::Index::new(); let mut show_control = hkg::control::show::Show::new(); // topics request let status_message = list_page(&mut app.state_manager, &tx_req); app.status_bar.append(&app.screen_manager, &status_message); let (tx_in, rx_in) = channel::<::termion::event::Key>(); let working1 = working.clone(); let working2 = working.clone(); thread::spawn(move || { while (*working1).load(Ordering::Relaxed) { let stdin = stdin(); for c in stdin.keys() { // println!("{:?}", c); tx_in.send(c.ok().unwrap()).unwrap(); } } }); while (*working2).load(Ordering::Relaxed) { respsoner.try_recv(&mut app); match rx_in.try_recv() { Ok(c) => { info!("receive input: {:?}", c); info!("current state: {:?}", app.state_manager.get_state() ); match app.state_manager.get_state() { Status::Startup => {} Status::List => { match index_control.handle(c, &mut app) { Some(i) => { if i == 0 { match control.upgrade() { Some(working) => (*working).store(false, Ordering::Relaxed), None => {} } } else { print_screen(&mut app); } } None => error!("index_control handle receive none.") } } Status::Show => { match show_control.handle(c, &mut app) { Some(i) => { if i == 0 { match control.upgrade() { Some(working) => (*working).store(false, Ordering::Relaxed), None => {} } } else { print_screen(&mut app); } } None => error!("show_control handle receive none.") } } } } Err(e) => {} }; if app.state_manager.is_to_print_screen() { print_screen(&mut app); app.state_manager.set_to_print_screen(false); } if app.screen_manager.is_width_changed() || app.screen_manager.is_height_changed() { hkg::screen::common::clear_screen(); print_screen(&mut app); } thread::sleep(std::time::Duration::from_millis(50)); } } fn list_page(state_manager: &mut StateManager, tx_req: &Sender<ChannelItem>) -> String { let ci = ChannelItem { extra: Some(ChannelItemType::Index(Default::default())), result: Default::default() }; let status_message = match tx_req.send(ci) { Ok(()) => { state_manager.set_web_request(true); // *is_web_requesting = true; "SOK".to_string() } Err(e) => format!("{}:{}", "SFAIL", e).to_string(), }; status_message } fn print_screen(app: &mut hkg::App) { match app.state_manager.get_state() { Status::Startup => {} Status::List => { app.index.print(&mut app.stdout, &app.list_topic_items); } Status::Show => { app.show.print(&mut app.stdout, &app.show_item); } } app.status_bar.print(&app.screen_manager); app.stdout.flush().expect("fail to flush the stdout"); }
{ // Initialize log4rs::init_file("config/log4rs.yaml", Default::default()).expect("fail to init log4rs"); info!("app start"); // Clear the screen. hkg::screen::common::clear_screen(); let _stdout = stdout(); // web background services let (tx_req, rx_req) = channel::<ChannelItem>(); let (tx_res, rx_res) = channel::<ChannelItem>(); let (tx_state, rx_state) = channel::<(Status,Status)>(); let working = Arc::new(AtomicBool::new(true)); let control = Arc::downgrade(&working);
identifier_body
main.rs
extern crate hkg; extern crate termion; extern crate rustc_serialize; extern crate kuchiki; extern crate chrono; extern crate cancellation; extern crate crossbeam; #[macro_use] extern crate log; extern crate log4rs; use std::io::{stdout, stdin, Write}; use std::io::{self, Read}; use std::sync::mpsc::channel; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, Ordering}; use rustc_serialize::json; use termion::input::TermRead; use termion::raw::IntoRawMode; use hkg::status::*; use hkg::model::IconItem; use hkg::state_manager::*; use hkg::screen_manager::*; use hkg::resources::*; use hkg::web::*; use hkg::responser::*; use std::thread; fn main() { // Initialize log4rs::init_file("config/log4rs.yaml", Default::default()).expect("fail to init log4rs"); info!("app start"); // Clear the screen. hkg::screen::common::clear_screen(); let _stdout = stdout(); // web background services let (tx_req, rx_req) = channel::<ChannelItem>(); let (tx_res, rx_res) = channel::<ChannelItem>(); let (tx_state, rx_state) = channel::<(Status,Status)>(); let working = Arc::new(AtomicBool::new(true)); let control = Arc::downgrade(&working); let mut app = { let stdout = { Box::new(_stdout.lock().into_raw_mode().expect("fail to lock stdout")) }; let icon_collection: Box<Vec<IconItem>> = { let icon_manifest_string = hkg::utility::readfile(String::from("data/icon.manifest.json")); Box::new(json::decode(&icon_manifest_string).expect("fail to lock stdout")) }; hkg::App { index_builder: hkg::builders::index::Index::new(), show_builder: hkg::builders::show::Show::new(), state_manager: StateManager::new(tx_state), screen_manager: ScreenManager::new(), // initialize empty page list_topic_items: Default::default(), show_item: Default::default(), status_bar: hkg::screen::status_bar::StatusBar::new(), index: hkg::screen::index::Index::new(), show: hkg::screen::show::Show::new(icon_collection), image_request_count_lock: Arc::new(Mutex::new(0)), tx_req: &tx_req, rx_res: &rx_res, stdout: stdout, } }; Requester::new(rx_req, tx_res, working.clone()); let respsoner = Responser::new(); let mut index_control = hkg::control::index::Index::new(); let mut show_control = hkg::control::show::Show::new(); // topics request let status_message = list_page(&mut app.state_manager, &tx_req); app.status_bar.append(&app.screen_manager, &status_message); let (tx_in, rx_in) = channel::<::termion::event::Key>(); let working1 = working.clone(); let working2 = working.clone(); thread::spawn(move || { while (*working1).load(Ordering::Relaxed) { let stdin = stdin(); for c in stdin.keys() { // println!("{:?}", c); tx_in.send(c.ok().unwrap()).unwrap(); } } }); while (*working2).load(Ordering::Relaxed) { respsoner.try_recv(&mut app); match rx_in.try_recv() { Ok(c) => { info!("receive input: {:?}", c); info!("current state: {:?}", app.state_manager.get_state() ); match app.state_manager.get_state() { Status::Startup => {} Status::List => { match index_control.handle(c, &mut app) { Some(i) => { if i == 0 { match control.upgrade() { Some(working) => (*working).store(false, Ordering::Relaxed), None => {} } } else { print_screen(&mut app); } } None => error!("index_control handle receive none.") } } Status::Show => { match show_control.handle(c, &mut app) { Some(i) => { if i == 0 { match control.upgrade() { Some(working) => (*working).store(false, Ordering::Relaxed), None => {} } } else { print_screen(&mut app); } } None => error!("show_control handle receive none.") } } } } Err(e) => {} }; if app.state_manager.is_to_print_screen() { print_screen(&mut app); app.state_manager.set_to_print_screen(false); } if app.screen_manager.is_width_changed() || app.screen_manager.is_height_changed() { hkg::screen::common::clear_screen(); print_screen(&mut app); } thread::sleep(std::time::Duration::from_millis(50)); } } fn
(state_manager: &mut StateManager, tx_req: &Sender<ChannelItem>) -> String { let ci = ChannelItem { extra: Some(ChannelItemType::Index(Default::default())), result: Default::default() }; let status_message = match tx_req.send(ci) { Ok(()) => { state_manager.set_web_request(true); // *is_web_requesting = true; "SOK".to_string() } Err(e) => format!("{}:{}", "SFAIL", e).to_string(), }; status_message } fn print_screen(app: &mut hkg::App) { match app.state_manager.get_state() { Status::Startup => {} Status::List => { app.index.print(&mut app.stdout, &app.list_topic_items); } Status::Show => { app.show.print(&mut app.stdout, &app.show_item); } } app.status_bar.print(&app.screen_manager); app.stdout.flush().expect("fail to flush the stdout"); }
list_page
identifier_name
traits.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::collections::BTreeMap; use util::{U256, Address, H256, H2048, Bytes, Itertools}; use blockchain::TreeRoute; use verification::queue::QueueInfo as BlockQueueInfo; use block::{OpenBlock, SealedBlock}; use header::{BlockNumber}; use transaction::{LocalizedTransaction, SignedTransaction}; use log_entry::LocalizedLogEntry; use filter::Filter; use views::{BlockView}; use error::{ImportResult, CallError}; use receipt::LocalizedReceipt; use trace::LocalizedTrace; use evm::Factory as EvmFactory; use types::ids::*; use types::trace_filter::Filter as TraceFilter; use executive::Executed; use env_info::LastHashes; use types::call_analytics::CallAnalytics; use block_import_error::BlockImportError; use ipc::IpcConfig; use types::blockchain_info::BlockChainInfo; use types::block_status::BlockStatus; #[ipc(client_ident="RemoteClient")] /// Blockchain database client. Owns and manages a blockchain and a block queue. pub trait BlockChainClient : Sync + Send { /// Should be called by any external-facing interface when actively using the client. /// To minimise chatter, there's no need to call more than once every 30s. fn keep_alive(&self) {} /// Get raw block header data by block id. fn block_header(&self, id: BlockID) -> Option<Bytes>; /// Get raw block body data by block id. /// Block body is an RLP list of two items: uncles and transactions. fn block_body(&self, id: BlockID) -> Option<Bytes>; /// Get raw block data by block header hash. fn block(&self, id: BlockID) -> Option<Bytes>; /// Get block status by block header hash. fn block_status(&self, id: BlockID) -> BlockStatus; /// Get block total difficulty. fn block_total_difficulty(&self, id: BlockID) -> Option<U256>; /// Attempt to get address nonce at given block. /// May not fail on BlockID::Latest. fn nonce(&self, address: &Address, id: BlockID) -> Option<U256>; /// Get address nonce at the latest block's state. fn latest_nonce(&self, address: &Address) -> U256 { self.nonce(address, BlockID::Latest) .expect("nonce will return Some when given BlockID::Latest. nonce was given BlockID::Latest. \ Therefore nonce has returned Some; qed") } /// Get block hash. fn block_hash(&self, id: BlockID) -> Option<H256>; /// Get address code at given block's state. fn code(&self, address: &Address, id: BlockID) -> Option<Option<Bytes>>; /// Get address code at the latest block's state. fn latest_code(&self, address: &Address) -> Option<Bytes> { self.code(address, BlockID::Latest) .expect("code will return Some if given BlockID::Latest; qed") } /// Get address balance at the given block's state. /// /// May not return None if given BlockID::Latest. /// Returns None if and only if the block's root hash has been pruned from the DB. fn balance(&self, address: &Address, id: BlockID) -> Option<U256>; /// Get address balance at the latest block's state. fn latest_balance(&self, address: &Address) -> U256 { self.balance(address, BlockID::Latest) .expect("balance will return Some if given BlockID::Latest. balance was given BlockID::Latest \ Therefore balance has returned Some; qed") } /// Get value of the storage at given position at the given block's state. /// /// May not return None if given BlockID::Latest. /// Returns None if and only if the block's root hash has been pruned from the DB. fn storage_at(&self, address: &Address, position: &H256, id: BlockID) -> Option<H256>; /// Get value of the storage at given position at the latest block's state. fn latest_storage_at(&self, address: &Address, position: &H256) -> H256 { self.storage_at(address, position, BlockID::Latest) .expect("storage_at will return Some if given BlockID::Latest. storage_at was given BlockID::Latest. \ Therefore storage_at has returned Some; qed") } /// Get a list of all accounts in the block `id`, if fat DB is in operation, otherwise `None`. fn list_accounts(&self, id: BlockID) -> Option<Vec<Address>>; /// Get transaction with given hash. fn transaction(&self, id: TransactionID) -> Option<LocalizedTransaction>; /// Get uncle with given id. fn uncle(&self, id: UncleID) -> Option<Bytes>; /// Get transaction receipt with given hash. fn transaction_receipt(&self, id: TransactionID) -> Option<LocalizedReceipt>; /// Get a tree route between `from` and `to`. /// See `BlockChain::tree_route`. fn tree_route(&self, from: &H256, to: &H256) -> Option<TreeRoute>; /// Get all possible uncle hashes for a block. fn find_uncles(&self, hash: &H256) -> Option<Vec<H256>>; /// Get latest state node fn state_data(&self, hash: &H256) -> Option<Bytes>; /// Get raw block receipts data by block header hash. fn block_receipts(&self, hash: &H256) -> Option<Bytes>; /// Import a block into the blockchain. fn import_block(&self, bytes: Bytes) -> Result<H256, BlockImportError>; /// Import a block with transaction receipts. Does no sealing and transaction validation. fn import_block_with_receipts(&self, block_bytes: Bytes, receipts_bytes: Bytes) -> Result<H256, BlockImportError>; /// Get block queue information. fn queue_info(&self) -> BlockQueueInfo; /// Clear block queue and abort all import activity. fn clear_queue(&self); /// Get blockchain information. fn chain_info(&self) -> BlockChainInfo; /// Get the registrar address, if it exists. fn additional_params(&self) -> BTreeMap<String, String>; /// Get the best block header. fn best_block_header(&self) -> Bytes; /// Returns numbers of blocks containing given bloom. fn blocks_with_bloom(&self, bloom: &H2048, from_block: BlockID, to_block: BlockID) -> Option<Vec<BlockNumber>>; /// Returns logs matching given filter. fn logs(&self, filter: Filter) -> Vec<LocalizedLogEntry>; /// Makes a non-persistent transaction call. fn call(&self, t: &SignedTransaction, block: BlockID, analytics: CallAnalytics) -> Result<Executed, CallError>; /// Replays a given transaction for inspection. fn replay(&self, t: TransactionID, analytics: CallAnalytics) -> Result<Executed, CallError>; /// Returns traces matching given filter. fn filter_traces(&self, filter: TraceFilter) -> Option<Vec<LocalizedTrace>>; /// Returns trace with given id. fn trace(&self, trace: TraceId) -> Option<LocalizedTrace>; /// Returns traces created by transaction. fn transaction_traces(&self, trace: TransactionID) -> Option<Vec<LocalizedTrace>>; /// Returns traces created by transaction from block. fn block_traces(&self, trace: BlockID) -> Option<Vec<LocalizedTrace>>; /// Get last hashes starting from best block. fn last_hashes(&self) -> LastHashes; /// Queue transactions for importing. fn queue_transactions(&self, transactions: Vec<Bytes>); /// list all transactions fn pending_transactions(&self) -> Vec<SignedTransaction>; /// Get the gas price distribution. fn gas_price_statistics(&self, sample_size: usize, distribution_size: usize) -> Result<Vec<U256>, ()> { let mut h = self.chain_info().best_block_hash; let mut corpus = Vec::new(); while corpus.is_empty() { for _ in 0..sample_size { let block_bytes = self.block(BlockID::Hash(h)).expect("h is either the best_block_hash or an ancestor; qed"); let block = BlockView::new(&block_bytes); let header = block.header_view(); if header.number() == 0 {
block.transaction_views().iter().foreach(|t| corpus.push(t.gas_price())); h = header.parent_hash().clone(); } } corpus.sort(); let n = corpus.len(); if n > 0 { Ok((0..(distribution_size + 1)) .map(|i| corpus[i * (n - 1) / distribution_size]) .collect::<Vec<_>>() ) } else { Err(()) } } } /// Extended client interface used for mining pub trait MiningBlockChainClient : BlockChainClient { /// Returns OpenBlock prepared for closing. fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes ) -> OpenBlock; /// Returns EvmFactory. fn vm_factory(&self) -> &EvmFactory; /// Import sealed block. Skips all verifications. fn import_sealed_block(&self, block: SealedBlock) -> ImportResult; } impl IpcConfig for BlockChainClient { }
if corpus.is_empty() { corpus.push(20_000_000_000u64.into()); // we have literally no information - it' as good a number as any. } break; }
random_line_split
traits.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::collections::BTreeMap; use util::{U256, Address, H256, H2048, Bytes, Itertools}; use blockchain::TreeRoute; use verification::queue::QueueInfo as BlockQueueInfo; use block::{OpenBlock, SealedBlock}; use header::{BlockNumber}; use transaction::{LocalizedTransaction, SignedTransaction}; use log_entry::LocalizedLogEntry; use filter::Filter; use views::{BlockView}; use error::{ImportResult, CallError}; use receipt::LocalizedReceipt; use trace::LocalizedTrace; use evm::Factory as EvmFactory; use types::ids::*; use types::trace_filter::Filter as TraceFilter; use executive::Executed; use env_info::LastHashes; use types::call_analytics::CallAnalytics; use block_import_error::BlockImportError; use ipc::IpcConfig; use types::blockchain_info::BlockChainInfo; use types::block_status::BlockStatus; #[ipc(client_ident="RemoteClient")] /// Blockchain database client. Owns and manages a blockchain and a block queue. pub trait BlockChainClient : Sync + Send { /// Should be called by any external-facing interface when actively using the client. /// To minimise chatter, there's no need to call more than once every 30s. fn keep_alive(&self) {} /// Get raw block header data by block id. fn block_header(&self, id: BlockID) -> Option<Bytes>; /// Get raw block body data by block id. /// Block body is an RLP list of two items: uncles and transactions. fn block_body(&self, id: BlockID) -> Option<Bytes>; /// Get raw block data by block header hash. fn block(&self, id: BlockID) -> Option<Bytes>; /// Get block status by block header hash. fn block_status(&self, id: BlockID) -> BlockStatus; /// Get block total difficulty. fn block_total_difficulty(&self, id: BlockID) -> Option<U256>; /// Attempt to get address nonce at given block. /// May not fail on BlockID::Latest. fn nonce(&self, address: &Address, id: BlockID) -> Option<U256>; /// Get address nonce at the latest block's state. fn latest_nonce(&self, address: &Address) -> U256 { self.nonce(address, BlockID::Latest) .expect("nonce will return Some when given BlockID::Latest. nonce was given BlockID::Latest. \ Therefore nonce has returned Some; qed") } /// Get block hash. fn block_hash(&self, id: BlockID) -> Option<H256>; /// Get address code at given block's state. fn code(&self, address: &Address, id: BlockID) -> Option<Option<Bytes>>; /// Get address code at the latest block's state. fn latest_code(&self, address: &Address) -> Option<Bytes> { self.code(address, BlockID::Latest) .expect("code will return Some if given BlockID::Latest; qed") } /// Get address balance at the given block's state. /// /// May not return None if given BlockID::Latest. /// Returns None if and only if the block's root hash has been pruned from the DB. fn balance(&self, address: &Address, id: BlockID) -> Option<U256>; /// Get address balance at the latest block's state. fn latest_balance(&self, address: &Address) -> U256 { self.balance(address, BlockID::Latest) .expect("balance will return Some if given BlockID::Latest. balance was given BlockID::Latest \ Therefore balance has returned Some; qed") } /// Get value of the storage at given position at the given block's state. /// /// May not return None if given BlockID::Latest. /// Returns None if and only if the block's root hash has been pruned from the DB. fn storage_at(&self, address: &Address, position: &H256, id: BlockID) -> Option<H256>; /// Get value of the storage at given position at the latest block's state. fn latest_storage_at(&self, address: &Address, position: &H256) -> H256 { self.storage_at(address, position, BlockID::Latest) .expect("storage_at will return Some if given BlockID::Latest. storage_at was given BlockID::Latest. \ Therefore storage_at has returned Some; qed") } /// Get a list of all accounts in the block `id`, if fat DB is in operation, otherwise `None`. fn list_accounts(&self, id: BlockID) -> Option<Vec<Address>>; /// Get transaction with given hash. fn transaction(&self, id: TransactionID) -> Option<LocalizedTransaction>; /// Get uncle with given id. fn uncle(&self, id: UncleID) -> Option<Bytes>; /// Get transaction receipt with given hash. fn transaction_receipt(&self, id: TransactionID) -> Option<LocalizedReceipt>; /// Get a tree route between `from` and `to`. /// See `BlockChain::tree_route`. fn tree_route(&self, from: &H256, to: &H256) -> Option<TreeRoute>; /// Get all possible uncle hashes for a block. fn find_uncles(&self, hash: &H256) -> Option<Vec<H256>>; /// Get latest state node fn state_data(&self, hash: &H256) -> Option<Bytes>; /// Get raw block receipts data by block header hash. fn block_receipts(&self, hash: &H256) -> Option<Bytes>; /// Import a block into the blockchain. fn import_block(&self, bytes: Bytes) -> Result<H256, BlockImportError>; /// Import a block with transaction receipts. Does no sealing and transaction validation. fn import_block_with_receipts(&self, block_bytes: Bytes, receipts_bytes: Bytes) -> Result<H256, BlockImportError>; /// Get block queue information. fn queue_info(&self) -> BlockQueueInfo; /// Clear block queue and abort all import activity. fn clear_queue(&self); /// Get blockchain information. fn chain_info(&self) -> BlockChainInfo; /// Get the registrar address, if it exists. fn additional_params(&self) -> BTreeMap<String, String>; /// Get the best block header. fn best_block_header(&self) -> Bytes; /// Returns numbers of blocks containing given bloom. fn blocks_with_bloom(&self, bloom: &H2048, from_block: BlockID, to_block: BlockID) -> Option<Vec<BlockNumber>>; /// Returns logs matching given filter. fn logs(&self, filter: Filter) -> Vec<LocalizedLogEntry>; /// Makes a non-persistent transaction call. fn call(&self, t: &SignedTransaction, block: BlockID, analytics: CallAnalytics) -> Result<Executed, CallError>; /// Replays a given transaction for inspection. fn replay(&self, t: TransactionID, analytics: CallAnalytics) -> Result<Executed, CallError>; /// Returns traces matching given filter. fn filter_traces(&self, filter: TraceFilter) -> Option<Vec<LocalizedTrace>>; /// Returns trace with given id. fn trace(&self, trace: TraceId) -> Option<LocalizedTrace>; /// Returns traces created by transaction. fn transaction_traces(&self, trace: TransactionID) -> Option<Vec<LocalizedTrace>>; /// Returns traces created by transaction from block. fn block_traces(&self, trace: BlockID) -> Option<Vec<LocalizedTrace>>; /// Get last hashes starting from best block. fn last_hashes(&self) -> LastHashes; /// Queue transactions for importing. fn queue_transactions(&self, transactions: Vec<Bytes>); /// list all transactions fn pending_transactions(&self) -> Vec<SignedTransaction>; /// Get the gas price distribution. fn gas_price_statistics(&self, sample_size: usize, distribution_size: usize) -> Result<Vec<U256>, ()> { let mut h = self.chain_info().best_block_hash; let mut corpus = Vec::new(); while corpus.is_empty() { for _ in 0..sample_size { let block_bytes = self.block(BlockID::Hash(h)).expect("h is either the best_block_hash or an ancestor; qed"); let block = BlockView::new(&block_bytes); let header = block.header_view(); if header.number() == 0
block.transaction_views().iter().foreach(|t| corpus.push(t.gas_price())); h = header.parent_hash().clone(); } } corpus.sort(); let n = corpus.len(); if n > 0 { Ok((0..(distribution_size + 1)) .map(|i| corpus[i * (n - 1) / distribution_size]) .collect::<Vec<_>>() ) } else { Err(()) } } } /// Extended client interface used for mining pub trait MiningBlockChainClient : BlockChainClient { /// Returns OpenBlock prepared for closing. fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes ) -> OpenBlock; /// Returns EvmFactory. fn vm_factory(&self) -> &EvmFactory; /// Import sealed block. Skips all verifications. fn import_sealed_block(&self, block: SealedBlock) -> ImportResult; } impl IpcConfig for BlockChainClient { }
{ if corpus.is_empty() { corpus.push(20_000_000_000u64.into()); // we have literally no information - it' as good a number as any. } break; }
conditional_block
traits.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::collections::BTreeMap; use util::{U256, Address, H256, H2048, Bytes, Itertools}; use blockchain::TreeRoute; use verification::queue::QueueInfo as BlockQueueInfo; use block::{OpenBlock, SealedBlock}; use header::{BlockNumber}; use transaction::{LocalizedTransaction, SignedTransaction}; use log_entry::LocalizedLogEntry; use filter::Filter; use views::{BlockView}; use error::{ImportResult, CallError}; use receipt::LocalizedReceipt; use trace::LocalizedTrace; use evm::Factory as EvmFactory; use types::ids::*; use types::trace_filter::Filter as TraceFilter; use executive::Executed; use env_info::LastHashes; use types::call_analytics::CallAnalytics; use block_import_error::BlockImportError; use ipc::IpcConfig; use types::blockchain_info::BlockChainInfo; use types::block_status::BlockStatus; #[ipc(client_ident="RemoteClient")] /// Blockchain database client. Owns and manages a blockchain and a block queue. pub trait BlockChainClient : Sync + Send { /// Should be called by any external-facing interface when actively using the client. /// To minimise chatter, there's no need to call more than once every 30s. fn keep_alive(&self) {} /// Get raw block header data by block id. fn block_header(&self, id: BlockID) -> Option<Bytes>; /// Get raw block body data by block id. /// Block body is an RLP list of two items: uncles and transactions. fn block_body(&self, id: BlockID) -> Option<Bytes>; /// Get raw block data by block header hash. fn block(&self, id: BlockID) -> Option<Bytes>; /// Get block status by block header hash. fn block_status(&self, id: BlockID) -> BlockStatus; /// Get block total difficulty. fn block_total_difficulty(&self, id: BlockID) -> Option<U256>; /// Attempt to get address nonce at given block. /// May not fail on BlockID::Latest. fn nonce(&self, address: &Address, id: BlockID) -> Option<U256>; /// Get address nonce at the latest block's state. fn latest_nonce(&self, address: &Address) -> U256 { self.nonce(address, BlockID::Latest) .expect("nonce will return Some when given BlockID::Latest. nonce was given BlockID::Latest. \ Therefore nonce has returned Some; qed") } /// Get block hash. fn block_hash(&self, id: BlockID) -> Option<H256>; /// Get address code at given block's state. fn code(&self, address: &Address, id: BlockID) -> Option<Option<Bytes>>; /// Get address code at the latest block's state. fn latest_code(&self, address: &Address) -> Option<Bytes>
/// Get address balance at the given block's state. /// /// May not return None if given BlockID::Latest. /// Returns None if and only if the block's root hash has been pruned from the DB. fn balance(&self, address: &Address, id: BlockID) -> Option<U256>; /// Get address balance at the latest block's state. fn latest_balance(&self, address: &Address) -> U256 { self.balance(address, BlockID::Latest) .expect("balance will return Some if given BlockID::Latest. balance was given BlockID::Latest \ Therefore balance has returned Some; qed") } /// Get value of the storage at given position at the given block's state. /// /// May not return None if given BlockID::Latest. /// Returns None if and only if the block's root hash has been pruned from the DB. fn storage_at(&self, address: &Address, position: &H256, id: BlockID) -> Option<H256>; /// Get value of the storage at given position at the latest block's state. fn latest_storage_at(&self, address: &Address, position: &H256) -> H256 { self.storage_at(address, position, BlockID::Latest) .expect("storage_at will return Some if given BlockID::Latest. storage_at was given BlockID::Latest. \ Therefore storage_at has returned Some; qed") } /// Get a list of all accounts in the block `id`, if fat DB is in operation, otherwise `None`. fn list_accounts(&self, id: BlockID) -> Option<Vec<Address>>; /// Get transaction with given hash. fn transaction(&self, id: TransactionID) -> Option<LocalizedTransaction>; /// Get uncle with given id. fn uncle(&self, id: UncleID) -> Option<Bytes>; /// Get transaction receipt with given hash. fn transaction_receipt(&self, id: TransactionID) -> Option<LocalizedReceipt>; /// Get a tree route between `from` and `to`. /// See `BlockChain::tree_route`. fn tree_route(&self, from: &H256, to: &H256) -> Option<TreeRoute>; /// Get all possible uncle hashes for a block. fn find_uncles(&self, hash: &H256) -> Option<Vec<H256>>; /// Get latest state node fn state_data(&self, hash: &H256) -> Option<Bytes>; /// Get raw block receipts data by block header hash. fn block_receipts(&self, hash: &H256) -> Option<Bytes>; /// Import a block into the blockchain. fn import_block(&self, bytes: Bytes) -> Result<H256, BlockImportError>; /// Import a block with transaction receipts. Does no sealing and transaction validation. fn import_block_with_receipts(&self, block_bytes: Bytes, receipts_bytes: Bytes) -> Result<H256, BlockImportError>; /// Get block queue information. fn queue_info(&self) -> BlockQueueInfo; /// Clear block queue and abort all import activity. fn clear_queue(&self); /// Get blockchain information. fn chain_info(&self) -> BlockChainInfo; /// Get the registrar address, if it exists. fn additional_params(&self) -> BTreeMap<String, String>; /// Get the best block header. fn best_block_header(&self) -> Bytes; /// Returns numbers of blocks containing given bloom. fn blocks_with_bloom(&self, bloom: &H2048, from_block: BlockID, to_block: BlockID) -> Option<Vec<BlockNumber>>; /// Returns logs matching given filter. fn logs(&self, filter: Filter) -> Vec<LocalizedLogEntry>; /// Makes a non-persistent transaction call. fn call(&self, t: &SignedTransaction, block: BlockID, analytics: CallAnalytics) -> Result<Executed, CallError>; /// Replays a given transaction for inspection. fn replay(&self, t: TransactionID, analytics: CallAnalytics) -> Result<Executed, CallError>; /// Returns traces matching given filter. fn filter_traces(&self, filter: TraceFilter) -> Option<Vec<LocalizedTrace>>; /// Returns trace with given id. fn trace(&self, trace: TraceId) -> Option<LocalizedTrace>; /// Returns traces created by transaction. fn transaction_traces(&self, trace: TransactionID) -> Option<Vec<LocalizedTrace>>; /// Returns traces created by transaction from block. fn block_traces(&self, trace: BlockID) -> Option<Vec<LocalizedTrace>>; /// Get last hashes starting from best block. fn last_hashes(&self) -> LastHashes; /// Queue transactions for importing. fn queue_transactions(&self, transactions: Vec<Bytes>); /// list all transactions fn pending_transactions(&self) -> Vec<SignedTransaction>; /// Get the gas price distribution. fn gas_price_statistics(&self, sample_size: usize, distribution_size: usize) -> Result<Vec<U256>, ()> { let mut h = self.chain_info().best_block_hash; let mut corpus = Vec::new(); while corpus.is_empty() { for _ in 0..sample_size { let block_bytes = self.block(BlockID::Hash(h)).expect("h is either the best_block_hash or an ancestor; qed"); let block = BlockView::new(&block_bytes); let header = block.header_view(); if header.number() == 0 { if corpus.is_empty() { corpus.push(20_000_000_000u64.into()); // we have literally no information - it' as good a number as any. } break; } block.transaction_views().iter().foreach(|t| corpus.push(t.gas_price())); h = header.parent_hash().clone(); } } corpus.sort(); let n = corpus.len(); if n > 0 { Ok((0..(distribution_size + 1)) .map(|i| corpus[i * (n - 1) / distribution_size]) .collect::<Vec<_>>() ) } else { Err(()) } } } /// Extended client interface used for mining pub trait MiningBlockChainClient : BlockChainClient { /// Returns OpenBlock prepared for closing. fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes ) -> OpenBlock; /// Returns EvmFactory. fn vm_factory(&self) -> &EvmFactory; /// Import sealed block. Skips all verifications. fn import_sealed_block(&self, block: SealedBlock) -> ImportResult; } impl IpcConfig for BlockChainClient { }
{ self.code(address, BlockID::Latest) .expect("code will return Some if given BlockID::Latest; qed") }
identifier_body
traits.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::collections::BTreeMap; use util::{U256, Address, H256, H2048, Bytes, Itertools}; use blockchain::TreeRoute; use verification::queue::QueueInfo as BlockQueueInfo; use block::{OpenBlock, SealedBlock}; use header::{BlockNumber}; use transaction::{LocalizedTransaction, SignedTransaction}; use log_entry::LocalizedLogEntry; use filter::Filter; use views::{BlockView}; use error::{ImportResult, CallError}; use receipt::LocalizedReceipt; use trace::LocalizedTrace; use evm::Factory as EvmFactory; use types::ids::*; use types::trace_filter::Filter as TraceFilter; use executive::Executed; use env_info::LastHashes; use types::call_analytics::CallAnalytics; use block_import_error::BlockImportError; use ipc::IpcConfig; use types::blockchain_info::BlockChainInfo; use types::block_status::BlockStatus; #[ipc(client_ident="RemoteClient")] /// Blockchain database client. Owns and manages a blockchain and a block queue. pub trait BlockChainClient : Sync + Send { /// Should be called by any external-facing interface when actively using the client. /// To minimise chatter, there's no need to call more than once every 30s. fn keep_alive(&self) {} /// Get raw block header data by block id. fn block_header(&self, id: BlockID) -> Option<Bytes>; /// Get raw block body data by block id. /// Block body is an RLP list of two items: uncles and transactions. fn block_body(&self, id: BlockID) -> Option<Bytes>; /// Get raw block data by block header hash. fn block(&self, id: BlockID) -> Option<Bytes>; /// Get block status by block header hash. fn block_status(&self, id: BlockID) -> BlockStatus; /// Get block total difficulty. fn block_total_difficulty(&self, id: BlockID) -> Option<U256>; /// Attempt to get address nonce at given block. /// May not fail on BlockID::Latest. fn nonce(&self, address: &Address, id: BlockID) -> Option<U256>; /// Get address nonce at the latest block's state. fn latest_nonce(&self, address: &Address) -> U256 { self.nonce(address, BlockID::Latest) .expect("nonce will return Some when given BlockID::Latest. nonce was given BlockID::Latest. \ Therefore nonce has returned Some; qed") } /// Get block hash. fn block_hash(&self, id: BlockID) -> Option<H256>; /// Get address code at given block's state. fn code(&self, address: &Address, id: BlockID) -> Option<Option<Bytes>>; /// Get address code at the latest block's state. fn latest_code(&self, address: &Address) -> Option<Bytes> { self.code(address, BlockID::Latest) .expect("code will return Some if given BlockID::Latest; qed") } /// Get address balance at the given block's state. /// /// May not return None if given BlockID::Latest. /// Returns None if and only if the block's root hash has been pruned from the DB. fn balance(&self, address: &Address, id: BlockID) -> Option<U256>; /// Get address balance at the latest block's state. fn latest_balance(&self, address: &Address) -> U256 { self.balance(address, BlockID::Latest) .expect("balance will return Some if given BlockID::Latest. balance was given BlockID::Latest \ Therefore balance has returned Some; qed") } /// Get value of the storage at given position at the given block's state. /// /// May not return None if given BlockID::Latest. /// Returns None if and only if the block's root hash has been pruned from the DB. fn storage_at(&self, address: &Address, position: &H256, id: BlockID) -> Option<H256>; /// Get value of the storage at given position at the latest block's state. fn
(&self, address: &Address, position: &H256) -> H256 { self.storage_at(address, position, BlockID::Latest) .expect("storage_at will return Some if given BlockID::Latest. storage_at was given BlockID::Latest. \ Therefore storage_at has returned Some; qed") } /// Get a list of all accounts in the block `id`, if fat DB is in operation, otherwise `None`. fn list_accounts(&self, id: BlockID) -> Option<Vec<Address>>; /// Get transaction with given hash. fn transaction(&self, id: TransactionID) -> Option<LocalizedTransaction>; /// Get uncle with given id. fn uncle(&self, id: UncleID) -> Option<Bytes>; /// Get transaction receipt with given hash. fn transaction_receipt(&self, id: TransactionID) -> Option<LocalizedReceipt>; /// Get a tree route between `from` and `to`. /// See `BlockChain::tree_route`. fn tree_route(&self, from: &H256, to: &H256) -> Option<TreeRoute>; /// Get all possible uncle hashes for a block. fn find_uncles(&self, hash: &H256) -> Option<Vec<H256>>; /// Get latest state node fn state_data(&self, hash: &H256) -> Option<Bytes>; /// Get raw block receipts data by block header hash. fn block_receipts(&self, hash: &H256) -> Option<Bytes>; /// Import a block into the blockchain. fn import_block(&self, bytes: Bytes) -> Result<H256, BlockImportError>; /// Import a block with transaction receipts. Does no sealing and transaction validation. fn import_block_with_receipts(&self, block_bytes: Bytes, receipts_bytes: Bytes) -> Result<H256, BlockImportError>; /// Get block queue information. fn queue_info(&self) -> BlockQueueInfo; /// Clear block queue and abort all import activity. fn clear_queue(&self); /// Get blockchain information. fn chain_info(&self) -> BlockChainInfo; /// Get the registrar address, if it exists. fn additional_params(&self) -> BTreeMap<String, String>; /// Get the best block header. fn best_block_header(&self) -> Bytes; /// Returns numbers of blocks containing given bloom. fn blocks_with_bloom(&self, bloom: &H2048, from_block: BlockID, to_block: BlockID) -> Option<Vec<BlockNumber>>; /// Returns logs matching given filter. fn logs(&self, filter: Filter) -> Vec<LocalizedLogEntry>; /// Makes a non-persistent transaction call. fn call(&self, t: &SignedTransaction, block: BlockID, analytics: CallAnalytics) -> Result<Executed, CallError>; /// Replays a given transaction for inspection. fn replay(&self, t: TransactionID, analytics: CallAnalytics) -> Result<Executed, CallError>; /// Returns traces matching given filter. fn filter_traces(&self, filter: TraceFilter) -> Option<Vec<LocalizedTrace>>; /// Returns trace with given id. fn trace(&self, trace: TraceId) -> Option<LocalizedTrace>; /// Returns traces created by transaction. fn transaction_traces(&self, trace: TransactionID) -> Option<Vec<LocalizedTrace>>; /// Returns traces created by transaction from block. fn block_traces(&self, trace: BlockID) -> Option<Vec<LocalizedTrace>>; /// Get last hashes starting from best block. fn last_hashes(&self) -> LastHashes; /// Queue transactions for importing. fn queue_transactions(&self, transactions: Vec<Bytes>); /// list all transactions fn pending_transactions(&self) -> Vec<SignedTransaction>; /// Get the gas price distribution. fn gas_price_statistics(&self, sample_size: usize, distribution_size: usize) -> Result<Vec<U256>, ()> { let mut h = self.chain_info().best_block_hash; let mut corpus = Vec::new(); while corpus.is_empty() { for _ in 0..sample_size { let block_bytes = self.block(BlockID::Hash(h)).expect("h is either the best_block_hash or an ancestor; qed"); let block = BlockView::new(&block_bytes); let header = block.header_view(); if header.number() == 0 { if corpus.is_empty() { corpus.push(20_000_000_000u64.into()); // we have literally no information - it' as good a number as any. } break; } block.transaction_views().iter().foreach(|t| corpus.push(t.gas_price())); h = header.parent_hash().clone(); } } corpus.sort(); let n = corpus.len(); if n > 0 { Ok((0..(distribution_size + 1)) .map(|i| corpus[i * (n - 1) / distribution_size]) .collect::<Vec<_>>() ) } else { Err(()) } } } /// Extended client interface used for mining pub trait MiningBlockChainClient : BlockChainClient { /// Returns OpenBlock prepared for closing. fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes ) -> OpenBlock; /// Returns EvmFactory. fn vm_factory(&self) -> &EvmFactory; /// Import sealed block. Skips all verifications. fn import_sealed_block(&self, block: SealedBlock) -> ImportResult; } impl IpcConfig for BlockChainClient { }
latest_storage_at
identifier_name
std_tests.rs
#![cfg(feature = "std")] #[macro_use] extern crate throw; use throw::Result; #[derive(Debug)] struct CustomError(String); impl std::fmt::Display for CustomError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "CustomError: {}", self.0) } } impl std::error::Error for CustomError { fn
(&self) -> &str { self.0.as_str() } } fn throws_error_with_description() -> Result<(), CustomError> { throw!(Err(CustomError("err".to_owned()))); Ok(()) } fn throws_error_with_description_and_key_value_pairs() -> Result<(), CustomError> { throw!( Err(CustomError("err".to_owned())), "key" => "value" ); Ok(()) } #[test] fn test_error_description() { use std::error::Error; let error = throws_error_with_description().unwrap_err(); assert_eq!(error.description(), "err"); } #[test] fn test_error_description_with_key_value_pairs() { use std::error::Error; let error = throws_error_with_description_and_key_value_pairs().unwrap_err(); assert_eq!(error.description(), "err"); } #[test] fn test_error_with_cause() { use std::error::Error; let error = throws_error_with_description().unwrap_err(); assert_eq!( format!("{}", error.cause().unwrap()), "CustomError: err" ); }
description
identifier_name
std_tests.rs
#![cfg(feature = "std")] #[macro_use] extern crate throw; use throw::Result; #[derive(Debug)] struct CustomError(String); impl std::fmt::Display for CustomError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "CustomError: {}", self.0) } } impl std::error::Error for CustomError { fn description(&self) -> &str { self.0.as_str() } } fn throws_error_with_description() -> Result<(), CustomError> { throw!(Err(CustomError("err".to_owned()))); Ok(()) } fn throws_error_with_description_and_key_value_pairs() -> Result<(), CustomError> { throw!( Err(CustomError("err".to_owned())), "key" => "value" ); Ok(()) } #[test] fn test_error_description() {
use std::error::Error; let error = throws_error_with_description().unwrap_err(); assert_eq!(error.description(), "err"); } #[test] fn test_error_description_with_key_value_pairs() { use std::error::Error; let error = throws_error_with_description_and_key_value_pairs().unwrap_err(); assert_eq!(error.description(), "err"); } #[test] fn test_error_with_cause() { use std::error::Error; let error = throws_error_with_description().unwrap_err(); assert_eq!( format!("{}", error.cause().unwrap()), "CustomError: err" ); }
random_line_split
std_tests.rs
#![cfg(feature = "std")] #[macro_use] extern crate throw; use throw::Result; #[derive(Debug)] struct CustomError(String); impl std::fmt::Display for CustomError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "CustomError: {}", self.0) } } impl std::error::Error for CustomError { fn description(&self) -> &str
} fn throws_error_with_description() -> Result<(), CustomError> { throw!(Err(CustomError("err".to_owned()))); Ok(()) } fn throws_error_with_description_and_key_value_pairs() -> Result<(), CustomError> { throw!( Err(CustomError("err".to_owned())), "key" => "value" ); Ok(()) } #[test] fn test_error_description() { use std::error::Error; let error = throws_error_with_description().unwrap_err(); assert_eq!(error.description(), "err"); } #[test] fn test_error_description_with_key_value_pairs() { use std::error::Error; let error = throws_error_with_description_and_key_value_pairs().unwrap_err(); assert_eq!(error.description(), "err"); } #[test] fn test_error_with_cause() { use std::error::Error; let error = throws_error_with_description().unwrap_err(); assert_eq!( format!("{}", error.cause().unwrap()), "CustomError: err" ); }
{ self.0.as_str() }
identifier_body
mod.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use base::prelude::*; use core::{mem}; use arch_fns::{memrchr}; use fmt::{Debug, Display, Write}; use byte_str::{ByteStr}; mod index; /// A byte slice with no null bytes. pub struct NoNullStr([u8]);
/// Sets a byte in the slice to a value. /// /// [argument, idx] /// The index of the byte to be set. /// /// [argument, val] /// The value of the byte. /// /// = Remarks /// /// If `val == 0`, the process is aborted. pub fn set(&mut self, idx: usize, val: u8) { assert!(val!= 0); self.0[idx] = val; } /// Returns a `NoNullStr` that consists of the segment after the last '/'. pub fn file(&self) -> &NoNullStr { self.split_path().1 } /// Returns a mutable `NoNullStr` that consists of the segment after the last '/'. pub fn file_mut(&mut self) -> &mut NoNullStr { self.split_path_mut().1 } /// Returns a `NoNullStr` that consists of the segment before the last '/'. pub fn dir(&self) -> &NoNullStr { self.split_path().0 } /// Returns a mutable `NoNullStr` that consists of the segment before the last '/'. pub fn dir_mut(&mut self) -> &mut NoNullStr { self.split_path_mut().0 } /// Splits the string into its directory and file components. pub fn split_path(&self) -> (&NoNullStr, &NoNullStr) { let bytes = &self.0; let (l, r) = match memrchr(bytes, b'/') { Some(idx) => (&bytes[..idx], &bytes[idx+1..]), _ => (&[][..], bytes), }; unsafe { mem::cast((l, r)) } } /// Splits the string into its directory and file components. pub fn split_path_mut(&mut self) -> (&mut NoNullStr, &mut NoNullStr) { unsafe { mem::cast(self.split_path()) } } } impl Deref for NoNullStr { type Target = ByteStr; fn deref(&self) -> &ByteStr { self.as_ref() } } impl Debug for NoNullStr { fn fmt<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Debug::fmt(bs, w) } } impl Display for NoNullStr { fn fmt<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Display::fmt(bs, w) } }
impl NoNullStr {
random_line_split
mod.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use base::prelude::*; use core::{mem}; use arch_fns::{memrchr}; use fmt::{Debug, Display, Write}; use byte_str::{ByteStr}; mod index; /// A byte slice with no null bytes. pub struct NoNullStr([u8]); impl NoNullStr { /// Sets a byte in the slice to a value. /// /// [argument, idx] /// The index of the byte to be set. /// /// [argument, val] /// The value of the byte. /// /// = Remarks /// /// If `val == 0`, the process is aborted. pub fn set(&mut self, idx: usize, val: u8) { assert!(val!= 0); self.0[idx] = val; } /// Returns a `NoNullStr` that consists of the segment after the last '/'. pub fn file(&self) -> &NoNullStr { self.split_path().1 } /// Returns a mutable `NoNullStr` that consists of the segment after the last '/'. pub fn file_mut(&mut self) -> &mut NoNullStr { self.split_path_mut().1 } /// Returns a `NoNullStr` that consists of the segment before the last '/'. pub fn dir(&self) -> &NoNullStr { self.split_path().0 } /// Returns a mutable `NoNullStr` that consists of the segment before the last '/'. pub fn dir_mut(&mut self) -> &mut NoNullStr { self.split_path_mut().0 } /// Splits the string into its directory and file components. pub fn split_path(&self) -> (&NoNullStr, &NoNullStr) { let bytes = &self.0; let (l, r) = match memrchr(bytes, b'/') { Some(idx) => (&bytes[..idx], &bytes[idx+1..]), _ => (&[][..], bytes), }; unsafe { mem::cast((l, r)) } } /// Splits the string into its directory and file components. pub fn split_path_mut(&mut self) -> (&mut NoNullStr, &mut NoNullStr) { unsafe { mem::cast(self.split_path()) } } } impl Deref for NoNullStr { type Target = ByteStr; fn deref(&self) -> &ByteStr { self.as_ref() } } impl Debug for NoNullStr { fn
<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Debug::fmt(bs, w) } } impl Display for NoNullStr { fn fmt<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Display::fmt(bs, w) } }
fmt
identifier_name
mod.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use base::prelude::*; use core::{mem}; use arch_fns::{memrchr}; use fmt::{Debug, Display, Write}; use byte_str::{ByteStr}; mod index; /// A byte slice with no null bytes. pub struct NoNullStr([u8]); impl NoNullStr { /// Sets a byte in the slice to a value. /// /// [argument, idx] /// The index of the byte to be set. /// /// [argument, val] /// The value of the byte. /// /// = Remarks /// /// If `val == 0`, the process is aborted. pub fn set(&mut self, idx: usize, val: u8) { assert!(val!= 0); self.0[idx] = val; } /// Returns a `NoNullStr` that consists of the segment after the last '/'. pub fn file(&self) -> &NoNullStr { self.split_path().1 } /// Returns a mutable `NoNullStr` that consists of the segment after the last '/'. pub fn file_mut(&mut self) -> &mut NoNullStr { self.split_path_mut().1 } /// Returns a `NoNullStr` that consists of the segment before the last '/'. pub fn dir(&self) -> &NoNullStr { self.split_path().0 } /// Returns a mutable `NoNullStr` that consists of the segment before the last '/'. pub fn dir_mut(&mut self) -> &mut NoNullStr { self.split_path_mut().0 } /// Splits the string into its directory and file components. pub fn split_path(&self) -> (&NoNullStr, &NoNullStr) { let bytes = &self.0; let (l, r) = match memrchr(bytes, b'/') { Some(idx) => (&bytes[..idx], &bytes[idx+1..]), _ => (&[][..], bytes), }; unsafe { mem::cast((l, r)) } } /// Splits the string into its directory and file components. pub fn split_path_mut(&mut self) -> (&mut NoNullStr, &mut NoNullStr) { unsafe { mem::cast(self.split_path()) } } } impl Deref for NoNullStr { type Target = ByteStr; fn deref(&self) -> &ByteStr
} impl Debug for NoNullStr { fn fmt<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Debug::fmt(bs, w) } } impl Display for NoNullStr { fn fmt<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Display::fmt(bs, w) } }
{ self.as_ref() }
identifier_body
str2sig.rs
//! Convert between signal names and numbers. #[cfg(not(windows))] use libc; use libc::{c_char, c_int}; use std::ffi::CStr; use std::str::FromStr; #[cfg(not(unix))] const numname: [(&'static str, c_int); 0] = []; #[cfg(all(unix, not(target_os = "macos")))] const numname: [(&str, c_int); 30] = [ ("HUP", libc::SIGHUP), ("INT", libc::SIGINT), ("QUIT", libc::SIGQUIT), ("ILL", libc::SIGILL), ("TRAP", libc::SIGTRAP), ("ABRT", libc::SIGABRT), ("IOT", libc::SIGIOT), ("BUS", libc::SIGBUS), ("FPE", libc::SIGFPE), ("KILL", libc::SIGKILL), ("USR1", libc::SIGUSR1), ("USR2", libc::SIGUSR2), ("SEGV", libc::SIGSEGV), ("PIPE", libc::SIGPIPE), ("ALRM", libc::SIGALRM), ("TERM", libc::SIGTERM), ("STKFLT", libc::SIGSTKFLT), ("CHLD", libc::SIGCHLD), ("CONT", libc::SIGCONT), ("STOP", libc::SIGSTOP), ("TSTP", libc::SIGTSTP), ("TTIN", libc::SIGTTIN), ("TTOU", libc::SIGTTOU), ("URG", libc::SIGURG), ("XCPU", libc::SIGXCPU), ("PROF", libc::SIGPROF), ("WINCH", libc::SIGWINCH),
#[cfg(target_os = "macos")] const numname: [(&str, c_int); 27] = [ ("HUP", libc::SIGHUP), ("INT", libc::SIGINT), ("QUIT", libc::SIGQUIT), ("ILL", libc::SIGILL), ("TRAP", libc::SIGTRAP), ("ABRT", libc::SIGABRT), ("IOT", libc::SIGIOT), ("BUS", libc::SIGBUS), ("FPE", libc::SIGFPE), ("KILL", libc::SIGKILL), ("USR1", libc::SIGUSR1), ("USR2", libc::SIGUSR2), ("SEGV", libc::SIGSEGV), ("PIPE", libc::SIGPIPE), ("ALRM", libc::SIGALRM), ("TERM", libc::SIGTERM), ("CHLD", libc::SIGCHLD), ("CONT", libc::SIGCONT), ("STOP", libc::SIGSTOP), ("TSTP", libc::SIGTSTP), ("TTIN", libc::SIGTTIN), ("TTOU", libc::SIGTTOU), ("URG", libc::SIGURG), ("XCPU", libc::SIGXCPU), ("PROF", libc::SIGPROF), ("WINCH", libc::SIGWINCH), ("SYS", libc::SIGSYS), ]; /// Convert the signal name SIGNAME to the signal number /// *SIGNUM. Return 0 if successful, -1 otherwise. #[no_mangle] pub unsafe extern "C" fn str2sig(signame: *const c_char, signum: *mut c_int) -> c_int { let s = CStr::from_ptr(signame).to_string_lossy(); match FromStr::from_str(s.as_ref()) { Ok(i) => { *signum = i; return 0; } Err(_) => { for &(name, num) in &numname { if name == s { *signum = num; return 0; } } } } -1 }
("POLL", libc::SIGPOLL), ("PWR", libc::SIGPWR), ("SYS", libc::SIGSYS), ];
random_line_split
str2sig.rs
//! Convert between signal names and numbers. #[cfg(not(windows))] use libc; use libc::{c_char, c_int}; use std::ffi::CStr; use std::str::FromStr; #[cfg(not(unix))] const numname: [(&'static str, c_int); 0] = []; #[cfg(all(unix, not(target_os = "macos")))] const numname: [(&str, c_int); 30] = [ ("HUP", libc::SIGHUP), ("INT", libc::SIGINT), ("QUIT", libc::SIGQUIT), ("ILL", libc::SIGILL), ("TRAP", libc::SIGTRAP), ("ABRT", libc::SIGABRT), ("IOT", libc::SIGIOT), ("BUS", libc::SIGBUS), ("FPE", libc::SIGFPE), ("KILL", libc::SIGKILL), ("USR1", libc::SIGUSR1), ("USR2", libc::SIGUSR2), ("SEGV", libc::SIGSEGV), ("PIPE", libc::SIGPIPE), ("ALRM", libc::SIGALRM), ("TERM", libc::SIGTERM), ("STKFLT", libc::SIGSTKFLT), ("CHLD", libc::SIGCHLD), ("CONT", libc::SIGCONT), ("STOP", libc::SIGSTOP), ("TSTP", libc::SIGTSTP), ("TTIN", libc::SIGTTIN), ("TTOU", libc::SIGTTOU), ("URG", libc::SIGURG), ("XCPU", libc::SIGXCPU), ("PROF", libc::SIGPROF), ("WINCH", libc::SIGWINCH), ("POLL", libc::SIGPOLL), ("PWR", libc::SIGPWR), ("SYS", libc::SIGSYS), ]; #[cfg(target_os = "macos")] const numname: [(&str, c_int); 27] = [ ("HUP", libc::SIGHUP), ("INT", libc::SIGINT), ("QUIT", libc::SIGQUIT), ("ILL", libc::SIGILL), ("TRAP", libc::SIGTRAP), ("ABRT", libc::SIGABRT), ("IOT", libc::SIGIOT), ("BUS", libc::SIGBUS), ("FPE", libc::SIGFPE), ("KILL", libc::SIGKILL), ("USR1", libc::SIGUSR1), ("USR2", libc::SIGUSR2), ("SEGV", libc::SIGSEGV), ("PIPE", libc::SIGPIPE), ("ALRM", libc::SIGALRM), ("TERM", libc::SIGTERM), ("CHLD", libc::SIGCHLD), ("CONT", libc::SIGCONT), ("STOP", libc::SIGSTOP), ("TSTP", libc::SIGTSTP), ("TTIN", libc::SIGTTIN), ("TTOU", libc::SIGTTOU), ("URG", libc::SIGURG), ("XCPU", libc::SIGXCPU), ("PROF", libc::SIGPROF), ("WINCH", libc::SIGWINCH), ("SYS", libc::SIGSYS), ]; /// Convert the signal name SIGNAME to the signal number /// *SIGNUM. Return 0 if successful, -1 otherwise. #[no_mangle] pub unsafe extern "C" fn str2sig(signame: *const c_char, signum: *mut c_int) -> c_int
{ let s = CStr::from_ptr(signame).to_string_lossy(); match FromStr::from_str(s.as_ref()) { Ok(i) => { *signum = i; return 0; } Err(_) => { for &(name, num) in &numname { if name == s { *signum = num; return 0; } } } } -1 }
identifier_body
str2sig.rs
//! Convert between signal names and numbers. #[cfg(not(windows))] use libc; use libc::{c_char, c_int}; use std::ffi::CStr; use std::str::FromStr; #[cfg(not(unix))] const numname: [(&'static str, c_int); 0] = []; #[cfg(all(unix, not(target_os = "macos")))] const numname: [(&str, c_int); 30] = [ ("HUP", libc::SIGHUP), ("INT", libc::SIGINT), ("QUIT", libc::SIGQUIT), ("ILL", libc::SIGILL), ("TRAP", libc::SIGTRAP), ("ABRT", libc::SIGABRT), ("IOT", libc::SIGIOT), ("BUS", libc::SIGBUS), ("FPE", libc::SIGFPE), ("KILL", libc::SIGKILL), ("USR1", libc::SIGUSR1), ("USR2", libc::SIGUSR2), ("SEGV", libc::SIGSEGV), ("PIPE", libc::SIGPIPE), ("ALRM", libc::SIGALRM), ("TERM", libc::SIGTERM), ("STKFLT", libc::SIGSTKFLT), ("CHLD", libc::SIGCHLD), ("CONT", libc::SIGCONT), ("STOP", libc::SIGSTOP), ("TSTP", libc::SIGTSTP), ("TTIN", libc::SIGTTIN), ("TTOU", libc::SIGTTOU), ("URG", libc::SIGURG), ("XCPU", libc::SIGXCPU), ("PROF", libc::SIGPROF), ("WINCH", libc::SIGWINCH), ("POLL", libc::SIGPOLL), ("PWR", libc::SIGPWR), ("SYS", libc::SIGSYS), ]; #[cfg(target_os = "macos")] const numname: [(&str, c_int); 27] = [ ("HUP", libc::SIGHUP), ("INT", libc::SIGINT), ("QUIT", libc::SIGQUIT), ("ILL", libc::SIGILL), ("TRAP", libc::SIGTRAP), ("ABRT", libc::SIGABRT), ("IOT", libc::SIGIOT), ("BUS", libc::SIGBUS), ("FPE", libc::SIGFPE), ("KILL", libc::SIGKILL), ("USR1", libc::SIGUSR1), ("USR2", libc::SIGUSR2), ("SEGV", libc::SIGSEGV), ("PIPE", libc::SIGPIPE), ("ALRM", libc::SIGALRM), ("TERM", libc::SIGTERM), ("CHLD", libc::SIGCHLD), ("CONT", libc::SIGCONT), ("STOP", libc::SIGSTOP), ("TSTP", libc::SIGTSTP), ("TTIN", libc::SIGTTIN), ("TTOU", libc::SIGTTOU), ("URG", libc::SIGURG), ("XCPU", libc::SIGXCPU), ("PROF", libc::SIGPROF), ("WINCH", libc::SIGWINCH), ("SYS", libc::SIGSYS), ]; /// Convert the signal name SIGNAME to the signal number /// *SIGNUM. Return 0 if successful, -1 otherwise. #[no_mangle] pub unsafe extern "C" fn
(signame: *const c_char, signum: *mut c_int) -> c_int { let s = CStr::from_ptr(signame).to_string_lossy(); match FromStr::from_str(s.as_ref()) { Ok(i) => { *signum = i; return 0; } Err(_) => { for &(name, num) in &numname { if name == s { *signum = num; return 0; } } } } -1 }
str2sig
identifier_name
reshape.rs
use std::fmt; use traits::{MatrixGet, MatrixSet, MatrixRawGet, MatrixRawSet, MatrixShape, MatrixReshape, SameShape}; use matrix::write_mat; impl<T: MatrixShape> MatrixReshape for T { unsafe fn unsafe_reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::unsafe_new(self, nrow, ncol) } fn reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::new(self, nrow, ncol) } } #[derive(Copy)] pub struct Reshape<T> { base: T, nrow: usize, ncol: usize, } impl<T: MatrixShape> Reshape<T> { pub unsafe fn unsafe_new(base: T, nrow: usize, ncol: usize) -> Reshape<T> { Reshape{ base: base, nrow: nrow, ncol: ncol } } pub fn new(base: T, nrow: usize, ncol: usize) -> Reshape<T> { assert!(nrow * ncol == base.len()); Reshape{ base: base, nrow: nrow, ncol: ncol } } } impl<T: MatrixGet<usize>> MatrixRawGet for Reshape<T> { unsafe fn raw_get(&self, r: usize, c: usize) -> f64 { self.base.unsafe_get(r * self.ncol() + c) } } impl<T: MatrixSet<usize>> MatrixRawSet for Reshape<T> { unsafe fn raw_set(&self, r: usize, c: usize, val: f64) { self.base.unsafe_set(r * self.ncol() + c, val) } } impl<T> MatrixShape for Reshape<T> { fn nrow(&self) -> usize { self.nrow } fn ncol(&self) -> usize { self.ncol } } impl<T: MatrixShape> SameShape for Reshape<T> { fn same_shape(&self, nrow: usize, ncol: usize) -> bool { self.nrow() == nrow && self.ncol() == ncol } } impl<T: Clone> Clone for Reshape<T> {
fn clone(&self) -> Reshape<T> { Reshape{ base: self.base.clone(), nrow: self.nrow, ncol: self.ncol } } } impl<T: MatrixRawGet + MatrixShape> fmt::Display for Reshape<T> { fn fmt(&self, buf: &mut fmt::Formatter) -> fmt::Result { write_mat(buf, self) } }
random_line_split
reshape.rs
use std::fmt; use traits::{MatrixGet, MatrixSet, MatrixRawGet, MatrixRawSet, MatrixShape, MatrixReshape, SameShape}; use matrix::write_mat; impl<T: MatrixShape> MatrixReshape for T { unsafe fn unsafe_reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::unsafe_new(self, nrow, ncol) } fn reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::new(self, nrow, ncol) } } #[derive(Copy)] pub struct Reshape<T> { base: T, nrow: usize, ncol: usize, } impl<T: MatrixShape> Reshape<T> { pub unsafe fn unsafe_new(base: T, nrow: usize, ncol: usize) -> Reshape<T> { Reshape{ base: base, nrow: nrow, ncol: ncol } } pub fn new(base: T, nrow: usize, ncol: usize) -> Reshape<T> { assert!(nrow * ncol == base.len()); Reshape{ base: base, nrow: nrow, ncol: ncol } } } impl<T: MatrixGet<usize>> MatrixRawGet for Reshape<T> { unsafe fn raw_get(&self, r: usize, c: usize) -> f64 { self.base.unsafe_get(r * self.ncol() + c) } } impl<T: MatrixSet<usize>> MatrixRawSet for Reshape<T> { unsafe fn raw_set(&self, r: usize, c: usize, val: f64) { self.base.unsafe_set(r * self.ncol() + c, val) } } impl<T> MatrixShape for Reshape<T> { fn nrow(&self) -> usize { self.nrow } fn ncol(&self) -> usize { self.ncol } } impl<T: MatrixShape> SameShape for Reshape<T> { fn same_shape(&self, nrow: usize, ncol: usize) -> bool { self.nrow() == nrow && self.ncol() == ncol } } impl<T: Clone> Clone for Reshape<T> { fn clone(&self) -> Reshape<T> { Reshape{ base: self.base.clone(), nrow: self.nrow, ncol: self.ncol } } } impl<T: MatrixRawGet + MatrixShape> fmt::Display for Reshape<T> { fn fmt(&self, buf: &mut fmt::Formatter) -> fmt::Result
}
{ write_mat(buf, self) }
identifier_body
reshape.rs
use std::fmt; use traits::{MatrixGet, MatrixSet, MatrixRawGet, MatrixRawSet, MatrixShape, MatrixReshape, SameShape}; use matrix::write_mat; impl<T: MatrixShape> MatrixReshape for T { unsafe fn unsafe_reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::unsafe_new(self, nrow, ncol) } fn reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::new(self, nrow, ncol) } } #[derive(Copy)] pub struct Reshape<T> { base: T, nrow: usize, ncol: usize, } impl<T: MatrixShape> Reshape<T> { pub unsafe fn unsafe_new(base: T, nrow: usize, ncol: usize) -> Reshape<T> { Reshape{ base: base, nrow: nrow, ncol: ncol } } pub fn new(base: T, nrow: usize, ncol: usize) -> Reshape<T> { assert!(nrow * ncol == base.len()); Reshape{ base: base, nrow: nrow, ncol: ncol } } } impl<T: MatrixGet<usize>> MatrixRawGet for Reshape<T> { unsafe fn raw_get(&self, r: usize, c: usize) -> f64 { self.base.unsafe_get(r * self.ncol() + c) } } impl<T: MatrixSet<usize>> MatrixRawSet for Reshape<T> { unsafe fn
(&self, r: usize, c: usize, val: f64) { self.base.unsafe_set(r * self.ncol() + c, val) } } impl<T> MatrixShape for Reshape<T> { fn nrow(&self) -> usize { self.nrow } fn ncol(&self) -> usize { self.ncol } } impl<T: MatrixShape> SameShape for Reshape<T> { fn same_shape(&self, nrow: usize, ncol: usize) -> bool { self.nrow() == nrow && self.ncol() == ncol } } impl<T: Clone> Clone for Reshape<T> { fn clone(&self) -> Reshape<T> { Reshape{ base: self.base.clone(), nrow: self.nrow, ncol: self.ncol } } } impl<T: MatrixRawGet + MatrixShape> fmt::Display for Reshape<T> { fn fmt(&self, buf: &mut fmt::Formatter) -> fmt::Result { write_mat(buf, self) } }
raw_set
identifier_name
q_flags.rs
use std::fmt; use std::marker::PhantomData; use std::ops::{BitAnd, BitOr, BitXor}; use std::os::raw::c_int; /// An OR-combination of integer values of the enum type `E`. /// /// This type serves as a replacement for Qt's `QFlags` C++ template class. #[derive(Clone, Copy)] pub struct QFlags<E> { value: c_int, _phantom_data: PhantomData<E>, } impl<E> From<c_int> for QFlags<E> { fn from(value: c_int) -> Self { Self { value, _phantom_data: PhantomData, } } } impl<E> From<QFlags<E>> for c_int { fn from(flags: QFlags<E>) -> Self { flags.value } }
} impl<E: Into<QFlags<E>>> QFlags<E> { /// Returns `true` if `flag` is enabled in `self`. pub fn test_flag(self, flag: E) -> bool { self.value & flag.into().value!= 0 } /// Returns `true` if this value has no flags enabled. pub fn is_empty(self) -> bool { self.value == 0 } } impl<E, T: Into<QFlags<E>>> BitOr<T> for QFlags<E> { type Output = QFlags<E>; fn bitor(self, rhs: T) -> QFlags<E> { Self { value: self.value | rhs.into().value, _phantom_data: PhantomData, } } } impl<E, T: Into<QFlags<E>>> BitAnd<T> for QFlags<E> { type Output = QFlags<E>; fn bitand(self, rhs: T) -> QFlags<E> { Self { value: self.value & rhs.into().value, _phantom_data: PhantomData, } } } impl<E, T: Into<QFlags<E>>> BitXor<T> for QFlags<E> { type Output = QFlags<E>; fn bitxor(self, rhs: T) -> QFlags<E> { Self { value: self.value ^ rhs.into().value, _phantom_data: PhantomData, } } } impl<E> Default for QFlags<E> { fn default() -> Self { QFlags { value: 0, _phantom_data: PhantomData, } } } impl<T> fmt::Debug for QFlags<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "QFlags({})", self.value) } }
impl<E> QFlags<E> { pub fn to_int(self) -> c_int { self.value }
random_line_split
q_flags.rs
use std::fmt; use std::marker::PhantomData; use std::ops::{BitAnd, BitOr, BitXor}; use std::os::raw::c_int; /// An OR-combination of integer values of the enum type `E`. /// /// This type serves as a replacement for Qt's `QFlags` C++ template class. #[derive(Clone, Copy)] pub struct QFlags<E> { value: c_int, _phantom_data: PhantomData<E>, } impl<E> From<c_int> for QFlags<E> { fn from(value: c_int) -> Self
} impl<E> From<QFlags<E>> for c_int { fn from(flags: QFlags<E>) -> Self { flags.value } } impl<E> QFlags<E> { pub fn to_int(self) -> c_int { self.value } } impl<E: Into<QFlags<E>>> QFlags<E> { /// Returns `true` if `flag` is enabled in `self`. pub fn test_flag(self, flag: E) -> bool { self.value & flag.into().value!= 0 } /// Returns `true` if this value has no flags enabled. pub fn is_empty(self) -> bool { self.value == 0 } } impl<E, T: Into<QFlags<E>>> BitOr<T> for QFlags<E> { type Output = QFlags<E>; fn bitor(self, rhs: T) -> QFlags<E> { Self { value: self.value | rhs.into().value, _phantom_data: PhantomData, } } } impl<E, T: Into<QFlags<E>>> BitAnd<T> for QFlags<E> { type Output = QFlags<E>; fn bitand(self, rhs: T) -> QFlags<E> { Self { value: self.value & rhs.into().value, _phantom_data: PhantomData, } } } impl<E, T: Into<QFlags<E>>> BitXor<T> for QFlags<E> { type Output = QFlags<E>; fn bitxor(self, rhs: T) -> QFlags<E> { Self { value: self.value ^ rhs.into().value, _phantom_data: PhantomData, } } } impl<E> Default for QFlags<E> { fn default() -> Self { QFlags { value: 0, _phantom_data: PhantomData, } } } impl<T> fmt::Debug for QFlags<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "QFlags({})", self.value) } }
{ Self { value, _phantom_data: PhantomData, } }
identifier_body
q_flags.rs
use std::fmt; use std::marker::PhantomData; use std::ops::{BitAnd, BitOr, BitXor}; use std::os::raw::c_int; /// An OR-combination of integer values of the enum type `E`. /// /// This type serves as a replacement for Qt's `QFlags` C++ template class. #[derive(Clone, Copy)] pub struct QFlags<E> { value: c_int, _phantom_data: PhantomData<E>, } impl<E> From<c_int> for QFlags<E> { fn from(value: c_int) -> Self { Self { value, _phantom_data: PhantomData, } } } impl<E> From<QFlags<E>> for c_int { fn from(flags: QFlags<E>) -> Self { flags.value } } impl<E> QFlags<E> { pub fn
(self) -> c_int { self.value } } impl<E: Into<QFlags<E>>> QFlags<E> { /// Returns `true` if `flag` is enabled in `self`. pub fn test_flag(self, flag: E) -> bool { self.value & flag.into().value!= 0 } /// Returns `true` if this value has no flags enabled. pub fn is_empty(self) -> bool { self.value == 0 } } impl<E, T: Into<QFlags<E>>> BitOr<T> for QFlags<E> { type Output = QFlags<E>; fn bitor(self, rhs: T) -> QFlags<E> { Self { value: self.value | rhs.into().value, _phantom_data: PhantomData, } } } impl<E, T: Into<QFlags<E>>> BitAnd<T> for QFlags<E> { type Output = QFlags<E>; fn bitand(self, rhs: T) -> QFlags<E> { Self { value: self.value & rhs.into().value, _phantom_data: PhantomData, } } } impl<E, T: Into<QFlags<E>>> BitXor<T> for QFlags<E> { type Output = QFlags<E>; fn bitxor(self, rhs: T) -> QFlags<E> { Self { value: self.value ^ rhs.into().value, _phantom_data: PhantomData, } } } impl<E> Default for QFlags<E> { fn default() -> Self { QFlags { value: 0, _phantom_data: PhantomData, } } } impl<T> fmt::Debug for QFlags<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "QFlags({})", self.value) } }
to_int
identifier_name
arithmetic.rs
// Adapted from PEG.js example - https://github.com/pegjs/pegjs/blob/master/examples/arithmetics.pegjs #[macro_use] extern crate peggler; use peggler::{ParseError, ParseResult}; fn digits(input: &str) -> ParseResult<&str> { let mut end : usize; let mut char_indices = input.char_indices(); loop { match char_indices.next() { Some((index, char)) => { if!char.is_digit(10) { end = index; break; } }, None => { end = input.len(); break; } } } if end > 0 { Ok((&input[..end], &input[end..])) } else { Err(ParseError) } } rule!(expression:i32 = first:term rest: (ws op:(["+"] / ["-"]) ws term:term => {(op, term)})* => { rest.iter().fold(first, |acc, &item| { let &(op, term) = &item; match op { "+" => acc + term, "-" => acc - term, _ => unreachable!() } }) } ); rule!(term:i32 = first:factor
=> { rest.iter().fold(first, |acc, &item| { let &(op, factor) = &item; match op { "*" => acc * factor, "/" => acc / factor, _ => unreachable!() } }) } ); rule!(factor:i32 = (["("] ws expr:expression ws [")"] => { expr }) / integer); rule!(integer:i32 = digits:digits => { digits.parse::<i32>().unwrap() }); rule!(ws:() = ([" "] / ["\t"] / ["\n"] / ["\r"])* => { () }); #[test] fn test_digits() { assert_eq!(digits(""), Err(ParseError)); assert_eq!(digits("x"), Err(ParseError)); assert_eq!(digits("0"), Ok(("0", ""))); assert_eq!(digits("1"), Ok(("1", ""))); assert_eq!(digits("9"), Ok(("9", ""))); assert_eq!(digits("123"), Ok(("123", ""))); assert_eq!(digits("123x"), Ok(("123", "x"))); } #[test] fn test_expression() { assert_eq!(expression("1 + 2"), Ok((3, ""))); assert_eq!(expression("1 + 2 + 3"), Ok((6, ""))); assert_eq!(expression("1 - 2"), Ok((-1, ""))); assert_eq!(expression("1 - 2 - 3"), Ok((-4, ""))); assert_eq!(expression("1 - 2 + 3"), Ok((2, ""))); assert_eq!(expression("1 + 2 * 3"), Ok((7, ""))); assert_eq!(expression("1 + (2 * 3)"), Ok((7, ""))); assert_eq!(expression("(1 + 2) * 3"), Ok((9, ""))); } #[test] fn test_term() { assert_eq!(term("1"), Ok((1, ""))); assert_eq!(term("1 * 2"), Ok((2, ""))); assert_eq!(term("1 * 2 * 3"), Ok((6, ""))); assert_eq!(term("1 / 2"), Ok((0, ""))); assert_eq!(term("3 / 2 / 1"), Ok((1, ""))); assert_eq!(term("3 / 2 * 2"), Ok((2, ""))); } #[test] fn test_factor() { assert_eq!(term("1"), Ok((1, ""))); assert_eq!(term("(1)"), Ok((1, ""))); assert_eq!(term("((1))"), Ok((1, ""))); } #[test] fn test_integer() { assert_eq!(integer("0"), Ok((0, ""))); assert_eq!(integer("1"), Ok((1, ""))); assert_eq!(integer("01"), Ok((1, ""))); assert_eq!(integer("12"), Ok((12, ""))); assert_eq!(integer("123"), Ok((123, ""))); } #[test] fn test_ws() { assert_eq!(ws(" "), Ok(((), ""))); assert_eq!(ws(" "), Ok(((), ""))); assert_eq!(ws(" \t\n\r"), Ok(((), ""))); }
rest:(ws op:(["*"] / ["/"]) ws factor:factor => {(op, factor)})*
random_line_split
arithmetic.rs
// Adapted from PEG.js example - https://github.com/pegjs/pegjs/blob/master/examples/arithmetics.pegjs #[macro_use] extern crate peggler; use peggler::{ParseError, ParseResult}; fn digits(input: &str) -> ParseResult<&str>
Ok((&input[..end], &input[end..])) } else { Err(ParseError) } } rule!(expression:i32 = first:term rest: (ws op:(["+"] / ["-"]) ws term:term => {(op, term)})* => { rest.iter().fold(first, |acc, &item| { let &(op, term) = &item; match op { "+" => acc + term, "-" => acc - term, _ => unreachable!() } }) } ); rule!(term:i32 = first:factor rest:(ws op:(["*"] / ["/"]) ws factor:factor => {(op, factor)})* => { rest.iter().fold(first, |acc, &item| { let &(op, factor) = &item; match op { "*" => acc * factor, "/" => acc / factor, _ => unreachable!() } }) } ); rule!(factor:i32 = (["("] ws expr:expression ws [")"] => { expr }) / integer); rule!(integer:i32 = digits:digits => { digits.parse::<i32>().unwrap() }); rule!(ws:() = ([" "] / ["\t"] / ["\n"] / ["\r"])* => { () }); #[test] fn test_digits() { assert_eq!(digits(""), Err(ParseError)); assert_eq!(digits("x"), Err(ParseError)); assert_eq!(digits("0"), Ok(("0", ""))); assert_eq!(digits("1"), Ok(("1", ""))); assert_eq!(digits("9"), Ok(("9", ""))); assert_eq!(digits("123"), Ok(("123", ""))); assert_eq!(digits("123x"), Ok(("123", "x"))); } #[test] fn test_expression() { assert_eq!(expression("1 + 2"), Ok((3, ""))); assert_eq!(expression("1 + 2 + 3"), Ok((6, ""))); assert_eq!(expression("1 - 2"), Ok((-1, ""))); assert_eq!(expression("1 - 2 - 3"), Ok((-4, ""))); assert_eq!(expression("1 - 2 + 3"), Ok((2, ""))); assert_eq!(expression("1 + 2 * 3"), Ok((7, ""))); assert_eq!(expression("1 + (2 * 3)"), Ok((7, ""))); assert_eq!(expression("(1 + 2) * 3"), Ok((9, ""))); } #[test] fn test_term() { assert_eq!(term("1"), Ok((1, ""))); assert_eq!(term("1 * 2"), Ok((2, ""))); assert_eq!(term("1 * 2 * 3"), Ok((6, ""))); assert_eq!(term("1 / 2"), Ok((0, ""))); assert_eq!(term("3 / 2 / 1"), Ok((1, ""))); assert_eq!(term("3 / 2 * 2"), Ok((2, ""))); } #[test] fn test_factor() { assert_eq!(term("1"), Ok((1, ""))); assert_eq!(term("(1)"), Ok((1, ""))); assert_eq!(term("((1))"), Ok((1, ""))); } #[test] fn test_integer() { assert_eq!(integer("0"), Ok((0, ""))); assert_eq!(integer("1"), Ok((1, ""))); assert_eq!(integer("01"), Ok((1, ""))); assert_eq!(integer("12"), Ok((12, ""))); assert_eq!(integer("123"), Ok((123, ""))); } #[test] fn test_ws() { assert_eq!(ws(" "), Ok(((), ""))); assert_eq!(ws(" "), Ok(((), ""))); assert_eq!(ws(" \t\n\r"), Ok(((), ""))); }
{ let mut end : usize; let mut char_indices = input.char_indices(); loop { match char_indices.next() { Some((index, char)) => { if !char.is_digit(10) { end = index; break; } }, None => { end = input.len(); break; } } } if end > 0 {
identifier_body
arithmetic.rs
// Adapted from PEG.js example - https://github.com/pegjs/pegjs/blob/master/examples/arithmetics.pegjs #[macro_use] extern crate peggler; use peggler::{ParseError, ParseResult}; fn digits(input: &str) -> ParseResult<&str> { let mut end : usize; let mut char_indices = input.char_indices(); loop { match char_indices.next() { Some((index, char)) =>
, None => { end = input.len(); break; } } } if end > 0 { Ok((&input[..end], &input[end..])) } else { Err(ParseError) } } rule!(expression:i32 = first:term rest: (ws op:(["+"] / ["-"]) ws term:term => {(op, term)})* => { rest.iter().fold(first, |acc, &item| { let &(op, term) = &item; match op { "+" => acc + term, "-" => acc - term, _ => unreachable!() } }) } ); rule!(term:i32 = first:factor rest:(ws op:(["*"] / ["/"]) ws factor:factor => {(op, factor)})* => { rest.iter().fold(first, |acc, &item| { let &(op, factor) = &item; match op { "*" => acc * factor, "/" => acc / factor, _ => unreachable!() } }) } ); rule!(factor:i32 = (["("] ws expr:expression ws [")"] => { expr }) / integer); rule!(integer:i32 = digits:digits => { digits.parse::<i32>().unwrap() }); rule!(ws:() = ([" "] / ["\t"] / ["\n"] / ["\r"])* => { () }); #[test] fn test_digits() { assert_eq!(digits(""), Err(ParseError)); assert_eq!(digits("x"), Err(ParseError)); assert_eq!(digits("0"), Ok(("0", ""))); assert_eq!(digits("1"), Ok(("1", ""))); assert_eq!(digits("9"), Ok(("9", ""))); assert_eq!(digits("123"), Ok(("123", ""))); assert_eq!(digits("123x"), Ok(("123", "x"))); } #[test] fn test_expression() { assert_eq!(expression("1 + 2"), Ok((3, ""))); assert_eq!(expression("1 + 2 + 3"), Ok((6, ""))); assert_eq!(expression("1 - 2"), Ok((-1, ""))); assert_eq!(expression("1 - 2 - 3"), Ok((-4, ""))); assert_eq!(expression("1 - 2 + 3"), Ok((2, ""))); assert_eq!(expression("1 + 2 * 3"), Ok((7, ""))); assert_eq!(expression("1 + (2 * 3)"), Ok((7, ""))); assert_eq!(expression("(1 + 2) * 3"), Ok((9, ""))); } #[test] fn test_term() { assert_eq!(term("1"), Ok((1, ""))); assert_eq!(term("1 * 2"), Ok((2, ""))); assert_eq!(term("1 * 2 * 3"), Ok((6, ""))); assert_eq!(term("1 / 2"), Ok((0, ""))); assert_eq!(term("3 / 2 / 1"), Ok((1, ""))); assert_eq!(term("3 / 2 * 2"), Ok((2, ""))); } #[test] fn test_factor() { assert_eq!(term("1"), Ok((1, ""))); assert_eq!(term("(1)"), Ok((1, ""))); assert_eq!(term("((1))"), Ok((1, ""))); } #[test] fn test_integer() { assert_eq!(integer("0"), Ok((0, ""))); assert_eq!(integer("1"), Ok((1, ""))); assert_eq!(integer("01"), Ok((1, ""))); assert_eq!(integer("12"), Ok((12, ""))); assert_eq!(integer("123"), Ok((123, ""))); } #[test] fn test_ws() { assert_eq!(ws(" "), Ok(((), ""))); assert_eq!(ws(" "), Ok(((), ""))); assert_eq!(ws(" \t\n\r"), Ok(((), ""))); }
{ if !char.is_digit(10) { end = index; break; } }
conditional_block
arithmetic.rs
// Adapted from PEG.js example - https://github.com/pegjs/pegjs/blob/master/examples/arithmetics.pegjs #[macro_use] extern crate peggler; use peggler::{ParseError, ParseResult}; fn
(input: &str) -> ParseResult<&str> { let mut end : usize; let mut char_indices = input.char_indices(); loop { match char_indices.next() { Some((index, char)) => { if!char.is_digit(10) { end = index; break; } }, None => { end = input.len(); break; } } } if end > 0 { Ok((&input[..end], &input[end..])) } else { Err(ParseError) } } rule!(expression:i32 = first:term rest: (ws op:(["+"] / ["-"]) ws term:term => {(op, term)})* => { rest.iter().fold(first, |acc, &item| { let &(op, term) = &item; match op { "+" => acc + term, "-" => acc - term, _ => unreachable!() } }) } ); rule!(term:i32 = first:factor rest:(ws op:(["*"] / ["/"]) ws factor:factor => {(op, factor)})* => { rest.iter().fold(first, |acc, &item| { let &(op, factor) = &item; match op { "*" => acc * factor, "/" => acc / factor, _ => unreachable!() } }) } ); rule!(factor:i32 = (["("] ws expr:expression ws [")"] => { expr }) / integer); rule!(integer:i32 = digits:digits => { digits.parse::<i32>().unwrap() }); rule!(ws:() = ([" "] / ["\t"] / ["\n"] / ["\r"])* => { () }); #[test] fn test_digits() { assert_eq!(digits(""), Err(ParseError)); assert_eq!(digits("x"), Err(ParseError)); assert_eq!(digits("0"), Ok(("0", ""))); assert_eq!(digits("1"), Ok(("1", ""))); assert_eq!(digits("9"), Ok(("9", ""))); assert_eq!(digits("123"), Ok(("123", ""))); assert_eq!(digits("123x"), Ok(("123", "x"))); } #[test] fn test_expression() { assert_eq!(expression("1 + 2"), Ok((3, ""))); assert_eq!(expression("1 + 2 + 3"), Ok((6, ""))); assert_eq!(expression("1 - 2"), Ok((-1, ""))); assert_eq!(expression("1 - 2 - 3"), Ok((-4, ""))); assert_eq!(expression("1 - 2 + 3"), Ok((2, ""))); assert_eq!(expression("1 + 2 * 3"), Ok((7, ""))); assert_eq!(expression("1 + (2 * 3)"), Ok((7, ""))); assert_eq!(expression("(1 + 2) * 3"), Ok((9, ""))); } #[test] fn test_term() { assert_eq!(term("1"), Ok((1, ""))); assert_eq!(term("1 * 2"), Ok((2, ""))); assert_eq!(term("1 * 2 * 3"), Ok((6, ""))); assert_eq!(term("1 / 2"), Ok((0, ""))); assert_eq!(term("3 / 2 / 1"), Ok((1, ""))); assert_eq!(term("3 / 2 * 2"), Ok((2, ""))); } #[test] fn test_factor() { assert_eq!(term("1"), Ok((1, ""))); assert_eq!(term("(1)"), Ok((1, ""))); assert_eq!(term("((1))"), Ok((1, ""))); } #[test] fn test_integer() { assert_eq!(integer("0"), Ok((0, ""))); assert_eq!(integer("1"), Ok((1, ""))); assert_eq!(integer("01"), Ok((1, ""))); assert_eq!(integer("12"), Ok((12, ""))); assert_eq!(integer("123"), Ok((123, ""))); } #[test] fn test_ws() { assert_eq!(ws(" "), Ok(((), ""))); assert_eq!(ws(" "), Ok(((), ""))); assert_eq!(ws(" \t\n\r"), Ok(((), ""))); }
digits
identifier_name
bounds.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use deriving::path_std; use deriving::generic::*; use deriving::generic::ty::*; use syntax::ast::MetaItem; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; pub fn
(cx: &mut ExtCtxt, span: Span, _: &MetaItem, _: &Annotatable, _: &mut dyn FnMut(Annotatable)) { cx.span_err(span, "this unsafe trait should be implemented explicitly"); } pub fn expand_deriving_copy(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable, push: &mut dyn FnMut(Annotatable)) { let trait_def = TraitDef { span, attributes: Vec::new(), path: path_std!(cx, marker::Copy), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), is_unsafe: false, supports_unions: true, methods: Vec::new(), associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push); }
expand_deriving_unsafe_bound
identifier_name
bounds.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use deriving::path_std; use deriving::generic::*; use deriving::generic::ty::*; use syntax::ast::MetaItem; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; pub fn expand_deriving_unsafe_bound(cx: &mut ExtCtxt, span: Span, _: &MetaItem, _: &Annotatable, _: &mut dyn FnMut(Annotatable)) { cx.span_err(span, "this unsafe trait should be implemented explicitly"); } pub fn expand_deriving_copy(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable, push: &mut dyn FnMut(Annotatable))
{ let trait_def = TraitDef { span, attributes: Vec::new(), path: path_std!(cx, marker::Copy), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), is_unsafe: false, supports_unions: true, methods: Vec::new(), associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push); }
identifier_body
bounds.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
use deriving::generic::*; use deriving::generic::ty::*; use syntax::ast::MetaItem; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; pub fn expand_deriving_unsafe_bound(cx: &mut ExtCtxt, span: Span, _: &MetaItem, _: &Annotatable, _: &mut dyn FnMut(Annotatable)) { cx.span_err(span, "this unsafe trait should be implemented explicitly"); } pub fn expand_deriving_copy(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable, push: &mut dyn FnMut(Annotatable)) { let trait_def = TraitDef { span, attributes: Vec::new(), path: path_std!(cx, marker::Copy), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), is_unsafe: false, supports_unions: true, methods: Vec::new(), associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push); }
// <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 deriving::path_std;
random_line_split
lib.rs
//! A wrapper for the Strava API //! //! # Organization //! //! The module layout in this crate mirrors the [Strava API documentation][]. All functions //! interacting with the strava servers will return a //! [`strava::error::Result`](error/type.Result.html) for which the `E` parameter is curried to //! [`strava::error::ApiError`](error/enum.ApiError.html). The module listing below includes //! **UNIMPLEMENTED** tags to make it clear what hasn't been written yet. Modules without that tag //! are not guaranteed to exhaustively wrap all endpoints for that type, but they are guaranteed to //! have support for between `1..all` endpoints for that type. //! //! # Examples //! //! The simplest thing one can do with the strava API is to get an athlete and print it out. Every //! request made against the Strava API requires a valid access token. Since this example provides a //! fake token, the `unwrap` call will panic with an `ApiError::InvalidAccessToken`. You can get a //! token by registering an application on strava.com. //! //! ```no_run //! use strava::athletes::Athlete; //! use strava::api::AccessToken; //! //! // Create a token //! let token = AccessToken::new("<my token>".to_string());
//! // Get the athlete associated with the given token //! let athlete = Athlete::get_current(&token).unwrap(); //! //! // All of the strava types implement Debug and can be printed like so: //! println!("{:?}", athlete); //! ``` //! //! [Strava API Documentation]: http://strava.github.io/api/ extern crate hyper; extern crate rustc_serialize; /// Internal http api which currently wraps hyper #[doc(hidden)] mod http; // Support modules pub mod api; pub mod error; pub mod resources; // Modules corresponding to strava docs pub mod activities; pub mod athletes; pub mod clubs; pub mod gear; pub mod segmentefforts; pub mod segments; pub mod streams; pub mod uploads;
//!
random_line_split
day4.rs
// thanks to https://gist.github.com/gkbrk/2e4835e3a17b3fb6e1e7 // for the optimizations use crypto::md5::Md5; use crypto::digest::Digest; const INPUT: &'static str = "iwrupvqb"; pub fn
() -> u64 { calculate_part1(INPUT.as_bytes()) } pub fn part2() -> u64 { calculate_part2(INPUT.as_bytes()) } fn calculate_part1(input: &[u8]) -> u64 { let mut hasher = Md5::new(); for i in 0..::std::u64::MAX { hasher.input(input); hasher.input(i.to_string().as_bytes()); let mut output = [0; 16]; hasher.result(&mut output); let first_five = (output[0] as i32) + (output[1] as i32) + ((output[2] >> 4) as i32); if first_five == 0 { return i } hasher.reset(); } panic!("The mining operation has failed!"); } fn calculate_part2(input: &[u8]) -> u64 { let mut hasher = Md5::new(); for i in 0..::std::u64::MAX { hasher.input(input); hasher.input(i.to_string().as_bytes()); let mut output = [0; 16]; hasher.result(&mut output); let first_five = (output[0] as i32) + (output[1] as i32) + (output[2] as i32); if first_five == 0 { return i } hasher.reset(); } panic!("The mining operation has failed!"); } #[cfg(test)] mod tests { #[test] fn test1() { assert_eq!(609043, super::calculate_part1("abcdef".as_bytes())); } #[test] fn test2() { assert_eq!(1048970, super::calculate_part1("pqrstuv".as_bytes())); } }
part1
identifier_name
day4.rs
// thanks to https://gist.github.com/gkbrk/2e4835e3a17b3fb6e1e7 // for the optimizations use crypto::md5::Md5; use crypto::digest::Digest; const INPUT: &'static str = "iwrupvqb"; pub fn part1() -> u64 { calculate_part1(INPUT.as_bytes()) } pub fn part2() -> u64 { calculate_part2(INPUT.as_bytes()) } fn calculate_part1(input: &[u8]) -> u64 { let mut hasher = Md5::new(); for i in 0..::std::u64::MAX { hasher.input(input); hasher.input(i.to_string().as_bytes()); let mut output = [0; 16]; hasher.result(&mut output); let first_five = (output[0] as i32) + (output[1] as i32) + ((output[2] >> 4) as i32); if first_five == 0
hasher.reset(); } panic!("The mining operation has failed!"); } fn calculate_part2(input: &[u8]) -> u64 { let mut hasher = Md5::new(); for i in 0..::std::u64::MAX { hasher.input(input); hasher.input(i.to_string().as_bytes()); let mut output = [0; 16]; hasher.result(&mut output); let first_five = (output[0] as i32) + (output[1] as i32) + (output[2] as i32); if first_five == 0 { return i } hasher.reset(); } panic!("The mining operation has failed!"); } #[cfg(test)] mod tests { #[test] fn test1() { assert_eq!(609043, super::calculate_part1("abcdef".as_bytes())); } #[test] fn test2() { assert_eq!(1048970, super::calculate_part1("pqrstuv".as_bytes())); } }
{ return i }
conditional_block
day4.rs
// thanks to https://gist.github.com/gkbrk/2e4835e3a17b3fb6e1e7 // for the optimizations use crypto::md5::Md5; use crypto::digest::Digest; const INPUT: &'static str = "iwrupvqb"; pub fn part1() -> u64 { calculate_part1(INPUT.as_bytes()) } pub fn part2() -> u64 { calculate_part2(INPUT.as_bytes()) } fn calculate_part1(input: &[u8]) -> u64 { let mut hasher = Md5::new(); for i in 0..::std::u64::MAX { hasher.input(input); hasher.input(i.to_string().as_bytes()); let mut output = [0; 16]; hasher.result(&mut output); let first_five = (output[0] as i32) + (output[1] as i32) + ((output[2] >> 4) as i32); if first_five == 0 { return i } hasher.reset(); } panic!("The mining operation has failed!"); } fn calculate_part2(input: &[u8]) -> u64 { let mut hasher = Md5::new(); for i in 0..::std::u64::MAX { hasher.input(input); hasher.input(i.to_string().as_bytes()); let mut output = [0; 16]; hasher.result(&mut output); let first_five = (output[0] as i32) + (output[1] as i32) + (output[2] as i32); if first_five == 0 { return i } hasher.reset(); } panic!("The mining operation has failed!"); }
fn test1() { assert_eq!(609043, super::calculate_part1("abcdef".as_bytes())); } #[test] fn test2() { assert_eq!(1048970, super::calculate_part1("pqrstuv".as_bytes())); } }
#[cfg(test)] mod tests { #[test]
random_line_split
day4.rs
// thanks to https://gist.github.com/gkbrk/2e4835e3a17b3fb6e1e7 // for the optimizations use crypto::md5::Md5; use crypto::digest::Digest; const INPUT: &'static str = "iwrupvqb"; pub fn part1() -> u64 { calculate_part1(INPUT.as_bytes()) } pub fn part2() -> u64 { calculate_part2(INPUT.as_bytes()) } fn calculate_part1(input: &[u8]) -> u64 { let mut hasher = Md5::new(); for i in 0..::std::u64::MAX { hasher.input(input); hasher.input(i.to_string().as_bytes()); let mut output = [0; 16]; hasher.result(&mut output); let first_five = (output[0] as i32) + (output[1] as i32) + ((output[2] >> 4) as i32); if first_five == 0 { return i } hasher.reset(); } panic!("The mining operation has failed!"); } fn calculate_part2(input: &[u8]) -> u64 { let mut hasher = Md5::new(); for i in 0..::std::u64::MAX { hasher.input(input); hasher.input(i.to_string().as_bytes()); let mut output = [0; 16]; hasher.result(&mut output); let first_five = (output[0] as i32) + (output[1] as i32) + (output[2] as i32); if first_five == 0 { return i } hasher.reset(); } panic!("The mining operation has failed!"); } #[cfg(test)] mod tests { #[test] fn test1() { assert_eq!(609043, super::calculate_part1("abcdef".as_bytes())); } #[test] fn test2()
}
{ assert_eq!(1048970, super::calculate_part1("pqrstuv".as_bytes())); }
identifier_body
specified_value_info.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Value information for devtools. use servo_arc::Arc; use std::ops::Range; use std::sync::Arc as StdArc; /// Type of value that a property supports. This is used by Gecko's /// devtools to make sense about value it parses, and types listed /// here should match TYPE_* constants in InspectorUtils.webidl. /// /// XXX This should really be a bitflags rather than a namespace mod, /// but currently we cannot use bitflags in const. #[allow(non_snake_case)] pub mod CssType { /// <color> pub const COLOR: u8 = 1 << 0; /// <gradient> pub const GRADIENT: u8 = 1 << 1; /// <timing-function> pub const TIMING_FUNCTION: u8 = 1 << 2; } /// See SpecifiedValueInfo::collect_completion_keywords. pub type KeywordsCollectFn<'a> = &'a mut FnMut(&[&'static str]); /// Information of values of a given specified value type. /// /// This trait is derivable with `#[derive(SpecifiedValueInfo)]`. /// /// The algorithm traverses the type definition. For `SUPPORTED_TYPES`, /// it puts an or'ed value of `SUPPORTED_TYPES` of all types it finds. /// For `collect_completion_keywords`, it recursively invokes this /// method on types found, and lists all keyword values and function /// names following the same rule as `ToCss` in that method. /// /// Some attributes of `ToCss` can affect the behavior, specifically: /// * If `#[css(function)]` is found, the content inside the annotated /// variant (or the whole type) isn't traversed, only the function /// name is listed in `collect_completion_keywords`. /// * If `#[css(skip)]` is found, the content inside the variant or /// field is ignored. /// * Values listed in `#[css(if_empty)]`, `#[parse(aliases)]`, and /// `#[css(keyword)]` are added into `collect_completion_keywords`. /// /// In addition to `css` attributes, it also has `value_info` helper /// attributes, including: /// * `#[value_info(ty = "TYPE")]` can be used to specify a constant /// from `CssType` to `SUPPORTED_TYPES`. /// * `#[value_info(other_values = "value1,value2")]` can be used to /// add other values related to a field, variant, or the type itself /// into `collect_completion_keywords`. /// * `#[value_info(starts_with_keyword)]` can be used on variants to /// add the name of a non-unit variant (serialized like `ToCss`) into /// `collect_completion_keywords`. pub trait SpecifiedValueInfo { /// Supported CssTypes by the given value type. /// /// XXX This should be typed CssType when that becomes a bitflags. /// Currently we cannot do so since bitflags cannot be used in constant. const SUPPORTED_TYPES: u8 = 0; /// Collect value starting words for the given specified value type. /// This includes keyword and function names which can appear at the /// beginning of a value of this type. /// /// Caller should pass in a callback function to accept the list of /// values. The callback function can be called multiple times, and /// some values passed to the callback may be duplicate. fn collect_completion_keywords(_f: KeywordsCollectFn) {} } impl SpecifiedValueInfo for bool {} impl SpecifiedValueInfo for f32 {} impl SpecifiedValueInfo for i8 {} impl SpecifiedValueInfo for i32 {} impl SpecifiedValueInfo for u8 {} impl SpecifiedValueInfo for u16 {} impl SpecifiedValueInfo for u32 {} impl SpecifiedValueInfo for str {} impl SpecifiedValueInfo for String {} #[cfg(feature = "servo")] impl SpecifiedValueInfo for ::servo_atoms::Atom {} #[cfg(feature = "servo")] impl SpecifiedValueInfo for ::servo_url::ServoUrl {} impl<T: SpecifiedValueInfo +?Sized> SpecifiedValueInfo for Box<T> { const SUPPORTED_TYPES: u8 = T::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn) { T::collect_completion_keywords(f); } } impl<T: SpecifiedValueInfo> SpecifiedValueInfo for [T] { const SUPPORTED_TYPES: u8 = T::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn) { T::collect_completion_keywords(f);
macro_rules! impl_generic_specified_value_info { ($ty:ident<$param:ident>) => { impl<$param: SpecifiedValueInfo> SpecifiedValueInfo for $ty<$param> { const SUPPORTED_TYPES: u8 = $param::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn) { $param::collect_completion_keywords(f); } } }; } impl_generic_specified_value_info!(Option<T>); impl_generic_specified_value_info!(Vec<T>); impl_generic_specified_value_info!(Arc<T>); impl_generic_specified_value_info!(StdArc<T>); impl_generic_specified_value_info!(Range<Idx>); impl<T1, T2> SpecifiedValueInfo for (T1, T2) where T1: SpecifiedValueInfo, T2: SpecifiedValueInfo, { const SUPPORTED_TYPES: u8 = T1::SUPPORTED_TYPES | T2::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn) { T1::collect_completion_keywords(f); T2::collect_completion_keywords(f); } }
} }
random_line_split
specified_value_info.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Value information for devtools. use servo_arc::Arc; use std::ops::Range; use std::sync::Arc as StdArc; /// Type of value that a property supports. This is used by Gecko's /// devtools to make sense about value it parses, and types listed /// here should match TYPE_* constants in InspectorUtils.webidl. /// /// XXX This should really be a bitflags rather than a namespace mod, /// but currently we cannot use bitflags in const. #[allow(non_snake_case)] pub mod CssType { /// <color> pub const COLOR: u8 = 1 << 0; /// <gradient> pub const GRADIENT: u8 = 1 << 1; /// <timing-function> pub const TIMING_FUNCTION: u8 = 1 << 2; } /// See SpecifiedValueInfo::collect_completion_keywords. pub type KeywordsCollectFn<'a> = &'a mut FnMut(&[&'static str]); /// Information of values of a given specified value type. /// /// This trait is derivable with `#[derive(SpecifiedValueInfo)]`. /// /// The algorithm traverses the type definition. For `SUPPORTED_TYPES`, /// it puts an or'ed value of `SUPPORTED_TYPES` of all types it finds. /// For `collect_completion_keywords`, it recursively invokes this /// method on types found, and lists all keyword values and function /// names following the same rule as `ToCss` in that method. /// /// Some attributes of `ToCss` can affect the behavior, specifically: /// * If `#[css(function)]` is found, the content inside the annotated /// variant (or the whole type) isn't traversed, only the function /// name is listed in `collect_completion_keywords`. /// * If `#[css(skip)]` is found, the content inside the variant or /// field is ignored. /// * Values listed in `#[css(if_empty)]`, `#[parse(aliases)]`, and /// `#[css(keyword)]` are added into `collect_completion_keywords`. /// /// In addition to `css` attributes, it also has `value_info` helper /// attributes, including: /// * `#[value_info(ty = "TYPE")]` can be used to specify a constant /// from `CssType` to `SUPPORTED_TYPES`. /// * `#[value_info(other_values = "value1,value2")]` can be used to /// add other values related to a field, variant, or the type itself /// into `collect_completion_keywords`. /// * `#[value_info(starts_with_keyword)]` can be used on variants to /// add the name of a non-unit variant (serialized like `ToCss`) into /// `collect_completion_keywords`. pub trait SpecifiedValueInfo { /// Supported CssTypes by the given value type. /// /// XXX This should be typed CssType when that becomes a bitflags. /// Currently we cannot do so since bitflags cannot be used in constant. const SUPPORTED_TYPES: u8 = 0; /// Collect value starting words for the given specified value type. /// This includes keyword and function names which can appear at the /// beginning of a value of this type. /// /// Caller should pass in a callback function to accept the list of /// values. The callback function can be called multiple times, and /// some values passed to the callback may be duplicate. fn collect_completion_keywords(_f: KeywordsCollectFn) {} } impl SpecifiedValueInfo for bool {} impl SpecifiedValueInfo for f32 {} impl SpecifiedValueInfo for i8 {} impl SpecifiedValueInfo for i32 {} impl SpecifiedValueInfo for u8 {} impl SpecifiedValueInfo for u16 {} impl SpecifiedValueInfo for u32 {} impl SpecifiedValueInfo for str {} impl SpecifiedValueInfo for String {} #[cfg(feature = "servo")] impl SpecifiedValueInfo for ::servo_atoms::Atom {} #[cfg(feature = "servo")] impl SpecifiedValueInfo for ::servo_url::ServoUrl {} impl<T: SpecifiedValueInfo +?Sized> SpecifiedValueInfo for Box<T> { const SUPPORTED_TYPES: u8 = T::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn) { T::collect_completion_keywords(f); } } impl<T: SpecifiedValueInfo> SpecifiedValueInfo for [T] { const SUPPORTED_TYPES: u8 = T::SUPPORTED_TYPES; fn
(f: KeywordsCollectFn) { T::collect_completion_keywords(f); } } macro_rules! impl_generic_specified_value_info { ($ty:ident<$param:ident>) => { impl<$param: SpecifiedValueInfo> SpecifiedValueInfo for $ty<$param> { const SUPPORTED_TYPES: u8 = $param::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn) { $param::collect_completion_keywords(f); } } }; } impl_generic_specified_value_info!(Option<T>); impl_generic_specified_value_info!(Vec<T>); impl_generic_specified_value_info!(Arc<T>); impl_generic_specified_value_info!(StdArc<T>); impl_generic_specified_value_info!(Range<Idx>); impl<T1, T2> SpecifiedValueInfo for (T1, T2) where T1: SpecifiedValueInfo, T2: SpecifiedValueInfo, { const SUPPORTED_TYPES: u8 = T1::SUPPORTED_TYPES | T2::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn) { T1::collect_completion_keywords(f); T2::collect_completion_keywords(f); } }
collect_completion_keywords
identifier_name
specified_value_info.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Value information for devtools. use servo_arc::Arc; use std::ops::Range; use std::sync::Arc as StdArc; /// Type of value that a property supports. This is used by Gecko's /// devtools to make sense about value it parses, and types listed /// here should match TYPE_* constants in InspectorUtils.webidl. /// /// XXX This should really be a bitflags rather than a namespace mod, /// but currently we cannot use bitflags in const. #[allow(non_snake_case)] pub mod CssType { /// <color> pub const COLOR: u8 = 1 << 0; /// <gradient> pub const GRADIENT: u8 = 1 << 1; /// <timing-function> pub const TIMING_FUNCTION: u8 = 1 << 2; } /// See SpecifiedValueInfo::collect_completion_keywords. pub type KeywordsCollectFn<'a> = &'a mut FnMut(&[&'static str]); /// Information of values of a given specified value type. /// /// This trait is derivable with `#[derive(SpecifiedValueInfo)]`. /// /// The algorithm traverses the type definition. For `SUPPORTED_TYPES`, /// it puts an or'ed value of `SUPPORTED_TYPES` of all types it finds. /// For `collect_completion_keywords`, it recursively invokes this /// method on types found, and lists all keyword values and function /// names following the same rule as `ToCss` in that method. /// /// Some attributes of `ToCss` can affect the behavior, specifically: /// * If `#[css(function)]` is found, the content inside the annotated /// variant (or the whole type) isn't traversed, only the function /// name is listed in `collect_completion_keywords`. /// * If `#[css(skip)]` is found, the content inside the variant or /// field is ignored. /// * Values listed in `#[css(if_empty)]`, `#[parse(aliases)]`, and /// `#[css(keyword)]` are added into `collect_completion_keywords`. /// /// In addition to `css` attributes, it also has `value_info` helper /// attributes, including: /// * `#[value_info(ty = "TYPE")]` can be used to specify a constant /// from `CssType` to `SUPPORTED_TYPES`. /// * `#[value_info(other_values = "value1,value2")]` can be used to /// add other values related to a field, variant, or the type itself /// into `collect_completion_keywords`. /// * `#[value_info(starts_with_keyword)]` can be used on variants to /// add the name of a non-unit variant (serialized like `ToCss`) into /// `collect_completion_keywords`. pub trait SpecifiedValueInfo { /// Supported CssTypes by the given value type. /// /// XXX This should be typed CssType when that becomes a bitflags. /// Currently we cannot do so since bitflags cannot be used in constant. const SUPPORTED_TYPES: u8 = 0; /// Collect value starting words for the given specified value type. /// This includes keyword and function names which can appear at the /// beginning of a value of this type. /// /// Caller should pass in a callback function to accept the list of /// values. The callback function can be called multiple times, and /// some values passed to the callback may be duplicate. fn collect_completion_keywords(_f: KeywordsCollectFn) {} } impl SpecifiedValueInfo for bool {} impl SpecifiedValueInfo for f32 {} impl SpecifiedValueInfo for i8 {} impl SpecifiedValueInfo for i32 {} impl SpecifiedValueInfo for u8 {} impl SpecifiedValueInfo for u16 {} impl SpecifiedValueInfo for u32 {} impl SpecifiedValueInfo for str {} impl SpecifiedValueInfo for String {} #[cfg(feature = "servo")] impl SpecifiedValueInfo for ::servo_atoms::Atom {} #[cfg(feature = "servo")] impl SpecifiedValueInfo for ::servo_url::ServoUrl {} impl<T: SpecifiedValueInfo +?Sized> SpecifiedValueInfo for Box<T> { const SUPPORTED_TYPES: u8 = T::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn) { T::collect_completion_keywords(f); } } impl<T: SpecifiedValueInfo> SpecifiedValueInfo for [T] { const SUPPORTED_TYPES: u8 = T::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn)
} macro_rules! impl_generic_specified_value_info { ($ty:ident<$param:ident>) => { impl<$param: SpecifiedValueInfo> SpecifiedValueInfo for $ty<$param> { const SUPPORTED_TYPES: u8 = $param::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn) { $param::collect_completion_keywords(f); } } }; } impl_generic_specified_value_info!(Option<T>); impl_generic_specified_value_info!(Vec<T>); impl_generic_specified_value_info!(Arc<T>); impl_generic_specified_value_info!(StdArc<T>); impl_generic_specified_value_info!(Range<Idx>); impl<T1, T2> SpecifiedValueInfo for (T1, T2) where T1: SpecifiedValueInfo, T2: SpecifiedValueInfo, { const SUPPORTED_TYPES: u8 = T1::SUPPORTED_TYPES | T2::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn) { T1::collect_completion_keywords(f); T2::collect_completion_keywords(f); } }
{ T::collect_completion_keywords(f); }
identifier_body
events.rs
//! Contains `XmlEvent` datatype, instances of which are emitted by the parser. use std::fmt; use name::OwnedName; use attribute::OwnedAttribute; use common::{HasPosition, XmlVersion}; use common::Error as CommonError; use namespace::Namespace; /// An element of an XML input stream. /// /// Items of this enum are emitted by `reader::EventReader`. They correspond to different /// elements of an XML document. #[derive(PartialEq, Clone)] pub enum XmlEvent { /// Corresponds to XML document declaration. /// /// This event is always emitted before any other event (except `Error`). It is emitted /// even if the actual declaration is not present in the document. StartDocument { /// XML version. /// /// If XML declaration is not present, defaults to `Version10`. version: XmlVersion, /// XML document encoding. /// /// If XML declaration is not present or does not contain `encoding` attribute, /// defaults to `"UTF-8"`. This field is currently used for no other purpose than /// informational.
/// XML standalone declaration. /// /// If XML document is not present or does not contain `standalone` attribute, /// defaults to `None`. This field is currently used for no other purpose than /// informational. standalone: Option<bool> }, /// Denotes to the end of the document stream. /// /// This event is always emitted after any other event (except `Error`). After it /// is emitted for the first time, it will always be emitted on next event pull attempts. EndDocument, /// Denotes an XML processing instruction. /// /// This event contains a processing instruction target (`name`) and opaque `data`. It /// is up to the application to process them. ProcessingInstruction { /// Processing instruction target. name: String, /// Processing instruction content. data: Option<String> }, /// Denotes a beginning of an XML element. /// /// This event is emitted after parsing opening tags or after parsing bodiless tags. In the /// latter case `EndElement` event immediately follows. StartElement { /// Qualified name of the element. name: OwnedName, /// A list of attributes associated with the element. /// /// Currently attributes are not checked for duplicates (TODO) attributes: Vec<OwnedAttribute>, /// Contents of the namespace mapping at this point of the document. namespace: Namespace, }, /// Denotes an end of an XML document. /// /// This event is emitted after parsing closing tags or after parsing bodiless tags. In the /// latter case it is emitted immediately after corresponding `StartElement` event. EndElement { /// Qualified name of the element. name: OwnedName }, /// Denotes CDATA content. /// /// This event contains unparsed data. No unescaping will be performed. /// /// It is possible to configure a parser to emit `Characters` event instead of `CData`. See /// `pull::ParserConfiguration` structure for more information. CData(String), /// Denotes a comment. /// /// It is possible to configure a parser to ignore comments, so this event will never be emitted. /// See `pull::ParserConfiguration` structure for more information. Comment(String), /// Denotes character data outside of tags. /// /// Contents of this event will always be unescaped, so no entities like `&lt;` or `&amp;` or `&#123;` /// will appear in it. /// /// It is possible to configure a parser to trim leading and trailing whitespace for this event. /// See `pull::ParserConfiguration` structure for more information. Characters(String), /// Denotes a chunk of whitespace outside of tags. /// /// It is possible to configure a parser to emit `Characters` event instead of `Whitespace`. /// See `pull::ParserConfiguration` structure for more information. When combined with whitespace /// trimming, it will eliminate standalone whitespace from the event stream completely. Whitespace(String), /// Denotes parsing error. /// /// This event will always be the last event in the stream; no further XML processing will be done /// as is required by XML specification, [section 1.2][1]. /// /// [1]: http://www.w3.org/TR/2006/REC-xml11-20060816/#sec-terminology Error(CommonError) } impl fmt::Debug for XmlEvent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { XmlEvent::StartDocument { ref version, ref encoding, ref standalone } => write!(f, "StartDocument({}, {}, {:?})", version, *encoding, *standalone), XmlEvent::EndDocument => write!(f, "EndDocument"), XmlEvent::ProcessingInstruction { ref name, ref data } => write!(f, "ProcessingInstruction({}{})", *name, match *data { Some(ref data) => format!(", {}", data), None => String::new() }), XmlEvent::StartElement { ref name, ref attributes, namespace: Namespace(ref namespace) } => write!(f, "StartElement({}, {:?}{})", name, namespace, if attributes.is_empty() { String::new() } else { let attributes: Vec<String> = attributes.iter().map( |a| format!("{} -> {}", a.name, a.value) ).collect(); format!(", [{}]", attributes.connect(", ")) }), XmlEvent::EndElement { ref name } => write!(f, "EndElement({})", name), XmlEvent::Comment(ref data) => write!(f, "Comment({})", data), XmlEvent::CData(ref data) => write!(f, "CData({})", data), XmlEvent::Characters(ref data) => write!(f, "Characters({})", data), XmlEvent::Whitespace(ref data) => write!(f, "Whitespace({})", data), XmlEvent::Error(ref e) => write!(f, "Error(row: {}, col: {}, message: {})", e.row()+1, e.col()+1, e.msg()) } } } impl XmlEvent { pub fn as_writer_event<'a>(&'a self) -> Option<::writer::events::XmlEvent<'a>> { match *self { XmlEvent::StartDocument { version, ref encoding, standalone } => Some(::writer::events::XmlEvent::StartDocument { version: version, encoding: Some(encoding.as_slice()), standalone: standalone }), XmlEvent::ProcessingInstruction { ref name, ref data } => Some(::writer::events::XmlEvent::ProcessingInstruction { name: name.as_slice(), data: data.as_ref().map(|s| s.as_slice()) }), XmlEvent::StartElement { ref name, ref attributes, ref namespace } => Some(::writer::events::XmlEvent::StartElement { name: name.borrow(), attributes: attributes.iter().map(|a| a.borrow()).collect(), namespace: namespace }), XmlEvent::EndElement { ref name } => Some(::writer::events::XmlEvent::EndElement { name: name.borrow() }), XmlEvent::Comment(ref data) => Some(::writer::events::XmlEvent::Comment(data.as_slice())), XmlEvent::CData(ref data) => Some(::writer::events::XmlEvent::CData(data.as_slice())), XmlEvent::Characters(ref data) => Some(::writer::events::XmlEvent::Characters(data.as_slice())), XmlEvent::Whitespace(ref data) => Some(::writer::events::XmlEvent::Characters(data.as_slice())), _ => None } } }
encoding: String,
random_line_split
events.rs
//! Contains `XmlEvent` datatype, instances of which are emitted by the parser. use std::fmt; use name::OwnedName; use attribute::OwnedAttribute; use common::{HasPosition, XmlVersion}; use common::Error as CommonError; use namespace::Namespace; /// An element of an XML input stream. /// /// Items of this enum are emitted by `reader::EventReader`. They correspond to different /// elements of an XML document. #[derive(PartialEq, Clone)] pub enum XmlEvent { /// Corresponds to XML document declaration. /// /// This event is always emitted before any other event (except `Error`). It is emitted /// even if the actual declaration is not present in the document. StartDocument { /// XML version. /// /// If XML declaration is not present, defaults to `Version10`. version: XmlVersion, /// XML document encoding. /// /// If XML declaration is not present or does not contain `encoding` attribute, /// defaults to `"UTF-8"`. This field is currently used for no other purpose than /// informational. encoding: String, /// XML standalone declaration. /// /// If XML document is not present or does not contain `standalone` attribute, /// defaults to `None`. This field is currently used for no other purpose than /// informational. standalone: Option<bool> }, /// Denotes to the end of the document stream. /// /// This event is always emitted after any other event (except `Error`). After it /// is emitted for the first time, it will always be emitted on next event pull attempts. EndDocument, /// Denotes an XML processing instruction. /// /// This event contains a processing instruction target (`name`) and opaque `data`. It /// is up to the application to process them. ProcessingInstruction { /// Processing instruction target. name: String, /// Processing instruction content. data: Option<String> }, /// Denotes a beginning of an XML element. /// /// This event is emitted after parsing opening tags or after parsing bodiless tags. In the /// latter case `EndElement` event immediately follows. StartElement { /// Qualified name of the element. name: OwnedName, /// A list of attributes associated with the element. /// /// Currently attributes are not checked for duplicates (TODO) attributes: Vec<OwnedAttribute>, /// Contents of the namespace mapping at this point of the document. namespace: Namespace, }, /// Denotes an end of an XML document. /// /// This event is emitted after parsing closing tags or after parsing bodiless tags. In the /// latter case it is emitted immediately after corresponding `StartElement` event. EndElement { /// Qualified name of the element. name: OwnedName }, /// Denotes CDATA content. /// /// This event contains unparsed data. No unescaping will be performed. /// /// It is possible to configure a parser to emit `Characters` event instead of `CData`. See /// `pull::ParserConfiguration` structure for more information. CData(String), /// Denotes a comment. /// /// It is possible to configure a parser to ignore comments, so this event will never be emitted. /// See `pull::ParserConfiguration` structure for more information. Comment(String), /// Denotes character data outside of tags. /// /// Contents of this event will always be unescaped, so no entities like `&lt;` or `&amp;` or `&#123;` /// will appear in it. /// /// It is possible to configure a parser to trim leading and trailing whitespace for this event. /// See `pull::ParserConfiguration` structure for more information. Characters(String), /// Denotes a chunk of whitespace outside of tags. /// /// It is possible to configure a parser to emit `Characters` event instead of `Whitespace`. /// See `pull::ParserConfiguration` structure for more information. When combined with whitespace /// trimming, it will eliminate standalone whitespace from the event stream completely. Whitespace(String), /// Denotes parsing error. /// /// This event will always be the last event in the stream; no further XML processing will be done /// as is required by XML specification, [section 1.2][1]. /// /// [1]: http://www.w3.org/TR/2006/REC-xml11-20060816/#sec-terminology Error(CommonError) } impl fmt::Debug for XmlEvent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { XmlEvent::StartDocument { ref version, ref encoding, ref standalone } => write!(f, "StartDocument({}, {}, {:?})", version, *encoding, *standalone), XmlEvent::EndDocument => write!(f, "EndDocument"), XmlEvent::ProcessingInstruction { ref name, ref data } => write!(f, "ProcessingInstruction({}{})", *name, match *data { Some(ref data) => format!(", {}", data), None => String::new() }), XmlEvent::StartElement { ref name, ref attributes, namespace: Namespace(ref namespace) } => write!(f, "StartElement({}, {:?}{})", name, namespace, if attributes.is_empty() { String::new() } else { let attributes: Vec<String> = attributes.iter().map( |a| format!("{} -> {}", a.name, a.value) ).collect(); format!(", [{}]", attributes.connect(", ")) }), XmlEvent::EndElement { ref name } => write!(f, "EndElement({})", name), XmlEvent::Comment(ref data) => write!(f, "Comment({})", data), XmlEvent::CData(ref data) => write!(f, "CData({})", data), XmlEvent::Characters(ref data) => write!(f, "Characters({})", data), XmlEvent::Whitespace(ref data) => write!(f, "Whitespace({})", data), XmlEvent::Error(ref e) => write!(f, "Error(row: {}, col: {}, message: {})", e.row()+1, e.col()+1, e.msg()) } } } impl XmlEvent { pub fn as_writer_event<'a>(&'a self) -> Option<::writer::events::XmlEvent<'a>>
Some(::writer::events::XmlEvent::EndElement { name: name.borrow() }), XmlEvent::Comment(ref data) => Some(::writer::events::XmlEvent::Comment(data.as_slice())), XmlEvent::CData(ref data) => Some(::writer::events::XmlEvent::CData(data.as_slice())), XmlEvent::Characters(ref data) => Some(::writer::events::XmlEvent::Characters(data.as_slice())), XmlEvent::Whitespace(ref data) => Some(::writer::events::XmlEvent::Characters(data.as_slice())), _ => None } } }
{ match *self { XmlEvent::StartDocument { version, ref encoding, standalone } => Some(::writer::events::XmlEvent::StartDocument { version: version, encoding: Some(encoding.as_slice()), standalone: standalone }), XmlEvent::ProcessingInstruction { ref name, ref data } => Some(::writer::events::XmlEvent::ProcessingInstruction { name: name.as_slice(), data: data.as_ref().map(|s| s.as_slice()) }), XmlEvent::StartElement { ref name, ref attributes, ref namespace } => Some(::writer::events::XmlEvent::StartElement { name: name.borrow(), attributes: attributes.iter().map(|a| a.borrow()).collect(), namespace: namespace }), XmlEvent::EndElement { ref name } =>
identifier_body
events.rs
//! Contains `XmlEvent` datatype, instances of which are emitted by the parser. use std::fmt; use name::OwnedName; use attribute::OwnedAttribute; use common::{HasPosition, XmlVersion}; use common::Error as CommonError; use namespace::Namespace; /// An element of an XML input stream. /// /// Items of this enum are emitted by `reader::EventReader`. They correspond to different /// elements of an XML document. #[derive(PartialEq, Clone)] pub enum XmlEvent { /// Corresponds to XML document declaration. /// /// This event is always emitted before any other event (except `Error`). It is emitted /// even if the actual declaration is not present in the document. StartDocument { /// XML version. /// /// If XML declaration is not present, defaults to `Version10`. version: XmlVersion, /// XML document encoding. /// /// If XML declaration is not present or does not contain `encoding` attribute, /// defaults to `"UTF-8"`. This field is currently used for no other purpose than /// informational. encoding: String, /// XML standalone declaration. /// /// If XML document is not present or does not contain `standalone` attribute, /// defaults to `None`. This field is currently used for no other purpose than /// informational. standalone: Option<bool> }, /// Denotes to the end of the document stream. /// /// This event is always emitted after any other event (except `Error`). After it /// is emitted for the first time, it will always be emitted on next event pull attempts. EndDocument, /// Denotes an XML processing instruction. /// /// This event contains a processing instruction target (`name`) and opaque `data`. It /// is up to the application to process them. ProcessingInstruction { /// Processing instruction target. name: String, /// Processing instruction content. data: Option<String> }, /// Denotes a beginning of an XML element. /// /// This event is emitted after parsing opening tags or after parsing bodiless tags. In the /// latter case `EndElement` event immediately follows. StartElement { /// Qualified name of the element. name: OwnedName, /// A list of attributes associated with the element. /// /// Currently attributes are not checked for duplicates (TODO) attributes: Vec<OwnedAttribute>, /// Contents of the namespace mapping at this point of the document. namespace: Namespace, }, /// Denotes an end of an XML document. /// /// This event is emitted after parsing closing tags or after parsing bodiless tags. In the /// latter case it is emitted immediately after corresponding `StartElement` event. EndElement { /// Qualified name of the element. name: OwnedName }, /// Denotes CDATA content. /// /// This event contains unparsed data. No unescaping will be performed. /// /// It is possible to configure a parser to emit `Characters` event instead of `CData`. See /// `pull::ParserConfiguration` structure for more information. CData(String), /// Denotes a comment. /// /// It is possible to configure a parser to ignore comments, so this event will never be emitted. /// See `pull::ParserConfiguration` structure for more information. Comment(String), /// Denotes character data outside of tags. /// /// Contents of this event will always be unescaped, so no entities like `&lt;` or `&amp;` or `&#123;` /// will appear in it. /// /// It is possible to configure a parser to trim leading and trailing whitespace for this event. /// See `pull::ParserConfiguration` structure for more information. Characters(String), /// Denotes a chunk of whitespace outside of tags. /// /// It is possible to configure a parser to emit `Characters` event instead of `Whitespace`. /// See `pull::ParserConfiguration` structure for more information. When combined with whitespace /// trimming, it will eliminate standalone whitespace from the event stream completely. Whitespace(String), /// Denotes parsing error. /// /// This event will always be the last event in the stream; no further XML processing will be done /// as is required by XML specification, [section 1.2][1]. /// /// [1]: http://www.w3.org/TR/2006/REC-xml11-20060816/#sec-terminology Error(CommonError) } impl fmt::Debug for XmlEvent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { XmlEvent::StartDocument { ref version, ref encoding, ref standalone } => write!(f, "StartDocument({}, {}, {:?})", version, *encoding, *standalone), XmlEvent::EndDocument => write!(f, "EndDocument"), XmlEvent::ProcessingInstruction { ref name, ref data } => write!(f, "ProcessingInstruction({}{})", *name, match *data { Some(ref data) => format!(", {}", data), None => String::new() }), XmlEvent::StartElement { ref name, ref attributes, namespace: Namespace(ref namespace) } => write!(f, "StartElement({}, {:?}{})", name, namespace, if attributes.is_empty() { String::new() } else { let attributes: Vec<String> = attributes.iter().map( |a| format!("{} -> {}", a.name, a.value) ).collect(); format!(", [{}]", attributes.connect(", ")) }), XmlEvent::EndElement { ref name } => write!(f, "EndElement({})", name), XmlEvent::Comment(ref data) => write!(f, "Comment({})", data), XmlEvent::CData(ref data) => write!(f, "CData({})", data), XmlEvent::Characters(ref data) => write!(f, "Characters({})", data), XmlEvent::Whitespace(ref data) => write!(f, "Whitespace({})", data), XmlEvent::Error(ref e) => write!(f, "Error(row: {}, col: {}, message: {})", e.row()+1, e.col()+1, e.msg()) } } } impl XmlEvent { pub fn
<'a>(&'a self) -> Option<::writer::events::XmlEvent<'a>> { match *self { XmlEvent::StartDocument { version, ref encoding, standalone } => Some(::writer::events::XmlEvent::StartDocument { version: version, encoding: Some(encoding.as_slice()), standalone: standalone }), XmlEvent::ProcessingInstruction { ref name, ref data } => Some(::writer::events::XmlEvent::ProcessingInstruction { name: name.as_slice(), data: data.as_ref().map(|s| s.as_slice()) }), XmlEvent::StartElement { ref name, ref attributes, ref namespace } => Some(::writer::events::XmlEvent::StartElement { name: name.borrow(), attributes: attributes.iter().map(|a| a.borrow()).collect(), namespace: namespace }), XmlEvent::EndElement { ref name } => Some(::writer::events::XmlEvent::EndElement { name: name.borrow() }), XmlEvent::Comment(ref data) => Some(::writer::events::XmlEvent::Comment(data.as_slice())), XmlEvent::CData(ref data) => Some(::writer::events::XmlEvent::CData(data.as_slice())), XmlEvent::Characters(ref data) => Some(::writer::events::XmlEvent::Characters(data.as_slice())), XmlEvent::Whitespace(ref data) => Some(::writer::events::XmlEvent::Characters(data.as_slice())), _ => None } } }
as_writer_event
identifier_name
filemanager_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::create_embedder_proxy; use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_thread::FileManager; use net::resource_thread::CoreResourceThreadPool; use net_traits::blob_url_store::BlobURLStoreError; use net_traits::filemanager_thread::{ FileManagerThreadError, FileManagerThreadMsg, ReadFileProgress, }; use servo_config::set_pref; use std::fs::File; use std::io::Read; use std::path::PathBuf; use std::sync::Arc; #[test] fn test_filemanager()
filemanager.handle(FileManagerThreadMsg::SelectFile( patterns.clone(), tx, origin.clone(), Some("tests/test.jpeg".to_string()), )); let selected = rx .recv() .expect("Broken channel") .expect("The file manager failed to find test.jpeg"); // Expecting attributes conforming the spec assert_eq!(selected.filename, PathBuf::from("test.jpeg")); assert_eq!(selected.type_string, "image/jpeg".to_string()); // Test by reading, expecting same content { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); if let ReadFileProgress::Meta(blob_buf) = msg.expect("File manager reading failure is unexpected") { let mut bytes = blob_buf.bytes; loop { match rx2 .recv() .expect("Broken channel") .expect("File manager reading failure is unexpected") { ReadFileProgress::Meta(_) => { panic!("Invalid FileManager reply"); }, ReadFileProgress::Partial(mut bytes_in) => { bytes.append(&mut bytes_in); }, ReadFileProgress::EOF => { break; }, } } assert_eq!(test_file_content, bytes, "Read content differs"); } else { panic!("Invalid FileManager reply"); } } // Delete the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::DecRef( selected.id.clone(), origin.clone(), tx2, )); let ret = rx2.recv().expect("Broken channel"); assert!(ret.is_ok(), "DecRef is not okay"); } // Test by reading again, expecting read error because we invalidated the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); match msg { Err(FileManagerThreadError::BlobURLStoreError( BlobURLStoreError::InvalidFileID, )) => {}, other => { assert!( false, "Get unexpected response after deleting the id: {:?}", other ); }, } } } }
{ let pool = CoreResourceThreadPool::new(1); let pool_handle = Arc::new(pool); let filemanager = FileManager::new(create_embedder_proxy(), Arc::downgrade(&pool_handle)); set_pref!(dom.testing.html_input_element.select_files.enabled, true); // Try to open a dummy file "components/net/tests/test.jpeg" in tree let mut handler = File::open("tests/test.jpeg").expect("test.jpeg is stolen"); let mut test_file_content = vec![]; handler .read_to_end(&mut test_file_content) .expect("Read components/net/tests/test.jpeg error"); let patterns = vec![FilterPattern(".txt".to_string())]; let origin = "test.com".to_string(); { // Try to select a dummy file "components/net/tests/test.jpeg" let (tx, rx) = ipc::channel().unwrap();
identifier_body
filemanager_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::create_embedder_proxy; use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_thread::FileManager; use net::resource_thread::CoreResourceThreadPool; use net_traits::blob_url_store::BlobURLStoreError; use net_traits::filemanager_thread::{ FileManagerThreadError, FileManagerThreadMsg, ReadFileProgress, }; use servo_config::set_pref; use std::fs::File; use std::io::Read; use std::path::PathBuf; use std::sync::Arc; #[test] fn test_filemanager() { let pool = CoreResourceThreadPool::new(1); let pool_handle = Arc::new(pool); let filemanager = FileManager::new(create_embedder_proxy(), Arc::downgrade(&pool_handle)); set_pref!(dom.testing.html_input_element.select_files.enabled, true); // Try to open a dummy file "components/net/tests/test.jpeg" in tree let mut handler = File::open("tests/test.jpeg").expect("test.jpeg is stolen"); let mut test_file_content = vec![]; handler .read_to_end(&mut test_file_content) .expect("Read components/net/tests/test.jpeg error"); let patterns = vec![FilterPattern(".txt".to_string())]; let origin = "test.com".to_string(); { // Try to select a dummy file "components/net/tests/test.jpeg" let (tx, rx) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::SelectFile( patterns.clone(), tx, origin.clone(), Some("tests/test.jpeg".to_string()), )); let selected = rx .recv() .expect("Broken channel") .expect("The file manager failed to find test.jpeg"); // Expecting attributes conforming the spec assert_eq!(selected.filename, PathBuf::from("test.jpeg")); assert_eq!(selected.type_string, "image/jpeg".to_string()); // Test by reading, expecting same content { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); if let ReadFileProgress::Meta(blob_buf) = msg.expect("File manager reading failure is unexpected") { let mut bytes = blob_buf.bytes; loop { match rx2 .recv() .expect("Broken channel") .expect("File manager reading failure is unexpected") { ReadFileProgress::Meta(_) => { panic!("Invalid FileManager reply"); }, ReadFileProgress::Partial(mut bytes_in) => { bytes.append(&mut bytes_in); }, ReadFileProgress::EOF => { break; }, } } assert_eq!(test_file_content, bytes, "Read content differs"); } else
} // Delete the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::DecRef( selected.id.clone(), origin.clone(), tx2, )); let ret = rx2.recv().expect("Broken channel"); assert!(ret.is_ok(), "DecRef is not okay"); } // Test by reading again, expecting read error because we invalidated the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); match msg { Err(FileManagerThreadError::BlobURLStoreError( BlobURLStoreError::InvalidFileID, )) => {}, other => { assert!( false, "Get unexpected response after deleting the id: {:?}", other ); }, } } } }
{ panic!("Invalid FileManager reply"); }
conditional_block
filemanager_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::create_embedder_proxy; use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_thread::FileManager; use net::resource_thread::CoreResourceThreadPool; use net_traits::blob_url_store::BlobURLStoreError; use net_traits::filemanager_thread::{ FileManagerThreadError, FileManagerThreadMsg, ReadFileProgress, }; use servo_config::set_pref; use std::fs::File; use std::io::Read; use std::path::PathBuf; use std::sync::Arc; #[test] fn test_filemanager() { let pool = CoreResourceThreadPool::new(1); let pool_handle = Arc::new(pool); let filemanager = FileManager::new(create_embedder_proxy(), Arc::downgrade(&pool_handle)); set_pref!(dom.testing.html_input_element.select_files.enabled, true); // Try to open a dummy file "components/net/tests/test.jpeg" in tree let mut handler = File::open("tests/test.jpeg").expect("test.jpeg is stolen"); let mut test_file_content = vec![]; handler .read_to_end(&mut test_file_content) .expect("Read components/net/tests/test.jpeg error"); let patterns = vec![FilterPattern(".txt".to_string())]; let origin = "test.com".to_string(); { // Try to select a dummy file "components/net/tests/test.jpeg" let (tx, rx) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::SelectFile( patterns.clone(), tx, origin.clone(), Some("tests/test.jpeg".to_string()), )); let selected = rx .recv() .expect("Broken channel") .expect("The file manager failed to find test.jpeg"); // Expecting attributes conforming the spec assert_eq!(selected.filename, PathBuf::from("test.jpeg")); assert_eq!(selected.type_string, "image/jpeg".to_string()); // Test by reading, expecting same content { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); if let ReadFileProgress::Meta(blob_buf) = msg.expect("File manager reading failure is unexpected") { let mut bytes = blob_buf.bytes; loop { match rx2 .recv() .expect("Broken channel") .expect("File manager reading failure is unexpected") { ReadFileProgress::Meta(_) => { panic!("Invalid FileManager reply"); }, ReadFileProgress::Partial(mut bytes_in) => { bytes.append(&mut bytes_in); }, ReadFileProgress::EOF => { break; }, } } assert_eq!(test_file_content, bytes, "Read content differs"); } else { panic!("Invalid FileManager reply"); } } // Delete the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::DecRef( selected.id.clone(), origin.clone(), tx2, )); let ret = rx2.recv().expect("Broken channel"); assert!(ret.is_ok(), "DecRef is not okay"); } // Test by reading again, expecting read error because we invalidated the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); match msg { Err(FileManagerThreadError::BlobURLStoreError( BlobURLStoreError::InvalidFileID, )) => {}, other => {
); }, } } } }
assert!( false, "Get unexpected response after deleting the id: {:?}", other
random_line_split
filemanager_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::create_embedder_proxy; use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_thread::FileManager; use net::resource_thread::CoreResourceThreadPool; use net_traits::blob_url_store::BlobURLStoreError; use net_traits::filemanager_thread::{ FileManagerThreadError, FileManagerThreadMsg, ReadFileProgress, }; use servo_config::set_pref; use std::fs::File; use std::io::Read; use std::path::PathBuf; use std::sync::Arc; #[test] fn
() { let pool = CoreResourceThreadPool::new(1); let pool_handle = Arc::new(pool); let filemanager = FileManager::new(create_embedder_proxy(), Arc::downgrade(&pool_handle)); set_pref!(dom.testing.html_input_element.select_files.enabled, true); // Try to open a dummy file "components/net/tests/test.jpeg" in tree let mut handler = File::open("tests/test.jpeg").expect("test.jpeg is stolen"); let mut test_file_content = vec![]; handler .read_to_end(&mut test_file_content) .expect("Read components/net/tests/test.jpeg error"); let patterns = vec![FilterPattern(".txt".to_string())]; let origin = "test.com".to_string(); { // Try to select a dummy file "components/net/tests/test.jpeg" let (tx, rx) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::SelectFile( patterns.clone(), tx, origin.clone(), Some("tests/test.jpeg".to_string()), )); let selected = rx .recv() .expect("Broken channel") .expect("The file manager failed to find test.jpeg"); // Expecting attributes conforming the spec assert_eq!(selected.filename, PathBuf::from("test.jpeg")); assert_eq!(selected.type_string, "image/jpeg".to_string()); // Test by reading, expecting same content { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); if let ReadFileProgress::Meta(blob_buf) = msg.expect("File manager reading failure is unexpected") { let mut bytes = blob_buf.bytes; loop { match rx2 .recv() .expect("Broken channel") .expect("File manager reading failure is unexpected") { ReadFileProgress::Meta(_) => { panic!("Invalid FileManager reply"); }, ReadFileProgress::Partial(mut bytes_in) => { bytes.append(&mut bytes_in); }, ReadFileProgress::EOF => { break; }, } } assert_eq!(test_file_content, bytes, "Read content differs"); } else { panic!("Invalid FileManager reply"); } } // Delete the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::DecRef( selected.id.clone(), origin.clone(), tx2, )); let ret = rx2.recv().expect("Broken channel"); assert!(ret.is_ok(), "DecRef is not okay"); } // Test by reading again, expecting read error because we invalidated the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); match msg { Err(FileManagerThreadError::BlobURLStoreError( BlobURLStoreError::InvalidFileID, )) => {}, other => { assert!( false, "Get unexpected response after deleting the id: {:?}", other ); }, } } } }
test_filemanager
identifier_name
client.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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. //! The Butterfly client library. //! //! This will connect to a given butterfly members `Pull` thread, and inject a rumor. use habitat_core::crypto::SymKey; use habitat_core::service::ServiceGroup; use zmq; use ZMQ_CONTEXT; use message; use rumor::Rumor; use rumor::departure::Departure; use rumor::service_config::ServiceConfig; use rumor::service_file::ServiceFile; use error::{Error, Result}; /// Holds a ZMQ Push socket, and an optional ring encryption key. pub struct Client { socket: zmq::Socket, ring_key: Option<SymKey>, } impl Client { /// Connect this client to the address, and optionally encrypt the traffic. pub fn new<A>(addr: A, ring_key: Option<SymKey>) -> Result<Client> where A: ToString, { let socket = (**ZMQ_CONTEXT) .as_mut() .socket(zmq::PUSH) .expect("Failure to create the ZMQ push socket"); socket .set_linger(-1) .expect("Failure to set the ZMQ push socket to not linger"); socket .set_tcp_keepalive(0) .expect("Failure to set the ZMQ push socket to not use keepalive"); socket .set_immediate(true) .expect("Failure to set the ZMQ push socket to immediate"); socket .set_sndhwm(1000) .expect("Failure to set the ZMQ push socket hwm"); socket .set_sndtimeo(500) .expect("Failure to set the ZMQ send timeout"); let to_addr = format!("tcp://{}", addr.to_string()); socket.connect(&to_addr).map_err(Error::ZmqConnectError)?; Ok(Client { socket: socket, ring_key: ring_key, }) } /// Create a departure notification and send it to the server. pub fn send_departure<T>(&mut self, member_id: T) -> Result<()> where T: ToString, { let departure = Departure::new(member_id); self.send(departure) } /// Create a service configuration and send it to the server. pub fn send_service_config( &mut self, service_group: ServiceGroup, incarnation: u64,
sc.set_incarnation(incarnation); sc.set_encrypted(encrypted); self.send(sc) } /// Create a service file and send it to the server. pub fn send_service_file<S: Into<String>>( &mut self, service_group: ServiceGroup, filename: S, incarnation: u64, body: Vec<u8>, encrypted: bool, ) -> Result<()> { let mut sf = ServiceFile::new("butterflyclient", service_group, filename, body); sf.set_incarnation(incarnation); sf.set_encrypted(encrypted); self.send(sf) } /// Send any `Rumor` to the server. pub fn send<T: Rumor>(&mut self, rumor: T) -> Result<()> { let bytes = rumor.write_to_bytes()?; let wire_msg = message::generate_wire(bytes, self.ring_key.as_ref())?; self.socket.send(&wire_msg, 0).map_err(Error::ZmqSendError) } }
config: Vec<u8>, encrypted: bool, ) -> Result<()> { let mut sc = ServiceConfig::new("butterflyclient", service_group, config);
random_line_split
client.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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. //! The Butterfly client library. //! //! This will connect to a given butterfly members `Pull` thread, and inject a rumor. use habitat_core::crypto::SymKey; use habitat_core::service::ServiceGroup; use zmq; use ZMQ_CONTEXT; use message; use rumor::Rumor; use rumor::departure::Departure; use rumor::service_config::ServiceConfig; use rumor::service_file::ServiceFile; use error::{Error, Result}; /// Holds a ZMQ Push socket, and an optional ring encryption key. pub struct
{ socket: zmq::Socket, ring_key: Option<SymKey>, } impl Client { /// Connect this client to the address, and optionally encrypt the traffic. pub fn new<A>(addr: A, ring_key: Option<SymKey>) -> Result<Client> where A: ToString, { let socket = (**ZMQ_CONTEXT) .as_mut() .socket(zmq::PUSH) .expect("Failure to create the ZMQ push socket"); socket .set_linger(-1) .expect("Failure to set the ZMQ push socket to not linger"); socket .set_tcp_keepalive(0) .expect("Failure to set the ZMQ push socket to not use keepalive"); socket .set_immediate(true) .expect("Failure to set the ZMQ push socket to immediate"); socket .set_sndhwm(1000) .expect("Failure to set the ZMQ push socket hwm"); socket .set_sndtimeo(500) .expect("Failure to set the ZMQ send timeout"); let to_addr = format!("tcp://{}", addr.to_string()); socket.connect(&to_addr).map_err(Error::ZmqConnectError)?; Ok(Client { socket: socket, ring_key: ring_key, }) } /// Create a departure notification and send it to the server. pub fn send_departure<T>(&mut self, member_id: T) -> Result<()> where T: ToString, { let departure = Departure::new(member_id); self.send(departure) } /// Create a service configuration and send it to the server. pub fn send_service_config( &mut self, service_group: ServiceGroup, incarnation: u64, config: Vec<u8>, encrypted: bool, ) -> Result<()> { let mut sc = ServiceConfig::new("butterflyclient", service_group, config); sc.set_incarnation(incarnation); sc.set_encrypted(encrypted); self.send(sc) } /// Create a service file and send it to the server. pub fn send_service_file<S: Into<String>>( &mut self, service_group: ServiceGroup, filename: S, incarnation: u64, body: Vec<u8>, encrypted: bool, ) -> Result<()> { let mut sf = ServiceFile::new("butterflyclient", service_group, filename, body); sf.set_incarnation(incarnation); sf.set_encrypted(encrypted); self.send(sf) } /// Send any `Rumor` to the server. pub fn send<T: Rumor>(&mut self, rumor: T) -> Result<()> { let bytes = rumor.write_to_bytes()?; let wire_msg = message::generate_wire(bytes, self.ring_key.as_ref())?; self.socket.send(&wire_msg, 0).map_err(Error::ZmqSendError) } }
Client
identifier_name
client.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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. //! The Butterfly client library. //! //! This will connect to a given butterfly members `Pull` thread, and inject a rumor. use habitat_core::crypto::SymKey; use habitat_core::service::ServiceGroup; use zmq; use ZMQ_CONTEXT; use message; use rumor::Rumor; use rumor::departure::Departure; use rumor::service_config::ServiceConfig; use rumor::service_file::ServiceFile; use error::{Error, Result}; /// Holds a ZMQ Push socket, and an optional ring encryption key. pub struct Client { socket: zmq::Socket, ring_key: Option<SymKey>, } impl Client { /// Connect this client to the address, and optionally encrypt the traffic. pub fn new<A>(addr: A, ring_key: Option<SymKey>) -> Result<Client> where A: ToString, { let socket = (**ZMQ_CONTEXT) .as_mut() .socket(zmq::PUSH) .expect("Failure to create the ZMQ push socket"); socket .set_linger(-1) .expect("Failure to set the ZMQ push socket to not linger"); socket .set_tcp_keepalive(0) .expect("Failure to set the ZMQ push socket to not use keepalive"); socket .set_immediate(true) .expect("Failure to set the ZMQ push socket to immediate"); socket .set_sndhwm(1000) .expect("Failure to set the ZMQ push socket hwm"); socket .set_sndtimeo(500) .expect("Failure to set the ZMQ send timeout"); let to_addr = format!("tcp://{}", addr.to_string()); socket.connect(&to_addr).map_err(Error::ZmqConnectError)?; Ok(Client { socket: socket, ring_key: ring_key, }) } /// Create a departure notification and send it to the server. pub fn send_departure<T>(&mut self, member_id: T) -> Result<()> where T: ToString, { let departure = Departure::new(member_id); self.send(departure) } /// Create a service configuration and send it to the server. pub fn send_service_config( &mut self, service_group: ServiceGroup, incarnation: u64, config: Vec<u8>, encrypted: bool, ) -> Result<()> { let mut sc = ServiceConfig::new("butterflyclient", service_group, config); sc.set_incarnation(incarnation); sc.set_encrypted(encrypted); self.send(sc) } /// Create a service file and send it to the server. pub fn send_service_file<S: Into<String>>( &mut self, service_group: ServiceGroup, filename: S, incarnation: u64, body: Vec<u8>, encrypted: bool, ) -> Result<()>
/// Send any `Rumor` to the server. pub fn send<T: Rumor>(&mut self, rumor: T) -> Result<()> { let bytes = rumor.write_to_bytes()?; let wire_msg = message::generate_wire(bytes, self.ring_key.as_ref())?; self.socket.send(&wire_msg, 0).map_err(Error::ZmqSendError) } }
{ let mut sf = ServiceFile::new("butterflyclient", service_group, filename, body); sf.set_incarnation(incarnation); sf.set_encrypted(encrypted); self.send(sf) }
identifier_body
recycle.rs
//! Recycle allocator //! Uses freed frames if possible, then uses inner allocator use alloc::Vec; use paging::PhysicalAddress; use super::{Frame, FrameAllocator}; pub struct RecycleAllocator<T: FrameAllocator> { inner: T, noncore: bool, free: Vec<(usize, usize)>, } impl<T: FrameAllocator> RecycleAllocator<T> { pub fn new(inner: T) -> Self { Self { inner: inner, noncore: false, free: Vec::new(), } } fn free_count(&self) -> usize { let mut count = 0; for free in self.free.iter() { count += free.1; } count } fn merge(&mut self, address: usize, count: usize) -> bool { for i in 0.. self.free.len() { let changed = { let free = &mut self.free[i]; if address + count * 4096 == free.0 { free.0 = address; free.1 += count; true } else if free.0 + free.1 * 4096 == address { free.1 += count; true } else { false } }; if changed { //TODO: Use do not use recursion let (address, count) = self.free[i]; if self.merge(address, count) { self.free.remove(i); } return true; } } false } } impl<T: FrameAllocator> FrameAllocator for RecycleAllocator<T> { fn set_noncore(&mut self, noncore: bool) { self.noncore = noncore; } fn free_frames(&self) -> usize { self.inner.free_frames() + self.free_count() } fn used_frames(&self) -> usize { self.inner.used_frames() - self.free_count() } fn
(&mut self, count: usize) -> Option<Frame> { let mut small_i = None; { let mut small = (0, 0); for i in 0..self.free.len() { let free = self.free[i]; // Later entries can be removed faster if free.1 >= count { if free.1 <= small.1 || small_i.is_none() { small_i = Some(i); small = free; } } } } if let Some(i) = small_i { let (address, remove) = { let free = &mut self.free[i]; free.1 -= count; (free.0 + free.1 * 4096, free.1 == 0) }; if remove { self.free.remove(i); } //println!("Restoring frame {:?}, {}", frame, count); Some(Frame::containing_address(PhysicalAddress::new(address))) } else { //println!("No saved frames {}", count); self.inner.allocate_frames(count) } } fn deallocate_frames(&mut self, frame: Frame, count: usize) { if self.noncore { let address = frame.start_address().get(); if! self.merge(address, count) { self.free.push((address, count)); } } else { //println!("Could not save frame {:?}, {}", frame, count); self.inner.deallocate_frames(frame, count); } } }
allocate_frames
identifier_name
recycle.rs
//! Recycle allocator //! Uses freed frames if possible, then uses inner allocator use alloc::Vec; use paging::PhysicalAddress; use super::{Frame, FrameAllocator}; pub struct RecycleAllocator<T: FrameAllocator> { inner: T, noncore: bool, free: Vec<(usize, usize)>, } impl<T: FrameAllocator> RecycleAllocator<T> { pub fn new(inner: T) -> Self { Self { inner: inner, noncore: false, free: Vec::new(), } } fn free_count(&self) -> usize { let mut count = 0; for free in self.free.iter() { count += free.1; } count } fn merge(&mut self, address: usize, count: usize) -> bool { for i in 0.. self.free.len() { let changed = { let free = &mut self.free[i]; if address + count * 4096 == free.0 { free.0 = address; free.1 += count; true } else if free.0 + free.1 * 4096 == address { free.1 += count; true } else { false } }; if changed { //TODO: Use do not use recursion let (address, count) = self.free[i]; if self.merge(address, count) { self.free.remove(i); } return true; } } false } } impl<T: FrameAllocator> FrameAllocator for RecycleAllocator<T> { fn set_noncore(&mut self, noncore: bool) { self.noncore = noncore; } fn free_frames(&self) -> usize { self.inner.free_frames() + self.free_count() } fn used_frames(&self) -> usize { self.inner.used_frames() - self.free_count() } fn allocate_frames(&mut self, count: usize) -> Option<Frame> { let mut small_i = None; { let mut small = (0, 0);
// Later entries can be removed faster if free.1 >= count { if free.1 <= small.1 || small_i.is_none() { small_i = Some(i); small = free; } } } } if let Some(i) = small_i { let (address, remove) = { let free = &mut self.free[i]; free.1 -= count; (free.0 + free.1 * 4096, free.1 == 0) }; if remove { self.free.remove(i); } //println!("Restoring frame {:?}, {}", frame, count); Some(Frame::containing_address(PhysicalAddress::new(address))) } else { //println!("No saved frames {}", count); self.inner.allocate_frames(count) } } fn deallocate_frames(&mut self, frame: Frame, count: usize) { if self.noncore { let address = frame.start_address().get(); if! self.merge(address, count) { self.free.push((address, count)); } } else { //println!("Could not save frame {:?}, {}", frame, count); self.inner.deallocate_frames(frame, count); } } }
for i in 0..self.free.len() { let free = self.free[i];
random_line_split
recycle.rs
//! Recycle allocator //! Uses freed frames if possible, then uses inner allocator use alloc::Vec; use paging::PhysicalAddress; use super::{Frame, FrameAllocator}; pub struct RecycleAllocator<T: FrameAllocator> { inner: T, noncore: bool, free: Vec<(usize, usize)>, } impl<T: FrameAllocator> RecycleAllocator<T> { pub fn new(inner: T) -> Self { Self { inner: inner, noncore: false, free: Vec::new(), } } fn free_count(&self) -> usize { let mut count = 0; for free in self.free.iter() { count += free.1; } count } fn merge(&mut self, address: usize, count: usize) -> bool { for i in 0.. self.free.len() { let changed = { let free = &mut self.free[i]; if address + count * 4096 == free.0 { free.0 = address; free.1 += count; true } else if free.0 + free.1 * 4096 == address { free.1 += count; true } else { false } }; if changed { //TODO: Use do not use recursion let (address, count) = self.free[i]; if self.merge(address, count)
return true; } } false } } impl<T: FrameAllocator> FrameAllocator for RecycleAllocator<T> { fn set_noncore(&mut self, noncore: bool) { self.noncore = noncore; } fn free_frames(&self) -> usize { self.inner.free_frames() + self.free_count() } fn used_frames(&self) -> usize { self.inner.used_frames() - self.free_count() } fn allocate_frames(&mut self, count: usize) -> Option<Frame> { let mut small_i = None; { let mut small = (0, 0); for i in 0..self.free.len() { let free = self.free[i]; // Later entries can be removed faster if free.1 >= count { if free.1 <= small.1 || small_i.is_none() { small_i = Some(i); small = free; } } } } if let Some(i) = small_i { let (address, remove) = { let free = &mut self.free[i]; free.1 -= count; (free.0 + free.1 * 4096, free.1 == 0) }; if remove { self.free.remove(i); } //println!("Restoring frame {:?}, {}", frame, count); Some(Frame::containing_address(PhysicalAddress::new(address))) } else { //println!("No saved frames {}", count); self.inner.allocate_frames(count) } } fn deallocate_frames(&mut self, frame: Frame, count: usize) { if self.noncore { let address = frame.start_address().get(); if! self.merge(address, count) { self.free.push((address, count)); } } else { //println!("Could not save frame {:?}, {}", frame, count); self.inner.deallocate_frames(frame, count); } } }
{ self.free.remove(i); }
conditional_block
recycle.rs
//! Recycle allocator //! Uses freed frames if possible, then uses inner allocator use alloc::Vec; use paging::PhysicalAddress; use super::{Frame, FrameAllocator}; pub struct RecycleAllocator<T: FrameAllocator> { inner: T, noncore: bool, free: Vec<(usize, usize)>, } impl<T: FrameAllocator> RecycleAllocator<T> { pub fn new(inner: T) -> Self { Self { inner: inner, noncore: false, free: Vec::new(), } } fn free_count(&self) -> usize { let mut count = 0; for free in self.free.iter() { count += free.1; } count } fn merge(&mut self, address: usize, count: usize) -> bool { for i in 0.. self.free.len() { let changed = { let free = &mut self.free[i]; if address + count * 4096 == free.0 { free.0 = address; free.1 += count; true } else if free.0 + free.1 * 4096 == address { free.1 += count; true } else { false } }; if changed { //TODO: Use do not use recursion let (address, count) = self.free[i]; if self.merge(address, count) { self.free.remove(i); } return true; } } false } } impl<T: FrameAllocator> FrameAllocator for RecycleAllocator<T> { fn set_noncore(&mut self, noncore: bool) { self.noncore = noncore; } fn free_frames(&self) -> usize { self.inner.free_frames() + self.free_count() } fn used_frames(&self) -> usize { self.inner.used_frames() - self.free_count() } fn allocate_frames(&mut self, count: usize) -> Option<Frame>
(free.0 + free.1 * 4096, free.1 == 0) }; if remove { self.free.remove(i); } //println!("Restoring frame {:?}, {}", frame, count); Some(Frame::containing_address(PhysicalAddress::new(address))) } else { //println!("No saved frames {}", count); self.inner.allocate_frames(count) } } fn deallocate_frames(&mut self, frame: Frame, count: usize) { if self.noncore { let address = frame.start_address().get(); if! self.merge(address, count) { self.free.push((address, count)); } } else { //println!("Could not save frame {:?}, {}", frame, count); self.inner.deallocate_frames(frame, count); } } }
{ let mut small_i = None; { let mut small = (0, 0); for i in 0..self.free.len() { let free = self.free[i]; // Later entries can be removed faster if free.1 >= count { if free.1 <= small.1 || small_i.is_none() { small_i = Some(i); small = free; } } } } if let Some(i) = small_i { let (address, remove) = { let free = &mut self.free[i]; free.1 -= count;
identifier_body
row.rs
use fallible_iterator::FallibleIterator; use fallible_streaming_iterator::FallibleStreamingIterator; use std::convert; use super::{Error, Result, Statement}; use crate::types::{FromSql, FromSqlError, ValueRef}; /// An handle for the resulting rows of a query. #[must_use = "Rows is lazy and will do nothing unless consumed"] pub struct Rows<'stmt> { pub(crate) stmt: Option<&'stmt Statement<'stmt>>, row: Option<Row<'stmt>>, } impl<'stmt> Rows<'stmt> { #[inline] fn reset(&mut self) { if let Some(stmt) = self.stmt.take() { stmt.reset(); } } /// Attempt to get the next row from the query. Returns `Ok(Some(Row))` if /// there is another row, `Err(...)` if there was an error /// getting the next row, and `Ok(None)` if all rows have been retrieved. /// /// ## Note /// /// This interface is not compatible with Rust's `Iterator` trait, because /// the lifetime of the returned row is tied to the lifetime of `self`. /// This is a fallible "streaming iterator". For a more natural interface, /// consider using [`query_map`](crate::Statement::query_map) or [`query_and_then`](crate::Statement::query_and_then) instead, which /// return types that implement `Iterator`. #[allow(clippy::should_implement_trait)] // cannot implement Iterator #[inline] pub fn next(&mut self) -> Result<Option<&Row<'stmt>>> { self.advance()?; Ok((*self).get()) } /// Map over this `Rows`, converting it to a [`Map`], which /// implements `FallibleIterator`. /// ```rust,no_run /// use fallible_iterator::FallibleIterator; /// # use rusqlite::{Result, Statement}; /// fn query(stmt: &mut Statement) -> Result<Vec<i64>> { /// let rows = stmt.query([])?; /// rows.map(|r| r.get(0)).collect() /// } /// ``` // FIXME Hide FallibleStreamingIterator::map #[inline] pub fn map<F, B>(self, f: F) -> Map<'stmt, F> where F: FnMut(&Row<'_>) -> Result<B>, { Map { rows: self, f } } /// Map over this `Rows`, converting it to a [`MappedRows`], which /// implements `Iterator`. #[inline] pub fn mapped<F, B>(self, f: F) -> MappedRows<'stmt, F> where F: FnMut(&Row<'_>) -> Result<B>, { MappedRows { rows: self, map: f } } /// Map over this `Rows` with a fallible function, converting it to a /// [`AndThenRows`], which implements `Iterator` (instead of /// `FallibleStreamingIterator`). #[inline] pub fn and_then<F, T, E>(self, f: F) -> AndThenRows<'stmt, F> where F: FnMut(&Row<'_>) -> Result<T, E>, { AndThenRows { rows: self, map: f } } } impl<'stmt> Rows<'stmt> { #[inline] pub(crate) fn new(stmt: &'stmt Statement<'stmt>) -> Rows<'stmt> { Rows { stmt: Some(stmt), row: None, } } #[inline] pub(crate) fn get_expected_row(&mut self) -> Result<&Row<'stmt>> { match self.next()? { Some(row) => Ok(row), None => Err(Error::QueryReturnedNoRows), } } } impl Drop for Rows<'_> { #[inline] fn drop(&mut self) { self.reset(); } } /// `F` is used to tranform the _streaming_ iterator into a _fallible_ iterator. #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct Map<'stmt, F> { rows: Rows<'stmt>, f: F, } impl<F, B> FallibleIterator for Map<'_, F> where F: FnMut(&Row<'_>) -> Result<B>, { type Error = Error; type Item = B; #[inline] fn next(&mut self) -> Result<Option<B>> { match self.rows.next()? { Some(v) => Ok(Some((self.f)(v)?)), None => Ok(None), } } } /// An iterator over the mapped resulting rows of a query. /// /// `F` is used to tranform the _streaming_ iterator into a _standard_ iterator. #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct MappedRows<'stmt, F> { rows: Rows<'stmt>, map: F, } impl<T, F> Iterator for MappedRows<'_, F> where F: FnMut(&Row<'_>) -> Result<T>, { type Item = Result<T>; #[inline] fn next(&mut self) -> Option<Result<T>> { let map = &mut self.map; self.rows .next() .transpose() .map(|row_result| row_result.and_then(|row| (map)(&row))) } } /// An iterator over the mapped resulting rows of a query, with an Error type /// unifying with Error. #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct AndThenRows<'stmt, F> { rows: Rows<'stmt>, map: F, } impl<T, E, F> Iterator for AndThenRows<'_, F> where E: convert::From<Error>, F: FnMut(&Row<'_>) -> Result<T, E>, { type Item = Result<T, E>; #[inline] fn next(&mut self) -> Option<Self::Item> { let map = &mut self.map; self.rows .next() .transpose() .map(|row_result| row_result.map_err(E::from).and_then(|row| (map)(&row))) } } /// `FallibleStreamingIterator` differs from the standard library's `Iterator` /// in two ways: /// * each call to `next` (sqlite3_step) can fail. /// * returned `Row` is valid until `next` is called again or `Statement` is /// reset or finalized. /// /// While these iterators cannot be used with Rust `for` loops, `while let` /// loops offer a similar level of ergonomics: /// ```rust,no_run /// # use rusqlite::{Result, Statement}; /// fn query(stmt: &mut Statement) -> Result<()> { /// let mut rows = stmt.query([])?; /// while let Some(row) = rows.next()? { /// // scan columns value /// } /// Ok(()) /// } /// ``` impl<'stmt> FallibleStreamingIterator for Rows<'stmt> { type Error = Error; type Item = Row<'stmt>; #[inline] fn advance(&mut self) -> Result<()> { match self.stmt { Some(ref stmt) => match stmt.step() { Ok(true) => { self.row = Some(Row { stmt }); Ok(()) } Ok(false) => { self.reset(); self.row = None; Ok(()) } Err(e) => { self.reset(); self.row = None; Err(e) } }, None => { self.row = None; Ok(()) } } } #[inline] fn get(&self) -> Option<&Row<'stmt>> { self.row.as_ref() } } /// A single result row of a query. pub struct Row<'stmt> { pub(crate) stmt: &'stmt Statement<'stmt>, } impl<'stmt> Row<'stmt> { /// Get the value of a particular column of the result row. /// /// ## Failure /// /// Panics if calling [`row.get(idx)`](Row::get) would return an error, /// including: /// /// * If the underlying SQLite column type is not a valid type as a source /// for `T` /// * If the underlying SQLite integral value is outside the range /// representable by `T` /// * If `idx` is outside the range of columns in the returned query pub fn get_unwrap<I: RowIndex, T: FromSql>(&self, idx: I) -> T { self.get(idx).unwrap() } /// Get the value of a particular column of the result row. /// /// ## Failure /// /// Returns an `Error::InvalidColumnType` if the underlying SQLite column /// type is not a valid type as a source for `T`. /// /// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid /// column range for this row. /// /// Returns an `Error::InvalidColumnName` if `idx` is not a valid column /// name for this row. /// /// If the result type is i128 (which requires the `i128_blob` feature to be /// enabled), and the underlying SQLite column is a blob whose size is not /// 16 bytes, `Error::InvalidColumnType` will also be returned. pub fn get<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> { let idx = idx.idx(self.stmt)?; let value = self.stmt.value_ref(idx); FromSql::column_result(value).map_err(|err| match err { FromSqlError::InvalidType => Error::InvalidColumnType( idx, self.stmt.column_name_unwrap(idx).into(), value.data_type(), ), FromSqlError::OutOfRange(i) => Error::IntegralValueOutOfRange(idx, i), FromSqlError::Other(err) =>
#[cfg(feature = "i128_blob")] FromSqlError::InvalidI128Size(_) => Error::InvalidColumnType( idx, self.stmt.column_name_unwrap(idx).into(), value.data_type(), ), #[cfg(feature = "uuid")] FromSqlError::InvalidUuidSize(_) => Error::InvalidColumnType( idx, self.stmt.column_name_unwrap(idx).into(), value.data_type(), ), }) } /// Get the value of a particular column of the result row as a `ValueRef`, /// allowing data to be read out of a row without copying. /// /// This `ValueRef` is valid only as long as this Row, which is enforced by /// it's lifetime. This means that while this method is completely safe, /// it can be somewhat difficult to use, and most callers will be better /// served by [`get`](Row::get) or [`get_unwrap`](Row::get_unwrap). /// /// ## Failure /// /// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid /// column range for this row. /// /// Returns an `Error::InvalidColumnName` if `idx` is not a valid column /// name for this row. pub fn get_ref<I: RowIndex>(&self, idx: I) -> Result<ValueRef<'_>> { let idx = idx.idx(self.stmt)?; // Narrowing from `ValueRef<'stmt>` (which `self.stmt.value_ref(idx)` // returns) to `ValueRef<'a>` is needed because it's only valid until // the next call to sqlite3_step. let val_ref = self.stmt.value_ref(idx); Ok(val_ref) } /// Get the value of a particular column of the result row as a `ValueRef`, /// allowing data to be read out of a row without copying. /// /// This `ValueRef` is valid only as long as this Row, which is enforced by /// it's lifetime. This means that while this method is completely safe, /// it can be difficult to use, and most callers will be better served by /// [`get`](Row::get) or [`get_unwrap`](Row::get_unwrap). /// /// ## Failure /// /// Panics if calling [`row.get_ref(idx)`](Row::get_ref) would return an error, /// including: /// /// * If `idx` is outside the range of columns in the returned query. /// * If `idx` is not a valid column name for this row. pub fn get_ref_unwrap<I: RowIndex>(&self, idx: I) -> ValueRef<'_> { self.get_ref(idx).unwrap() } /// Renamed to [`get_ref`](Row::get_ref). #[deprecated = "Use [`get_ref`](Row::get_ref) instead."] #[inline] pub fn get_raw_checked<I: RowIndex>(&self, idx: I) -> Result<ValueRef<'_>> { self.get_ref(idx) } /// Renamed to [`get_ref_unwrap`](Row::get_ref_unwrap). #[deprecated = "Use [`get_ref_unwrap`](Row::get_ref_unwrap) instead."] #[inline] pub fn get_raw<I: RowIndex>(&self, idx: I) -> ValueRef<'_> { self.get_ref_unwrap(idx) } } mod sealed { /// This trait exists just to ensure that the only impls of `trait Params` /// that are allowed are ones in this crate. pub trait Sealed {} impl Sealed for usize {} impl Sealed for &str {} } /// A trait implemented by types that can index into columns of a row. /// /// It is only implemented for `usize` and `&str`. pub trait RowIndex: sealed::Sealed { /// Returns the index of the appropriate column, or `None` if no such /// column exists. fn idx(&self, stmt: &Statement<'_>) -> Result<usize>; } impl RowIndex for usize { #[inline] fn idx(&self, stmt: &Statement<'_>) -> Result<usize> { if *self >= stmt.column_count() { Err(Error::InvalidColumnIndex(*self)) } else { Ok(*self) } } } impl RowIndex for &'_ str { #[inline] fn idx(&self, stmt: &Statement<'_>) -> Result<usize> { stmt.column_index(*self) } } macro_rules! tuple_try_from_row { ($($field:ident),*) => { impl<'a, $($field,)*> convert::TryFrom<&'a Row<'a>> for ($($field,)*) where $($field: FromSql,)* { type Error = crate::Error; // we end with index += 1, which rustc warns about // unused_variables and unused_mut are allowed for () #[allow(unused_assignments, unused_variables, unused_mut)] fn try_from(row: &'a Row<'a>) -> Result<Self> { let mut index = 0; $( #[allow(non_snake_case)] let $field = row.get::<_, $field>(index)?; index += 1; )* Ok(($($field,)*)) } } } } macro_rules! tuples_try_from_row { () => { // not very useful, but maybe some other macro users will find this helpful tuple_try_from_row!(); }; ($first:ident $(, $remaining:ident)*) => { tuple_try_from_row!($first $(, $remaining)*); tuples_try_from_row!($($remaining),*); }; } tuples_try_from_row!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P); #[cfg(test)] mod tests { #![allow(clippy::redundant_closure)] // false positives due to lifetime issues; clippy issue #5594 use crate::{Connection, Result}; #[test] fn test_try_from_row_for_tuple_1() -> Result<()> { use crate::ToSql; use std::convert::TryFrom; let conn = Connection::open_in_memory()?; conn.execute( "CREATE TABLE test (a INTEGER)", crate::params_from_iter(std::iter::empty::<&dyn ToSql>()), )?; conn.execute("INSERT INTO test VALUES (42)", [])?; let val = conn.query_row("SELECT a FROM test", [], |row| <(u32,)>::try_from(row))?; assert_eq!(val, (42,)); let fail = conn.query_row("SELECT a FROM test", [], |row| <(u32, u32)>::try_from(row)); assert!(fail.is_err()); Ok(()) } #[test] fn test_try_from_row_for_tuple_2() -> Result<()> { use std::convert::TryFrom; let conn = Connection::open_in_memory()?; conn.execute("CREATE TABLE test (a INTEGER, b INTEGER)", [])?; conn.execute("INSERT INTO test VALUES (42, 47)", [])?; let val = conn.query_row("SELECT a, b FROM test", [], |row| { <(u32, u32)>::try_from(row) })?; assert_eq!(val, (42, 47)); let fail = conn.query_row("SELECT a, b FROM test", [], |row| { <(u32, u32, u32)>::try_from(row) }); assert!(fail.is_err()); Ok(()) } #[test] fn test_try_from_row_for_tuple_16() -> Result<()> { use std::convert::TryFrom; let create_table = "CREATE TABLE test ( a INTEGER, b INTEGER, c INTEGER, d INTEGER, e INTEGER, f INTEGER, g INTEGER, h INTEGER, i INTEGER, j INTEGER, k INTEGER, l INTEGER, m INTEGER, n INTEGER, o INTEGER, p INTEGER )"; let insert_values = "INSERT INTO test VALUES ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 )"; type BigTuple = ( u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, ); let conn = Connection::open_in_memory()?; conn.execute(create_table, [])?; conn.execute(insert_values, [])?; let val = conn.query_row("SELECT * FROM test", [], |row| BigTuple::try_from(row))?; // Debug is not implemented for tuples of 16 assert_eq!(val.0, 0); assert_eq!(val.1, 1); assert_eq!(val.2, 2); assert_eq!(val.3, 3); assert_eq!(val.4, 4); assert_eq!(val.5, 5); assert_eq!(val.6, 6); assert_eq!(val.7, 7); assert_eq!(val.8, 8); assert_eq!(val.9, 9); assert_eq!(val.10, 10); assert_eq!(val.11, 11); assert_eq!(val.12, 12); assert_eq!(val.13, 13); assert_eq!(val.14, 14); assert_eq!(val.15, 15); // We don't test one bigger because it's unimplemented Ok(()) } }
{ Error::FromSqlConversionFailure(idx as usize, value.data_type(), err) }
conditional_block
row.rs
use fallible_iterator::FallibleIterator; use fallible_streaming_iterator::FallibleStreamingIterator; use std::convert; use super::{Error, Result, Statement}; use crate::types::{FromSql, FromSqlError, ValueRef}; /// An handle for the resulting rows of a query. #[must_use = "Rows is lazy and will do nothing unless consumed"] pub struct Rows<'stmt> { pub(crate) stmt: Option<&'stmt Statement<'stmt>>, row: Option<Row<'stmt>>, } impl<'stmt> Rows<'stmt> { #[inline] fn reset(&mut self) { if let Some(stmt) = self.stmt.take() { stmt.reset(); } } /// Attempt to get the next row from the query. Returns `Ok(Some(Row))` if /// there is another row, `Err(...)` if there was an error /// getting the next row, and `Ok(None)` if all rows have been retrieved. /// /// ## Note /// /// This interface is not compatible with Rust's `Iterator` trait, because /// the lifetime of the returned row is tied to the lifetime of `self`. /// This is a fallible "streaming iterator". For a more natural interface, /// consider using [`query_map`](crate::Statement::query_map) or [`query_and_then`](crate::Statement::query_and_then) instead, which /// return types that implement `Iterator`. #[allow(clippy::should_implement_trait)] // cannot implement Iterator #[inline] pub fn next(&mut self) -> Result<Option<&Row<'stmt>>> { self.advance()?; Ok((*self).get()) } /// Map over this `Rows`, converting it to a [`Map`], which /// implements `FallibleIterator`. /// ```rust,no_run /// use fallible_iterator::FallibleIterator; /// # use rusqlite::{Result, Statement}; /// fn query(stmt: &mut Statement) -> Result<Vec<i64>> { /// let rows = stmt.query([])?; /// rows.map(|r| r.get(0)).collect() /// } /// ``` // FIXME Hide FallibleStreamingIterator::map #[inline] pub fn map<F, B>(self, f: F) -> Map<'stmt, F> where F: FnMut(&Row<'_>) -> Result<B>, { Map { rows: self, f } } /// Map over this `Rows`, converting it to a [`MappedRows`], which /// implements `Iterator`. #[inline] pub fn mapped<F, B>(self, f: F) -> MappedRows<'stmt, F> where F: FnMut(&Row<'_>) -> Result<B>, { MappedRows { rows: self, map: f } } /// Map over this `Rows` with a fallible function, converting it to a /// [`AndThenRows`], which implements `Iterator` (instead of /// `FallibleStreamingIterator`). #[inline] pub fn and_then<F, T, E>(self, f: F) -> AndThenRows<'stmt, F> where F: FnMut(&Row<'_>) -> Result<T, E>, { AndThenRows { rows: self, map: f } } } impl<'stmt> Rows<'stmt> { #[inline] pub(crate) fn new(stmt: &'stmt Statement<'stmt>) -> Rows<'stmt> { Rows { stmt: Some(stmt), row: None, } } #[inline] pub(crate) fn get_expected_row(&mut self) -> Result<&Row<'stmt>> { match self.next()? { Some(row) => Ok(row), None => Err(Error::QueryReturnedNoRows), } } } impl Drop for Rows<'_> { #[inline] fn drop(&mut self) { self.reset(); } } /// `F` is used to tranform the _streaming_ iterator into a _fallible_ iterator. #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct Map<'stmt, F> { rows: Rows<'stmt>, f: F, } impl<F, B> FallibleIterator for Map<'_, F> where F: FnMut(&Row<'_>) -> Result<B>, { type Error = Error; type Item = B; #[inline] fn next(&mut self) -> Result<Option<B>> { match self.rows.next()? { Some(v) => Ok(Some((self.f)(v)?)), None => Ok(None), } } } /// An iterator over the mapped resulting rows of a query. /// /// `F` is used to tranform the _streaming_ iterator into a _standard_ iterator. #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct MappedRows<'stmt, F> { rows: Rows<'stmt>, map: F, } impl<T, F> Iterator for MappedRows<'_, F> where F: FnMut(&Row<'_>) -> Result<T>, { type Item = Result<T>; #[inline] fn next(&mut self) -> Option<Result<T>> { let map = &mut self.map; self.rows .next() .transpose() .map(|row_result| row_result.and_then(|row| (map)(&row))) } } /// An iterator over the mapped resulting rows of a query, with an Error type /// unifying with Error. #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct AndThenRows<'stmt, F> { rows: Rows<'stmt>, map: F, } impl<T, E, F> Iterator for AndThenRows<'_, F> where E: convert::From<Error>, F: FnMut(&Row<'_>) -> Result<T, E>, { type Item = Result<T, E>; #[inline] fn next(&mut self) -> Option<Self::Item> { let map = &mut self.map; self.rows .next() .transpose() .map(|row_result| row_result.map_err(E::from).and_then(|row| (map)(&row))) } } /// `FallibleStreamingIterator` differs from the standard library's `Iterator` /// in two ways: /// * each call to `next` (sqlite3_step) can fail. /// * returned `Row` is valid until `next` is called again or `Statement` is /// reset or finalized. /// /// While these iterators cannot be used with Rust `for` loops, `while let` /// loops offer a similar level of ergonomics: /// ```rust,no_run /// # use rusqlite::{Result, Statement}; /// fn query(stmt: &mut Statement) -> Result<()> { /// let mut rows = stmt.query([])?; /// while let Some(row) = rows.next()? { /// // scan columns value /// } /// Ok(()) /// } /// ``` impl<'stmt> FallibleStreamingIterator for Rows<'stmt> { type Error = Error;
#[inline] fn advance(&mut self) -> Result<()> { match self.stmt { Some(ref stmt) => match stmt.step() { Ok(true) => { self.row = Some(Row { stmt }); Ok(()) } Ok(false) => { self.reset(); self.row = None; Ok(()) } Err(e) => { self.reset(); self.row = None; Err(e) } }, None => { self.row = None; Ok(()) } } } #[inline] fn get(&self) -> Option<&Row<'stmt>> { self.row.as_ref() } } /// A single result row of a query. pub struct Row<'stmt> { pub(crate) stmt: &'stmt Statement<'stmt>, } impl<'stmt> Row<'stmt> { /// Get the value of a particular column of the result row. /// /// ## Failure /// /// Panics if calling [`row.get(idx)`](Row::get) would return an error, /// including: /// /// * If the underlying SQLite column type is not a valid type as a source /// for `T` /// * If the underlying SQLite integral value is outside the range /// representable by `T` /// * If `idx` is outside the range of columns in the returned query pub fn get_unwrap<I: RowIndex, T: FromSql>(&self, idx: I) -> T { self.get(idx).unwrap() } /// Get the value of a particular column of the result row. /// /// ## Failure /// /// Returns an `Error::InvalidColumnType` if the underlying SQLite column /// type is not a valid type as a source for `T`. /// /// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid /// column range for this row. /// /// Returns an `Error::InvalidColumnName` if `idx` is not a valid column /// name for this row. /// /// If the result type is i128 (which requires the `i128_blob` feature to be /// enabled), and the underlying SQLite column is a blob whose size is not /// 16 bytes, `Error::InvalidColumnType` will also be returned. pub fn get<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> { let idx = idx.idx(self.stmt)?; let value = self.stmt.value_ref(idx); FromSql::column_result(value).map_err(|err| match err { FromSqlError::InvalidType => Error::InvalidColumnType( idx, self.stmt.column_name_unwrap(idx).into(), value.data_type(), ), FromSqlError::OutOfRange(i) => Error::IntegralValueOutOfRange(idx, i), FromSqlError::Other(err) => { Error::FromSqlConversionFailure(idx as usize, value.data_type(), err) } #[cfg(feature = "i128_blob")] FromSqlError::InvalidI128Size(_) => Error::InvalidColumnType( idx, self.stmt.column_name_unwrap(idx).into(), value.data_type(), ), #[cfg(feature = "uuid")] FromSqlError::InvalidUuidSize(_) => Error::InvalidColumnType( idx, self.stmt.column_name_unwrap(idx).into(), value.data_type(), ), }) } /// Get the value of a particular column of the result row as a `ValueRef`, /// allowing data to be read out of a row without copying. /// /// This `ValueRef` is valid only as long as this Row, which is enforced by /// it's lifetime. This means that while this method is completely safe, /// it can be somewhat difficult to use, and most callers will be better /// served by [`get`](Row::get) or [`get_unwrap`](Row::get_unwrap). /// /// ## Failure /// /// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid /// column range for this row. /// /// Returns an `Error::InvalidColumnName` if `idx` is not a valid column /// name for this row. pub fn get_ref<I: RowIndex>(&self, idx: I) -> Result<ValueRef<'_>> { let idx = idx.idx(self.stmt)?; // Narrowing from `ValueRef<'stmt>` (which `self.stmt.value_ref(idx)` // returns) to `ValueRef<'a>` is needed because it's only valid until // the next call to sqlite3_step. let val_ref = self.stmt.value_ref(idx); Ok(val_ref) } /// Get the value of a particular column of the result row as a `ValueRef`, /// allowing data to be read out of a row without copying. /// /// This `ValueRef` is valid only as long as this Row, which is enforced by /// it's lifetime. This means that while this method is completely safe, /// it can be difficult to use, and most callers will be better served by /// [`get`](Row::get) or [`get_unwrap`](Row::get_unwrap). /// /// ## Failure /// /// Panics if calling [`row.get_ref(idx)`](Row::get_ref) would return an error, /// including: /// /// * If `idx` is outside the range of columns in the returned query. /// * If `idx` is not a valid column name for this row. pub fn get_ref_unwrap<I: RowIndex>(&self, idx: I) -> ValueRef<'_> { self.get_ref(idx).unwrap() } /// Renamed to [`get_ref`](Row::get_ref). #[deprecated = "Use [`get_ref`](Row::get_ref) instead."] #[inline] pub fn get_raw_checked<I: RowIndex>(&self, idx: I) -> Result<ValueRef<'_>> { self.get_ref(idx) } /// Renamed to [`get_ref_unwrap`](Row::get_ref_unwrap). #[deprecated = "Use [`get_ref_unwrap`](Row::get_ref_unwrap) instead."] #[inline] pub fn get_raw<I: RowIndex>(&self, idx: I) -> ValueRef<'_> { self.get_ref_unwrap(idx) } } mod sealed { /// This trait exists just to ensure that the only impls of `trait Params` /// that are allowed are ones in this crate. pub trait Sealed {} impl Sealed for usize {} impl Sealed for &str {} } /// A trait implemented by types that can index into columns of a row. /// /// It is only implemented for `usize` and `&str`. pub trait RowIndex: sealed::Sealed { /// Returns the index of the appropriate column, or `None` if no such /// column exists. fn idx(&self, stmt: &Statement<'_>) -> Result<usize>; } impl RowIndex for usize { #[inline] fn idx(&self, stmt: &Statement<'_>) -> Result<usize> { if *self >= stmt.column_count() { Err(Error::InvalidColumnIndex(*self)) } else { Ok(*self) } } } impl RowIndex for &'_ str { #[inline] fn idx(&self, stmt: &Statement<'_>) -> Result<usize> { stmt.column_index(*self) } } macro_rules! tuple_try_from_row { ($($field:ident),*) => { impl<'a, $($field,)*> convert::TryFrom<&'a Row<'a>> for ($($field,)*) where $($field: FromSql,)* { type Error = crate::Error; // we end with index += 1, which rustc warns about // unused_variables and unused_mut are allowed for () #[allow(unused_assignments, unused_variables, unused_mut)] fn try_from(row: &'a Row<'a>) -> Result<Self> { let mut index = 0; $( #[allow(non_snake_case)] let $field = row.get::<_, $field>(index)?; index += 1; )* Ok(($($field,)*)) } } } } macro_rules! tuples_try_from_row { () => { // not very useful, but maybe some other macro users will find this helpful tuple_try_from_row!(); }; ($first:ident $(, $remaining:ident)*) => { tuple_try_from_row!($first $(, $remaining)*); tuples_try_from_row!($($remaining),*); }; } tuples_try_from_row!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P); #[cfg(test)] mod tests { #![allow(clippy::redundant_closure)] // false positives due to lifetime issues; clippy issue #5594 use crate::{Connection, Result}; #[test] fn test_try_from_row_for_tuple_1() -> Result<()> { use crate::ToSql; use std::convert::TryFrom; let conn = Connection::open_in_memory()?; conn.execute( "CREATE TABLE test (a INTEGER)", crate::params_from_iter(std::iter::empty::<&dyn ToSql>()), )?; conn.execute("INSERT INTO test VALUES (42)", [])?; let val = conn.query_row("SELECT a FROM test", [], |row| <(u32,)>::try_from(row))?; assert_eq!(val, (42,)); let fail = conn.query_row("SELECT a FROM test", [], |row| <(u32, u32)>::try_from(row)); assert!(fail.is_err()); Ok(()) } #[test] fn test_try_from_row_for_tuple_2() -> Result<()> { use std::convert::TryFrom; let conn = Connection::open_in_memory()?; conn.execute("CREATE TABLE test (a INTEGER, b INTEGER)", [])?; conn.execute("INSERT INTO test VALUES (42, 47)", [])?; let val = conn.query_row("SELECT a, b FROM test", [], |row| { <(u32, u32)>::try_from(row) })?; assert_eq!(val, (42, 47)); let fail = conn.query_row("SELECT a, b FROM test", [], |row| { <(u32, u32, u32)>::try_from(row) }); assert!(fail.is_err()); Ok(()) } #[test] fn test_try_from_row_for_tuple_16() -> Result<()> { use std::convert::TryFrom; let create_table = "CREATE TABLE test ( a INTEGER, b INTEGER, c INTEGER, d INTEGER, e INTEGER, f INTEGER, g INTEGER, h INTEGER, i INTEGER, j INTEGER, k INTEGER, l INTEGER, m INTEGER, n INTEGER, o INTEGER, p INTEGER )"; let insert_values = "INSERT INTO test VALUES ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 )"; type BigTuple = ( u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, ); let conn = Connection::open_in_memory()?; conn.execute(create_table, [])?; conn.execute(insert_values, [])?; let val = conn.query_row("SELECT * FROM test", [], |row| BigTuple::try_from(row))?; // Debug is not implemented for tuples of 16 assert_eq!(val.0, 0); assert_eq!(val.1, 1); assert_eq!(val.2, 2); assert_eq!(val.3, 3); assert_eq!(val.4, 4); assert_eq!(val.5, 5); assert_eq!(val.6, 6); assert_eq!(val.7, 7); assert_eq!(val.8, 8); assert_eq!(val.9, 9); assert_eq!(val.10, 10); assert_eq!(val.11, 11); assert_eq!(val.12, 12); assert_eq!(val.13, 13); assert_eq!(val.14, 14); assert_eq!(val.15, 15); // We don't test one bigger because it's unimplemented Ok(()) } }
type Item = Row<'stmt>;
random_line_split
row.rs
use fallible_iterator::FallibleIterator; use fallible_streaming_iterator::FallibleStreamingIterator; use std::convert; use super::{Error, Result, Statement}; use crate::types::{FromSql, FromSqlError, ValueRef}; /// An handle for the resulting rows of a query. #[must_use = "Rows is lazy and will do nothing unless consumed"] pub struct
<'stmt> { pub(crate) stmt: Option<&'stmt Statement<'stmt>>, row: Option<Row<'stmt>>, } impl<'stmt> Rows<'stmt> { #[inline] fn reset(&mut self) { if let Some(stmt) = self.stmt.take() { stmt.reset(); } } /// Attempt to get the next row from the query. Returns `Ok(Some(Row))` if /// there is another row, `Err(...)` if there was an error /// getting the next row, and `Ok(None)` if all rows have been retrieved. /// /// ## Note /// /// This interface is not compatible with Rust's `Iterator` trait, because /// the lifetime of the returned row is tied to the lifetime of `self`. /// This is a fallible "streaming iterator". For a more natural interface, /// consider using [`query_map`](crate::Statement::query_map) or [`query_and_then`](crate::Statement::query_and_then) instead, which /// return types that implement `Iterator`. #[allow(clippy::should_implement_trait)] // cannot implement Iterator #[inline] pub fn next(&mut self) -> Result<Option<&Row<'stmt>>> { self.advance()?; Ok((*self).get()) } /// Map over this `Rows`, converting it to a [`Map`], which /// implements `FallibleIterator`. /// ```rust,no_run /// use fallible_iterator::FallibleIterator; /// # use rusqlite::{Result, Statement}; /// fn query(stmt: &mut Statement) -> Result<Vec<i64>> { /// let rows = stmt.query([])?; /// rows.map(|r| r.get(0)).collect() /// } /// ``` // FIXME Hide FallibleStreamingIterator::map #[inline] pub fn map<F, B>(self, f: F) -> Map<'stmt, F> where F: FnMut(&Row<'_>) -> Result<B>, { Map { rows: self, f } } /// Map over this `Rows`, converting it to a [`MappedRows`], which /// implements `Iterator`. #[inline] pub fn mapped<F, B>(self, f: F) -> MappedRows<'stmt, F> where F: FnMut(&Row<'_>) -> Result<B>, { MappedRows { rows: self, map: f } } /// Map over this `Rows` with a fallible function, converting it to a /// [`AndThenRows`], which implements `Iterator` (instead of /// `FallibleStreamingIterator`). #[inline] pub fn and_then<F, T, E>(self, f: F) -> AndThenRows<'stmt, F> where F: FnMut(&Row<'_>) -> Result<T, E>, { AndThenRows { rows: self, map: f } } } impl<'stmt> Rows<'stmt> { #[inline] pub(crate) fn new(stmt: &'stmt Statement<'stmt>) -> Rows<'stmt> { Rows { stmt: Some(stmt), row: None, } } #[inline] pub(crate) fn get_expected_row(&mut self) -> Result<&Row<'stmt>> { match self.next()? { Some(row) => Ok(row), None => Err(Error::QueryReturnedNoRows), } } } impl Drop for Rows<'_> { #[inline] fn drop(&mut self) { self.reset(); } } /// `F` is used to tranform the _streaming_ iterator into a _fallible_ iterator. #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct Map<'stmt, F> { rows: Rows<'stmt>, f: F, } impl<F, B> FallibleIterator for Map<'_, F> where F: FnMut(&Row<'_>) -> Result<B>, { type Error = Error; type Item = B; #[inline] fn next(&mut self) -> Result<Option<B>> { match self.rows.next()? { Some(v) => Ok(Some((self.f)(v)?)), None => Ok(None), } } } /// An iterator over the mapped resulting rows of a query. /// /// `F` is used to tranform the _streaming_ iterator into a _standard_ iterator. #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct MappedRows<'stmt, F> { rows: Rows<'stmt>, map: F, } impl<T, F> Iterator for MappedRows<'_, F> where F: FnMut(&Row<'_>) -> Result<T>, { type Item = Result<T>; #[inline] fn next(&mut self) -> Option<Result<T>> { let map = &mut self.map; self.rows .next() .transpose() .map(|row_result| row_result.and_then(|row| (map)(&row))) } } /// An iterator over the mapped resulting rows of a query, with an Error type /// unifying with Error. #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct AndThenRows<'stmt, F> { rows: Rows<'stmt>, map: F, } impl<T, E, F> Iterator for AndThenRows<'_, F> where E: convert::From<Error>, F: FnMut(&Row<'_>) -> Result<T, E>, { type Item = Result<T, E>; #[inline] fn next(&mut self) -> Option<Self::Item> { let map = &mut self.map; self.rows .next() .transpose() .map(|row_result| row_result.map_err(E::from).and_then(|row| (map)(&row))) } } /// `FallibleStreamingIterator` differs from the standard library's `Iterator` /// in two ways: /// * each call to `next` (sqlite3_step) can fail. /// * returned `Row` is valid until `next` is called again or `Statement` is /// reset or finalized. /// /// While these iterators cannot be used with Rust `for` loops, `while let` /// loops offer a similar level of ergonomics: /// ```rust,no_run /// # use rusqlite::{Result, Statement}; /// fn query(stmt: &mut Statement) -> Result<()> { /// let mut rows = stmt.query([])?; /// while let Some(row) = rows.next()? { /// // scan columns value /// } /// Ok(()) /// } /// ``` impl<'stmt> FallibleStreamingIterator for Rows<'stmt> { type Error = Error; type Item = Row<'stmt>; #[inline] fn advance(&mut self) -> Result<()> { match self.stmt { Some(ref stmt) => match stmt.step() { Ok(true) => { self.row = Some(Row { stmt }); Ok(()) } Ok(false) => { self.reset(); self.row = None; Ok(()) } Err(e) => { self.reset(); self.row = None; Err(e) } }, None => { self.row = None; Ok(()) } } } #[inline] fn get(&self) -> Option<&Row<'stmt>> { self.row.as_ref() } } /// A single result row of a query. pub struct Row<'stmt> { pub(crate) stmt: &'stmt Statement<'stmt>, } impl<'stmt> Row<'stmt> { /// Get the value of a particular column of the result row. /// /// ## Failure /// /// Panics if calling [`row.get(idx)`](Row::get) would return an error, /// including: /// /// * If the underlying SQLite column type is not a valid type as a source /// for `T` /// * If the underlying SQLite integral value is outside the range /// representable by `T` /// * If `idx` is outside the range of columns in the returned query pub fn get_unwrap<I: RowIndex, T: FromSql>(&self, idx: I) -> T { self.get(idx).unwrap() } /// Get the value of a particular column of the result row. /// /// ## Failure /// /// Returns an `Error::InvalidColumnType` if the underlying SQLite column /// type is not a valid type as a source for `T`. /// /// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid /// column range for this row. /// /// Returns an `Error::InvalidColumnName` if `idx` is not a valid column /// name for this row. /// /// If the result type is i128 (which requires the `i128_blob` feature to be /// enabled), and the underlying SQLite column is a blob whose size is not /// 16 bytes, `Error::InvalidColumnType` will also be returned. pub fn get<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> { let idx = idx.idx(self.stmt)?; let value = self.stmt.value_ref(idx); FromSql::column_result(value).map_err(|err| match err { FromSqlError::InvalidType => Error::InvalidColumnType( idx, self.stmt.column_name_unwrap(idx).into(), value.data_type(), ), FromSqlError::OutOfRange(i) => Error::IntegralValueOutOfRange(idx, i), FromSqlError::Other(err) => { Error::FromSqlConversionFailure(idx as usize, value.data_type(), err) } #[cfg(feature = "i128_blob")] FromSqlError::InvalidI128Size(_) => Error::InvalidColumnType( idx, self.stmt.column_name_unwrap(idx).into(), value.data_type(), ), #[cfg(feature = "uuid")] FromSqlError::InvalidUuidSize(_) => Error::InvalidColumnType( idx, self.stmt.column_name_unwrap(idx).into(), value.data_type(), ), }) } /// Get the value of a particular column of the result row as a `ValueRef`, /// allowing data to be read out of a row without copying. /// /// This `ValueRef` is valid only as long as this Row, which is enforced by /// it's lifetime. This means that while this method is completely safe, /// it can be somewhat difficult to use, and most callers will be better /// served by [`get`](Row::get) or [`get_unwrap`](Row::get_unwrap). /// /// ## Failure /// /// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid /// column range for this row. /// /// Returns an `Error::InvalidColumnName` if `idx` is not a valid column /// name for this row. pub fn get_ref<I: RowIndex>(&self, idx: I) -> Result<ValueRef<'_>> { let idx = idx.idx(self.stmt)?; // Narrowing from `ValueRef<'stmt>` (which `self.stmt.value_ref(idx)` // returns) to `ValueRef<'a>` is needed because it's only valid until // the next call to sqlite3_step. let val_ref = self.stmt.value_ref(idx); Ok(val_ref) } /// Get the value of a particular column of the result row as a `ValueRef`, /// allowing data to be read out of a row without copying. /// /// This `ValueRef` is valid only as long as this Row, which is enforced by /// it's lifetime. This means that while this method is completely safe, /// it can be difficult to use, and most callers will be better served by /// [`get`](Row::get) or [`get_unwrap`](Row::get_unwrap). /// /// ## Failure /// /// Panics if calling [`row.get_ref(idx)`](Row::get_ref) would return an error, /// including: /// /// * If `idx` is outside the range of columns in the returned query. /// * If `idx` is not a valid column name for this row. pub fn get_ref_unwrap<I: RowIndex>(&self, idx: I) -> ValueRef<'_> { self.get_ref(idx).unwrap() } /// Renamed to [`get_ref`](Row::get_ref). #[deprecated = "Use [`get_ref`](Row::get_ref) instead."] #[inline] pub fn get_raw_checked<I: RowIndex>(&self, idx: I) -> Result<ValueRef<'_>> { self.get_ref(idx) } /// Renamed to [`get_ref_unwrap`](Row::get_ref_unwrap). #[deprecated = "Use [`get_ref_unwrap`](Row::get_ref_unwrap) instead."] #[inline] pub fn get_raw<I: RowIndex>(&self, idx: I) -> ValueRef<'_> { self.get_ref_unwrap(idx) } } mod sealed { /// This trait exists just to ensure that the only impls of `trait Params` /// that are allowed are ones in this crate. pub trait Sealed {} impl Sealed for usize {} impl Sealed for &str {} } /// A trait implemented by types that can index into columns of a row. /// /// It is only implemented for `usize` and `&str`. pub trait RowIndex: sealed::Sealed { /// Returns the index of the appropriate column, or `None` if no such /// column exists. fn idx(&self, stmt: &Statement<'_>) -> Result<usize>; } impl RowIndex for usize { #[inline] fn idx(&self, stmt: &Statement<'_>) -> Result<usize> { if *self >= stmt.column_count() { Err(Error::InvalidColumnIndex(*self)) } else { Ok(*self) } } } impl RowIndex for &'_ str { #[inline] fn idx(&self, stmt: &Statement<'_>) -> Result<usize> { stmt.column_index(*self) } } macro_rules! tuple_try_from_row { ($($field:ident),*) => { impl<'a, $($field,)*> convert::TryFrom<&'a Row<'a>> for ($($field,)*) where $($field: FromSql,)* { type Error = crate::Error; // we end with index += 1, which rustc warns about // unused_variables and unused_mut are allowed for () #[allow(unused_assignments, unused_variables, unused_mut)] fn try_from(row: &'a Row<'a>) -> Result<Self> { let mut index = 0; $( #[allow(non_snake_case)] let $field = row.get::<_, $field>(index)?; index += 1; )* Ok(($($field,)*)) } } } } macro_rules! tuples_try_from_row { () => { // not very useful, but maybe some other macro users will find this helpful tuple_try_from_row!(); }; ($first:ident $(, $remaining:ident)*) => { tuple_try_from_row!($first $(, $remaining)*); tuples_try_from_row!($($remaining),*); }; } tuples_try_from_row!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P); #[cfg(test)] mod tests { #![allow(clippy::redundant_closure)] // false positives due to lifetime issues; clippy issue #5594 use crate::{Connection, Result}; #[test] fn test_try_from_row_for_tuple_1() -> Result<()> { use crate::ToSql; use std::convert::TryFrom; let conn = Connection::open_in_memory()?; conn.execute( "CREATE TABLE test (a INTEGER)", crate::params_from_iter(std::iter::empty::<&dyn ToSql>()), )?; conn.execute("INSERT INTO test VALUES (42)", [])?; let val = conn.query_row("SELECT a FROM test", [], |row| <(u32,)>::try_from(row))?; assert_eq!(val, (42,)); let fail = conn.query_row("SELECT a FROM test", [], |row| <(u32, u32)>::try_from(row)); assert!(fail.is_err()); Ok(()) } #[test] fn test_try_from_row_for_tuple_2() -> Result<()> { use std::convert::TryFrom; let conn = Connection::open_in_memory()?; conn.execute("CREATE TABLE test (a INTEGER, b INTEGER)", [])?; conn.execute("INSERT INTO test VALUES (42, 47)", [])?; let val = conn.query_row("SELECT a, b FROM test", [], |row| { <(u32, u32)>::try_from(row) })?; assert_eq!(val, (42, 47)); let fail = conn.query_row("SELECT a, b FROM test", [], |row| { <(u32, u32, u32)>::try_from(row) }); assert!(fail.is_err()); Ok(()) } #[test] fn test_try_from_row_for_tuple_16() -> Result<()> { use std::convert::TryFrom; let create_table = "CREATE TABLE test ( a INTEGER, b INTEGER, c INTEGER, d INTEGER, e INTEGER, f INTEGER, g INTEGER, h INTEGER, i INTEGER, j INTEGER, k INTEGER, l INTEGER, m INTEGER, n INTEGER, o INTEGER, p INTEGER )"; let insert_values = "INSERT INTO test VALUES ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 )"; type BigTuple = ( u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, ); let conn = Connection::open_in_memory()?; conn.execute(create_table, [])?; conn.execute(insert_values, [])?; let val = conn.query_row("SELECT * FROM test", [], |row| BigTuple::try_from(row))?; // Debug is not implemented for tuples of 16 assert_eq!(val.0, 0); assert_eq!(val.1, 1); assert_eq!(val.2, 2); assert_eq!(val.3, 3); assert_eq!(val.4, 4); assert_eq!(val.5, 5); assert_eq!(val.6, 6); assert_eq!(val.7, 7); assert_eq!(val.8, 8); assert_eq!(val.9, 9); assert_eq!(val.10, 10); assert_eq!(val.11, 11); assert_eq!(val.12, 12); assert_eq!(val.13, 13); assert_eq!(val.14, 14); assert_eq!(val.15, 15); // We don't test one bigger because it's unimplemented Ok(()) } }
Rows
identifier_name