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
compare.rs
#![crate_id="compare#0.1"] #![crate_type="bin"] extern crate bancnova; use std::os; use bancnova::syntax::bscode; use bancnova::syntax::tokenize; use bancnova::syntax::tokenize::Tokenizer; use bancnova::syntax::tree::Tree; use std::io::IoResult; use std::cmp::min; mod util; fn main()
fn read_tree<R: Reader>(tokenizer: &mut Tokenizer<R>) -> IoResult<Tree<bscode::Instruction>> { match Tree::parse(tokenizer) { Ok(tree) => Ok(tree), Err(s) => util::make_ioerr(s, tokenizer), } } struct ComparisonReporter<'a> { filename1: &'a str, filename2: &'a str, count: uint, } impl<'a> ComparisonReporter<'a> { fn new(filename1: &'a str, filename2: &'a str) -> ComparisonReporter<'a> { ComparisonReporter::<'a> { filename1: filename1, filename2: filename2, count: 0 } } fn report_general(&mut self, line: uint, message1: &str, message2: &str) { println!("{}:{}: {}", self.filename1, line, message1); println!("{}:{}: {}", self.filename2, line, message2); self.count += 1; } fn report(&mut self, line: uint, message: &str, inst1: &bscode::Instruction, inst2: &bscode::Instruction) { println!("{}:{}: {} {}", self.filename1, line, message, inst1); println!("{}:{}: {} {}", self.filename2, line, message, inst2); self.count += 1; } fn end(&self) -> IoResult<()> { if self.count == 0 { Ok(()) } else { util::make_ioerr_noline("files do not match") } } } fn compare(tree1: Tree<bscode::Instruction>, tree2: Tree<bscode::Instruction>, reporter: &mut ComparisonReporter) -> IoResult<()> { let length = min(tree1.len(), tree2.len()); for i in range(0, length) { let inst1 = tree1.get(i); let inst2 = tree2.get(i); if inst1!= inst2 { reporter.report(i+1, "mismatch", inst1, inst2); } } if tree1.len()!= tree2.len() { reporter.report_general(0, format!("{} line(s)", tree1.len()).as_slice(), format!("{} line(s)", tree2.len()).as_slice() ); } reporter.end() } fn compare_files(filename1: &str, filename2: &str) -> IoResult<()> { let file1 = match util::open_input(filename1) { Ok(p) => p, Err(e) => { return Err(e); }, }; let file2 = match util::open_input(filename2) { Ok(p) => p, Err(e) => { return Err(e); }, }; let mut tokenizer1 = tokenize::from_file(file1); let mut tokenizer2 = tokenize::from_file(file2); let tree1 = read_tree(&mut tokenizer1); let tree2 = read_tree(&mut tokenizer2); let mut reporter = ComparisonReporter::new(filename1, filename2); match (tree1, tree2) { (Ok(tree1), Ok(tree2)) => compare(tree1, tree2, &mut reporter), (Err(e), Ok(_)) => Err(e), (_, Err(e)) => Err(e), } }
{ let args = os::args(); match compare_files(args.get(1).as_slice(), args.get(2).as_slice()) { Err(err) => { println!("error: [{}] {}", err.kind, err.desc); if err.detail.is_some() { println!("\t{}", err.detail.unwrap()); } os::set_exit_status(-1); }, _ => { println!("files match"); }, } }
identifier_body
lib.rs
#![cfg_attr(test, deny(warnings))] #![warn(trivial_casts)] #![forbid(unused, unused_extern_crates, unused_import_braces, unused_qualifications)] pub fn nav(subdomain: &str, page: &str, is_admin: bool) -> String
<li{active_kontakt}><a href="{wiw}/kontakt"><span class="fa fa-envelope"></span>Kontakt</a></li> <li{active_boerse}><a href="{boerse}/"><span class="fa fa-exchange"></span>Börse</a></li> </ul> {right} </div> </nav> "#, wiw=if subdomain == "boerse" { "//willkommeninwoellstein.de" } else { "" }, boerse=if subdomain == "boerse" { "" } else { "//boerse.willkommeninwoellstein.de" }, right=if subdomain == "boerse" && is_admin { r#"<ul class="navbar-boerse-admin nav navbar-nav navbar-right"><li><a href="/notiz/neu"><span class="fa fa-plus"></span>neue Notiz</a></li></ul>"# } else { "" }, active_home=if subdomain!= "boerse" && page == "/" { " class=\"active\"" } else { "" }, active_angebote=if subdomain!= "boerse" && page.starts_with("/angebote") { " class=\"active\"" } else { "" }, active_veranstaltungen=if subdomain!= "boerse" && page.starts_with("/veranstaltungen") { " class=\"active\"" } else { "" }, active_presse=if subdomain!= "boerse" && page.starts_with("/presse") { " class=\"active\"" } else { "" }, active_galerie=if subdomain!= "boerse" && page.starts_with("/galerie") { " class=\"active\"" } else { "" }, active_kontakt=if subdomain!= "boerse" && page.starts_with("/kontakt") { " class=\"active\"" } else { "" }, active_boerse=if subdomain == "boerse" { " class=\"active\"" } else { "" }, ) }
{ format!( r#" <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{wiw}/">Willkommen in Wöllstein</a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul id="navbar-list" class="nav navbar-nav"> <li{active_home}><a href="{wiw}/"><span class="fa fa-home"></span>Home</a></li> <li{active_angebote}><a href="{wiw}/angebote"><span class="fa fa-smile-o"></span>Unsere Angebote</a></li> <li{active_veranstaltungen}><a href="{wiw}/veranstaltungen"><span class="fa fa-calendar"></span>Veranstaltungen</a></li> <li{active_presse}><a href="{wiw}/presse"><span class="fa fa-comments"></span>Presse</a></li> <li{active_galerie}><a href="{wiw}/galerie"><span class="fa fa-picture-o"></span>Galerie</a></li>
identifier_body
lib.rs
#![cfg_attr(test, deny(warnings))] #![warn(trivial_casts)] #![forbid(unused, unused_extern_crates, unused_import_braces, unused_qualifications)] pub fn
(subdomain: &str, page: &str, is_admin: bool) -> String { format!( r#" <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{wiw}/">Willkommen in Wöllstein</a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul id="navbar-list" class="nav navbar-nav"> <li{active_home}><a href="{wiw}/"><span class="fa fa-home"></span>Home</a></li> <li{active_angebote}><a href="{wiw}/angebote"><span class="fa fa-smile-o"></span>Unsere Angebote</a></li> <li{active_veranstaltungen}><a href="{wiw}/veranstaltungen"><span class="fa fa-calendar"></span>Veranstaltungen</a></li> <li{active_presse}><a href="{wiw}/presse"><span class="fa fa-comments"></span>Presse</a></li> <li{active_galerie}><a href="{wiw}/galerie"><span class="fa fa-picture-o"></span>Galerie</a></li> <li{active_kontakt}><a href="{wiw}/kontakt"><span class="fa fa-envelope"></span>Kontakt</a></li> <li{active_boerse}><a href="{boerse}/"><span class="fa fa-exchange"></span>Börse</a></li> </ul> {right} </div> </nav> "#, wiw=if subdomain == "boerse" { "//willkommeninwoellstein.de" } else { "" }, boerse=if subdomain == "boerse" { "" } else { "//boerse.willkommeninwoellstein.de" }, right=if subdomain == "boerse" && is_admin { r#"<ul class="navbar-boerse-admin nav navbar-nav navbar-right"><li><a href="/notiz/neu"><span class="fa fa-plus"></span>neue Notiz</a></li></ul>"# } else { "" }, active_home=if subdomain!= "boerse" && page == "/" { " class=\"active\"" } else { "" }, active_angebote=if subdomain!= "boerse" && page.starts_with("/angebote") { " class=\"active\"" } else { "" }, active_veranstaltungen=if subdomain!= "boerse" && page.starts_with("/veranstaltungen") { " class=\"active\"" } else { "" }, active_presse=if subdomain!= "boerse" && page.starts_with("/presse") { " class=\"active\"" } else { "" }, active_galerie=if subdomain!= "boerse" && page.starts_with("/galerie") { " class=\"active\"" } else { "" }, active_kontakt=if subdomain!= "boerse" && page.starts_with("/kontakt") { " class=\"active\"" } else { "" }, active_boerse=if subdomain == "boerse" { " class=\"active\"" } else { "" }, ) }
nav
identifier_name
lib.rs
#![cfg_attr(test, deny(warnings))] #![warn(trivial_casts)] #![forbid(unused, unused_extern_crates, unused_import_braces, unused_qualifications)] pub fn nav(subdomain: &str, page: &str, is_admin: bool) -> String { format!( r#" <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span>
<ul id="navbar-list" class="nav navbar-nav"> <li{active_home}><a href="{wiw}/"><span class="fa fa-home"></span>Home</a></li> <li{active_angebote}><a href="{wiw}/angebote"><span class="fa fa-smile-o"></span>Unsere Angebote</a></li> <li{active_veranstaltungen}><a href="{wiw}/veranstaltungen"><span class="fa fa-calendar"></span>Veranstaltungen</a></li> <li{active_presse}><a href="{wiw}/presse"><span class="fa fa-comments"></span>Presse</a></li> <li{active_galerie}><a href="{wiw}/galerie"><span class="fa fa-picture-o"></span>Galerie</a></li> <li{active_kontakt}><a href="{wiw}/kontakt"><span class="fa fa-envelope"></span>Kontakt</a></li> <li{active_boerse}><a href="{boerse}/"><span class="fa fa-exchange"></span>Börse</a></li> </ul> {right} </div> </nav> "#, wiw=if subdomain == "boerse" { "//willkommeninwoellstein.de" } else { "" }, boerse=if subdomain == "boerse" { "" } else { "//boerse.willkommeninwoellstein.de" }, right=if subdomain == "boerse" && is_admin { r#"<ul class="navbar-boerse-admin nav navbar-nav navbar-right"><li><a href="/notiz/neu"><span class="fa fa-plus"></span>neue Notiz</a></li></ul>"# } else { "" }, active_home=if subdomain!= "boerse" && page == "/" { " class=\"active\"" } else { "" }, active_angebote=if subdomain!= "boerse" && page.starts_with("/angebote") { " class=\"active\"" } else { "" }, active_veranstaltungen=if subdomain!= "boerse" && page.starts_with("/veranstaltungen") { " class=\"active\"" } else { "" }, active_presse=if subdomain!= "boerse" && page.starts_with("/presse") { " class=\"active\"" } else { "" }, active_galerie=if subdomain!= "boerse" && page.starts_with("/galerie") { " class=\"active\"" } else { "" }, active_kontakt=if subdomain!= "boerse" && page.starts_with("/kontakt") { " class=\"active\"" } else { "" }, active_boerse=if subdomain == "boerse" { " class=\"active\"" } else { "" }, ) }
<span class="icon-bar"></span> </button> <a class="navbar-brand" href="{wiw}/">Willkommen in Wöllstein</a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse">
random_line_split
list.rs
// Copyright 2016 Jeremy Letang. // 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 api::context::Context; use backit::responses; use db::repositories::repo as repo_repo; use iron::{Request, Response, IronResult}; use serde_json; use std::error::Error;
Ok(l) => responses::ok(serde_json::to_string(&l).unwrap()), Err(e) => responses::internal_error(e.description()), } }
// get /api/v1/tags pub fn list(ctx: Context, _: &mut Request) -> IronResult<Response> { let db = &mut *ctx.db.get().expect("cannot get sqlite connection from the context"); match repo_repo::list_for_user_id(db, &*ctx.user.id) {
random_line_split
list.rs
// Copyright 2016 Jeremy Letang. // 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 api::context::Context; use backit::responses; use db::repositories::repo as repo_repo; use iron::{Request, Response, IronResult}; use serde_json; use std::error::Error; // get /api/v1/tags pub fn list(ctx: Context, _: &mut Request) -> IronResult<Response>
{ let db = &mut *ctx.db.get().expect("cannot get sqlite connection from the context"); match repo_repo::list_for_user_id(db, &*ctx.user.id) { Ok(l) => responses::ok(serde_json::to_string(&l).unwrap()), Err(e) => responses::internal_error(e.description()), } }
identifier_body
list.rs
// Copyright 2016 Jeremy Letang. // 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 api::context::Context; use backit::responses; use db::repositories::repo as repo_repo; use iron::{Request, Response, IronResult}; use serde_json; use std::error::Error; // get /api/v1/tags pub fn
(ctx: Context, _: &mut Request) -> IronResult<Response> { let db = &mut *ctx.db.get().expect("cannot get sqlite connection from the context"); match repo_repo::list_for_user_id(db, &*ctx.user.id) { Ok(l) => responses::ok(serde_json::to_string(&l).unwrap()), Err(e) => responses::internal_error(e.description()), } }
list
identifier_name
network.rs
use std::ptr::{null, copy}; use std::ffi::{CString}; use std::io::Error as IoError; use std::io::Result as IoResult; use std::net::Ipv4Addr; use libc::{c_int, size_t, c_char, EINVAL}; #[repr(C)] struct hostent { h_name: *const c_char, /* official name of host */ h_aliases: *const *const c_char, /* alias list */ h_addrtype: c_int, /* host address type */ h_length: c_int, /* length of address */ h_addr_list: *const *const c_char, /* list of addresses */ } extern { fn gethostname(name: *mut c_char, size: size_t) -> c_int; fn gethostbyname(name: *const c_char) -> *const hostent; } pub fn get_host_ip() -> IoResult<String> { let host = try!(get_host_name()); let addr = try!(get_host_address(&host[..])); return Ok(addr); } pub fn get_host_name() -> IoResult<String> { let mut buf: Vec<u8> = Vec::with_capacity(256); let nbytes = unsafe { buf.set_len(256); gethostname( (&mut buf[..]).as_ptr() as *mut i8, 256) }; if nbytes!= 0 { return Err(IoError::last_os_error()); } return buf[..].splitn(2, |x| *x == 0u8) .next() .and_then(|x| String::from_utf8(x.to_vec()).ok()) .ok_or(IoError::from_raw_os_error(EINVAL)); } pub fn get_host_address(val: &str) -> IoResult<String> { let cval = CString::new(val).unwrap(); unsafe { let hostent = gethostbyname(cval.as_ptr()); if hostent == null()
if (*hostent).h_length == 0 { return Err(IoError::from_raw_os_error(EINVAL)); } let mut addr = [0u8; 4]; copy(*(*hostent).h_addr_list, addr.as_mut_ptr() as *mut i8, 4); return Ok(format!("{}", Ipv4Addr::new(addr[0], addr[1], addr[2], addr[3]))); } }
{ return Err(IoError::last_os_error()); }
conditional_block
network.rs
use std::ptr::{null, copy}; use std::ffi::{CString}; use std::io::Error as IoError; use std::io::Result as IoResult; use std::net::Ipv4Addr; use libc::{c_int, size_t, c_char, EINVAL}; #[repr(C)] struct hostent { h_name: *const c_char, /* official name of host */ h_aliases: *const *const c_char, /* alias list */ h_addrtype: c_int, /* host address type */ h_length: c_int, /* length of address */ h_addr_list: *const *const c_char, /* list of addresses */ } extern { fn gethostname(name: *mut c_char, size: size_t) -> c_int; fn gethostbyname(name: *const c_char) -> *const hostent; } pub fn
() -> IoResult<String> { let host = try!(get_host_name()); let addr = try!(get_host_address(&host[..])); return Ok(addr); } pub fn get_host_name() -> IoResult<String> { let mut buf: Vec<u8> = Vec::with_capacity(256); let nbytes = unsafe { buf.set_len(256); gethostname( (&mut buf[..]).as_ptr() as *mut i8, 256) }; if nbytes!= 0 { return Err(IoError::last_os_error()); } return buf[..].splitn(2, |x| *x == 0u8) .next() .and_then(|x| String::from_utf8(x.to_vec()).ok()) .ok_or(IoError::from_raw_os_error(EINVAL)); } pub fn get_host_address(val: &str) -> IoResult<String> { let cval = CString::new(val).unwrap(); unsafe { let hostent = gethostbyname(cval.as_ptr()); if hostent == null() { return Err(IoError::last_os_error()); } if (*hostent).h_length == 0 { return Err(IoError::from_raw_os_error(EINVAL)); } let mut addr = [0u8; 4]; copy(*(*hostent).h_addr_list, addr.as_mut_ptr() as *mut i8, 4); return Ok(format!("{}", Ipv4Addr::new(addr[0], addr[1], addr[2], addr[3]))); } }
get_host_ip
identifier_name
network.rs
use std::ptr::{null, copy}; use std::ffi::{CString}; use std::io::Error as IoError; use std::io::Result as IoResult; use std::net::Ipv4Addr; use libc::{c_int, size_t, c_char, EINVAL}; #[repr(C)] struct hostent { h_name: *const c_char, /* official name of host */ h_aliases: *const *const c_char, /* alias list */ h_addrtype: c_int, /* host address type */ h_length: c_int, /* length of address */ h_addr_list: *const *const c_char, /* list of addresses */ } extern { fn gethostname(name: *mut c_char, size: size_t) -> c_int; fn gethostbyname(name: *const c_char) -> *const hostent; } pub fn get_host_ip() -> IoResult<String> { let host = try!(get_host_name()); let addr = try!(get_host_address(&host[..])); return Ok(addr); } pub fn get_host_name() -> IoResult<String> { let mut buf: Vec<u8> = Vec::with_capacity(256); let nbytes = unsafe { buf.set_len(256); gethostname( (&mut buf[..]).as_ptr() as *mut i8, 256) }; if nbytes!= 0 { return Err(IoError::last_os_error()); } return buf[..].splitn(2, |x| *x == 0u8) .next() .and_then(|x| String::from_utf8(x.to_vec()).ok()) .ok_or(IoError::from_raw_os_error(EINVAL)); } pub fn get_host_address(val: &str) -> IoResult<String> { let cval = CString::new(val).unwrap(); unsafe { let hostent = gethostbyname(cval.as_ptr());
} let mut addr = [0u8; 4]; copy(*(*hostent).h_addr_list, addr.as_mut_ptr() as *mut i8, 4); return Ok(format!("{}", Ipv4Addr::new(addr[0], addr[1], addr[2], addr[3]))); } }
if hostent == null() { return Err(IoError::last_os_error()); } if (*hostent).h_length == 0 { return Err(IoError::from_raw_os_error(EINVAL));
random_line_split
htmltablesectionelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding::{ self, HTMLTableSectionElementMethods, }; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::error::{ErrorResult, Fallible}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRoot, LayoutDom, RootedReference}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::{Element, RawLayoutElementHelpers}; use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection}; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmltablerowelement::HTMLTableRowElement; use crate::dom::node::{window_from_node, Node}; use crate::dom::virtualmethods::VirtualMethods; use cssparser::RGBA; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use style::attr::AttrValue; #[dom_struct] pub struct HTMLTableSectionElement { htmlelement: HTMLElement, } impl HTMLTableSectionElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLTableSectionElement { HTMLTableSectionElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn
( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLTableSectionElement> { Node::reflect_node( Box::new(HTMLTableSectionElement::new_inherited( local_name, prefix, document, )), document, HTMLTableSectionElementBinding::Wrap, ) } } #[derive(JSTraceable)] struct RowsFilter; impl CollectionFilter for RowsFilter { fn filter(&self, elem: &Element, root: &Node) -> bool { elem.is::<HTMLTableRowElement>() && elem.upcast::<Node>().GetParentNode().r() == Some(root) } } impl HTMLTableSectionElementMethods for HTMLTableSectionElement { // https://html.spec.whatwg.org/multipage/#dom-tbody-rows fn Rows(&self) -> DomRoot<HTMLCollection> { HTMLCollection::create(&window_from_node(self), self.upcast(), Box::new(RowsFilter)) } // https://html.spec.whatwg.org/multipage/#dom-tbody-insertrow fn InsertRow(&self, index: i32) -> Fallible<DomRoot<HTMLElement>> { let node = self.upcast::<Node>(); node.insert_cell_or_row( index, || self.Rows(), || HTMLTableRowElement::new(local_name!("tr"), None, &node.owner_doc()), ) } // https://html.spec.whatwg.org/multipage/#dom-tbody-deleterow fn DeleteRow(&self, index: i32) -> ErrorResult { let node = self.upcast::<Node>(); node.delete_cell_or_row(index, || self.Rows(), |n| n.is::<HTMLTableRowElement>()) } } pub trait HTMLTableSectionElementLayoutHelpers { fn get_background_color(&self) -> Option<RGBA>; } #[allow(unsafe_code)] impl HTMLTableSectionElementLayoutHelpers for LayoutDom<HTMLTableSectionElement> { fn get_background_color(&self) -> Option<RGBA> { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("bgcolor")) .and_then(AttrValue::as_color) .cloned() } } } impl VirtualMethods for HTMLTableSectionElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue { match *local_name { local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()), _ => self .super_type() .unwrap() .parse_plain_attribute(local_name, value), } } }
new
identifier_name
htmltablesectionelement.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
use crate::dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding::{ self, HTMLTableSectionElementMethods, }; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::error::{ErrorResult, Fallible}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRoot, LayoutDom, RootedReference}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::{Element, RawLayoutElementHelpers}; use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection}; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmltablerowelement::HTMLTableRowElement; use crate::dom::node::{window_from_node, Node}; use crate::dom::virtualmethods::VirtualMethods; use cssparser::RGBA; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use style::attr::AttrValue; #[dom_struct] pub struct HTMLTableSectionElement { htmlelement: HTMLElement, } impl HTMLTableSectionElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLTableSectionElement { HTMLTableSectionElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLTableSectionElement> { Node::reflect_node( Box::new(HTMLTableSectionElement::new_inherited( local_name, prefix, document, )), document, HTMLTableSectionElementBinding::Wrap, ) } } #[derive(JSTraceable)] struct RowsFilter; impl CollectionFilter for RowsFilter { fn filter(&self, elem: &Element, root: &Node) -> bool { elem.is::<HTMLTableRowElement>() && elem.upcast::<Node>().GetParentNode().r() == Some(root) } } impl HTMLTableSectionElementMethods for HTMLTableSectionElement { // https://html.spec.whatwg.org/multipage/#dom-tbody-rows fn Rows(&self) -> DomRoot<HTMLCollection> { HTMLCollection::create(&window_from_node(self), self.upcast(), Box::new(RowsFilter)) } // https://html.spec.whatwg.org/multipage/#dom-tbody-insertrow fn InsertRow(&self, index: i32) -> Fallible<DomRoot<HTMLElement>> { let node = self.upcast::<Node>(); node.insert_cell_or_row( index, || self.Rows(), || HTMLTableRowElement::new(local_name!("tr"), None, &node.owner_doc()), ) } // https://html.spec.whatwg.org/multipage/#dom-tbody-deleterow fn DeleteRow(&self, index: i32) -> ErrorResult { let node = self.upcast::<Node>(); node.delete_cell_or_row(index, || self.Rows(), |n| n.is::<HTMLTableRowElement>()) } } pub trait HTMLTableSectionElementLayoutHelpers { fn get_background_color(&self) -> Option<RGBA>; } #[allow(unsafe_code)] impl HTMLTableSectionElementLayoutHelpers for LayoutDom<HTMLTableSectionElement> { fn get_background_color(&self) -> Option<RGBA> { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("bgcolor")) .and_then(AttrValue::as_color) .cloned() } } } impl VirtualMethods for HTMLTableSectionElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue { match *local_name { local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()), _ => self .super_type() .unwrap() .parse_plain_attribute(local_name, value), } } }
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
random_line_split
htmltablesectionelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding::{ self, HTMLTableSectionElementMethods, }; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::error::{ErrorResult, Fallible}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRoot, LayoutDom, RootedReference}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::{Element, RawLayoutElementHelpers}; use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection}; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmltablerowelement::HTMLTableRowElement; use crate::dom::node::{window_from_node, Node}; use crate::dom::virtualmethods::VirtualMethods; use cssparser::RGBA; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use style::attr::AttrValue; #[dom_struct] pub struct HTMLTableSectionElement { htmlelement: HTMLElement, } impl HTMLTableSectionElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLTableSectionElement
#[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLTableSectionElement> { Node::reflect_node( Box::new(HTMLTableSectionElement::new_inherited( local_name, prefix, document, )), document, HTMLTableSectionElementBinding::Wrap, ) } } #[derive(JSTraceable)] struct RowsFilter; impl CollectionFilter for RowsFilter { fn filter(&self, elem: &Element, root: &Node) -> bool { elem.is::<HTMLTableRowElement>() && elem.upcast::<Node>().GetParentNode().r() == Some(root) } } impl HTMLTableSectionElementMethods for HTMLTableSectionElement { // https://html.spec.whatwg.org/multipage/#dom-tbody-rows fn Rows(&self) -> DomRoot<HTMLCollection> { HTMLCollection::create(&window_from_node(self), self.upcast(), Box::new(RowsFilter)) } // https://html.spec.whatwg.org/multipage/#dom-tbody-insertrow fn InsertRow(&self, index: i32) -> Fallible<DomRoot<HTMLElement>> { let node = self.upcast::<Node>(); node.insert_cell_or_row( index, || self.Rows(), || HTMLTableRowElement::new(local_name!("tr"), None, &node.owner_doc()), ) } // https://html.spec.whatwg.org/multipage/#dom-tbody-deleterow fn DeleteRow(&self, index: i32) -> ErrorResult { let node = self.upcast::<Node>(); node.delete_cell_or_row(index, || self.Rows(), |n| n.is::<HTMLTableRowElement>()) } } pub trait HTMLTableSectionElementLayoutHelpers { fn get_background_color(&self) -> Option<RGBA>; } #[allow(unsafe_code)] impl HTMLTableSectionElementLayoutHelpers for LayoutDom<HTMLTableSectionElement> { fn get_background_color(&self) -> Option<RGBA> { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("bgcolor")) .and_then(AttrValue::as_color) .cloned() } } } impl VirtualMethods for HTMLTableSectionElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue { match *local_name { local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()), _ => self .super_type() .unwrap() .parse_plain_attribute(local_name, value), } } }
{ HTMLTableSectionElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } }
identifier_body
mod.rs
#![allow(dead_code)] use std::rc::Rc; use std::ops::{ Add, Sub, }; use chunk::{ChunkOption}; pub struct
{ x: f64, y: f64, z: f64, } pub struct Entity { mass: Rc<ChunkOption>, velocity: Vec3f64, location: Vec3f64, rotation: Vec3f64, } impl Add<Vec3f64> for Vec3f64 { type Output = Vec3f64; fn add(self, _rhs: Vec3f64) -> Vec3f64 { Vec3f64 { x: self.x + _rhs.x, y: self.y + _rhs.y, z: self.z + _rhs.z } } } impl Sub<Vec3f64> for Vec3f64 { type Output = Vec3f64; fn sub(self, _rhs: Vec3f64) -> Vec3f64 { Vec3f64 { x: self.x + _rhs.x, y: self.y + _rhs.y, z: self.z + _rhs.z } } }
Vec3f64
identifier_name
mod.rs
#![allow(dead_code)] use std::rc::Rc; use std::ops::{ Add, Sub, }; use chunk::{ChunkOption}; pub struct Vec3f64 { x: f64, y: f64, z: f64, } pub struct Entity { mass: Rc<ChunkOption>, velocity: Vec3f64,
location: Vec3f64, rotation: Vec3f64, } impl Add<Vec3f64> for Vec3f64 { type Output = Vec3f64; fn add(self, _rhs: Vec3f64) -> Vec3f64 { Vec3f64 { x: self.x + _rhs.x, y: self.y + _rhs.y, z: self.z + _rhs.z } } } impl Sub<Vec3f64> for Vec3f64 { type Output = Vec3f64; fn sub(self, _rhs: Vec3f64) -> Vec3f64 { Vec3f64 { x: self.x + _rhs.x, y: self.y + _rhs.y, z: self.z + _rhs.z } } }
random_line_split
mod.rs
#![allow(dead_code)] use std::rc::Rc; use std::ops::{ Add, Sub, }; use chunk::{ChunkOption}; pub struct Vec3f64 { x: f64, y: f64, z: f64, } pub struct Entity { mass: Rc<ChunkOption>, velocity: Vec3f64, location: Vec3f64, rotation: Vec3f64, } impl Add<Vec3f64> for Vec3f64 { type Output = Vec3f64; fn add(self, _rhs: Vec3f64) -> Vec3f64
} impl Sub<Vec3f64> for Vec3f64 { type Output = Vec3f64; fn sub(self, _rhs: Vec3f64) -> Vec3f64 { Vec3f64 { x: self.x + _rhs.x, y: self.y + _rhs.y, z: self.z + _rhs.z } } }
{ Vec3f64 { x: self.x + _rhs.x, y: self.y + _rhs.y, z: self.z + _rhs.z } }
identifier_body
case.rs
use super::super::ArgumentSplitter; use std::fmt::{self, Display, Formatter}; #[derive(Debug, PartialEq)]
} impl<'a> Display for CaseError<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { CaseError::NoBindVariable => write!(f, "no bind variable was supplied"), CaseError::NoConditional => write!(f, "no conditional statement was given"), CaseError::ExtraBind(value) => write!(f, "extra value, '{}', was given to bind", value), CaseError::ExtraVar(value) => { write!(f, "extra variable, '{}', was given to case", value) } } } } pub(crate) fn parse_case<'a>( data: &'a str, ) -> Result<(Option<&'a str>, Option<&'a str>, Option<String>), CaseError<'a>> { let mut splitter = ArgumentSplitter::new(data); // let argument = splitter.next().ok_or(CaseError::Empty)?; let mut argument = None; let mut binding = None; let mut conditional = None; loop { match splitter.next() { Some("@") => { binding = Some(splitter.next().ok_or(CaseError::NoBindVariable)?); match splitter.next() { Some("if") => { let string = splitter.collect::<Vec<_>>().join(" "); if string.is_empty() { return Err(CaseError::NoConditional); } conditional = Some(string); } Some(value) => return Err(CaseError::ExtraBind(value)), None => (), } } Some("if") => { let string = splitter.collect::<Vec<_>>().join(" "); if string.is_empty() { return Err(CaseError::NoConditional); } conditional = Some(string); } Some(inner) => if argument.is_none() { argument = Some(inner); continue; } else { return Err(CaseError::ExtraVar(inner)); }, None => (), } break; } Ok((argument, binding, conditional)) } #[cfg(test)] mod tests { use super::parse_case; #[test] fn case_parsing() { assert_eq!( Ok((Some("test"), Some("test"), Some("exists".into()))), parse_case("test @ test if exists") ); assert_eq!( Ok((Some("test"), Some("test"), None)), parse_case("test @ test") ); assert_eq!(Ok((Some("test"), None, None)), parse_case("test")); } }
pub(crate) enum CaseError<'a> { NoBindVariable, NoConditional, ExtraBind(&'a str), ExtraVar(&'a str),
random_line_split
case.rs
use super::super::ArgumentSplitter; use std::fmt::{self, Display, Formatter}; #[derive(Debug, PartialEq)] pub(crate) enum CaseError<'a> { NoBindVariable, NoConditional, ExtraBind(&'a str), ExtraVar(&'a str), } impl<'a> Display for CaseError<'a> { fn
(&self, f: &mut Formatter) -> fmt::Result { match *self { CaseError::NoBindVariable => write!(f, "no bind variable was supplied"), CaseError::NoConditional => write!(f, "no conditional statement was given"), CaseError::ExtraBind(value) => write!(f, "extra value, '{}', was given to bind", value), CaseError::ExtraVar(value) => { write!(f, "extra variable, '{}', was given to case", value) } } } } pub(crate) fn parse_case<'a>( data: &'a str, ) -> Result<(Option<&'a str>, Option<&'a str>, Option<String>), CaseError<'a>> { let mut splitter = ArgumentSplitter::new(data); // let argument = splitter.next().ok_or(CaseError::Empty)?; let mut argument = None; let mut binding = None; let mut conditional = None; loop { match splitter.next() { Some("@") => { binding = Some(splitter.next().ok_or(CaseError::NoBindVariable)?); match splitter.next() { Some("if") => { let string = splitter.collect::<Vec<_>>().join(" "); if string.is_empty() { return Err(CaseError::NoConditional); } conditional = Some(string); } Some(value) => return Err(CaseError::ExtraBind(value)), None => (), } } Some("if") => { let string = splitter.collect::<Vec<_>>().join(" "); if string.is_empty() { return Err(CaseError::NoConditional); } conditional = Some(string); } Some(inner) => if argument.is_none() { argument = Some(inner); continue; } else { return Err(CaseError::ExtraVar(inner)); }, None => (), } break; } Ok((argument, binding, conditional)) } #[cfg(test)] mod tests { use super::parse_case; #[test] fn case_parsing() { assert_eq!( Ok((Some("test"), Some("test"), Some("exists".into()))), parse_case("test @ test if exists") ); assert_eq!( Ok((Some("test"), Some("test"), None)), parse_case("test @ test") ); assert_eq!(Ok((Some("test"), None, None)), parse_case("test")); } }
fmt
identifier_name
case.rs
use super::super::ArgumentSplitter; use std::fmt::{self, Display, Formatter}; #[derive(Debug, PartialEq)] pub(crate) enum CaseError<'a> { NoBindVariable, NoConditional, ExtraBind(&'a str), ExtraVar(&'a str), } impl<'a> Display for CaseError<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { CaseError::NoBindVariable => write!(f, "no bind variable was supplied"), CaseError::NoConditional => write!(f, "no conditional statement was given"), CaseError::ExtraBind(value) => write!(f, "extra value, '{}', was given to bind", value), CaseError::ExtraVar(value) => { write!(f, "extra variable, '{}', was given to case", value) } } } } pub(crate) fn parse_case<'a>( data: &'a str, ) -> Result<(Option<&'a str>, Option<&'a str>, Option<String>), CaseError<'a>> { let mut splitter = ArgumentSplitter::new(data); // let argument = splitter.next().ok_or(CaseError::Empty)?; let mut argument = None; let mut binding = None; let mut conditional = None; loop { match splitter.next() { Some("@") => { binding = Some(splitter.next().ok_or(CaseError::NoBindVariable)?); match splitter.next() { Some("if") => { let string = splitter.collect::<Vec<_>>().join(" "); if string.is_empty() { return Err(CaseError::NoConditional); } conditional = Some(string); } Some(value) => return Err(CaseError::ExtraBind(value)), None => (), } } Some("if") => { let string = splitter.collect::<Vec<_>>().join(" "); if string.is_empty() { return Err(CaseError::NoConditional); } conditional = Some(string); } Some(inner) => if argument.is_none() { argument = Some(inner); continue; } else { return Err(CaseError::ExtraVar(inner)); }, None => (), } break; } Ok((argument, binding, conditional)) } #[cfg(test)] mod tests { use super::parse_case; #[test] fn case_parsing()
}
{ assert_eq!( Ok((Some("test"), Some("test"), Some("exists".into()))), parse_case("test @ test if exists") ); assert_eq!( Ok((Some("test"), Some("test"), None)), parse_case("test @ test") ); assert_eq!(Ok((Some("test"), None, None)), parse_case("test")); }
identifier_body
errors.rs
use actix_web::{error, http, HttpResponse}; use diesel; use failure::Fail; use r2d2; use std::convert::From; #[derive(Fail, Debug)] pub enum MailboxerError { #[fail(display = "Mailbox already exists")] MailboxAlreadyExists, #[fail(display = "Mailbox not found")] MailboxNotFound, #[fail(display = "Internal error")] InternalServerError, } impl From<diesel::result::Error> for MailboxerError { fn from(_err: diesel::result::Error) -> Self { MailboxerError::InternalServerError } } impl From<r2d2::Error> for MailboxerError { fn from(_err: r2d2::Error) -> Self { MailboxerError::InternalServerError } } impl error::ResponseError for MailboxerError { fn error_response(&self) -> HttpResponse
}
{ match *self { MailboxerError::MailboxAlreadyExists => HttpResponse::new(http::StatusCode::CONFLICT), MailboxerError::InternalServerError => { HttpResponse::new(http::StatusCode::INTERNAL_SERVER_ERROR) } ref e @ MailboxerError::MailboxNotFound => { HttpResponse::with_body(http::StatusCode::NOT_FOUND, e.to_string()) } } }
identifier_body
errors.rs
use actix_web::{error, http, HttpResponse}; use diesel;
pub enum MailboxerError { #[fail(display = "Mailbox already exists")] MailboxAlreadyExists, #[fail(display = "Mailbox not found")] MailboxNotFound, #[fail(display = "Internal error")] InternalServerError, } impl From<diesel::result::Error> for MailboxerError { fn from(_err: diesel::result::Error) -> Self { MailboxerError::InternalServerError } } impl From<r2d2::Error> for MailboxerError { fn from(_err: r2d2::Error) -> Self { MailboxerError::InternalServerError } } impl error::ResponseError for MailboxerError { fn error_response(&self) -> HttpResponse { match *self { MailboxerError::MailboxAlreadyExists => HttpResponse::new(http::StatusCode::CONFLICT), MailboxerError::InternalServerError => { HttpResponse::new(http::StatusCode::INTERNAL_SERVER_ERROR) } ref e @ MailboxerError::MailboxNotFound => { HttpResponse::with_body(http::StatusCode::NOT_FOUND, e.to_string()) } } } }
use failure::Fail; use r2d2; use std::convert::From; #[derive(Fail, Debug)]
random_line_split
errors.rs
use actix_web::{error, http, HttpResponse}; use diesel; use failure::Fail; use r2d2; use std::convert::From; #[derive(Fail, Debug)] pub enum MailboxerError { #[fail(display = "Mailbox already exists")] MailboxAlreadyExists, #[fail(display = "Mailbox not found")] MailboxNotFound, #[fail(display = "Internal error")] InternalServerError, } impl From<diesel::result::Error> for MailboxerError { fn from(_err: diesel::result::Error) -> Self { MailboxerError::InternalServerError } } impl From<r2d2::Error> for MailboxerError { fn from(_err: r2d2::Error) -> Self { MailboxerError::InternalServerError } } impl error::ResponseError for MailboxerError { fn error_response(&self) -> HttpResponse { match *self { MailboxerError::MailboxAlreadyExists => HttpResponse::new(http::StatusCode::CONFLICT), MailboxerError::InternalServerError => { HttpResponse::new(http::StatusCode::INTERNAL_SERVER_ERROR) } ref e @ MailboxerError::MailboxNotFound =>
} } }
{ HttpResponse::with_body(http::StatusCode::NOT_FOUND, e.to_string()) }
conditional_block
errors.rs
use actix_web::{error, http, HttpResponse}; use diesel; use failure::Fail; use r2d2; use std::convert::From; #[derive(Fail, Debug)] pub enum MailboxerError { #[fail(display = "Mailbox already exists")] MailboxAlreadyExists, #[fail(display = "Mailbox not found")] MailboxNotFound, #[fail(display = "Internal error")] InternalServerError, } impl From<diesel::result::Error> for MailboxerError { fn
(_err: diesel::result::Error) -> Self { MailboxerError::InternalServerError } } impl From<r2d2::Error> for MailboxerError { fn from(_err: r2d2::Error) -> Self { MailboxerError::InternalServerError } } impl error::ResponseError for MailboxerError { fn error_response(&self) -> HttpResponse { match *self { MailboxerError::MailboxAlreadyExists => HttpResponse::new(http::StatusCode::CONFLICT), MailboxerError::InternalServerError => { HttpResponse::new(http::StatusCode::INTERNAL_SERVER_ERROR) } ref e @ MailboxerError::MailboxNotFound => { HttpResponse::with_body(http::StatusCode::NOT_FOUND, e.to_string()) } } } }
from
identifier_name
util.rs
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //! Some programming utilities /// Returns a float rounded upto a certain number of decimal digits #[inline] pub fn round_upto_digits(float: f64, decimal_digits: u32) -> f64
/** Evaluates a polynomial using Horner's algorithm # Arguments * `$x` : The value of the independent variable `f32 or f64` * `$c` : The constant term `f32 or f64` * `$($a),*`: Sequence of coefficient terms for `$x`, in ascending powers of `$x` **/ #[macro_export] macro_rules! Horner_eval { ($x:expr, $c:expr, $($a:expr),*) => { { let mut y = $c; let mut u = 1.0; $( u *= $x; y += u * $a; )* y } } }
{ let mut d = 1.0; for _ in 1..(decimal_digits + 1) { d *= 10.0; } (float * d).round() / d }
identifier_body
util.rs
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ //! Some programming utilities /// Returns a float rounded upto a certain number of decimal digits #[inline] pub fn round_upto_digits(float: f64, decimal_digits: u32) -> f64 { let mut d = 1.0; for _ in 1..(decimal_digits + 1) { d *= 10.0; } (float * d).round() / d } /** Evaluates a polynomial using Horner's algorithm # Arguments * `$x` : The value of the independent variable `f32 or f64` * `$c` : The constant term `f32 or f64` * `$($a),*`: Sequence of coefficient terms for `$x`, in ascending powers of `$x` **/ #[macro_export] macro_rules! Horner_eval { ($x:expr, $c:expr, $($a:expr),*) => { { let mut y = $c; let mut u = 1.0; $( u *= $x; y += u * $a; )* y } } }
random_line_split
util.rs
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //! Some programming utilities /// Returns a float rounded upto a certain number of decimal digits #[inline] pub fn
(float: f64, decimal_digits: u32) -> f64 { let mut d = 1.0; for _ in 1..(decimal_digits + 1) { d *= 10.0; } (float * d).round() / d } /** Evaluates a polynomial using Horner's algorithm # Arguments * `$x` : The value of the independent variable `f32 or f64` * `$c` : The constant term `f32 or f64` * `$($a),*`: Sequence of coefficient terms for `$x`, in ascending powers of `$x` **/ #[macro_export] macro_rules! Horner_eval { ($x:expr, $c:expr, $($a:expr),*) => { { let mut y = $c; let mut u = 1.0; $( u *= $x; y += u * $a; )* y } } }
round_upto_digits
identifier_name
build.rs
// Copyright (C) 2017-2022 Niklas Fiekas <[email protected]> // // This program 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. // // This program 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 this program. If not, see <http://www.gnu.org/licenses/>. #![cfg_attr(feature = "step", feature(step_trait))] #![cfg_attr(docs_rs, feature(doc_cfg))] #![forbid(unsafe_op_in_unsafe_fn)] #![allow(dead_code)] use std::{env, fmt::LowerHex, fs::File, io, io::Write, path::Path}; mod bitboard; mod color; mod magics; mod role; mod square; mod types; mod util; use crate::{bitboard::Bitboard, magics::Magic, square::Square}; const ROOK_DELTAS: [i32; 4] = [8, 1, -8, -1]; const BISHOP_DELTAS: [i32; 4] = [9, 7, -9, -7]; const KING_DELTAS: [i32; 8] = [9, 8, 7, 1, -9, -8, -7, -1]; const KNIGHT_DELTAS: [i32; 8] = [17, 15, 10, 6, -17, -15, -10, -6]; const WHITE_PAWN_DELTAS: [i32; 2] = [7, 9]; const BLACK_PAWN_DELTAS: [i32; 2] = [-7, -9]; fn sliding_attacks(sq: Square, occupied: Bitboard, deltas: &[i32]) -> Bitboard { let mut attack = Bitboard(0); for delta in deltas { let mut previous = sq; while let Some(s) = previous.offset(*delta) { if s.distance(previous) > 2 { break; } attack.add(s); if occupied.contains(s)
previous = s; } } attack } fn sliding_bishop_attacks(sq: Square, occupied: Bitboard) -> Bitboard { sliding_attacks(sq, occupied, &BISHOP_DELTAS) } fn sliding_rook_attacks(sq: Square, occupied: Bitboard) -> Bitboard { sliding_attacks(sq, occupied, &ROOK_DELTAS) } fn step_attacks(sq: Square, deltas: &[i32]) -> Bitboard { sliding_attacks(sq, Bitboard::FULL, deltas) } fn init_magics(sq: Square, magic: &Magic, shift: u32, attacks: &mut [Bitboard], deltas: &[i32]) { for subset in Bitboard(magic.mask).carry_rippler() { let attack = sliding_attacks(sq, subset, deltas); let idx = (magic.factor.wrapping_mul(subset.0) >> (64 - shift)) as usize + magic.offset; assert!(attacks[idx].is_empty() || attacks[idx] == attack); attacks[idx] = attack; } } fn dump_slice<W: Write, T: LowerHex>( w: &mut W, name: &str, table_name: &str, slice: &[T], ) -> io::Result<()> { writeln!(w, "#[allow(clippy::unreadable_literal)]")?; write!(w, "static {}: [{}; {}] = [", name, table_name, slice.len())?; for v in slice { write!(w, "0x{:x}, ", v)?; } writeln!(w, "];") } fn dump_table<W: Write, T: LowerHex>( w: &mut W, name: &str, tname: &str, table: &[[T; 64]; 64], ) -> io::Result<()> { writeln!(w, "#[allow(clippy::unreadable_literal)]")?; write!(w, "static {}: [[{}; 64]; 64] = [", name, tname)?; for row in table { write!(w, "[")?; for column in row { write!(w, "0x{:x}, ", column)?; } write!(w, "], ")?; } writeln!(w, "];") } fn main() -> io::Result<()> { // generate attacks.rs let out_dir = env::var("OUT_DIR").expect("got OUT_DIR"); let attacks_path = Path::new(&out_dir).join("attacks.rs"); let mut f = File::create(&attacks_path).expect("created attacks.rs"); generate_basics(&mut f)?; generate_sliding_attacks(&mut f) } fn generate_basics<W: Write>(f: &mut W) -> io::Result<()> { let mut knight_attacks = [Bitboard(0); 64]; let mut king_attacks = [Bitboard(0); 64]; let mut white_pawn_attacks = [Bitboard(0); 64]; let mut black_pawn_attacks = [Bitboard(0); 64]; let mut bb_rays = [[Bitboard(0); 64]; 64]; for sq in Square::ALL { knight_attacks[usize::from(sq)] = step_attacks(sq, &KNIGHT_DELTAS); king_attacks[usize::from(sq)] = step_attacks(sq, &KING_DELTAS); white_pawn_attacks[usize::from(sq)] = step_attacks(sq, &WHITE_PAWN_DELTAS); black_pawn_attacks[usize::from(sq)] = step_attacks(sq, &BLACK_PAWN_DELTAS); } for a in Square::ALL { for b in sliding_bishop_attacks(a, Bitboard(0)) { bb_rays[usize::from(a)][usize::from(b)] = (sliding_bishop_attacks(a, Bitboard(0)) & sliding_bishop_attacks(b, Bitboard(0))) .with(a) .with(b); } for b in sliding_rook_attacks(a, Bitboard(0)) { bb_rays[usize::from(a)][usize::from(b)] = (sliding_rook_attacks(a, Bitboard(0)) & sliding_rook_attacks(b, Bitboard(0))) .with(a) .with(b); } } dump_slice(f, "KNIGHT_ATTACKS", "u64", &knight_attacks)?; dump_slice(f, "KING_ATTACKS", "u64", &king_attacks)?; dump_slice(f, "WHITE_PAWN_ATTACKS", "u64", &white_pawn_attacks)?; dump_slice(f, "BLACK_PAWN_ATTACKS", "u64", &black_pawn_attacks)?; writeln!(f)?; dump_table(f, "BB_RAYS", "u64", &bb_rays)?; writeln!(f) } fn generate_sliding_attacks<W: Write>(f: &mut W) -> io::Result<()> { let mut attacks = vec![Bitboard(0); 88772]; for sq in Square::ALL { init_magics( sq, &magics::ROOK_MAGICS[usize::from(sq)], 12, &mut attacks, &ROOK_DELTAS, ); init_magics( sq, &magics::BISHOP_MAGICS[usize::from(sq)], 9, &mut attacks, &BISHOP_DELTAS, ); } dump_slice(f, "ATTACKS", "u64", &attacks) }
{ break; }
conditional_block
build.rs
// Copyright (C) 2017-2022 Niklas Fiekas <[email protected]> // // This program 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. // // This program 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 this program. If not, see <http://www.gnu.org/licenses/>. #![cfg_attr(feature = "step", feature(step_trait))] #![cfg_attr(docs_rs, feature(doc_cfg))] #![forbid(unsafe_op_in_unsafe_fn)] #![allow(dead_code)] use std::{env, fmt::LowerHex, fs::File, io, io::Write, path::Path}; mod bitboard; mod color; mod magics; mod role; mod square; mod types; mod util; use crate::{bitboard::Bitboard, magics::Magic, square::Square}; const ROOK_DELTAS: [i32; 4] = [8, 1, -8, -1]; const BISHOP_DELTAS: [i32; 4] = [9, 7, -9, -7]; const KING_DELTAS: [i32; 8] = [9, 8, 7, 1, -9, -8, -7, -1]; const KNIGHT_DELTAS: [i32; 8] = [17, 15, 10, 6, -17, -15, -10, -6]; const WHITE_PAWN_DELTAS: [i32; 2] = [7, 9]; const BLACK_PAWN_DELTAS: [i32; 2] = [-7, -9]; fn sliding_attacks(sq: Square, occupied: Bitboard, deltas: &[i32]) -> Bitboard { let mut attack = Bitboard(0); for delta in deltas { let mut previous = sq; while let Some(s) = previous.offset(*delta) { if s.distance(previous) > 2 { break; } attack.add(s); if occupied.contains(s) { break; } previous = s; } } attack } fn sliding_bishop_attacks(sq: Square, occupied: Bitboard) -> Bitboard { sliding_attacks(sq, occupied, &BISHOP_DELTAS) } fn sliding_rook_attacks(sq: Square, occupied: Bitboard) -> Bitboard { sliding_attacks(sq, occupied, &ROOK_DELTAS) } fn step_attacks(sq: Square, deltas: &[i32]) -> Bitboard { sliding_attacks(sq, Bitboard::FULL, deltas) } fn init_magics(sq: Square, magic: &Magic, shift: u32, attacks: &mut [Bitboard], deltas: &[i32]) { for subset in Bitboard(magic.mask).carry_rippler() { let attack = sliding_attacks(sq, subset, deltas); let idx = (magic.factor.wrapping_mul(subset.0) >> (64 - shift)) as usize + magic.offset; assert!(attacks[idx].is_empty() || attacks[idx] == attack); attacks[idx] = attack; } } fn dump_slice<W: Write, T: LowerHex>( w: &mut W, name: &str, table_name: &str, slice: &[T], ) -> io::Result<()> { writeln!(w, "#[allow(clippy::unreadable_literal)]")?; write!(w, "static {}: [{}; {}] = [", name, table_name, slice.len())?; for v in slice { write!(w, "0x{:x}, ", v)?; } writeln!(w, "];") } fn dump_table<W: Write, T: LowerHex>( w: &mut W, name: &str, tname: &str, table: &[[T; 64]; 64], ) -> io::Result<()> { writeln!(w, "#[allow(clippy::unreadable_literal)]")?; write!(w, "static {}: [[{}; 64]; 64] = [", name, tname)?; for row in table { write!(w, "[")?; for column in row { write!(w, "0x{:x}, ", column)?; } write!(w, "], ")?; } writeln!(w, "];") } fn main() -> io::Result<()> { // generate attacks.rs let out_dir = env::var("OUT_DIR").expect("got OUT_DIR"); let attacks_path = Path::new(&out_dir).join("attacks.rs"); let mut f = File::create(&attacks_path).expect("created attacks.rs"); generate_basics(&mut f)?; generate_sliding_attacks(&mut f) } fn generate_basics<W: Write>(f: &mut W) -> io::Result<()> { let mut knight_attacks = [Bitboard(0); 64]; let mut king_attacks = [Bitboard(0); 64]; let mut white_pawn_attacks = [Bitboard(0); 64]; let mut black_pawn_attacks = [Bitboard(0); 64]; let mut bb_rays = [[Bitboard(0); 64]; 64]; for sq in Square::ALL { knight_attacks[usize::from(sq)] = step_attacks(sq, &KNIGHT_DELTAS); king_attacks[usize::from(sq)] = step_attacks(sq, &KING_DELTAS); white_pawn_attacks[usize::from(sq)] = step_attacks(sq, &WHITE_PAWN_DELTAS); black_pawn_attacks[usize::from(sq)] = step_attacks(sq, &BLACK_PAWN_DELTAS); }
.with(a) .with(b); } for b in sliding_rook_attacks(a, Bitboard(0)) { bb_rays[usize::from(a)][usize::from(b)] = (sliding_rook_attacks(a, Bitboard(0)) & sliding_rook_attacks(b, Bitboard(0))) .with(a) .with(b); } } dump_slice(f, "KNIGHT_ATTACKS", "u64", &knight_attacks)?; dump_slice(f, "KING_ATTACKS", "u64", &king_attacks)?; dump_slice(f, "WHITE_PAWN_ATTACKS", "u64", &white_pawn_attacks)?; dump_slice(f, "BLACK_PAWN_ATTACKS", "u64", &black_pawn_attacks)?; writeln!(f)?; dump_table(f, "BB_RAYS", "u64", &bb_rays)?; writeln!(f) } fn generate_sliding_attacks<W: Write>(f: &mut W) -> io::Result<()> { let mut attacks = vec![Bitboard(0); 88772]; for sq in Square::ALL { init_magics( sq, &magics::ROOK_MAGICS[usize::from(sq)], 12, &mut attacks, &ROOK_DELTAS, ); init_magics( sq, &magics::BISHOP_MAGICS[usize::from(sq)], 9, &mut attacks, &BISHOP_DELTAS, ); } dump_slice(f, "ATTACKS", "u64", &attacks) }
for a in Square::ALL { for b in sliding_bishop_attacks(a, Bitboard(0)) { bb_rays[usize::from(a)][usize::from(b)] = (sliding_bishop_attacks(a, Bitboard(0)) & sliding_bishop_attacks(b, Bitboard(0)))
random_line_split
build.rs
// Copyright (C) 2017-2022 Niklas Fiekas <[email protected]> // // This program 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. // // This program 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 this program. If not, see <http://www.gnu.org/licenses/>. #![cfg_attr(feature = "step", feature(step_trait))] #![cfg_attr(docs_rs, feature(doc_cfg))] #![forbid(unsafe_op_in_unsafe_fn)] #![allow(dead_code)] use std::{env, fmt::LowerHex, fs::File, io, io::Write, path::Path}; mod bitboard; mod color; mod magics; mod role; mod square; mod types; mod util; use crate::{bitboard::Bitboard, magics::Magic, square::Square}; const ROOK_DELTAS: [i32; 4] = [8, 1, -8, -1]; const BISHOP_DELTAS: [i32; 4] = [9, 7, -9, -7]; const KING_DELTAS: [i32; 8] = [9, 8, 7, 1, -9, -8, -7, -1]; const KNIGHT_DELTAS: [i32; 8] = [17, 15, 10, 6, -17, -15, -10, -6]; const WHITE_PAWN_DELTAS: [i32; 2] = [7, 9]; const BLACK_PAWN_DELTAS: [i32; 2] = [-7, -9]; fn sliding_attacks(sq: Square, occupied: Bitboard, deltas: &[i32]) -> Bitboard { let mut attack = Bitboard(0); for delta in deltas { let mut previous = sq; while let Some(s) = previous.offset(*delta) { if s.distance(previous) > 2 { break; } attack.add(s); if occupied.contains(s) { break; } previous = s; } } attack } fn sliding_bishop_attacks(sq: Square, occupied: Bitboard) -> Bitboard { sliding_attacks(sq, occupied, &BISHOP_DELTAS) } fn sliding_rook_attacks(sq: Square, occupied: Bitboard) -> Bitboard { sliding_attacks(sq, occupied, &ROOK_DELTAS) } fn step_attacks(sq: Square, deltas: &[i32]) -> Bitboard { sliding_attacks(sq, Bitboard::FULL, deltas) } fn init_magics(sq: Square, magic: &Magic, shift: u32, attacks: &mut [Bitboard], deltas: &[i32]) { for subset in Bitboard(magic.mask).carry_rippler() { let attack = sliding_attacks(sq, subset, deltas); let idx = (magic.factor.wrapping_mul(subset.0) >> (64 - shift)) as usize + magic.offset; assert!(attacks[idx].is_empty() || attacks[idx] == attack); attacks[idx] = attack; } } fn dump_slice<W: Write, T: LowerHex>( w: &mut W, name: &str, table_name: &str, slice: &[T], ) -> io::Result<()> { writeln!(w, "#[allow(clippy::unreadable_literal)]")?; write!(w, "static {}: [{}; {}] = [", name, table_name, slice.len())?; for v in slice { write!(w, "0x{:x}, ", v)?; } writeln!(w, "];") } fn dump_table<W: Write, T: LowerHex>( w: &mut W, name: &str, tname: &str, table: &[[T; 64]; 64], ) -> io::Result<()> { writeln!(w, "#[allow(clippy::unreadable_literal)]")?; write!(w, "static {}: [[{}; 64]; 64] = [", name, tname)?; for row in table { write!(w, "[")?; for column in row { write!(w, "0x{:x}, ", column)?; } write!(w, "], ")?; } writeln!(w, "];") } fn main() -> io::Result<()> { // generate attacks.rs let out_dir = env::var("OUT_DIR").expect("got OUT_DIR"); let attacks_path = Path::new(&out_dir).join("attacks.rs"); let mut f = File::create(&attacks_path).expect("created attacks.rs"); generate_basics(&mut f)?; generate_sliding_attacks(&mut f) } fn
<W: Write>(f: &mut W) -> io::Result<()> { let mut knight_attacks = [Bitboard(0); 64]; let mut king_attacks = [Bitboard(0); 64]; let mut white_pawn_attacks = [Bitboard(0); 64]; let mut black_pawn_attacks = [Bitboard(0); 64]; let mut bb_rays = [[Bitboard(0); 64]; 64]; for sq in Square::ALL { knight_attacks[usize::from(sq)] = step_attacks(sq, &KNIGHT_DELTAS); king_attacks[usize::from(sq)] = step_attacks(sq, &KING_DELTAS); white_pawn_attacks[usize::from(sq)] = step_attacks(sq, &WHITE_PAWN_DELTAS); black_pawn_attacks[usize::from(sq)] = step_attacks(sq, &BLACK_PAWN_DELTAS); } for a in Square::ALL { for b in sliding_bishop_attacks(a, Bitboard(0)) { bb_rays[usize::from(a)][usize::from(b)] = (sliding_bishop_attacks(a, Bitboard(0)) & sliding_bishop_attacks(b, Bitboard(0))) .with(a) .with(b); } for b in sliding_rook_attacks(a, Bitboard(0)) { bb_rays[usize::from(a)][usize::from(b)] = (sliding_rook_attacks(a, Bitboard(0)) & sliding_rook_attacks(b, Bitboard(0))) .with(a) .with(b); } } dump_slice(f, "KNIGHT_ATTACKS", "u64", &knight_attacks)?; dump_slice(f, "KING_ATTACKS", "u64", &king_attacks)?; dump_slice(f, "WHITE_PAWN_ATTACKS", "u64", &white_pawn_attacks)?; dump_slice(f, "BLACK_PAWN_ATTACKS", "u64", &black_pawn_attacks)?; writeln!(f)?; dump_table(f, "BB_RAYS", "u64", &bb_rays)?; writeln!(f) } fn generate_sliding_attacks<W: Write>(f: &mut W) -> io::Result<()> { let mut attacks = vec![Bitboard(0); 88772]; for sq in Square::ALL { init_magics( sq, &magics::ROOK_MAGICS[usize::from(sq)], 12, &mut attacks, &ROOK_DELTAS, ); init_magics( sq, &magics::BISHOP_MAGICS[usize::from(sq)], 9, &mut attacks, &BISHOP_DELTAS, ); } dump_slice(f, "ATTACKS", "u64", &attacks) }
generate_basics
identifier_name
build.rs
// Copyright (C) 2017-2022 Niklas Fiekas <[email protected]> // // This program 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. // // This program 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 this program. If not, see <http://www.gnu.org/licenses/>. #![cfg_attr(feature = "step", feature(step_trait))] #![cfg_attr(docs_rs, feature(doc_cfg))] #![forbid(unsafe_op_in_unsafe_fn)] #![allow(dead_code)] use std::{env, fmt::LowerHex, fs::File, io, io::Write, path::Path}; mod bitboard; mod color; mod magics; mod role; mod square; mod types; mod util; use crate::{bitboard::Bitboard, magics::Magic, square::Square}; const ROOK_DELTAS: [i32; 4] = [8, 1, -8, -1]; const BISHOP_DELTAS: [i32; 4] = [9, 7, -9, -7]; const KING_DELTAS: [i32; 8] = [9, 8, 7, 1, -9, -8, -7, -1]; const KNIGHT_DELTAS: [i32; 8] = [17, 15, 10, 6, -17, -15, -10, -6]; const WHITE_PAWN_DELTAS: [i32; 2] = [7, 9]; const BLACK_PAWN_DELTAS: [i32; 2] = [-7, -9]; fn sliding_attacks(sq: Square, occupied: Bitboard, deltas: &[i32]) -> Bitboard { let mut attack = Bitboard(0); for delta in deltas { let mut previous = sq; while let Some(s) = previous.offset(*delta) { if s.distance(previous) > 2 { break; } attack.add(s); if occupied.contains(s) { break; } previous = s; } } attack } fn sliding_bishop_attacks(sq: Square, occupied: Bitboard) -> Bitboard { sliding_attacks(sq, occupied, &BISHOP_DELTAS) } fn sliding_rook_attacks(sq: Square, occupied: Bitboard) -> Bitboard
fn step_attacks(sq: Square, deltas: &[i32]) -> Bitboard { sliding_attacks(sq, Bitboard::FULL, deltas) } fn init_magics(sq: Square, magic: &Magic, shift: u32, attacks: &mut [Bitboard], deltas: &[i32]) { for subset in Bitboard(magic.mask).carry_rippler() { let attack = sliding_attacks(sq, subset, deltas); let idx = (magic.factor.wrapping_mul(subset.0) >> (64 - shift)) as usize + magic.offset; assert!(attacks[idx].is_empty() || attacks[idx] == attack); attacks[idx] = attack; } } fn dump_slice<W: Write, T: LowerHex>( w: &mut W, name: &str, table_name: &str, slice: &[T], ) -> io::Result<()> { writeln!(w, "#[allow(clippy::unreadable_literal)]")?; write!(w, "static {}: [{}; {}] = [", name, table_name, slice.len())?; for v in slice { write!(w, "0x{:x}, ", v)?; } writeln!(w, "];") } fn dump_table<W: Write, T: LowerHex>( w: &mut W, name: &str, tname: &str, table: &[[T; 64]; 64], ) -> io::Result<()> { writeln!(w, "#[allow(clippy::unreadable_literal)]")?; write!(w, "static {}: [[{}; 64]; 64] = [", name, tname)?; for row in table { write!(w, "[")?; for column in row { write!(w, "0x{:x}, ", column)?; } write!(w, "], ")?; } writeln!(w, "];") } fn main() -> io::Result<()> { // generate attacks.rs let out_dir = env::var("OUT_DIR").expect("got OUT_DIR"); let attacks_path = Path::new(&out_dir).join("attacks.rs"); let mut f = File::create(&attacks_path).expect("created attacks.rs"); generate_basics(&mut f)?; generate_sliding_attacks(&mut f) } fn generate_basics<W: Write>(f: &mut W) -> io::Result<()> { let mut knight_attacks = [Bitboard(0); 64]; let mut king_attacks = [Bitboard(0); 64]; let mut white_pawn_attacks = [Bitboard(0); 64]; let mut black_pawn_attacks = [Bitboard(0); 64]; let mut bb_rays = [[Bitboard(0); 64]; 64]; for sq in Square::ALL { knight_attacks[usize::from(sq)] = step_attacks(sq, &KNIGHT_DELTAS); king_attacks[usize::from(sq)] = step_attacks(sq, &KING_DELTAS); white_pawn_attacks[usize::from(sq)] = step_attacks(sq, &WHITE_PAWN_DELTAS); black_pawn_attacks[usize::from(sq)] = step_attacks(sq, &BLACK_PAWN_DELTAS); } for a in Square::ALL { for b in sliding_bishop_attacks(a, Bitboard(0)) { bb_rays[usize::from(a)][usize::from(b)] = (sliding_bishop_attacks(a, Bitboard(0)) & sliding_bishop_attacks(b, Bitboard(0))) .with(a) .with(b); } for b in sliding_rook_attacks(a, Bitboard(0)) { bb_rays[usize::from(a)][usize::from(b)] = (sliding_rook_attacks(a, Bitboard(0)) & sliding_rook_attacks(b, Bitboard(0))) .with(a) .with(b); } } dump_slice(f, "KNIGHT_ATTACKS", "u64", &knight_attacks)?; dump_slice(f, "KING_ATTACKS", "u64", &king_attacks)?; dump_slice(f, "WHITE_PAWN_ATTACKS", "u64", &white_pawn_attacks)?; dump_slice(f, "BLACK_PAWN_ATTACKS", "u64", &black_pawn_attacks)?; writeln!(f)?; dump_table(f, "BB_RAYS", "u64", &bb_rays)?; writeln!(f) } fn generate_sliding_attacks<W: Write>(f: &mut W) -> io::Result<()> { let mut attacks = vec![Bitboard(0); 88772]; for sq in Square::ALL { init_magics( sq, &magics::ROOK_MAGICS[usize::from(sq)], 12, &mut attacks, &ROOK_DELTAS, ); init_magics( sq, &magics::BISHOP_MAGICS[usize::from(sq)], 9, &mut attacks, &BISHOP_DELTAS, ); } dump_slice(f, "ATTACKS", "u64", &attacks) }
{ sliding_attacks(sq, occupied, &ROOK_DELTAS) }
identifier_body
menu.rs
// Copyright 2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib_ffi; use glib::object::Cast; use glib::translate::*; use Menu; use IsA; use Widget; use std::boxed::Box as Box_; use libc::c_int; use std::ptr; pub trait GtkMenuExtManual:'static { fn popup<T: IsA<Widget>, U: IsA<Widget>, F: Fn(&Self, &mut i32, &mut i32) -> bool +'static>( &self, parent_menu_shell: Option<&T>, parent_menu_item: Option<&U>, f: F, button: u32, activate_time: u32); fn popup_easy(&self, button: u32, activate_time: u32); } impl<O: IsA<Menu>> GtkMenuExtManual for O { fn popup<T: IsA<Widget>, U: IsA<Widget>, F: FnOnce(&Self, &mut i32, &mut i32) -> bool +'static>( &self, parent_menu_shell: Option<&T>, parent_menu_item: Option<&U>, f: F, button: u32, activate_time: u32) { unsafe { let f: Box_<Option<F>> = Box_::new(Some(f)); ffi::gtk_menu_popup(self.as_ref().to_glib_none().0, parent_menu_shell.map(|p| p.as_ref()).to_glib_none().0, parent_menu_item.map(|p| p.as_ref()).to_glib_none().0, Some(position_callback::<Self, F>), Box_::into_raw(f) as *mut _, button, activate_time) } }
button, activate_time) } } } unsafe extern "C" fn position_callback<T, F: FnOnce(&T, &mut i32, &mut i32) -> bool +'static>(this: *mut ffi::GtkMenu, x: *mut c_int, y: *mut c_int, push_in: *mut glib_ffi::gboolean, f: glib_ffi::gpointer) where T: IsA<Menu> { let mut f: Box<Option<F>> = Box::from_raw(f as *mut _); let f = f.take().expect("No callback"); *push_in = f(&Menu::from_glib_none(this).unsafe_cast(), x.as_mut().unwrap(), y.as_mut().unwrap()).to_glib(); }
fn popup_easy(&self, button: u32, activate_time: u32) { unsafe { ffi::gtk_menu_popup(self.as_ref().to_glib_none().0, ptr::null_mut(), ptr::null_mut(), None, ptr::null_mut(),
random_line_split
menu.rs
// Copyright 2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib_ffi; use glib::object::Cast; use glib::translate::*; use Menu; use IsA; use Widget; use std::boxed::Box as Box_; use libc::c_int; use std::ptr; pub trait GtkMenuExtManual:'static { fn popup<T: IsA<Widget>, U: IsA<Widget>, F: Fn(&Self, &mut i32, &mut i32) -> bool +'static>( &self, parent_menu_shell: Option<&T>, parent_menu_item: Option<&U>, f: F, button: u32, activate_time: u32); fn popup_easy(&self, button: u32, activate_time: u32); } impl<O: IsA<Menu>> GtkMenuExtManual for O { fn popup<T: IsA<Widget>, U: IsA<Widget>, F: FnOnce(&Self, &mut i32, &mut i32) -> bool +'static>( &self, parent_menu_shell: Option<&T>, parent_menu_item: Option<&U>, f: F, button: u32, activate_time: u32) { unsafe { let f: Box_<Option<F>> = Box_::new(Some(f)); ffi::gtk_menu_popup(self.as_ref().to_glib_none().0, parent_menu_shell.map(|p| p.as_ref()).to_glib_none().0, parent_menu_item.map(|p| p.as_ref()).to_glib_none().0, Some(position_callback::<Self, F>), Box_::into_raw(f) as *mut _, button, activate_time) } } fn
(&self, button: u32, activate_time: u32) { unsafe { ffi::gtk_menu_popup(self.as_ref().to_glib_none().0, ptr::null_mut(), ptr::null_mut(), None, ptr::null_mut(), button, activate_time) } } } unsafe extern "C" fn position_callback<T, F: FnOnce(&T, &mut i32, &mut i32) -> bool +'static>(this: *mut ffi::GtkMenu, x: *mut c_int, y: *mut c_int, push_in: *mut glib_ffi::gboolean, f: glib_ffi::gpointer) where T: IsA<Menu> { let mut f: Box<Option<F>> = Box::from_raw(f as *mut _); let f = f.take().expect("No callback"); *push_in = f(&Menu::from_glib_none(this).unsafe_cast(), x.as_mut().unwrap(), y.as_mut().unwrap()).to_glib(); }
popup_easy
identifier_name
menu.rs
// Copyright 2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib_ffi; use glib::object::Cast; use glib::translate::*; use Menu; use IsA; use Widget; use std::boxed::Box as Box_; use libc::c_int; use std::ptr; pub trait GtkMenuExtManual:'static { fn popup<T: IsA<Widget>, U: IsA<Widget>, F: Fn(&Self, &mut i32, &mut i32) -> bool +'static>( &self, parent_menu_shell: Option<&T>, parent_menu_item: Option<&U>, f: F, button: u32, activate_time: u32); fn popup_easy(&self, button: u32, activate_time: u32); } impl<O: IsA<Menu>> GtkMenuExtManual for O { fn popup<T: IsA<Widget>, U: IsA<Widget>, F: FnOnce(&Self, &mut i32, &mut i32) -> bool +'static>( &self, parent_menu_shell: Option<&T>, parent_menu_item: Option<&U>, f: F, button: u32, activate_time: u32)
fn popup_easy(&self, button: u32, activate_time: u32) { unsafe { ffi::gtk_menu_popup(self.as_ref().to_glib_none().0, ptr::null_mut(), ptr::null_mut(), None, ptr::null_mut(), button, activate_time) } } } unsafe extern "C" fn position_callback<T, F: FnOnce(&T, &mut i32, &mut i32) -> bool +'static>(this: *mut ffi::GtkMenu, x: *mut c_int, y: *mut c_int, push_in: *mut glib_ffi::gboolean, f: glib_ffi::gpointer) where T: IsA<Menu> { let mut f: Box<Option<F>> = Box::from_raw(f as *mut _); let f = f.take().expect("No callback"); *push_in = f(&Menu::from_glib_none(this).unsafe_cast(), x.as_mut().unwrap(), y.as_mut().unwrap()).to_glib(); }
{ unsafe { let f: Box_<Option<F>> = Box_::new(Some(f)); ffi::gtk_menu_popup(self.as_ref().to_glib_none().0, parent_menu_shell.map(|p| p.as_ref()).to_glib_none().0, parent_menu_item.map(|p| p.as_ref()).to_glib_none().0, Some(position_callback::<Self, F>), Box_::into_raw(f) as *mut _, button, activate_time) } }
identifier_body
all.rs
use crate::rutil::fix_new_line::fix_new_line; use crate::rutil::print_tty::{print_tty, print_writer}; use crate::rutil::safe_string::SafeString; use std::io::{BufRead, Write}; #[cfg(target_family = "wasm")] mod wasm { use std::io::{self, BufRead}; /// Reads a password from the TTY pub fn read_password() -> std::io::Result<String> { let tty = std::fs::File::open("/dev/tty")?; let mut reader = io::BufReader::new(tty); read_password_from_fd_with_hidden_input(&mut reader) } /// Reads a password from a given file descriptor fn read_password_from_fd_with_hidden_input( reader: &mut impl BufRead, ) -> std::io::Result<String> { let mut password = super::SafeString::new(); reader.read_line(&mut password)?; super::fix_new_line(password.into_inner()) } } #[cfg(target_family = "unix")] mod unix { use libc::{c_int, tcsetattr, termios, ECHO, ECHONL, TCSANOW}; use std::io::{self, BufRead}; use std::mem; use std::os::unix::io::AsRawFd; struct HiddenInput { fd: i32, term_orig: termios, } impl HiddenInput { fn new(fd: i32) -> io::Result<HiddenInput> { // Make two copies of the terminal settings. The first one will be modified // and the second one will act as a backup for when we want to set the // terminal back to its original state. let mut term = safe_tcgetattr(fd)?; let term_orig = safe_tcgetattr(fd)?; // Hide the password. This is what makes this function useful. term.c_lflag &=!ECHO; // But don't hide the NL character when the user hits ENTER. term.c_lflag |= ECHONL; // Save the settings for now. io_result(unsafe { tcsetattr(fd, TCSANOW, &term) })?; Ok(HiddenInput { fd, term_orig }) } } impl Drop for HiddenInput { fn drop(&mut self) { // Set the the mode back to normal unsafe { tcsetattr(self.fd, TCSANOW, &self.term_orig); } } } /// Turns a C function return into an IO Result fn io_result(ret: c_int) -> std::io::Result<()>
fn safe_tcgetattr(fd: c_int) -> std::io::Result<termios> { let mut term = mem::MaybeUninit::<termios>::uninit(); io_result(unsafe { ::libc::tcgetattr(fd, term.as_mut_ptr()) })?; Ok(unsafe { term.assume_init() }) } /// Reads a password from the TTY pub fn read_password() -> std::io::Result<String> { let tty = std::fs::File::open("/dev/tty")?; let fd = tty.as_raw_fd(); let mut reader = io::BufReader::new(tty); read_password_from_fd_with_hidden_input(&mut reader, fd) } /// Reads a password from a given file descriptor fn read_password_from_fd_with_hidden_input( reader: &mut impl BufRead, fd: i32, ) -> std::io::Result<String> { let mut password = super::SafeString::new(); let hidden_input = HiddenInput::new(fd)?; reader.read_line(&mut password)?; std::mem::drop(hidden_input); super::fix_new_line(password.into_inner()) } } #[cfg(target_family = "windows")] mod windows { use std::io::{self, BufReader}; use std::io::{BufRead, StdinLock}; use std::os::windows::io::FromRawHandle; use winapi::shared::minwindef::LPDWORD; use winapi::um::consoleapi::{GetConsoleMode, SetConsoleMode}; use winapi::um::fileapi::{CreateFileA, GetFileType, OPEN_EXISTING}; use winapi::um::handleapi::INVALID_HANDLE_VALUE; use winapi::um::processenv::GetStdHandle; use winapi::um::winbase::{FILE_TYPE_PIPE, STD_INPUT_HANDLE}; use winapi::um::wincon::{ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT}; use winapi::um::winnt::{ FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE, HANDLE, }; struct HiddenInput { mode: u32, handle: HANDLE, } impl HiddenInput { fn new(handle: HANDLE) -> io::Result<HiddenInput> { let mut mode = 0; // Get the old mode so we can reset back to it when we are done if unsafe { GetConsoleMode(handle, &mut mode as LPDWORD) } == 0 { return Err(std::io::Error::last_os_error()); } // We want to be able to read line by line, and we still want backspace to work let new_mode_flags = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT; if unsafe { SetConsoleMode(handle, new_mode_flags) } == 0 { return Err(std::io::Error::last_os_error()); } Ok(HiddenInput { mode, handle }) } } impl Drop for HiddenInput { fn drop(&mut self) { // Set the the mode back to normal unsafe { SetConsoleMode(self.handle, self.mode); } } } /// Reads a password from the TTY pub fn read_password() -> std::io::Result<String> { let handle = unsafe { CreateFileA( b"CONIN$\x00".as_ptr() as *const i8, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, std::ptr::null_mut(), OPEN_EXISTING, 0, std::ptr::null_mut(), ) }; if handle == INVALID_HANDLE_VALUE { return Err(std::io::Error::last_os_error()); } let mut stream = BufReader::new(unsafe { std::fs::File::from_raw_handle(handle) }); read_password_from_handle_with_hidden_input(&mut stream, handle) } /// Reads a password from a given file handle fn read_password_from_handle_with_hidden_input( reader: &mut impl BufRead, handle: HANDLE, ) -> io::Result<String> { let mut password = super::SafeString::new(); let hidden_input = HiddenInput::new(handle)?; reader.read_line(&mut password)?; // Newline for windows which otherwise prints on the same line. println!(); std::mem::drop(hidden_input); super::fix_new_line(password.into_inner()) } } #[cfg(target_family = "wasm")] pub use wasm::read_password; #[cfg(target_family = "unix")] pub use unix::read_password; #[cfg(target_family = "windows")] pub use windows::read_password; /// Reads a password from anything that implements BufRead pub fn read_password_from_bufread(reader: &mut impl BufRead) -> std::io::Result<String> { let mut password = SafeString::new(); reader.read_line(&mut password)?; fix_new_line(password.into_inner()) } /// Prompts on the TTY and then reads a password from anything that implements BufRead pub fn prompt_password_from_bufread( reader: &mut impl BufRead, writer: &mut impl Write, prompt: impl ToString, ) -> std::io::Result<String> { print_writer(writer, prompt.to_string().as_str()) .and_then(|_| read_password_from_bufread(reader)) } /// Prompts on the TTY and then reads a password from stdin pub fn prompt_password(prompt: impl ToString) -> std::io::Result<String> { print_tty(prompt.to_string().as_str()).and_then(|_| read_password()) } #[cfg(test)] mod tests { use std::io::Cursor; fn mock_input_crlf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\r\nAnother mocked response.\r\n"[..]) } fn mock_input_lf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\nAnother mocked response.\n"[..]) } #[test] fn can_read_from_redirected_input_many_times() { let mut reader_crlf = mock_input_crlf(); let response = crate::rpassword::read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "A mocked response."); let response = crate::rpassword::read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "Another mocked response."); let mut reader_lf = mock_input_lf(); let response = crate::rpassword::read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "A mocked response."); let response = crate::rpassword::read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "Another mocked response."); } }
{ match ret { 0 => Ok(()), _ => Err(std::io::Error::last_os_error()), } }
identifier_body
all.rs
use crate::rutil::fix_new_line::fix_new_line; use crate::rutil::print_tty::{print_tty, print_writer}; use crate::rutil::safe_string::SafeString; use std::io::{BufRead, Write}; #[cfg(target_family = "wasm")] mod wasm { use std::io::{self, BufRead}; /// Reads a password from the TTY pub fn read_password() -> std::io::Result<String> { let tty = std::fs::File::open("/dev/tty")?; let mut reader = io::BufReader::new(tty); read_password_from_fd_with_hidden_input(&mut reader) } /// Reads a password from a given file descriptor fn read_password_from_fd_with_hidden_input( reader: &mut impl BufRead, ) -> std::io::Result<String> { let mut password = super::SafeString::new(); reader.read_line(&mut password)?; super::fix_new_line(password.into_inner()) } } #[cfg(target_family = "unix")] mod unix { use libc::{c_int, tcsetattr, termios, ECHO, ECHONL, TCSANOW}; use std::io::{self, BufRead}; use std::mem; use std::os::unix::io::AsRawFd; struct HiddenInput { fd: i32, term_orig: termios, } impl HiddenInput { fn new(fd: i32) -> io::Result<HiddenInput> { // Make two copies of the terminal settings. The first one will be modified // and the second one will act as a backup for when we want to set the // terminal back to its original state. let mut term = safe_tcgetattr(fd)?; let term_orig = safe_tcgetattr(fd)?; // Hide the password. This is what makes this function useful. term.c_lflag &=!ECHO; // But don't hide the NL character when the user hits ENTER. term.c_lflag |= ECHONL; // Save the settings for now. io_result(unsafe { tcsetattr(fd, TCSANOW, &term) })?; Ok(HiddenInput { fd, term_orig }) } } impl Drop for HiddenInput { fn drop(&mut self) { // Set the the mode back to normal unsafe { tcsetattr(self.fd, TCSANOW, &self.term_orig); } } } /// Turns a C function return into an IO Result fn io_result(ret: c_int) -> std::io::Result<()> { match ret { 0 => Ok(()), _ => Err(std::io::Error::last_os_error()), } } fn safe_tcgetattr(fd: c_int) -> std::io::Result<termios> { let mut term = mem::MaybeUninit::<termios>::uninit(); io_result(unsafe { ::libc::tcgetattr(fd, term.as_mut_ptr()) })?; Ok(unsafe { term.assume_init() }) } /// Reads a password from the TTY pub fn read_password() -> std::io::Result<String> { let tty = std::fs::File::open("/dev/tty")?; let fd = tty.as_raw_fd(); let mut reader = io::BufReader::new(tty); read_password_from_fd_with_hidden_input(&mut reader, fd) } /// Reads a password from a given file descriptor fn read_password_from_fd_with_hidden_input( reader: &mut impl BufRead, fd: i32, ) -> std::io::Result<String> { let mut password = super::SafeString::new(); let hidden_input = HiddenInput::new(fd)?; reader.read_line(&mut password)?; std::mem::drop(hidden_input); super::fix_new_line(password.into_inner()) } } #[cfg(target_family = "windows")] mod windows { use std::io::{self, BufReader}; use std::io::{BufRead, StdinLock}; use std::os::windows::io::FromRawHandle; use winapi::shared::minwindef::LPDWORD; use winapi::um::consoleapi::{GetConsoleMode, SetConsoleMode}; use winapi::um::fileapi::{CreateFileA, GetFileType, OPEN_EXISTING}; use winapi::um::handleapi::INVALID_HANDLE_VALUE; use winapi::um::processenv::GetStdHandle; use winapi::um::winbase::{FILE_TYPE_PIPE, STD_INPUT_HANDLE}; use winapi::um::wincon::{ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT}; use winapi::um::winnt::{ FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE, HANDLE, }; struct HiddenInput { mode: u32, handle: HANDLE, } impl HiddenInput { fn new(handle: HANDLE) -> io::Result<HiddenInput> { let mut mode = 0; // Get the old mode so we can reset back to it when we are done if unsafe { GetConsoleMode(handle, &mut mode as LPDWORD) } == 0 { return Err(std::io::Error::last_os_error()); } // We want to be able to read line by line, and we still want backspace to work let new_mode_flags = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT; if unsafe { SetConsoleMode(handle, new_mode_flags) } == 0 { return Err(std::io::Error::last_os_error()); } Ok(HiddenInput { mode, handle }) } } impl Drop for HiddenInput { fn drop(&mut self) { // Set the the mode back to normal unsafe { SetConsoleMode(self.handle, self.mode); } } } /// Reads a password from the TTY pub fn read_password() -> std::io::Result<String> { let handle = unsafe { CreateFileA( b"CONIN$\x00".as_ptr() as *const i8, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, std::ptr::null_mut(), OPEN_EXISTING, 0, std::ptr::null_mut(), ) }; if handle == INVALID_HANDLE_VALUE { return Err(std::io::Error::last_os_error()); } let mut stream = BufReader::new(unsafe { std::fs::File::from_raw_handle(handle) }); read_password_from_handle_with_hidden_input(&mut stream, handle) } /// Reads a password from a given file handle fn read_password_from_handle_with_hidden_input( reader: &mut impl BufRead, handle: HANDLE, ) -> io::Result<String> { let mut password = super::SafeString::new(); let hidden_input = HiddenInput::new(handle)?; reader.read_line(&mut password)?; // Newline for windows which otherwise prints on the same line. println!(); std::mem::drop(hidden_input); super::fix_new_line(password.into_inner()) } } #[cfg(target_family = "wasm")] pub use wasm::read_password; #[cfg(target_family = "unix")] pub use unix::read_password; #[cfg(target_family = "windows")] pub use windows::read_password; /// Reads a password from anything that implements BufRead pub fn read_password_from_bufread(reader: &mut impl BufRead) -> std::io::Result<String> { let mut password = SafeString::new(); reader.read_line(&mut password)?; fix_new_line(password.into_inner()) } /// Prompts on the TTY and then reads a password from anything that implements BufRead pub fn
( reader: &mut impl BufRead, writer: &mut impl Write, prompt: impl ToString, ) -> std::io::Result<String> { print_writer(writer, prompt.to_string().as_str()) .and_then(|_| read_password_from_bufread(reader)) } /// Prompts on the TTY and then reads a password from stdin pub fn prompt_password(prompt: impl ToString) -> std::io::Result<String> { print_tty(prompt.to_string().as_str()).and_then(|_| read_password()) } #[cfg(test)] mod tests { use std::io::Cursor; fn mock_input_crlf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\r\nAnother mocked response.\r\n"[..]) } fn mock_input_lf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\nAnother mocked response.\n"[..]) } #[test] fn can_read_from_redirected_input_many_times() { let mut reader_crlf = mock_input_crlf(); let response = crate::rpassword::read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "A mocked response."); let response = crate::rpassword::read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "Another mocked response."); let mut reader_lf = mock_input_lf(); let response = crate::rpassword::read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "A mocked response."); let response = crate::rpassword::read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "Another mocked response."); } }
prompt_password_from_bufread
identifier_name
all.rs
use crate::rutil::fix_new_line::fix_new_line; use crate::rutil::print_tty::{print_tty, print_writer}; use crate::rutil::safe_string::SafeString; use std::io::{BufRead, Write}; #[cfg(target_family = "wasm")] mod wasm { use std::io::{self, BufRead}; /// Reads a password from the TTY pub fn read_password() -> std::io::Result<String> { let tty = std::fs::File::open("/dev/tty")?; let mut reader = io::BufReader::new(tty); read_password_from_fd_with_hidden_input(&mut reader) } /// Reads a password from a given file descriptor fn read_password_from_fd_with_hidden_input( reader: &mut impl BufRead, ) -> std::io::Result<String> { let mut password = super::SafeString::new(); reader.read_line(&mut password)?; super::fix_new_line(password.into_inner()) } } #[cfg(target_family = "unix")] mod unix { use libc::{c_int, tcsetattr, termios, ECHO, ECHONL, TCSANOW}; use std::io::{self, BufRead}; use std::mem; use std::os::unix::io::AsRawFd; struct HiddenInput { fd: i32, term_orig: termios, } impl HiddenInput { fn new(fd: i32) -> io::Result<HiddenInput> { // Make two copies of the terminal settings. The first one will be modified // and the second one will act as a backup for when we want to set the // terminal back to its original state. let mut term = safe_tcgetattr(fd)?; let term_orig = safe_tcgetattr(fd)?; // Hide the password. This is what makes this function useful. term.c_lflag &=!ECHO; // But don't hide the NL character when the user hits ENTER. term.c_lflag |= ECHONL; // Save the settings for now. io_result(unsafe { tcsetattr(fd, TCSANOW, &term) })?; Ok(HiddenInput { fd, term_orig }) } } impl Drop for HiddenInput { fn drop(&mut self) { // Set the the mode back to normal unsafe { tcsetattr(self.fd, TCSANOW, &self.term_orig); } } } /// Turns a C function return into an IO Result fn io_result(ret: c_int) -> std::io::Result<()> { match ret { 0 => Ok(()), _ => Err(std::io::Error::last_os_error()), } } fn safe_tcgetattr(fd: c_int) -> std::io::Result<termios> { let mut term = mem::MaybeUninit::<termios>::uninit(); io_result(unsafe { ::libc::tcgetattr(fd, term.as_mut_ptr()) })?; Ok(unsafe { term.assume_init() }) } /// Reads a password from the TTY pub fn read_password() -> std::io::Result<String> { let tty = std::fs::File::open("/dev/tty")?; let fd = tty.as_raw_fd(); let mut reader = io::BufReader::new(tty); read_password_from_fd_with_hidden_input(&mut reader, fd) } /// Reads a password from a given file descriptor fn read_password_from_fd_with_hidden_input( reader: &mut impl BufRead, fd: i32, ) -> std::io::Result<String> { let mut password = super::SafeString::new(); let hidden_input = HiddenInput::new(fd)?;
reader.read_line(&mut password)?; std::mem::drop(hidden_input); super::fix_new_line(password.into_inner()) } } #[cfg(target_family = "windows")] mod windows { use std::io::{self, BufReader}; use std::io::{BufRead, StdinLock}; use std::os::windows::io::FromRawHandle; use winapi::shared::minwindef::LPDWORD; use winapi::um::consoleapi::{GetConsoleMode, SetConsoleMode}; use winapi::um::fileapi::{CreateFileA, GetFileType, OPEN_EXISTING}; use winapi::um::handleapi::INVALID_HANDLE_VALUE; use winapi::um::processenv::GetStdHandle; use winapi::um::winbase::{FILE_TYPE_PIPE, STD_INPUT_HANDLE}; use winapi::um::wincon::{ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT}; use winapi::um::winnt::{ FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE, HANDLE, }; struct HiddenInput { mode: u32, handle: HANDLE, } impl HiddenInput { fn new(handle: HANDLE) -> io::Result<HiddenInput> { let mut mode = 0; // Get the old mode so we can reset back to it when we are done if unsafe { GetConsoleMode(handle, &mut mode as LPDWORD) } == 0 { return Err(std::io::Error::last_os_error()); } // We want to be able to read line by line, and we still want backspace to work let new_mode_flags = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT; if unsafe { SetConsoleMode(handle, new_mode_flags) } == 0 { return Err(std::io::Error::last_os_error()); } Ok(HiddenInput { mode, handle }) } } impl Drop for HiddenInput { fn drop(&mut self) { // Set the the mode back to normal unsafe { SetConsoleMode(self.handle, self.mode); } } } /// Reads a password from the TTY pub fn read_password() -> std::io::Result<String> { let handle = unsafe { CreateFileA( b"CONIN$\x00".as_ptr() as *const i8, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, std::ptr::null_mut(), OPEN_EXISTING, 0, std::ptr::null_mut(), ) }; if handle == INVALID_HANDLE_VALUE { return Err(std::io::Error::last_os_error()); } let mut stream = BufReader::new(unsafe { std::fs::File::from_raw_handle(handle) }); read_password_from_handle_with_hidden_input(&mut stream, handle) } /// Reads a password from a given file handle fn read_password_from_handle_with_hidden_input( reader: &mut impl BufRead, handle: HANDLE, ) -> io::Result<String> { let mut password = super::SafeString::new(); let hidden_input = HiddenInput::new(handle)?; reader.read_line(&mut password)?; // Newline for windows which otherwise prints on the same line. println!(); std::mem::drop(hidden_input); super::fix_new_line(password.into_inner()) } } #[cfg(target_family = "wasm")] pub use wasm::read_password; #[cfg(target_family = "unix")] pub use unix::read_password; #[cfg(target_family = "windows")] pub use windows::read_password; /// Reads a password from anything that implements BufRead pub fn read_password_from_bufread(reader: &mut impl BufRead) -> std::io::Result<String> { let mut password = SafeString::new(); reader.read_line(&mut password)?; fix_new_line(password.into_inner()) } /// Prompts on the TTY and then reads a password from anything that implements BufRead pub fn prompt_password_from_bufread( reader: &mut impl BufRead, writer: &mut impl Write, prompt: impl ToString, ) -> std::io::Result<String> { print_writer(writer, prompt.to_string().as_str()) .and_then(|_| read_password_from_bufread(reader)) } /// Prompts on the TTY and then reads a password from stdin pub fn prompt_password(prompt: impl ToString) -> std::io::Result<String> { print_tty(prompt.to_string().as_str()).and_then(|_| read_password()) } #[cfg(test)] mod tests { use std::io::Cursor; fn mock_input_crlf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\r\nAnother mocked response.\r\n"[..]) } fn mock_input_lf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\nAnother mocked response.\n"[..]) } #[test] fn can_read_from_redirected_input_many_times() { let mut reader_crlf = mock_input_crlf(); let response = crate::rpassword::read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "A mocked response."); let response = crate::rpassword::read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "Another mocked response."); let mut reader_lf = mock_input_lf(); let response = crate::rpassword::read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "A mocked response."); let response = crate::rpassword::read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "Another mocked response."); } }
random_line_split
htmlareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLAreaElementBinding; use dom::bindings::codegen::Bindings::HTMLAreaElementBinding::HTMLAreaElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::str::DOMString; use dom::document::Document; use dom::domtokenlist::DOMTokenList; use dom::htmlelement::HTMLElement; use dom::node::Node;
use dom::virtualmethods::VirtualMethods; use std::default::Default; use string_cache::Atom; #[dom_struct] pub struct HTMLAreaElement { htmlelement: HTMLElement, rel_list: MutNullableHeap<JS<DOMTokenList>>, } impl HTMLAreaElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLAreaElement { HTMLAreaElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document), rel_list: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLAreaElement> { let element = HTMLAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap) } } impl VirtualMethods for HTMLAreaElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } } impl HTMLAreaElementMethods for HTMLAreaElement { // https://html.spec.whatwg.org/multipage/#dom-area-rellist fn RelList(&self) -> Root<DOMTokenList> { self.rel_list.or_init(|| { DOMTokenList::new(self.upcast(), &atom!("rel")) }) } }
random_line_split
htmlareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLAreaElementBinding; use dom::bindings::codegen::Bindings::HTMLAreaElementBinding::HTMLAreaElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::str::DOMString; use dom::document::Document; use dom::domtokenlist::DOMTokenList; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use std::default::Default; use string_cache::Atom; #[dom_struct] pub struct HTMLAreaElement { htmlelement: HTMLElement, rel_list: MutNullableHeap<JS<DOMTokenList>>, } impl HTMLAreaElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLAreaElement { HTMLAreaElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document), rel_list: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLAreaElement> { let element = HTMLAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap) } } impl VirtualMethods for HTMLAreaElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue
} impl HTMLAreaElementMethods for HTMLAreaElement { // https://html.spec.whatwg.org/multipage/#dom-area-rellist fn RelList(&self) -> Root<DOMTokenList> { self.rel_list.or_init(|| { DOMTokenList::new(self.upcast(), &atom!("rel")) }) } }
{ match name { &atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } }
identifier_body
htmlareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLAreaElementBinding; use dom::bindings::codegen::Bindings::HTMLAreaElementBinding::HTMLAreaElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::str::DOMString; use dom::document::Document; use dom::domtokenlist::DOMTokenList; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use std::default::Default; use string_cache::Atom; #[dom_struct] pub struct HTMLAreaElement { htmlelement: HTMLElement, rel_list: MutNullableHeap<JS<DOMTokenList>>, } impl HTMLAreaElement { fn
(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLAreaElement { HTMLAreaElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document), rel_list: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLAreaElement> { let element = HTMLAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap) } } impl VirtualMethods for HTMLAreaElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } } impl HTMLAreaElementMethods for HTMLAreaElement { // https://html.spec.whatwg.org/multipage/#dom-area-rellist fn RelList(&self) -> Root<DOMTokenList> { self.rel_list.or_init(|| { DOMTokenList::new(self.upcast(), &atom!("rel")) }) } }
new_inherited
identifier_name
mod.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Ethcore rpc v1. //! //! Compliant with ethereum rpc. #[macro_use] mod helpers; mod impls;
pub mod tests; pub mod types; pub use self::traits::{Web3, Eth, EthFilter, EthSigning, Net, Parity, ParityAccounts, ParitySet, ParitySigning, Signer, Personal, Traces, Rpc}; pub use self::impls::*; pub use self::helpers::{SigningQueue, SignerService, ConfirmationsQueue, NetworkSettings, block_import};
pub mod traits;
random_line_split
range.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Generating numbers between two others. // this is surprisingly complicated to be both generic & correct use core::prelude::*; use core::num::Bounded; use Rng; use distributions::{Sample, IndependentSample}; /// Sample values uniformly between two bounds. /// /// This gives a uniform distribution (assuming the RNG used to sample /// it is itself uniform & the `SampleRange` implementation for the /// given type is correct), even for edge cases like `low = 0u8`, /// `high = 170u8`, for which a naive modulo operation would return /// numbers less than 85 with double the probability to those greater /// than 85. /// /// Types should attempt to sample in `[low, high)`, i.e., not /// including `high`, but this may be very difficult. All the /// primitive integer types satisfy this property, and the float types /// normally satisfy it, but rounding may mean `high` can occur. /// /// # Example /// /// ```rust /// use std::rand::distributions::{IndependentSample, Range}; /// /// fn main() { /// let between = Range::new(10u, 10000u); /// let mut rng = std::rand::task_rng(); /// let mut sum = 0; /// for _ in range(0u, 1000) { /// sum += between.ind_sample(&mut rng); /// } /// println!("{}", sum); /// } /// ``` pub struct Range<X> { low: X, range: X, accept_zone: X } impl<X: SampleRange + PartialOrd> Range<X> { /// Create a new `Range` instance that samples uniformly from /// `[low, high)`. Fails if `low >= high`. pub fn new(low: X, high: X) -> Range<X> { assert!(low < high, "Range::new called with `low >= high`"); SampleRange::construct_range(low, high) } } impl<Sup: SampleRange> Sample<Sup> for Range<Sup> { #[inline] fn sample<R: Rng>(&mut self, rng: &mut R) -> Sup { self.ind_sample(rng) } } impl<Sup: SampleRange> IndependentSample<Sup> for Range<Sup> { fn ind_sample<R: Rng>(&self, rng: &mut R) -> Sup { SampleRange::sample_range(self, rng) } } /// The helper trait for types that have a sensible way to sample /// uniformly between two values. This should not be used directly, /// and is only to facilitate `Range`. pub trait SampleRange { /// Construct the `Range` object that `sample_range` /// requires. This should not ever be called directly, only via /// `Range::new`, which will check that `low < high`, so this /// function doesn't have to repeat the check. fn construct_range(low: Self, high: Self) -> Range<Self>; /// Sample a value from the given `Range` with the given `Rng` as /// a source of randomness. fn sample_range<R: Rng>(r: &Range<Self>, rng: &mut R) -> Self; } macro_rules! integer_impl { ($ty:ty, $unsigned:ty) => { impl SampleRange for $ty { // we play free and fast with unsigned vs signed here // (when $ty is signed), but that's fine, since the // contract of this macro is for $ty and $unsigned to be // "bit-equal", so casting between them is a no-op & a // bijection. fn construct_range(low: $ty, high: $ty) -> Range<$ty> { let range = high as $unsigned - low as $unsigned; let unsigned_max: $unsigned = Bounded::max_value(); // this is the largest number that fits into $unsigned // that `range` divides evenly, so, if we've sampled // `n` uniformly from this region, then `n % range` is // uniform in [0, range) let zone = unsigned_max - unsigned_max % range; Range { low: low, range: range as $ty, accept_zone: zone as $ty } } #[inline] fn sample_range<R: Rng>(r: &Range<$ty>, rng: &mut R) -> $ty { loop { // rejection sample let v = rng.gen::<$unsigned>(); // until we find something that fits into the // region which r.range evenly divides (this will // be uniformly distributed) if v < r.accept_zone as $unsigned { // and return it, with some adjustments return r.low + (v % r.range as $unsigned) as $ty; } } } } } } integer_impl! { i8, u8 } integer_impl! { i16, u16 } integer_impl! { i32, u32 } integer_impl! { i64, u64 } integer_impl! { int, uint } integer_impl! { u8, u8 } integer_impl! { u16, u16 } integer_impl! { u32, u32 } integer_impl! { u64, u64 } integer_impl! { uint, uint } macro_rules! float_impl { ($ty:ty) => { impl SampleRange for $ty { fn construct_range(low: $ty, high: $ty) -> Range<$ty> { Range { low: low, range: high - low, accept_zone: 0.0 // unused } } fn sample_range<R: Rng>(r: &Range<$ty>, rng: &mut R) -> $ty { r.low + r.range * rng.gen() } } } } float_impl! { f32 } float_impl! { f64 } #[cfg(test)] mod tests { use std::prelude::*; use distributions::{Sample, IndependentSample}; use super::Range; use std::num::Bounded; #[should_fail] #[test] fn
() { Range::new(10i, 10i); } #[should_fail] #[test] fn test_range_bad_limits_flipped() { Range::new(10i, 5i); } #[test] fn test_integers() { let mut rng = ::test::rng(); macro_rules! t ( ($($ty:ty),*) => {{ $( let v: &[($ty, $ty)] = [(0, 10), (10, 127), (Bounded::min_value(), Bounded::max_value())]; for &(low, high) in v.iter() { let mut sampler: Range<$ty> = Range::new(low, high); for _ in range(0u, 1000) { let v = sampler.sample(&mut rng); assert!(low <= v && v < high); let v = sampler.ind_sample(&mut rng); assert!(low <= v && v < high); } } )* }} ); t!(i8, i16, i32, i64, int, u8, u16, u32, u64, uint) } #[test] fn test_floats() { let mut rng = ::test::rng(); macro_rules! t ( ($($ty:ty),*) => {{ $( let v: &[($ty, $ty)] = [(0.0, 100.0), (-1e35, -1e25), (1e-35, 1e-25), (-1e35, 1e35)]; for &(low, high) in v.iter() { let mut sampler: Range<$ty> = Range::new(low, high); for _ in range(0u, 1000) { let v = sampler.sample(&mut rng); assert!(low <= v && v < high); let v = sampler.ind_sample(&mut rng); assert!(low <= v && v < high); } } )* }} ); t!(f32, f64) } }
test_range_bad_limits_equal
identifier_name
range.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Generating numbers between two others. // this is surprisingly complicated to be both generic & correct use core::prelude::*; use core::num::Bounded; use Rng; use distributions::{Sample, IndependentSample}; /// Sample values uniformly between two bounds.
/// `high = 170u8`, for which a naive modulo operation would return /// numbers less than 85 with double the probability to those greater /// than 85. /// /// Types should attempt to sample in `[low, high)`, i.e., not /// including `high`, but this may be very difficult. All the /// primitive integer types satisfy this property, and the float types /// normally satisfy it, but rounding may mean `high` can occur. /// /// # Example /// /// ```rust /// use std::rand::distributions::{IndependentSample, Range}; /// /// fn main() { /// let between = Range::new(10u, 10000u); /// let mut rng = std::rand::task_rng(); /// let mut sum = 0; /// for _ in range(0u, 1000) { /// sum += between.ind_sample(&mut rng); /// } /// println!("{}", sum); /// } /// ``` pub struct Range<X> { low: X, range: X, accept_zone: X } impl<X: SampleRange + PartialOrd> Range<X> { /// Create a new `Range` instance that samples uniformly from /// `[low, high)`. Fails if `low >= high`. pub fn new(low: X, high: X) -> Range<X> { assert!(low < high, "Range::new called with `low >= high`"); SampleRange::construct_range(low, high) } } impl<Sup: SampleRange> Sample<Sup> for Range<Sup> { #[inline] fn sample<R: Rng>(&mut self, rng: &mut R) -> Sup { self.ind_sample(rng) } } impl<Sup: SampleRange> IndependentSample<Sup> for Range<Sup> { fn ind_sample<R: Rng>(&self, rng: &mut R) -> Sup { SampleRange::sample_range(self, rng) } } /// The helper trait for types that have a sensible way to sample /// uniformly between two values. This should not be used directly, /// and is only to facilitate `Range`. pub trait SampleRange { /// Construct the `Range` object that `sample_range` /// requires. This should not ever be called directly, only via /// `Range::new`, which will check that `low < high`, so this /// function doesn't have to repeat the check. fn construct_range(low: Self, high: Self) -> Range<Self>; /// Sample a value from the given `Range` with the given `Rng` as /// a source of randomness. fn sample_range<R: Rng>(r: &Range<Self>, rng: &mut R) -> Self; } macro_rules! integer_impl { ($ty:ty, $unsigned:ty) => { impl SampleRange for $ty { // we play free and fast with unsigned vs signed here // (when $ty is signed), but that's fine, since the // contract of this macro is for $ty and $unsigned to be // "bit-equal", so casting between them is a no-op & a // bijection. fn construct_range(low: $ty, high: $ty) -> Range<$ty> { let range = high as $unsigned - low as $unsigned; let unsigned_max: $unsigned = Bounded::max_value(); // this is the largest number that fits into $unsigned // that `range` divides evenly, so, if we've sampled // `n` uniformly from this region, then `n % range` is // uniform in [0, range) let zone = unsigned_max - unsigned_max % range; Range { low: low, range: range as $ty, accept_zone: zone as $ty } } #[inline] fn sample_range<R: Rng>(r: &Range<$ty>, rng: &mut R) -> $ty { loop { // rejection sample let v = rng.gen::<$unsigned>(); // until we find something that fits into the // region which r.range evenly divides (this will // be uniformly distributed) if v < r.accept_zone as $unsigned { // and return it, with some adjustments return r.low + (v % r.range as $unsigned) as $ty; } } } } } } integer_impl! { i8, u8 } integer_impl! { i16, u16 } integer_impl! { i32, u32 } integer_impl! { i64, u64 } integer_impl! { int, uint } integer_impl! { u8, u8 } integer_impl! { u16, u16 } integer_impl! { u32, u32 } integer_impl! { u64, u64 } integer_impl! { uint, uint } macro_rules! float_impl { ($ty:ty) => { impl SampleRange for $ty { fn construct_range(low: $ty, high: $ty) -> Range<$ty> { Range { low: low, range: high - low, accept_zone: 0.0 // unused } } fn sample_range<R: Rng>(r: &Range<$ty>, rng: &mut R) -> $ty { r.low + r.range * rng.gen() } } } } float_impl! { f32 } float_impl! { f64 } #[cfg(test)] mod tests { use std::prelude::*; use distributions::{Sample, IndependentSample}; use super::Range; use std::num::Bounded; #[should_fail] #[test] fn test_range_bad_limits_equal() { Range::new(10i, 10i); } #[should_fail] #[test] fn test_range_bad_limits_flipped() { Range::new(10i, 5i); } #[test] fn test_integers() { let mut rng = ::test::rng(); macro_rules! t ( ($($ty:ty),*) => {{ $( let v: &[($ty, $ty)] = [(0, 10), (10, 127), (Bounded::min_value(), Bounded::max_value())]; for &(low, high) in v.iter() { let mut sampler: Range<$ty> = Range::new(low, high); for _ in range(0u, 1000) { let v = sampler.sample(&mut rng); assert!(low <= v && v < high); let v = sampler.ind_sample(&mut rng); assert!(low <= v && v < high); } } )* }} ); t!(i8, i16, i32, i64, int, u8, u16, u32, u64, uint) } #[test] fn test_floats() { let mut rng = ::test::rng(); macro_rules! t ( ($($ty:ty),*) => {{ $( let v: &[($ty, $ty)] = [(0.0, 100.0), (-1e35, -1e25), (1e-35, 1e-25), (-1e35, 1e35)]; for &(low, high) in v.iter() { let mut sampler: Range<$ty> = Range::new(low, high); for _ in range(0u, 1000) { let v = sampler.sample(&mut rng); assert!(low <= v && v < high); let v = sampler.ind_sample(&mut rng); assert!(low <= v && v < high); } } )* }} ); t!(f32, f64) } }
/// /// This gives a uniform distribution (assuming the RNG used to sample /// it is itself uniform & the `SampleRange` implementation for the /// given type is correct), even for edge cases like `low = 0u8`,
random_line_split
hyper_server.rs
use std::collections::HashMap; use std::io; use std::net::SocketAddr; use std::pin::Pin; use std::sync::{Arc, Mutex}; use futures::prelude::*; use futures::StreamExt; use futures::task::{Context, Poll}; use hyper::{Body, Error, Response, Server}; use hyper::http::header::{HeaderName, HeaderValue}; use hyper::http::response::Builder as ResponseBuilder; use hyper::service::make_service_fn; use hyper::service::service_fn; use log::*; use maplit::*; use rustls::ServerConfig; use serde_json::json; use tokio::net::{TcpListener, TcpStream}; use tokio_rustls::TlsAcceptor; use tokio_rustls::server::TlsStream; use pact_matching::models::{HttpPart, OptionalBody, Request, RequestResponsePact}; use pact_matching::models::generators::GeneratorTestMode; use pact_matching::models::parse_query_string; use crate::matching::{match_request, MatchResult}; use crate::mock_server::MockServer; #[derive(Debug, Clone)] enum InteractionError { RequestHeaderEncodingError, RequestBodyError, ResponseHeaderEncodingError, ResponseBodyError } fn extract_path(uri: &hyper::Uri) -> String { uri.path_and_query() .map(|path_and_query| path_and_query.path()) .unwrap_or("/") .into() } fn extract_query_string(uri: &hyper::Uri) -> Option<HashMap<String, Vec<String>>> { debug!("Extracting query from uri {:?}", uri); uri.path_and_query() .and_then(|path_and_query| { trace!("path_and_query -> {:?}", path_and_query); path_and_query.query() }) .and_then(|query| parse_query_string(query)) } fn extract_headers(headers: &hyper::HeaderMap) -> Result<Option<HashMap<String, Vec<String>>>, InteractionError> { if!headers.is_empty() { let result: Result<HashMap<String, Vec<String>>, InteractionError> = headers.keys() .map(|name| -> Result<(String, Vec<String>), InteractionError> { let values = headers.get_all(name); let parsed_vals: Vec<Result<String, InteractionError>> = values.iter() .map(|val| val.to_str() .map(|v| v.to_string()) .map_err(|err| { warn!("Failed to parse HTTP header value: {}", err); InteractionError::RequestHeaderEncodingError }) ).collect(); if parsed_vals.iter().find(|val| val.is_err()).is_some() { Err(InteractionError::RequestHeaderEncodingError) } else { Ok((name.as_str().into(), parsed_vals.iter().cloned() .map(|val| val.unwrap_or_default()) .flat_map(|val| val.split(",").map(|v| v.to_string()).collect::<Vec<String>>()) .map(|val| val.trim().to_string()) .collect())) } }) .collect(); result.map(|map| Some(map)) } else { Ok(None) } } fn extract_body(bytes: bytes::Bytes, request: &Request) -> OptionalBody { if bytes.len() > 0 { OptionalBody::Present(bytes, request.content_type()) } else { OptionalBody::Empty } } async fn hyper_request_to_pact_request(req: hyper::Request<Body>) -> Result<Request, InteractionError> { let method = req.method().to_string(); let path = extract_path(req.uri()); let query = extract_query_string(req.uri()); let headers = extract_headers(req.headers())?; let body_bytes = hyper::body::to_bytes(req.into_body()) .await .map_err(|_| InteractionError::RequestBodyError)?; let request = Request { method, path, query, headers, .. Request::default() }; Ok(Request { body: extract_body(body_bytes, &request), .. request.clone() }) } fn set_hyper_headers(builder: &mut ResponseBuilder, headers: &Option<HashMap<String, Vec<String>>>) -> Result<(), InteractionError> { let hyper_headers = builder.headers_mut().unwrap(); match headers { Some(header_map) => { for (k, v) in header_map { for val in v { // FIXME?: Headers are not sent in "raw" mode. // Names are converted to lower case and values are parsed. hyper_headers.append( HeaderName::from_bytes(k.as_bytes()) .map_err(|err| { error!("Invalid header name '{}' ({})", k, err); InteractionError::ResponseHeaderEncodingError })?, val.parse::<HeaderValue>() .map_err(|err| { error!("Invalid header value '{}': '{}' ({})", k, val, err); InteractionError::ResponseHeaderEncodingError })? ); } } }, _ => {} } Ok(()) } fn error_body(request: &Request, error: &String) -> String { let body = json!({ "error" : format!("{} : {:?}", error, request) }); body.to_string() } fn match_result_to_hyper_response( request: &Request, match_result: MatchResult, mock_server: Arc<Mutex<MockServer>> ) -> Result<Response<Body>, InteractionError> { let cors_preflight = { let ms = mock_server.lock().unwrap(); ms.config.cors_preflight }; match match_result { MatchResult::RequestMatch(ref interaction) => {
let ms = mock_server.lock().unwrap(); let context = hashmap!{ "mockServer" => json!({ "href": ms.url(), "port": ms.port }) }; debug!("Test context = {:?}", context); let response = pact_matching::generate_response(&interaction.response, &GeneratorTestMode::Consumer, &context); info!("Request matched, sending response {}", response); if response.has_text_body() { debug!(" body: '{}'", response.body.str_value()); } let mut builder = Response::builder() .status(response.status) .header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*") .header(hyper::header::ACCESS_CONTROL_ALLOW_HEADERS, "*") .header(hyper::header::ACCESS_CONTROL_ALLOW_METHODS, "GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH") .header(hyper::header::ACCESS_CONTROL_EXPOSE_HEADERS, "Location, Link"); set_hyper_headers(&mut builder, &response.headers)?; builder.body(match response.body { OptionalBody::Present(ref s, _) => Body::from(s.clone()), _ => Body::empty() }) .map_err(|_| InteractionError::ResponseBodyError) }, _ => { debug!("Request did not match: {}", match_result); if cors_preflight && request.method.to_uppercase() == "OPTIONS" { info!("Responding to CORS pre-flight request"); let origin = match request.headers.clone() { Some(ref h) => h.iter() .find(|kv| kv.0.to_lowercase() == "referer") .map(|kv| kv.1.clone().join(", ")).unwrap_or("*".to_string()), None => "*".to_string() }; let cors_headers = match request.headers.clone() { Some(ref h) => h.iter() .find(|kv| kv.0.to_lowercase() == "access-control-request-headers") .map(|kv| kv.1.clone().join(", ") + ", *").unwrap_or("*".to_string()), None => "*".to_string() }; Response::builder() .status(204) .header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, origin) .header(hyper::header::ACCESS_CONTROL_ALLOW_METHODS, "GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH") .header(hyper::header::ACCESS_CONTROL_ALLOW_HEADERS, cors_headers) .header(hyper::header::ACCESS_CONTROL_EXPOSE_HEADERS, "Location, Link") .body(Body::empty()) .map_err(|_| InteractionError::ResponseBodyError) } else { Response::builder() .status(500) .header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*") .header(hyper::header::CONTENT_TYPE, "application/json; charset=utf-8") .header("X-Pact", match_result.match_key()) .body(Body::from(error_body(&request, &match_result.match_key()))) .map_err(|_| InteractionError::ResponseBodyError) } } } } async fn handle_request( req: hyper::Request<Body>, pact: Arc<RequestResponsePact>, matches: Arc<Mutex<Vec<MatchResult>>>, mock_server: Arc<Mutex<MockServer>> ) -> Result<Response<Body>, InteractionError> { debug!("Creating pact request from hyper request"); let pact_request = hyper_request_to_pact_request(req).await?; info!("Received request {}", pact_request); if pact_request.has_text_body() { debug!(" body: '{}'", pact_request.body.str_value()); } let match_result = match_request(&pact_request, &pact.interactions); matches.lock().unwrap().push(match_result.clone()); match_result_to_hyper_response(&pact_request, match_result, mock_server) } // TODO: Should instead use some form of X-Pact headers fn handle_mock_request_error(result: Result<Response<Body>, InteractionError>) -> Result<Response<Body>, Error> { match result { Ok(response) => Ok(response), Err(error) => { let response = match error { InteractionError::RequestHeaderEncodingError => Response::builder() .status(400) .body(Body::from("Found an invalid header encoding")), InteractionError::RequestBodyError => Response::builder() .status(500) .body(Body::from("Could not process request body")), InteractionError::ResponseBodyError => Response::builder() .status(500) .body(Body::from("Could not process response body")), InteractionError::ResponseHeaderEncodingError => Response::builder() .status(500) .body(Body::from("Could not set response header")) }; Ok(response.unwrap()) } } } // Create and bind the server, but do not start it. // Returns a future that drives the server. // The reason that the function itself is still async (even if it performs // no async operations) is that it needs a tokio context to be able to call try_bind. pub(crate) async fn create_and_bind( pact: RequestResponsePact, addr: SocketAddr, shutdown: impl std::future::Future<Output = ()>, matches: Arc<Mutex<Vec<MatchResult>>>, mock_server: Arc<Mutex<MockServer>> ) -> Result<(impl std::future::Future<Output = ()>, SocketAddr), hyper::Error> { let pact = Arc::new(pact); let server = Server::try_bind(&addr)? .serve(make_service_fn(move |_| { let pact = pact.clone(); let matches = matches.clone(); let mock_server = mock_server.clone(); async { Ok::<_, hyper::Error>( service_fn(move |req| { let pact = pact.clone(); let matches = matches.clone(); let mock_server = mock_server.clone(); async { handle_mock_request_error( handle_request(req, pact, matches, mock_server).await ) } }) ) } })); let socket_addr = server.local_addr(); Ok(( // This is the future that drives the server: async { let _ = server .with_graceful_shutdown(shutdown) .await; }, socket_addr )) } // Taken from https://github.com/ctz/hyper-rustls/blob/master/examples/server.rs struct HyperAcceptor { stream: Pin<Box<dyn Stream<Item = Result<TlsStream<TcpStream>, io::Error>> + Send>> } impl hyper::server::accept::Accept for HyperAcceptor { type Conn = TlsStream<TcpStream>; type Error = io::Error; fn poll_accept( mut self: Pin<&mut Self>, cx: &mut Context, ) -> Poll<Option<Result<Self::Conn, Self::Error>>> { self.as_mut().stream.poll_next_unpin(cx) } } pub(crate) async fn create_and_bind_tls( pact: RequestResponsePact, addr: SocketAddr, shutdown: impl std::future::Future<Output = ()>, matches: Arc<Mutex<Vec<MatchResult>>>, tls_cfg: ServerConfig, mock_server: Arc<Mutex<MockServer>> ) -> Result<(impl std::future::Future<Output = ()>, SocketAddr), io::Error> { let pact = Arc::new(pact); let tcp = TcpListener::bind(&addr).await?; let socket_addr = tcp.local_addr()?; let tls_acceptor = Arc::new(TlsAcceptor::from(Arc::new(tls_cfg))); let tls_stream = stream::unfold((Arc::new(tcp), tls_acceptor.clone()), |(listener, acceptor)| { async move { let (socket, _) = listener.accept().await.map_err(|err| { error!("Failed to accept TLS connection - {:?}", err); err }).ok()?; let stream = acceptor.accept(socket); Some((stream.await, (listener.clone(), acceptor.clone()))) } }); let server = Server::builder(HyperAcceptor { stream: tls_stream.boxed() }) .serve(make_service_fn(move |_| { let pact = pact.clone(); let matches = matches.clone(); let mock_server = mock_server.clone(); async { Ok::<_, hyper::Error>( service_fn(move |req| { let pact = pact.clone(); let matches = matches.clone(); let mock_server = mock_server.clone(); async { handle_mock_request_error( handle_request(req, pact, matches, mock_server).await ) } }) ) } })); Ok(( // This is the future that drives the server: async { let _ = server .with_graceful_shutdown(shutdown) .await; }, socket_addr )) } #[cfg(test)] mod tests { use expectest::expect; use expectest::prelude::*; use hyper::header::{ACCEPT, CONTENT_TYPE, USER_AGENT}; use hyper::HeaderMap; use super::*; #[tokio::test] async fn can_fetch_results_on_current_thread() { let (shutdown_tx, shutdown_rx) = futures::channel::oneshot::channel(); let matches = Arc::new(Mutex::new(vec![])); let (future, _) = create_and_bind( RequestResponsePact::default(), ([0, 0, 0, 0], 0 as u16).into(), async { shutdown_rx.await.ok(); }, matches.clone(), Arc::new(Mutex::new(MockServer::default())) ).await.unwrap(); let join_handle = tokio::task::spawn(future); shutdown_tx.send(()).unwrap(); // Server has shut down, now flush the server future from runtime join_handle.await.unwrap(); // 0 matches have been produced let all_matches = matches.lock().unwrap().clone(); assert_eq!(all_matches, vec![]); } #[test] fn handle_hyper_headers_with_multiple_values() { let mut headers = HeaderMap::new(); headers.append(ACCEPT, "application/xml, application/json".parse().unwrap()); headers.append(USER_AGENT, "test".parse().unwrap()); headers.append(USER_AGENT, "test2".parse().unwrap()); headers.append(CONTENT_TYPE, "text/plain".parse().unwrap()); let result = extract_headers(&headers); expect!(result).to(be_ok().value(Some(hashmap! { "accept".to_string() => vec!["application/xml".to_string(), "application/json".to_string()], "user-agent".to_string() => vec!["test".to_string(), "test2".to_string()], "content-type".to_string() => vec!["text/plain".to_string()] }))); } }
random_line_split
hyper_server.rs
use std::collections::HashMap; use std::io; use std::net::SocketAddr; use std::pin::Pin; use std::sync::{Arc, Mutex}; use futures::prelude::*; use futures::StreamExt; use futures::task::{Context, Poll}; use hyper::{Body, Error, Response, Server}; use hyper::http::header::{HeaderName, HeaderValue}; use hyper::http::response::Builder as ResponseBuilder; use hyper::service::make_service_fn; use hyper::service::service_fn; use log::*; use maplit::*; use rustls::ServerConfig; use serde_json::json; use tokio::net::{TcpListener, TcpStream}; use tokio_rustls::TlsAcceptor; use tokio_rustls::server::TlsStream; use pact_matching::models::{HttpPart, OptionalBody, Request, RequestResponsePact}; use pact_matching::models::generators::GeneratorTestMode; use pact_matching::models::parse_query_string; use crate::matching::{match_request, MatchResult}; use crate::mock_server::MockServer; #[derive(Debug, Clone)] enum InteractionError { RequestHeaderEncodingError, RequestBodyError, ResponseHeaderEncodingError, ResponseBodyError } fn extract_path(uri: &hyper::Uri) -> String { uri.path_and_query() .map(|path_and_query| path_and_query.path()) .unwrap_or("/") .into() } fn extract_query_string(uri: &hyper::Uri) -> Option<HashMap<String, Vec<String>>> { debug!("Extracting query from uri {:?}", uri); uri.path_and_query() .and_then(|path_and_query| { trace!("path_and_query -> {:?}", path_and_query); path_and_query.query() }) .and_then(|query| parse_query_string(query)) } fn extract_headers(headers: &hyper::HeaderMap) -> Result<Option<HashMap<String, Vec<String>>>, InteractionError> { if!headers.is_empty() { let result: Result<HashMap<String, Vec<String>>, InteractionError> = headers.keys() .map(|name| -> Result<(String, Vec<String>), InteractionError> { let values = headers.get_all(name); let parsed_vals: Vec<Result<String, InteractionError>> = values.iter() .map(|val| val.to_str() .map(|v| v.to_string()) .map_err(|err| { warn!("Failed to parse HTTP header value: {}", err); InteractionError::RequestHeaderEncodingError }) ).collect(); if parsed_vals.iter().find(|val| val.is_err()).is_some() { Err(InteractionError::RequestHeaderEncodingError) } else { Ok((name.as_str().into(), parsed_vals.iter().cloned() .map(|val| val.unwrap_or_default()) .flat_map(|val| val.split(",").map(|v| v.to_string()).collect::<Vec<String>>()) .map(|val| val.trim().to_string()) .collect())) } }) .collect(); result.map(|map| Some(map)) } else { Ok(None) } } fn extract_body(bytes: bytes::Bytes, request: &Request) -> OptionalBody { if bytes.len() > 0 { OptionalBody::Present(bytes, request.content_type()) } else { OptionalBody::Empty } } async fn hyper_request_to_pact_request(req: hyper::Request<Body>) -> Result<Request, InteractionError> { let method = req.method().to_string(); let path = extract_path(req.uri()); let query = extract_query_string(req.uri()); let headers = extract_headers(req.headers())?; let body_bytes = hyper::body::to_bytes(req.into_body()) .await .map_err(|_| InteractionError::RequestBodyError)?; let request = Request { method, path, query, headers, .. Request::default() }; Ok(Request { body: extract_body(body_bytes, &request), .. request.clone() }) } fn set_hyper_headers(builder: &mut ResponseBuilder, headers: &Option<HashMap<String, Vec<String>>>) -> Result<(), InteractionError> { let hyper_headers = builder.headers_mut().unwrap(); match headers { Some(header_map) => { for (k, v) in header_map { for val in v { // FIXME?: Headers are not sent in "raw" mode. // Names are converted to lower case and values are parsed. hyper_headers.append( HeaderName::from_bytes(k.as_bytes()) .map_err(|err| { error!("Invalid header name '{}' ({})", k, err); InteractionError::ResponseHeaderEncodingError })?, val.parse::<HeaderValue>() .map_err(|err| { error!("Invalid header value '{}': '{}' ({})", k, val, err); InteractionError::ResponseHeaderEncodingError })? ); } } }, _ => {} } Ok(()) } fn error_body(request: &Request, error: &String) -> String { let body = json!({ "error" : format!("{} : {:?}", error, request) }); body.to_string() } fn
( request: &Request, match_result: MatchResult, mock_server: Arc<Mutex<MockServer>> ) -> Result<Response<Body>, InteractionError> { let cors_preflight = { let ms = mock_server.lock().unwrap(); ms.config.cors_preflight }; match match_result { MatchResult::RequestMatch(ref interaction) => { let ms = mock_server.lock().unwrap(); let context = hashmap!{ "mockServer" => json!({ "href": ms.url(), "port": ms.port }) }; debug!("Test context = {:?}", context); let response = pact_matching::generate_response(&interaction.response, &GeneratorTestMode::Consumer, &context); info!("Request matched, sending response {}", response); if response.has_text_body() { debug!(" body: '{}'", response.body.str_value()); } let mut builder = Response::builder() .status(response.status) .header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*") .header(hyper::header::ACCESS_CONTROL_ALLOW_HEADERS, "*") .header(hyper::header::ACCESS_CONTROL_ALLOW_METHODS, "GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH") .header(hyper::header::ACCESS_CONTROL_EXPOSE_HEADERS, "Location, Link"); set_hyper_headers(&mut builder, &response.headers)?; builder.body(match response.body { OptionalBody::Present(ref s, _) => Body::from(s.clone()), _ => Body::empty() }) .map_err(|_| InteractionError::ResponseBodyError) }, _ => { debug!("Request did not match: {}", match_result); if cors_preflight && request.method.to_uppercase() == "OPTIONS" { info!("Responding to CORS pre-flight request"); let origin = match request.headers.clone() { Some(ref h) => h.iter() .find(|kv| kv.0.to_lowercase() == "referer") .map(|kv| kv.1.clone().join(", ")).unwrap_or("*".to_string()), None => "*".to_string() }; let cors_headers = match request.headers.clone() { Some(ref h) => h.iter() .find(|kv| kv.0.to_lowercase() == "access-control-request-headers") .map(|kv| kv.1.clone().join(", ") + ", *").unwrap_or("*".to_string()), None => "*".to_string() }; Response::builder() .status(204) .header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, origin) .header(hyper::header::ACCESS_CONTROL_ALLOW_METHODS, "GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH") .header(hyper::header::ACCESS_CONTROL_ALLOW_HEADERS, cors_headers) .header(hyper::header::ACCESS_CONTROL_EXPOSE_HEADERS, "Location, Link") .body(Body::empty()) .map_err(|_| InteractionError::ResponseBodyError) } else { Response::builder() .status(500) .header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*") .header(hyper::header::CONTENT_TYPE, "application/json; charset=utf-8") .header("X-Pact", match_result.match_key()) .body(Body::from(error_body(&request, &match_result.match_key()))) .map_err(|_| InteractionError::ResponseBodyError) } } } } async fn handle_request( req: hyper::Request<Body>, pact: Arc<RequestResponsePact>, matches: Arc<Mutex<Vec<MatchResult>>>, mock_server: Arc<Mutex<MockServer>> ) -> Result<Response<Body>, InteractionError> { debug!("Creating pact request from hyper request"); let pact_request = hyper_request_to_pact_request(req).await?; info!("Received request {}", pact_request); if pact_request.has_text_body() { debug!(" body: '{}'", pact_request.body.str_value()); } let match_result = match_request(&pact_request, &pact.interactions); matches.lock().unwrap().push(match_result.clone()); match_result_to_hyper_response(&pact_request, match_result, mock_server) } // TODO: Should instead use some form of X-Pact headers fn handle_mock_request_error(result: Result<Response<Body>, InteractionError>) -> Result<Response<Body>, Error> { match result { Ok(response) => Ok(response), Err(error) => { let response = match error { InteractionError::RequestHeaderEncodingError => Response::builder() .status(400) .body(Body::from("Found an invalid header encoding")), InteractionError::RequestBodyError => Response::builder() .status(500) .body(Body::from("Could not process request body")), InteractionError::ResponseBodyError => Response::builder() .status(500) .body(Body::from("Could not process response body")), InteractionError::ResponseHeaderEncodingError => Response::builder() .status(500) .body(Body::from("Could not set response header")) }; Ok(response.unwrap()) } } } // Create and bind the server, but do not start it. // Returns a future that drives the server. // The reason that the function itself is still async (even if it performs // no async operations) is that it needs a tokio context to be able to call try_bind. pub(crate) async fn create_and_bind( pact: RequestResponsePact, addr: SocketAddr, shutdown: impl std::future::Future<Output = ()>, matches: Arc<Mutex<Vec<MatchResult>>>, mock_server: Arc<Mutex<MockServer>> ) -> Result<(impl std::future::Future<Output = ()>, SocketAddr), hyper::Error> { let pact = Arc::new(pact); let server = Server::try_bind(&addr)? .serve(make_service_fn(move |_| { let pact = pact.clone(); let matches = matches.clone(); let mock_server = mock_server.clone(); async { Ok::<_, hyper::Error>( service_fn(move |req| { let pact = pact.clone(); let matches = matches.clone(); let mock_server = mock_server.clone(); async { handle_mock_request_error( handle_request(req, pact, matches, mock_server).await ) } }) ) } })); let socket_addr = server.local_addr(); Ok(( // This is the future that drives the server: async { let _ = server .with_graceful_shutdown(shutdown) .await; }, socket_addr )) } // Taken from https://github.com/ctz/hyper-rustls/blob/master/examples/server.rs struct HyperAcceptor { stream: Pin<Box<dyn Stream<Item = Result<TlsStream<TcpStream>, io::Error>> + Send>> } impl hyper::server::accept::Accept for HyperAcceptor { type Conn = TlsStream<TcpStream>; type Error = io::Error; fn poll_accept( mut self: Pin<&mut Self>, cx: &mut Context, ) -> Poll<Option<Result<Self::Conn, Self::Error>>> { self.as_mut().stream.poll_next_unpin(cx) } } pub(crate) async fn create_and_bind_tls( pact: RequestResponsePact, addr: SocketAddr, shutdown: impl std::future::Future<Output = ()>, matches: Arc<Mutex<Vec<MatchResult>>>, tls_cfg: ServerConfig, mock_server: Arc<Mutex<MockServer>> ) -> Result<(impl std::future::Future<Output = ()>, SocketAddr), io::Error> { let pact = Arc::new(pact); let tcp = TcpListener::bind(&addr).await?; let socket_addr = tcp.local_addr()?; let tls_acceptor = Arc::new(TlsAcceptor::from(Arc::new(tls_cfg))); let tls_stream = stream::unfold((Arc::new(tcp), tls_acceptor.clone()), |(listener, acceptor)| { async move { let (socket, _) = listener.accept().await.map_err(|err| { error!("Failed to accept TLS connection - {:?}", err); err }).ok()?; let stream = acceptor.accept(socket); Some((stream.await, (listener.clone(), acceptor.clone()))) } }); let server = Server::builder(HyperAcceptor { stream: tls_stream.boxed() }) .serve(make_service_fn(move |_| { let pact = pact.clone(); let matches = matches.clone(); let mock_server = mock_server.clone(); async { Ok::<_, hyper::Error>( service_fn(move |req| { let pact = pact.clone(); let matches = matches.clone(); let mock_server = mock_server.clone(); async { handle_mock_request_error( handle_request(req, pact, matches, mock_server).await ) } }) ) } })); Ok(( // This is the future that drives the server: async { let _ = server .with_graceful_shutdown(shutdown) .await; }, socket_addr )) } #[cfg(test)] mod tests { use expectest::expect; use expectest::prelude::*; use hyper::header::{ACCEPT, CONTENT_TYPE, USER_AGENT}; use hyper::HeaderMap; use super::*; #[tokio::test] async fn can_fetch_results_on_current_thread() { let (shutdown_tx, shutdown_rx) = futures::channel::oneshot::channel(); let matches = Arc::new(Mutex::new(vec![])); let (future, _) = create_and_bind( RequestResponsePact::default(), ([0, 0, 0, 0], 0 as u16).into(), async { shutdown_rx.await.ok(); }, matches.clone(), Arc::new(Mutex::new(MockServer::default())) ).await.unwrap(); let join_handle = tokio::task::spawn(future); shutdown_tx.send(()).unwrap(); // Server has shut down, now flush the server future from runtime join_handle.await.unwrap(); // 0 matches have been produced let all_matches = matches.lock().unwrap().clone(); assert_eq!(all_matches, vec![]); } #[test] fn handle_hyper_headers_with_multiple_values() { let mut headers = HeaderMap::new(); headers.append(ACCEPT, "application/xml, application/json".parse().unwrap()); headers.append(USER_AGENT, "test".parse().unwrap()); headers.append(USER_AGENT, "test2".parse().unwrap()); headers.append(CONTENT_TYPE, "text/plain".parse().unwrap()); let result = extract_headers(&headers); expect!(result).to(be_ok().value(Some(hashmap! { "accept".to_string() => vec!["application/xml".to_string(), "application/json".to_string()], "user-agent".to_string() => vec!["test".to_string(), "test2".to_string()], "content-type".to_string() => vec!["text/plain".to_string()] }))); } }
match_result_to_hyper_response
identifier_name
hyper_server.rs
use std::collections::HashMap; use std::io; use std::net::SocketAddr; use std::pin::Pin; use std::sync::{Arc, Mutex}; use futures::prelude::*; use futures::StreamExt; use futures::task::{Context, Poll}; use hyper::{Body, Error, Response, Server}; use hyper::http::header::{HeaderName, HeaderValue}; use hyper::http::response::Builder as ResponseBuilder; use hyper::service::make_service_fn; use hyper::service::service_fn; use log::*; use maplit::*; use rustls::ServerConfig; use serde_json::json; use tokio::net::{TcpListener, TcpStream}; use tokio_rustls::TlsAcceptor; use tokio_rustls::server::TlsStream; use pact_matching::models::{HttpPart, OptionalBody, Request, RequestResponsePact}; use pact_matching::models::generators::GeneratorTestMode; use pact_matching::models::parse_query_string; use crate::matching::{match_request, MatchResult}; use crate::mock_server::MockServer; #[derive(Debug, Clone)] enum InteractionError { RequestHeaderEncodingError, RequestBodyError, ResponseHeaderEncodingError, ResponseBodyError } fn extract_path(uri: &hyper::Uri) -> String { uri.path_and_query() .map(|path_and_query| path_and_query.path()) .unwrap_or("/") .into() } fn extract_query_string(uri: &hyper::Uri) -> Option<HashMap<String, Vec<String>>> { debug!("Extracting query from uri {:?}", uri); uri.path_and_query() .and_then(|path_and_query| { trace!("path_and_query -> {:?}", path_and_query); path_and_query.query() }) .and_then(|query| parse_query_string(query)) } fn extract_headers(headers: &hyper::HeaderMap) -> Result<Option<HashMap<String, Vec<String>>>, InteractionError>
.collect())) } }) .collect(); result.map(|map| Some(map)) } else { Ok(None) } } fn extract_body(bytes: bytes::Bytes, request: &Request) -> OptionalBody { if bytes.len() > 0 { OptionalBody::Present(bytes, request.content_type()) } else { OptionalBody::Empty } } async fn hyper_request_to_pact_request(req: hyper::Request<Body>) -> Result<Request, InteractionError> { let method = req.method().to_string(); let path = extract_path(req.uri()); let query = extract_query_string(req.uri()); let headers = extract_headers(req.headers())?; let body_bytes = hyper::body::to_bytes(req.into_body()) .await .map_err(|_| InteractionError::RequestBodyError)?; let request = Request { method, path, query, headers, .. Request::default() }; Ok(Request { body: extract_body(body_bytes, &request), .. request.clone() }) } fn set_hyper_headers(builder: &mut ResponseBuilder, headers: &Option<HashMap<String, Vec<String>>>) -> Result<(), InteractionError> { let hyper_headers = builder.headers_mut().unwrap(); match headers { Some(header_map) => { for (k, v) in header_map { for val in v { // FIXME?: Headers are not sent in "raw" mode. // Names are converted to lower case and values are parsed. hyper_headers.append( HeaderName::from_bytes(k.as_bytes()) .map_err(|err| { error!("Invalid header name '{}' ({})", k, err); InteractionError::ResponseHeaderEncodingError })?, val.parse::<HeaderValue>() .map_err(|err| { error!("Invalid header value '{}': '{}' ({})", k, val, err); InteractionError::ResponseHeaderEncodingError })? ); } } }, _ => {} } Ok(()) } fn error_body(request: &Request, error: &String) -> String { let body = json!({ "error" : format!("{} : {:?}", error, request) }); body.to_string() } fn match_result_to_hyper_response( request: &Request, match_result: MatchResult, mock_server: Arc<Mutex<MockServer>> ) -> Result<Response<Body>, InteractionError> { let cors_preflight = { let ms = mock_server.lock().unwrap(); ms.config.cors_preflight }; match match_result { MatchResult::RequestMatch(ref interaction) => { let ms = mock_server.lock().unwrap(); let context = hashmap!{ "mockServer" => json!({ "href": ms.url(), "port": ms.port }) }; debug!("Test context = {:?}", context); let response = pact_matching::generate_response(&interaction.response, &GeneratorTestMode::Consumer, &context); info!("Request matched, sending response {}", response); if response.has_text_body() { debug!(" body: '{}'", response.body.str_value()); } let mut builder = Response::builder() .status(response.status) .header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*") .header(hyper::header::ACCESS_CONTROL_ALLOW_HEADERS, "*") .header(hyper::header::ACCESS_CONTROL_ALLOW_METHODS, "GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH") .header(hyper::header::ACCESS_CONTROL_EXPOSE_HEADERS, "Location, Link"); set_hyper_headers(&mut builder, &response.headers)?; builder.body(match response.body { OptionalBody::Present(ref s, _) => Body::from(s.clone()), _ => Body::empty() }) .map_err(|_| InteractionError::ResponseBodyError) }, _ => { debug!("Request did not match: {}", match_result); if cors_preflight && request.method.to_uppercase() == "OPTIONS" { info!("Responding to CORS pre-flight request"); let origin = match request.headers.clone() { Some(ref h) => h.iter() .find(|kv| kv.0.to_lowercase() == "referer") .map(|kv| kv.1.clone().join(", ")).unwrap_or("*".to_string()), None => "*".to_string() }; let cors_headers = match request.headers.clone() { Some(ref h) => h.iter() .find(|kv| kv.0.to_lowercase() == "access-control-request-headers") .map(|kv| kv.1.clone().join(", ") + ", *").unwrap_or("*".to_string()), None => "*".to_string() }; Response::builder() .status(204) .header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, origin) .header(hyper::header::ACCESS_CONTROL_ALLOW_METHODS, "GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH") .header(hyper::header::ACCESS_CONTROL_ALLOW_HEADERS, cors_headers) .header(hyper::header::ACCESS_CONTROL_EXPOSE_HEADERS, "Location, Link") .body(Body::empty()) .map_err(|_| InteractionError::ResponseBodyError) } else { Response::builder() .status(500) .header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*") .header(hyper::header::CONTENT_TYPE, "application/json; charset=utf-8") .header("X-Pact", match_result.match_key()) .body(Body::from(error_body(&request, &match_result.match_key()))) .map_err(|_| InteractionError::ResponseBodyError) } } } } async fn handle_request( req: hyper::Request<Body>, pact: Arc<RequestResponsePact>, matches: Arc<Mutex<Vec<MatchResult>>>, mock_server: Arc<Mutex<MockServer>> ) -> Result<Response<Body>, InteractionError> { debug!("Creating pact request from hyper request"); let pact_request = hyper_request_to_pact_request(req).await?; info!("Received request {}", pact_request); if pact_request.has_text_body() { debug!(" body: '{}'", pact_request.body.str_value()); } let match_result = match_request(&pact_request, &pact.interactions); matches.lock().unwrap().push(match_result.clone()); match_result_to_hyper_response(&pact_request, match_result, mock_server) } // TODO: Should instead use some form of X-Pact headers fn handle_mock_request_error(result: Result<Response<Body>, InteractionError>) -> Result<Response<Body>, Error> { match result { Ok(response) => Ok(response), Err(error) => { let response = match error { InteractionError::RequestHeaderEncodingError => Response::builder() .status(400) .body(Body::from("Found an invalid header encoding")), InteractionError::RequestBodyError => Response::builder() .status(500) .body(Body::from("Could not process request body")), InteractionError::ResponseBodyError => Response::builder() .status(500) .body(Body::from("Could not process response body")), InteractionError::ResponseHeaderEncodingError => Response::builder() .status(500) .body(Body::from("Could not set response header")) }; Ok(response.unwrap()) } } } // Create and bind the server, but do not start it. // Returns a future that drives the server. // The reason that the function itself is still async (even if it performs // no async operations) is that it needs a tokio context to be able to call try_bind. pub(crate) async fn create_and_bind( pact: RequestResponsePact, addr: SocketAddr, shutdown: impl std::future::Future<Output = ()>, matches: Arc<Mutex<Vec<MatchResult>>>, mock_server: Arc<Mutex<MockServer>> ) -> Result<(impl std::future::Future<Output = ()>, SocketAddr), hyper::Error> { let pact = Arc::new(pact); let server = Server::try_bind(&addr)? .serve(make_service_fn(move |_| { let pact = pact.clone(); let matches = matches.clone(); let mock_server = mock_server.clone(); async { Ok::<_, hyper::Error>( service_fn(move |req| { let pact = pact.clone(); let matches = matches.clone(); let mock_server = mock_server.clone(); async { handle_mock_request_error( handle_request(req, pact, matches, mock_server).await ) } }) ) } })); let socket_addr = server.local_addr(); Ok(( // This is the future that drives the server: async { let _ = server .with_graceful_shutdown(shutdown) .await; }, socket_addr )) } // Taken from https://github.com/ctz/hyper-rustls/blob/master/examples/server.rs struct HyperAcceptor { stream: Pin<Box<dyn Stream<Item = Result<TlsStream<TcpStream>, io::Error>> + Send>> } impl hyper::server::accept::Accept for HyperAcceptor { type Conn = TlsStream<TcpStream>; type Error = io::Error; fn poll_accept( mut self: Pin<&mut Self>, cx: &mut Context, ) -> Poll<Option<Result<Self::Conn, Self::Error>>> { self.as_mut().stream.poll_next_unpin(cx) } } pub(crate) async fn create_and_bind_tls( pact: RequestResponsePact, addr: SocketAddr, shutdown: impl std::future::Future<Output = ()>, matches: Arc<Mutex<Vec<MatchResult>>>, tls_cfg: ServerConfig, mock_server: Arc<Mutex<MockServer>> ) -> Result<(impl std::future::Future<Output = ()>, SocketAddr), io::Error> { let pact = Arc::new(pact); let tcp = TcpListener::bind(&addr).await?; let socket_addr = tcp.local_addr()?; let tls_acceptor = Arc::new(TlsAcceptor::from(Arc::new(tls_cfg))); let tls_stream = stream::unfold((Arc::new(tcp), tls_acceptor.clone()), |(listener, acceptor)| { async move { let (socket, _) = listener.accept().await.map_err(|err| { error!("Failed to accept TLS connection - {:?}", err); err }).ok()?; let stream = acceptor.accept(socket); Some((stream.await, (listener.clone(), acceptor.clone()))) } }); let server = Server::builder(HyperAcceptor { stream: tls_stream.boxed() }) .serve(make_service_fn(move |_| { let pact = pact.clone(); let matches = matches.clone(); let mock_server = mock_server.clone(); async { Ok::<_, hyper::Error>( service_fn(move |req| { let pact = pact.clone(); let matches = matches.clone(); let mock_server = mock_server.clone(); async { handle_mock_request_error( handle_request(req, pact, matches, mock_server).await ) } }) ) } })); Ok(( // This is the future that drives the server: async { let _ = server .with_graceful_shutdown(shutdown) .await; }, socket_addr )) } #[cfg(test)] mod tests { use expectest::expect; use expectest::prelude::*; use hyper::header::{ACCEPT, CONTENT_TYPE, USER_AGENT}; use hyper::HeaderMap; use super::*; #[tokio::test] async fn can_fetch_results_on_current_thread() { let (shutdown_tx, shutdown_rx) = futures::channel::oneshot::channel(); let matches = Arc::new(Mutex::new(vec![])); let (future, _) = create_and_bind( RequestResponsePact::default(), ([0, 0, 0, 0], 0 as u16).into(), async { shutdown_rx.await.ok(); }, matches.clone(), Arc::new(Mutex::new(MockServer::default())) ).await.unwrap(); let join_handle = tokio::task::spawn(future); shutdown_tx.send(()).unwrap(); // Server has shut down, now flush the server future from runtime join_handle.await.unwrap(); // 0 matches have been produced let all_matches = matches.lock().unwrap().clone(); assert_eq!(all_matches, vec![]); } #[test] fn handle_hyper_headers_with_multiple_values() { let mut headers = HeaderMap::new(); headers.append(ACCEPT, "application/xml, application/json".parse().unwrap()); headers.append(USER_AGENT, "test".parse().unwrap()); headers.append(USER_AGENT, "test2".parse().unwrap()); headers.append(CONTENT_TYPE, "text/plain".parse().unwrap()); let result = extract_headers(&headers); expect!(result).to(be_ok().value(Some(hashmap! { "accept".to_string() => vec!["application/xml".to_string(), "application/json".to_string()], "user-agent".to_string() => vec!["test".to_string(), "test2".to_string()], "content-type".to_string() => vec!["text/plain".to_string()] }))); } }
{ if !headers.is_empty() { let result: Result<HashMap<String, Vec<String>>, InteractionError> = headers.keys() .map(|name| -> Result<(String, Vec<String>), InteractionError> { let values = headers.get_all(name); let parsed_vals: Vec<Result<String, InteractionError>> = values.iter() .map(|val| val.to_str() .map(|v| v.to_string()) .map_err(|err| { warn!("Failed to parse HTTP header value: {}", err); InteractionError::RequestHeaderEncodingError }) ).collect(); if parsed_vals.iter().find(|val| val.is_err()).is_some() { Err(InteractionError::RequestHeaderEncodingError) } else { Ok((name.as_str().into(), parsed_vals.iter().cloned() .map(|val| val.unwrap_or_default()) .flat_map(|val| val.split(",").map(|v| v.to_string()).collect::<Vec<String>>()) .map(|val| val.trim().to_string())
identifier_body
f64.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Operations and constants for 64-bits floats (`f64` type) #![doc(primitive = "f64")] // FIXME: MIN_VALUE and MAX_VALUE literals are parsed as -inf and inf #14353 #![allow(type_overflow)] use intrinsics; use mem; use num::{FPNormal, FPCategory, FPZero, FPSubnormal, FPInfinite, FPNaN}; use num::Float; use option::Option; // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective // members of `Bounded` and `Float`. pub const RADIX: uint = 2u; pub const MANTISSA_DIGITS: uint = 53u; pub const DIGITS: uint = 15u; pub const EPSILON: f64 = 2.2204460492503131e-16_f64; /// Smallest finite f64 value pub const MIN_VALUE: f64 = -1.7976931348623157e+308_f64; /// Smallest positive, normalized f64 value pub const MIN_POS_VALUE: f64 = 2.2250738585072014e-308_f64; /// Largest finite f64 value pub const MAX_VALUE: f64 = 1.7976931348623157e+308_f64; pub const MIN_EXP: int = -1021; pub const MAX_EXP: int = 1024; pub const MIN_10_EXP: int = -307; pub const MAX_10_EXP: int = 308; pub const NAN: f64 = 0.0_f64/0.0_f64; pub const INFINITY: f64 = 1.0_f64/0.0_f64; pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64; /// Various useful constants. pub mod consts { // FIXME: replace with mathematical constants from cmath. // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective members // of `Float`. /// Archimedes' constant pub const PI: f64 = 3.14159265358979323846264338327950288_f64; /// pi * 2.0 pub const PI_2: f64 = 6.28318530717958647692528676655900576_f64; /// pi/2.0 pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64; /// pi/3.0 pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64; /// pi/4.0 pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64; /// pi/6.0 pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64; /// pi/8.0 pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64; /// 1.0/pi pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64; /// 2.0/pi pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64; /// 2.0/sqrt(pi) pub const FRAC_2_SQRTPI: f64 = 1.12837916709551257389615890312154517_f64; /// sqrt(2.0) pub const SQRT2: f64 = 1.41421356237309504880168872420969808_f64; /// 1.0/sqrt(2.0) pub const FRAC_1_SQRT2: f64 = 0.707106781186547524400844362104849039_f64; /// Euler's number pub const E: f64 = 2.71828182845904523536028747135266250_f64; /// log2(e) pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64; /// log10(e) pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64; /// ln(2.0) pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64; /// ln(10.0) pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64; } impl Float for f64 { #[inline] fn nan() -> f64 { NAN } #[inline] fn infinity() -> f64 { INFINITY } #[inline] fn neg_infinity() -> f64 { NEG_INFINITY } #[inline] fn neg_zero() -> f64 { -0.0 } /// Returns `true` if the number is NaN. #[inline] fn is_nan(self) -> bool { self!= self } /// Returns `true` if the number is infinite. #[inline] fn is_infinite(self) -> bool { self == Float::infinity() || self == Float::neg_infinity() } /// Returns `true` if the number is neither infinite or NaN. #[inline] fn is_finite(self) -> bool { !(self.is_nan() || self.is_infinite()) } /// Returns `true` if the number is neither zero, infinite, subnormal or NaN. #[inline] fn is_normal(self) -> bool { self.classify() == FPNormal } /// Returns the floating point category of the number. If only one property /// is going to be tested, it is generally faster to use the specific /// predicate instead. fn classify(self) -> FPCategory { const EXP_MASK: u64 = 0x7ff0000000000000; const MAN_MASK: u64 = 0x000fffffffffffff; let bits: u64 = unsafe { mem::transmute(self) }; match (bits & MAN_MASK, bits & EXP_MASK) { (0, 0) => FPZero, (_, 0) => FPSubnormal, (0, EXP_MASK) => FPInfinite, (_, EXP_MASK) => FPNaN, _ => FPNormal, } } #[inline] fn mantissa_digits(_: Option<f64>) -> uint { MANTISSA_DIGITS } #[inline] fn digits(_: Option<f64>) -> uint { DIGITS } #[inline] fn epsilon() -> f64 { EPSILON } #[inline] fn min_exp(_: Option<f64>) -> int { MIN_EXP } #[inline] fn max_exp(_: Option<f64>) -> int { MAX_EXP } #[inline] fn min_10_exp(_: Option<f64>) -> int { MIN_10_EXP } #[inline] fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP } #[inline] fn min_pos_value(_: Option<f64>) -> f64 { MIN_POS_VALUE } /// Returns the mantissa, exponent and sign as integers. fn integer_decode(self) -> (u64, i16, i8) { let bits: u64 = unsafe { mem::transmute(self) }; let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 }; let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; let mantissa = if exponent == 0 { (bits & 0xfffffffffffff) << 1 } else { (bits & 0xfffffffffffff) | 0x10000000000000 }; // Exponent bias + mantissa shift exponent -= 1023 + 52; (mantissa, exponent, sign) } /// Rounds towards minus infinity.
/// Rounds towards plus infinity. #[inline] fn ceil(self) -> f64 { unsafe { intrinsics::ceilf64(self) } } /// Rounds to nearest integer. Rounds half-way cases away from zero. #[inline] fn round(self) -> f64 { unsafe { intrinsics::roundf64(self) } } /// Returns the integer part of the number (rounds towards zero). #[inline] fn trunc(self) -> f64 { unsafe { intrinsics::truncf64(self) } } /// The fractional part of the number, satisfying: /// /// ```rust /// let x = 1.65f64; /// assert!(x == x.trunc() + x.fract()) /// ``` #[inline] fn fract(self) -> f64 { self - self.trunc() } /// Fused multiply-add. Computes `(self * a) + b` with only one rounding /// error. This produces a more accurate result with better performance than /// a separate multiplication operation followed by an add. #[inline] fn mul_add(self, a: f64, b: f64) -> f64 { unsafe { intrinsics::fmaf64(self, a, b) } } /// Returns the reciprocal (multiplicative inverse) of the number. #[inline] fn recip(self) -> f64 { 1.0 / self } #[inline] fn powf(self, n: f64) -> f64 { unsafe { intrinsics::powf64(self, n) } } #[inline] fn powi(self, n: i32) -> f64 { unsafe { intrinsics::powif64(self, n) } } /// sqrt(2.0) #[inline] fn sqrt2() -> f64 { consts::SQRT2 } /// 1.0 / sqrt(2.0) #[inline] fn frac_1_sqrt2() -> f64 { consts::FRAC_1_SQRT2 } #[inline] fn sqrt(self) -> f64 { unsafe { intrinsics::sqrtf64(self) } } #[inline] fn rsqrt(self) -> f64 { self.sqrt().recip() } /// Archimedes' constant #[inline] fn pi() -> f64 { consts::PI } /// 2.0 * pi #[inline] fn two_pi() -> f64 { consts::PI_2 } /// pi / 2.0 #[inline] fn frac_pi_2() -> f64 { consts::FRAC_PI_2 } /// pi / 3.0 #[inline] fn frac_pi_3() -> f64 { consts::FRAC_PI_3 } /// pi / 4.0 #[inline] fn frac_pi_4() -> f64 { consts::FRAC_PI_4 } /// pi / 6.0 #[inline] fn frac_pi_6() -> f64 { consts::FRAC_PI_6 } /// pi / 8.0 #[inline] fn frac_pi_8() -> f64 { consts::FRAC_PI_8 } /// 1.0 / pi #[inline] fn frac_1_pi() -> f64 { consts::FRAC_1_PI } /// 2.0 / pi #[inline] fn frac_2_pi() -> f64 { consts::FRAC_2_PI } /// 2.0 / sqrt(pi) #[inline] fn frac_2_sqrtpi() -> f64 { consts::FRAC_2_SQRTPI } /// Euler's number #[inline] fn e() -> f64 { consts::E } /// log2(e) #[inline] fn log2_e() -> f64 { consts::LOG2_E } /// log10(e) #[inline] fn log10_e() -> f64 { consts::LOG10_E } /// ln(2.0) #[inline] fn ln_2() -> f64 { consts::LN_2 } /// ln(10.0) #[inline] fn ln_10() -> f64 { consts::LN_10 } /// Returns the exponential of the number. #[inline] fn exp(self) -> f64 { unsafe { intrinsics::expf64(self) } } /// Returns 2 raised to the power of the number. #[inline] fn exp2(self) -> f64 { unsafe { intrinsics::exp2f64(self) } } /// Returns the natural logarithm of the number. #[inline] fn ln(self) -> f64 { unsafe { intrinsics::logf64(self) } } /// Returns the logarithm of the number with respect to an arbitrary base. #[inline] fn log(self, base: f64) -> f64 { self.ln() / base.ln() } /// Returns the base 2 logarithm of the number. #[inline] fn log2(self) -> f64 { unsafe { intrinsics::log2f64(self) } } /// Returns the base 10 logarithm of the number. #[inline] fn log10(self) -> f64 { unsafe { intrinsics::log10f64(self) } } /// Converts to degrees, assuming the number is in radians. #[inline] fn to_degrees(self) -> f64 { self * (180.0f64 / Float::pi()) } /// Converts to radians, assuming the number is in degrees. #[inline] fn to_radians(self) -> f64 { let value: f64 = Float::pi(); self * (value / 180.0) } }
#[inline] fn floor(self) -> f64 { unsafe { intrinsics::floorf64(self) } }
random_line_split
f64.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Operations and constants for 64-bits floats (`f64` type) #![doc(primitive = "f64")] // FIXME: MIN_VALUE and MAX_VALUE literals are parsed as -inf and inf #14353 #![allow(type_overflow)] use intrinsics; use mem; use num::{FPNormal, FPCategory, FPZero, FPSubnormal, FPInfinite, FPNaN}; use num::Float; use option::Option; // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective // members of `Bounded` and `Float`. pub const RADIX: uint = 2u; pub const MANTISSA_DIGITS: uint = 53u; pub const DIGITS: uint = 15u; pub const EPSILON: f64 = 2.2204460492503131e-16_f64; /// Smallest finite f64 value pub const MIN_VALUE: f64 = -1.7976931348623157e+308_f64; /// Smallest positive, normalized f64 value pub const MIN_POS_VALUE: f64 = 2.2250738585072014e-308_f64; /// Largest finite f64 value pub const MAX_VALUE: f64 = 1.7976931348623157e+308_f64; pub const MIN_EXP: int = -1021; pub const MAX_EXP: int = 1024; pub const MIN_10_EXP: int = -307; pub const MAX_10_EXP: int = 308; pub const NAN: f64 = 0.0_f64/0.0_f64; pub const INFINITY: f64 = 1.0_f64/0.0_f64; pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64; /// Various useful constants. pub mod consts { // FIXME: replace with mathematical constants from cmath. // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective members // of `Float`. /// Archimedes' constant pub const PI: f64 = 3.14159265358979323846264338327950288_f64; /// pi * 2.0 pub const PI_2: f64 = 6.28318530717958647692528676655900576_f64; /// pi/2.0 pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64; /// pi/3.0 pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64; /// pi/4.0 pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64; /// pi/6.0 pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64; /// pi/8.0 pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64; /// 1.0/pi pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64; /// 2.0/pi pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64; /// 2.0/sqrt(pi) pub const FRAC_2_SQRTPI: f64 = 1.12837916709551257389615890312154517_f64; /// sqrt(2.0) pub const SQRT2: f64 = 1.41421356237309504880168872420969808_f64; /// 1.0/sqrt(2.0) pub const FRAC_1_SQRT2: f64 = 0.707106781186547524400844362104849039_f64; /// Euler's number pub const E: f64 = 2.71828182845904523536028747135266250_f64; /// log2(e) pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64; /// log10(e) pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64; /// ln(2.0) pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64; /// ln(10.0) pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64; } impl Float for f64 { #[inline] fn nan() -> f64 { NAN } #[inline] fn infinity() -> f64 { INFINITY } #[inline] fn neg_infinity() -> f64 { NEG_INFINITY } #[inline] fn neg_zero() -> f64 { -0.0 } /// Returns `true` if the number is NaN. #[inline] fn is_nan(self) -> bool { self!= self } /// Returns `true` if the number is infinite. #[inline] fn is_infinite(self) -> bool { self == Float::infinity() || self == Float::neg_infinity() } /// Returns `true` if the number is neither infinite or NaN. #[inline] fn is_finite(self) -> bool { !(self.is_nan() || self.is_infinite()) } /// Returns `true` if the number is neither zero, infinite, subnormal or NaN. #[inline] fn is_normal(self) -> bool { self.classify() == FPNormal } /// Returns the floating point category of the number. If only one property /// is going to be tested, it is generally faster to use the specific /// predicate instead. fn classify(self) -> FPCategory { const EXP_MASK: u64 = 0x7ff0000000000000; const MAN_MASK: u64 = 0x000fffffffffffff; let bits: u64 = unsafe { mem::transmute(self) }; match (bits & MAN_MASK, bits & EXP_MASK) { (0, 0) => FPZero, (_, 0) => FPSubnormal, (0, EXP_MASK) => FPInfinite, (_, EXP_MASK) => FPNaN, _ => FPNormal, } } #[inline] fn mantissa_digits(_: Option<f64>) -> uint { MANTISSA_DIGITS } #[inline] fn digits(_: Option<f64>) -> uint { DIGITS } #[inline] fn epsilon() -> f64 { EPSILON } #[inline] fn min_exp(_: Option<f64>) -> int { MIN_EXP } #[inline] fn max_exp(_: Option<f64>) -> int { MAX_EXP } #[inline] fn min_10_exp(_: Option<f64>) -> int
#[inline] fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP } #[inline] fn min_pos_value(_: Option<f64>) -> f64 { MIN_POS_VALUE } /// Returns the mantissa, exponent and sign as integers. fn integer_decode(self) -> (u64, i16, i8) { let bits: u64 = unsafe { mem::transmute(self) }; let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 }; let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; let mantissa = if exponent == 0 { (bits & 0xfffffffffffff) << 1 } else { (bits & 0xfffffffffffff) | 0x10000000000000 }; // Exponent bias + mantissa shift exponent -= 1023 + 52; (mantissa, exponent, sign) } /// Rounds towards minus infinity. #[inline] fn floor(self) -> f64 { unsafe { intrinsics::floorf64(self) } } /// Rounds towards plus infinity. #[inline] fn ceil(self) -> f64 { unsafe { intrinsics::ceilf64(self) } } /// Rounds to nearest integer. Rounds half-way cases away from zero. #[inline] fn round(self) -> f64 { unsafe { intrinsics::roundf64(self) } } /// Returns the integer part of the number (rounds towards zero). #[inline] fn trunc(self) -> f64 { unsafe { intrinsics::truncf64(self) } } /// The fractional part of the number, satisfying: /// /// ```rust /// let x = 1.65f64; /// assert!(x == x.trunc() + x.fract()) /// ``` #[inline] fn fract(self) -> f64 { self - self.trunc() } /// Fused multiply-add. Computes `(self * a) + b` with only one rounding /// error. This produces a more accurate result with better performance than /// a separate multiplication operation followed by an add. #[inline] fn mul_add(self, a: f64, b: f64) -> f64 { unsafe { intrinsics::fmaf64(self, a, b) } } /// Returns the reciprocal (multiplicative inverse) of the number. #[inline] fn recip(self) -> f64 { 1.0 / self } #[inline] fn powf(self, n: f64) -> f64 { unsafe { intrinsics::powf64(self, n) } } #[inline] fn powi(self, n: i32) -> f64 { unsafe { intrinsics::powif64(self, n) } } /// sqrt(2.0) #[inline] fn sqrt2() -> f64 { consts::SQRT2 } /// 1.0 / sqrt(2.0) #[inline] fn frac_1_sqrt2() -> f64 { consts::FRAC_1_SQRT2 } #[inline] fn sqrt(self) -> f64 { unsafe { intrinsics::sqrtf64(self) } } #[inline] fn rsqrt(self) -> f64 { self.sqrt().recip() } /// Archimedes' constant #[inline] fn pi() -> f64 { consts::PI } /// 2.0 * pi #[inline] fn two_pi() -> f64 { consts::PI_2 } /// pi / 2.0 #[inline] fn frac_pi_2() -> f64 { consts::FRAC_PI_2 } /// pi / 3.0 #[inline] fn frac_pi_3() -> f64 { consts::FRAC_PI_3 } /// pi / 4.0 #[inline] fn frac_pi_4() -> f64 { consts::FRAC_PI_4 } /// pi / 6.0 #[inline] fn frac_pi_6() -> f64 { consts::FRAC_PI_6 } /// pi / 8.0 #[inline] fn frac_pi_8() -> f64 { consts::FRAC_PI_8 } /// 1.0 / pi #[inline] fn frac_1_pi() -> f64 { consts::FRAC_1_PI } /// 2.0 / pi #[inline] fn frac_2_pi() -> f64 { consts::FRAC_2_PI } /// 2.0 / sqrt(pi) #[inline] fn frac_2_sqrtpi() -> f64 { consts::FRAC_2_SQRTPI } /// Euler's number #[inline] fn e() -> f64 { consts::E } /// log2(e) #[inline] fn log2_e() -> f64 { consts::LOG2_E } /// log10(e) #[inline] fn log10_e() -> f64 { consts::LOG10_E } /// ln(2.0) #[inline] fn ln_2() -> f64 { consts::LN_2 } /// ln(10.0) #[inline] fn ln_10() -> f64 { consts::LN_10 } /// Returns the exponential of the number. #[inline] fn exp(self) -> f64 { unsafe { intrinsics::expf64(self) } } /// Returns 2 raised to the power of the number. #[inline] fn exp2(self) -> f64 { unsafe { intrinsics::exp2f64(self) } } /// Returns the natural logarithm of the number. #[inline] fn ln(self) -> f64 { unsafe { intrinsics::logf64(self) } } /// Returns the logarithm of the number with respect to an arbitrary base. #[inline] fn log(self, base: f64) -> f64 { self.ln() / base.ln() } /// Returns the base 2 logarithm of the number. #[inline] fn log2(self) -> f64 { unsafe { intrinsics::log2f64(self) } } /// Returns the base 10 logarithm of the number. #[inline] fn log10(self) -> f64 { unsafe { intrinsics::log10f64(self) } } /// Converts to degrees, assuming the number is in radians. #[inline] fn to_degrees(self) -> f64 { self * (180.0f64 / Float::pi()) } /// Converts to radians, assuming the number is in degrees. #[inline] fn to_radians(self) -> f64 { let value: f64 = Float::pi(); self * (value / 180.0) } }
{ MIN_10_EXP }
identifier_body
f64.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Operations and constants for 64-bits floats (`f64` type) #![doc(primitive = "f64")] // FIXME: MIN_VALUE and MAX_VALUE literals are parsed as -inf and inf #14353 #![allow(type_overflow)] use intrinsics; use mem; use num::{FPNormal, FPCategory, FPZero, FPSubnormal, FPInfinite, FPNaN}; use num::Float; use option::Option; // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective // members of `Bounded` and `Float`. pub const RADIX: uint = 2u; pub const MANTISSA_DIGITS: uint = 53u; pub const DIGITS: uint = 15u; pub const EPSILON: f64 = 2.2204460492503131e-16_f64; /// Smallest finite f64 value pub const MIN_VALUE: f64 = -1.7976931348623157e+308_f64; /// Smallest positive, normalized f64 value pub const MIN_POS_VALUE: f64 = 2.2250738585072014e-308_f64; /// Largest finite f64 value pub const MAX_VALUE: f64 = 1.7976931348623157e+308_f64; pub const MIN_EXP: int = -1021; pub const MAX_EXP: int = 1024; pub const MIN_10_EXP: int = -307; pub const MAX_10_EXP: int = 308; pub const NAN: f64 = 0.0_f64/0.0_f64; pub const INFINITY: f64 = 1.0_f64/0.0_f64; pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64; /// Various useful constants. pub mod consts { // FIXME: replace with mathematical constants from cmath. // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective members // of `Float`. /// Archimedes' constant pub const PI: f64 = 3.14159265358979323846264338327950288_f64; /// pi * 2.0 pub const PI_2: f64 = 6.28318530717958647692528676655900576_f64; /// pi/2.0 pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64; /// pi/3.0 pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64; /// pi/4.0 pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64; /// pi/6.0 pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64; /// pi/8.0 pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64; /// 1.0/pi pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64; /// 2.0/pi pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64; /// 2.0/sqrt(pi) pub const FRAC_2_SQRTPI: f64 = 1.12837916709551257389615890312154517_f64; /// sqrt(2.0) pub const SQRT2: f64 = 1.41421356237309504880168872420969808_f64; /// 1.0/sqrt(2.0) pub const FRAC_1_SQRT2: f64 = 0.707106781186547524400844362104849039_f64; /// Euler's number pub const E: f64 = 2.71828182845904523536028747135266250_f64; /// log2(e) pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64; /// log10(e) pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64; /// ln(2.0) pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64; /// ln(10.0) pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64; } impl Float for f64 { #[inline] fn nan() -> f64 { NAN } #[inline] fn infinity() -> f64 { INFINITY } #[inline] fn neg_infinity() -> f64 { NEG_INFINITY } #[inline] fn neg_zero() -> f64 { -0.0 } /// Returns `true` if the number is NaN. #[inline] fn is_nan(self) -> bool { self!= self } /// Returns `true` if the number is infinite. #[inline] fn is_infinite(self) -> bool { self == Float::infinity() || self == Float::neg_infinity() } /// Returns `true` if the number is neither infinite or NaN. #[inline] fn is_finite(self) -> bool { !(self.is_nan() || self.is_infinite()) } /// Returns `true` if the number is neither zero, infinite, subnormal or NaN. #[inline] fn is_normal(self) -> bool { self.classify() == FPNormal } /// Returns the floating point category of the number. If only one property /// is going to be tested, it is generally faster to use the specific /// predicate instead. fn classify(self) -> FPCategory { const EXP_MASK: u64 = 0x7ff0000000000000; const MAN_MASK: u64 = 0x000fffffffffffff; let bits: u64 = unsafe { mem::transmute(self) }; match (bits & MAN_MASK, bits & EXP_MASK) { (0, 0) => FPZero, (_, 0) => FPSubnormal, (0, EXP_MASK) => FPInfinite, (_, EXP_MASK) => FPNaN, _ => FPNormal, } } #[inline] fn mantissa_digits(_: Option<f64>) -> uint { MANTISSA_DIGITS } #[inline] fn digits(_: Option<f64>) -> uint { DIGITS } #[inline] fn epsilon() -> f64 { EPSILON } #[inline] fn min_exp(_: Option<f64>) -> int { MIN_EXP } #[inline] fn max_exp(_: Option<f64>) -> int { MAX_EXP } #[inline] fn min_10_exp(_: Option<f64>) -> int { MIN_10_EXP } #[inline] fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP } #[inline] fn min_pos_value(_: Option<f64>) -> f64 { MIN_POS_VALUE } /// Returns the mantissa, exponent and sign as integers. fn integer_decode(self) -> (u64, i16, i8) { let bits: u64 = unsafe { mem::transmute(self) }; let sign: i8 = if bits >> 63 == 0 { 1 } else
; let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; let mantissa = if exponent == 0 { (bits & 0xfffffffffffff) << 1 } else { (bits & 0xfffffffffffff) | 0x10000000000000 }; // Exponent bias + mantissa shift exponent -= 1023 + 52; (mantissa, exponent, sign) } /// Rounds towards minus infinity. #[inline] fn floor(self) -> f64 { unsafe { intrinsics::floorf64(self) } } /// Rounds towards plus infinity. #[inline] fn ceil(self) -> f64 { unsafe { intrinsics::ceilf64(self) } } /// Rounds to nearest integer. Rounds half-way cases away from zero. #[inline] fn round(self) -> f64 { unsafe { intrinsics::roundf64(self) } } /// Returns the integer part of the number (rounds towards zero). #[inline] fn trunc(self) -> f64 { unsafe { intrinsics::truncf64(self) } } /// The fractional part of the number, satisfying: /// /// ```rust /// let x = 1.65f64; /// assert!(x == x.trunc() + x.fract()) /// ``` #[inline] fn fract(self) -> f64 { self - self.trunc() } /// Fused multiply-add. Computes `(self * a) + b` with only one rounding /// error. This produces a more accurate result with better performance than /// a separate multiplication operation followed by an add. #[inline] fn mul_add(self, a: f64, b: f64) -> f64 { unsafe { intrinsics::fmaf64(self, a, b) } } /// Returns the reciprocal (multiplicative inverse) of the number. #[inline] fn recip(self) -> f64 { 1.0 / self } #[inline] fn powf(self, n: f64) -> f64 { unsafe { intrinsics::powf64(self, n) } } #[inline] fn powi(self, n: i32) -> f64 { unsafe { intrinsics::powif64(self, n) } } /// sqrt(2.0) #[inline] fn sqrt2() -> f64 { consts::SQRT2 } /// 1.0 / sqrt(2.0) #[inline] fn frac_1_sqrt2() -> f64 { consts::FRAC_1_SQRT2 } #[inline] fn sqrt(self) -> f64 { unsafe { intrinsics::sqrtf64(self) } } #[inline] fn rsqrt(self) -> f64 { self.sqrt().recip() } /// Archimedes' constant #[inline] fn pi() -> f64 { consts::PI } /// 2.0 * pi #[inline] fn two_pi() -> f64 { consts::PI_2 } /// pi / 2.0 #[inline] fn frac_pi_2() -> f64 { consts::FRAC_PI_2 } /// pi / 3.0 #[inline] fn frac_pi_3() -> f64 { consts::FRAC_PI_3 } /// pi / 4.0 #[inline] fn frac_pi_4() -> f64 { consts::FRAC_PI_4 } /// pi / 6.0 #[inline] fn frac_pi_6() -> f64 { consts::FRAC_PI_6 } /// pi / 8.0 #[inline] fn frac_pi_8() -> f64 { consts::FRAC_PI_8 } /// 1.0 / pi #[inline] fn frac_1_pi() -> f64 { consts::FRAC_1_PI } /// 2.0 / pi #[inline] fn frac_2_pi() -> f64 { consts::FRAC_2_PI } /// 2.0 / sqrt(pi) #[inline] fn frac_2_sqrtpi() -> f64 { consts::FRAC_2_SQRTPI } /// Euler's number #[inline] fn e() -> f64 { consts::E } /// log2(e) #[inline] fn log2_e() -> f64 { consts::LOG2_E } /// log10(e) #[inline] fn log10_e() -> f64 { consts::LOG10_E } /// ln(2.0) #[inline] fn ln_2() -> f64 { consts::LN_2 } /// ln(10.0) #[inline] fn ln_10() -> f64 { consts::LN_10 } /// Returns the exponential of the number. #[inline] fn exp(self) -> f64 { unsafe { intrinsics::expf64(self) } } /// Returns 2 raised to the power of the number. #[inline] fn exp2(self) -> f64 { unsafe { intrinsics::exp2f64(self) } } /// Returns the natural logarithm of the number. #[inline] fn ln(self) -> f64 { unsafe { intrinsics::logf64(self) } } /// Returns the logarithm of the number with respect to an arbitrary base. #[inline] fn log(self, base: f64) -> f64 { self.ln() / base.ln() } /// Returns the base 2 logarithm of the number. #[inline] fn log2(self) -> f64 { unsafe { intrinsics::log2f64(self) } } /// Returns the base 10 logarithm of the number. #[inline] fn log10(self) -> f64 { unsafe { intrinsics::log10f64(self) } } /// Converts to degrees, assuming the number is in radians. #[inline] fn to_degrees(self) -> f64 { self * (180.0f64 / Float::pi()) } /// Converts to radians, assuming the number is in degrees. #[inline] fn to_radians(self) -> f64 { let value: f64 = Float::pi(); self * (value / 180.0) } }
{ -1 }
conditional_block
f64.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Operations and constants for 64-bits floats (`f64` type) #![doc(primitive = "f64")] // FIXME: MIN_VALUE and MAX_VALUE literals are parsed as -inf and inf #14353 #![allow(type_overflow)] use intrinsics; use mem; use num::{FPNormal, FPCategory, FPZero, FPSubnormal, FPInfinite, FPNaN}; use num::Float; use option::Option; // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective // members of `Bounded` and `Float`. pub const RADIX: uint = 2u; pub const MANTISSA_DIGITS: uint = 53u; pub const DIGITS: uint = 15u; pub const EPSILON: f64 = 2.2204460492503131e-16_f64; /// Smallest finite f64 value pub const MIN_VALUE: f64 = -1.7976931348623157e+308_f64; /// Smallest positive, normalized f64 value pub const MIN_POS_VALUE: f64 = 2.2250738585072014e-308_f64; /// Largest finite f64 value pub const MAX_VALUE: f64 = 1.7976931348623157e+308_f64; pub const MIN_EXP: int = -1021; pub const MAX_EXP: int = 1024; pub const MIN_10_EXP: int = -307; pub const MAX_10_EXP: int = 308; pub const NAN: f64 = 0.0_f64/0.0_f64; pub const INFINITY: f64 = 1.0_f64/0.0_f64; pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64; /// Various useful constants. pub mod consts { // FIXME: replace with mathematical constants from cmath. // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective members // of `Float`. /// Archimedes' constant pub const PI: f64 = 3.14159265358979323846264338327950288_f64; /// pi * 2.0 pub const PI_2: f64 = 6.28318530717958647692528676655900576_f64; /// pi/2.0 pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64; /// pi/3.0 pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64; /// pi/4.0 pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64; /// pi/6.0 pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64; /// pi/8.0 pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64; /// 1.0/pi pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64; /// 2.0/pi pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64; /// 2.0/sqrt(pi) pub const FRAC_2_SQRTPI: f64 = 1.12837916709551257389615890312154517_f64; /// sqrt(2.0) pub const SQRT2: f64 = 1.41421356237309504880168872420969808_f64; /// 1.0/sqrt(2.0) pub const FRAC_1_SQRT2: f64 = 0.707106781186547524400844362104849039_f64; /// Euler's number pub const E: f64 = 2.71828182845904523536028747135266250_f64; /// log2(e) pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64; /// log10(e) pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64; /// ln(2.0) pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64; /// ln(10.0) pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64; } impl Float for f64 { #[inline] fn nan() -> f64 { NAN } #[inline] fn infinity() -> f64 { INFINITY } #[inline] fn neg_infinity() -> f64 { NEG_INFINITY } #[inline] fn neg_zero() -> f64 { -0.0 } /// Returns `true` if the number is NaN. #[inline] fn is_nan(self) -> bool { self!= self } /// Returns `true` if the number is infinite. #[inline] fn is_infinite(self) -> bool { self == Float::infinity() || self == Float::neg_infinity() } /// Returns `true` if the number is neither infinite or NaN. #[inline] fn is_finite(self) -> bool { !(self.is_nan() || self.is_infinite()) } /// Returns `true` if the number is neither zero, infinite, subnormal or NaN. #[inline] fn is_normal(self) -> bool { self.classify() == FPNormal } /// Returns the floating point category of the number. If only one property /// is going to be tested, it is generally faster to use the specific /// predicate instead. fn classify(self) -> FPCategory { const EXP_MASK: u64 = 0x7ff0000000000000; const MAN_MASK: u64 = 0x000fffffffffffff; let bits: u64 = unsafe { mem::transmute(self) }; match (bits & MAN_MASK, bits & EXP_MASK) { (0, 0) => FPZero, (_, 0) => FPSubnormal, (0, EXP_MASK) => FPInfinite, (_, EXP_MASK) => FPNaN, _ => FPNormal, } } #[inline] fn mantissa_digits(_: Option<f64>) -> uint { MANTISSA_DIGITS } #[inline] fn digits(_: Option<f64>) -> uint { DIGITS } #[inline] fn epsilon() -> f64 { EPSILON } #[inline] fn min_exp(_: Option<f64>) -> int { MIN_EXP } #[inline] fn max_exp(_: Option<f64>) -> int { MAX_EXP } #[inline] fn min_10_exp(_: Option<f64>) -> int { MIN_10_EXP } #[inline] fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP } #[inline] fn min_pos_value(_: Option<f64>) -> f64 { MIN_POS_VALUE } /// Returns the mantissa, exponent and sign as integers. fn integer_decode(self) -> (u64, i16, i8) { let bits: u64 = unsafe { mem::transmute(self) }; let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 }; let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; let mantissa = if exponent == 0 { (bits & 0xfffffffffffff) << 1 } else { (bits & 0xfffffffffffff) | 0x10000000000000 }; // Exponent bias + mantissa shift exponent -= 1023 + 52; (mantissa, exponent, sign) } /// Rounds towards minus infinity. #[inline] fn floor(self) -> f64 { unsafe { intrinsics::floorf64(self) } } /// Rounds towards plus infinity. #[inline] fn ceil(self) -> f64 { unsafe { intrinsics::ceilf64(self) } } /// Rounds to nearest integer. Rounds half-way cases away from zero. #[inline] fn round(self) -> f64 { unsafe { intrinsics::roundf64(self) } } /// Returns the integer part of the number (rounds towards zero). #[inline] fn trunc(self) -> f64 { unsafe { intrinsics::truncf64(self) } } /// The fractional part of the number, satisfying: /// /// ```rust /// let x = 1.65f64; /// assert!(x == x.trunc() + x.fract()) /// ``` #[inline] fn fract(self) -> f64 { self - self.trunc() } /// Fused multiply-add. Computes `(self * a) + b` with only one rounding /// error. This produces a more accurate result with better performance than /// a separate multiplication operation followed by an add. #[inline] fn mul_add(self, a: f64, b: f64) -> f64 { unsafe { intrinsics::fmaf64(self, a, b) } } /// Returns the reciprocal (multiplicative inverse) of the number. #[inline] fn recip(self) -> f64 { 1.0 / self } #[inline] fn powf(self, n: f64) -> f64 { unsafe { intrinsics::powf64(self, n) } } #[inline] fn powi(self, n: i32) -> f64 { unsafe { intrinsics::powif64(self, n) } } /// sqrt(2.0) #[inline] fn sqrt2() -> f64 { consts::SQRT2 } /// 1.0 / sqrt(2.0) #[inline] fn frac_1_sqrt2() -> f64 { consts::FRAC_1_SQRT2 } #[inline] fn sqrt(self) -> f64 { unsafe { intrinsics::sqrtf64(self) } } #[inline] fn rsqrt(self) -> f64 { self.sqrt().recip() } /// Archimedes' constant #[inline] fn pi() -> f64 { consts::PI } /// 2.0 * pi #[inline] fn two_pi() -> f64 { consts::PI_2 } /// pi / 2.0 #[inline] fn frac_pi_2() -> f64 { consts::FRAC_PI_2 } /// pi / 3.0 #[inline] fn frac_pi_3() -> f64 { consts::FRAC_PI_3 } /// pi / 4.0 #[inline] fn frac_pi_4() -> f64 { consts::FRAC_PI_4 } /// pi / 6.0 #[inline] fn frac_pi_6() -> f64 { consts::FRAC_PI_6 } /// pi / 8.0 #[inline] fn frac_pi_8() -> f64 { consts::FRAC_PI_8 } /// 1.0 / pi #[inline] fn frac_1_pi() -> f64 { consts::FRAC_1_PI } /// 2.0 / pi #[inline] fn frac_2_pi() -> f64 { consts::FRAC_2_PI } /// 2.0 / sqrt(pi) #[inline] fn frac_2_sqrtpi() -> f64 { consts::FRAC_2_SQRTPI } /// Euler's number #[inline] fn e() -> f64 { consts::E } /// log2(e) #[inline] fn log2_e() -> f64 { consts::LOG2_E } /// log10(e) #[inline] fn
() -> f64 { consts::LOG10_E } /// ln(2.0) #[inline] fn ln_2() -> f64 { consts::LN_2 } /// ln(10.0) #[inline] fn ln_10() -> f64 { consts::LN_10 } /// Returns the exponential of the number. #[inline] fn exp(self) -> f64 { unsafe { intrinsics::expf64(self) } } /// Returns 2 raised to the power of the number. #[inline] fn exp2(self) -> f64 { unsafe { intrinsics::exp2f64(self) } } /// Returns the natural logarithm of the number. #[inline] fn ln(self) -> f64 { unsafe { intrinsics::logf64(self) } } /// Returns the logarithm of the number with respect to an arbitrary base. #[inline] fn log(self, base: f64) -> f64 { self.ln() / base.ln() } /// Returns the base 2 logarithm of the number. #[inline] fn log2(self) -> f64 { unsafe { intrinsics::log2f64(self) } } /// Returns the base 10 logarithm of the number. #[inline] fn log10(self) -> f64 { unsafe { intrinsics::log10f64(self) } } /// Converts to degrees, assuming the number is in radians. #[inline] fn to_degrees(self) -> f64 { self * (180.0f64 / Float::pi()) } /// Converts to radians, assuming the number is in degrees. #[inline] fn to_radians(self) -> f64 { let value: f64 = Float::pi(); self * (value / 180.0) } }
log10_e
identifier_name
mod.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program 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 * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ pub mod error; pub mod smb_records; pub mod smb1_records; pub mod smb2_records; pub mod nbss_records; pub mod dcerpc_records; pub mod ntlmssp_records; pub mod smb; pub mod smb1; pub mod smb1_session; pub mod smb2; pub mod smb2_session; pub mod smb2_ioctl; pub mod smb3; pub mod dcerpc; pub mod session; pub mod log; pub mod detect; pub mod debug; pub mod events; pub mod auth; pub mod files; pub mod funcs;
//#[cfg(feature = "lua")] //pub mod lua;
random_line_split
mod.rs
//! The SpaceAPI server struct. use std::net::ToSocketAddrs; use std::sync::Arc; use std::time::Duration; use iron::Iron; use log::debug; use r2d2; use r2d2_redis::RedisConnectionManager; use redis::{ConnectionInfo, IntoConnectionInfo}; use router::Router; use serde_json::map::Map; use serde_json::Value; mod handlers; use crate::api; use crate::errors::SpaceapiServerError; use crate::modifiers; use crate::sensors; use crate::types::RedisPool; enum RedisInfo { None, Pool(r2d2::Pool<r2d2_redis::RedisConnectionManager>), ConnectionInfo(ConnectionInfo), Err(SpaceapiServerError), } /// Builder to create a new [`SpaceapiServer`](struct.SpaceapiServer.html) /// instance. pub struct SpaceapiServerBuilder { status: api::Status, redis_info: RedisInfo, sensor_specs: Vec<sensors::SensorSpec>, status_modifiers: Vec<Box<dyn modifiers::StatusModifier>>, } impl SpaceapiServerBuilder { /// Create a new builder instance based on the provided static status data. pub fn new(mut status: api::Status) -> SpaceapiServerBuilder { // Instantiate versions object let mut versions = Map::new(); versions.insert("spaceapi-rs".into(), api::get_version().into()); versions.insert("spaceapi-server-rs".into(), crate::get_version().into()); // Add to extensions status .extensions .insert("versions".into(), Value::Object(versions)); SpaceapiServerBuilder { status, redis_info: RedisInfo::None, sensor_specs: vec![], status_modifiers: vec![], } } /// Specify a Redis connection string. /// /// This can be any object that implements /// [`redis::IntoConnectionInfo`](../redis/trait.IntoConnectionInfo.html), /// e.g. a connection string: /// /// ```ignore ///... ///.redis_connection_info("redis://127.0.0.1/") ///... /// ``` pub fn redis_connection_info<R: IntoConnectionInfo>(mut self, redis_connection_info: R) -> Self { self.redis_info = match redis_connection_info.into_connection_info() { Ok(ci) => RedisInfo::ConnectionInfo(ci), Err(e) => RedisInfo::Err(e.into()), }; self } /// Use this as an alternative to /// [`redis_connection_info`](struct.SpaceapiServerBuilder.html#method.redis_connection_info) /// if you want to initialize the Redis connection pool yourself, to have /// full control over the connection parameters. /// /// See /// [`examples/with_custom_redis_pool.rs`](https://github.com/spaceapi-community/spaceapi-server-rs/blob/master/examples/with_custom_redis_pool.rs) /// for a real example. pub fn redis_pool(mut self, redis_pool: r2d2::Pool<r2d2_redis::RedisConnectionManager>) -> Self { self.redis_info = RedisInfo::Pool(redis_pool); self } /// Add a status modifier, that modifies the status dynamically per /// request. /// /// This can be an instance of /// [`modifiers::StateFromPeopleNowPresent`](modifiers/struct.StateFromPeopleNowPresent.html), /// or your own implementation that uses the dynamic sensor data and/or /// external data. pub fn add_status_modifier<M: modifiers::StatusModifier +'static>(mut self, modifier: M) -> Self { self.status_modifiers.push(Box::new(modifier)); self } /// Add a new sensor. /// /// The first argument is a ``api::SensorTemplate`` instance containing all static data. /// The second argument specifies how to get the actual sensor value from Redis. pub fn add_sensor<T: api::SensorTemplate +'static>(mut self, template: T, data_key: String) -> Self { self.sensor_specs.push(sensors::SensorSpec { template: Box::new(template), data_key, }); self } /// Build a server instance. /// /// This can fail if not all required data has been provided. pub fn build(self) -> Result<SpaceapiServer, SpaceapiServerError> { let pool = match self.redis_info { RedisInfo::None => Err("No redis connection defined".into()), RedisInfo::Err(e) => Err(e), RedisInfo::Pool(p) => Ok(p), RedisInfo::ConnectionInfo(ci) => { // Log some useful debug information debug!("Connecting to redis database {} at {:?}", ci.db, ci.addr); let redis_manager = RedisConnectionManager::new(ci)?; // Create redis pool let redis_pool = r2d2::Pool::builder() // Provide up to 6 connections in connection pool .max_size(6) // At least 1 connection must be active .min_idle(Some(2)) // Try to get a connection for max 1 second .connection_timeout(Duration::from_secs(1)) // Don't log errors directly. // They can get quite verbose, and we're already catching and // logging the corresponding results anyways. .error_handler(Box::new(r2d2::NopErrorHandler)) // Initialize connection pool lazily. This allows the SpaceAPI
Ok(redis_pool) } }; Ok(SpaceapiServer { status: self.status, redis_pool: pool?, sensor_specs: Arc::new(self.sensor_specs), status_modifiers: self.status_modifiers, }) } } /// A SpaceAPI server instance. /// /// You can create a new instance using the ``new`` constructor method by /// passing it the host, the port, the ``Status`` object and a redis connection info object. /// /// The ``SpaceapiServer`` includes a web server through /// [Hyper](http://hyper.rs/hyper/hyper/server/index.html). Simply call the ``serve`` method. pub struct SpaceapiServer { status: api::Status, redis_pool: RedisPool, sensor_specs: sensors::SafeSensorSpecs, status_modifiers: Vec<Box<dyn modifiers::StatusModifier>>, } impl SpaceapiServer { /// Create and return a Router instance. fn route(self) -> Router { let mut router = Router::new(); router.get( "/", handlers::ReadHandler::new( self.status.clone(), self.redis_pool.clone(), self.sensor_specs.clone(), self.status_modifiers, ), "root", ); router.put( "/sensors/:sensor/", handlers::UpdateHandler::new(self.redis_pool.clone(), self.sensor_specs.clone()), "sensors", ); router } /// Start a HTTP server listening on ``self.host:self.port``. /// /// The call returns an `HttpResult<Listening>` object, see /// http://ironframework.io/doc/hyper/server/struct.Listening.html /// for more information. pub fn serve<S: ToSocketAddrs>(self, socket_addr: S) -> crate::HttpResult<crate::Listening> { // Launch server process let router = self.route(); println!("Starting HTTP server on:"); for a in socket_addr.to_socket_addrs()? { println!("\thttp://{}", a); } Iron::new(router).http(socket_addr) } }
// server to work even without a database connection. .build_unchecked(redis_manager);
random_line_split
mod.rs
//! The SpaceAPI server struct. use std::net::ToSocketAddrs; use std::sync::Arc; use std::time::Duration; use iron::Iron; use log::debug; use r2d2; use r2d2_redis::RedisConnectionManager; use redis::{ConnectionInfo, IntoConnectionInfo}; use router::Router; use serde_json::map::Map; use serde_json::Value; mod handlers; use crate::api; use crate::errors::SpaceapiServerError; use crate::modifiers; use crate::sensors; use crate::types::RedisPool; enum RedisInfo { None, Pool(r2d2::Pool<r2d2_redis::RedisConnectionManager>), ConnectionInfo(ConnectionInfo), Err(SpaceapiServerError), } /// Builder to create a new [`SpaceapiServer`](struct.SpaceapiServer.html) /// instance. pub struct SpaceapiServerBuilder { status: api::Status, redis_info: RedisInfo, sensor_specs: Vec<sensors::SensorSpec>, status_modifiers: Vec<Box<dyn modifiers::StatusModifier>>, } impl SpaceapiServerBuilder { /// Create a new builder instance based on the provided static status data. pub fn new(mut status: api::Status) -> SpaceapiServerBuilder { // Instantiate versions object let mut versions = Map::new(); versions.insert("spaceapi-rs".into(), api::get_version().into()); versions.insert("spaceapi-server-rs".into(), crate::get_version().into()); // Add to extensions status .extensions .insert("versions".into(), Value::Object(versions)); SpaceapiServerBuilder { status, redis_info: RedisInfo::None, sensor_specs: vec![], status_modifiers: vec![], } } /// Specify a Redis connection string. /// /// This can be any object that implements /// [`redis::IntoConnectionInfo`](../redis/trait.IntoConnectionInfo.html), /// e.g. a connection string: /// /// ```ignore ///... ///.redis_connection_info("redis://127.0.0.1/") ///... /// ``` pub fn redis_connection_info<R: IntoConnectionInfo>(mut self, redis_connection_info: R) -> Self { self.redis_info = match redis_connection_info.into_connection_info() { Ok(ci) => RedisInfo::ConnectionInfo(ci), Err(e) => RedisInfo::Err(e.into()), }; self } /// Use this as an alternative to /// [`redis_connection_info`](struct.SpaceapiServerBuilder.html#method.redis_connection_info) /// if you want to initialize the Redis connection pool yourself, to have /// full control over the connection parameters. /// /// See /// [`examples/with_custom_redis_pool.rs`](https://github.com/spaceapi-community/spaceapi-server-rs/blob/master/examples/with_custom_redis_pool.rs) /// for a real example. pub fn redis_pool(mut self, redis_pool: r2d2::Pool<r2d2_redis::RedisConnectionManager>) -> Self { self.redis_info = RedisInfo::Pool(redis_pool); self } /// Add a status modifier, that modifies the status dynamically per /// request. /// /// This can be an instance of /// [`modifiers::StateFromPeopleNowPresent`](modifiers/struct.StateFromPeopleNowPresent.html), /// or your own implementation that uses the dynamic sensor data and/or /// external data. pub fn add_status_modifier<M: modifiers::StatusModifier +'static>(mut self, modifier: M) -> Self { self.status_modifiers.push(Box::new(modifier)); self } /// Add a new sensor. /// /// The first argument is a ``api::SensorTemplate`` instance containing all static data. /// The second argument specifies how to get the actual sensor value from Redis. pub fn add_sensor<T: api::SensorTemplate +'static>(mut self, template: T, data_key: String) -> Self { self.sensor_specs.push(sensors::SensorSpec { template: Box::new(template), data_key, }); self } /// Build a server instance. /// /// This can fail if not all required data has been provided. pub fn
(self) -> Result<SpaceapiServer, SpaceapiServerError> { let pool = match self.redis_info { RedisInfo::None => Err("No redis connection defined".into()), RedisInfo::Err(e) => Err(e), RedisInfo::Pool(p) => Ok(p), RedisInfo::ConnectionInfo(ci) => { // Log some useful debug information debug!("Connecting to redis database {} at {:?}", ci.db, ci.addr); let redis_manager = RedisConnectionManager::new(ci)?; // Create redis pool let redis_pool = r2d2::Pool::builder() // Provide up to 6 connections in connection pool .max_size(6) // At least 1 connection must be active .min_idle(Some(2)) // Try to get a connection for max 1 second .connection_timeout(Duration::from_secs(1)) // Don't log errors directly. // They can get quite verbose, and we're already catching and // logging the corresponding results anyways. .error_handler(Box::new(r2d2::NopErrorHandler)) // Initialize connection pool lazily. This allows the SpaceAPI // server to work even without a database connection. .build_unchecked(redis_manager); Ok(redis_pool) } }; Ok(SpaceapiServer { status: self.status, redis_pool: pool?, sensor_specs: Arc::new(self.sensor_specs), status_modifiers: self.status_modifiers, }) } } /// A SpaceAPI server instance. /// /// You can create a new instance using the ``new`` constructor method by /// passing it the host, the port, the ``Status`` object and a redis connection info object. /// /// The ``SpaceapiServer`` includes a web server through /// [Hyper](http://hyper.rs/hyper/hyper/server/index.html). Simply call the ``serve`` method. pub struct SpaceapiServer { status: api::Status, redis_pool: RedisPool, sensor_specs: sensors::SafeSensorSpecs, status_modifiers: Vec<Box<dyn modifiers::StatusModifier>>, } impl SpaceapiServer { /// Create and return a Router instance. fn route(self) -> Router { let mut router = Router::new(); router.get( "/", handlers::ReadHandler::new( self.status.clone(), self.redis_pool.clone(), self.sensor_specs.clone(), self.status_modifiers, ), "root", ); router.put( "/sensors/:sensor/", handlers::UpdateHandler::new(self.redis_pool.clone(), self.sensor_specs.clone()), "sensors", ); router } /// Start a HTTP server listening on ``self.host:self.port``. /// /// The call returns an `HttpResult<Listening>` object, see /// http://ironframework.io/doc/hyper/server/struct.Listening.html /// for more information. pub fn serve<S: ToSocketAddrs>(self, socket_addr: S) -> crate::HttpResult<crate::Listening> { // Launch server process let router = self.route(); println!("Starting HTTP server on:"); for a in socket_addr.to_socket_addrs()? { println!("\thttp://{}", a); } Iron::new(router).http(socket_addr) } }
build
identifier_name
mod.rs
//! The SpaceAPI server struct. use std::net::ToSocketAddrs; use std::sync::Arc; use std::time::Duration; use iron::Iron; use log::debug; use r2d2; use r2d2_redis::RedisConnectionManager; use redis::{ConnectionInfo, IntoConnectionInfo}; use router::Router; use serde_json::map::Map; use serde_json::Value; mod handlers; use crate::api; use crate::errors::SpaceapiServerError; use crate::modifiers; use crate::sensors; use crate::types::RedisPool; enum RedisInfo { None, Pool(r2d2::Pool<r2d2_redis::RedisConnectionManager>), ConnectionInfo(ConnectionInfo), Err(SpaceapiServerError), } /// Builder to create a new [`SpaceapiServer`](struct.SpaceapiServer.html) /// instance. pub struct SpaceapiServerBuilder { status: api::Status, redis_info: RedisInfo, sensor_specs: Vec<sensors::SensorSpec>, status_modifiers: Vec<Box<dyn modifiers::StatusModifier>>, } impl SpaceapiServerBuilder { /// Create a new builder instance based on the provided static status data. pub fn new(mut status: api::Status) -> SpaceapiServerBuilder { // Instantiate versions object let mut versions = Map::new(); versions.insert("spaceapi-rs".into(), api::get_version().into()); versions.insert("spaceapi-server-rs".into(), crate::get_version().into()); // Add to extensions status .extensions .insert("versions".into(), Value::Object(versions)); SpaceapiServerBuilder { status, redis_info: RedisInfo::None, sensor_specs: vec![], status_modifiers: vec![], } } /// Specify a Redis connection string. /// /// This can be any object that implements /// [`redis::IntoConnectionInfo`](../redis/trait.IntoConnectionInfo.html), /// e.g. a connection string: /// /// ```ignore ///... ///.redis_connection_info("redis://127.0.0.1/") ///... /// ``` pub fn redis_connection_info<R: IntoConnectionInfo>(mut self, redis_connection_info: R) -> Self { self.redis_info = match redis_connection_info.into_connection_info() { Ok(ci) => RedisInfo::ConnectionInfo(ci), Err(e) => RedisInfo::Err(e.into()), }; self } /// Use this as an alternative to /// [`redis_connection_info`](struct.SpaceapiServerBuilder.html#method.redis_connection_info) /// if you want to initialize the Redis connection pool yourself, to have /// full control over the connection parameters. /// /// See /// [`examples/with_custom_redis_pool.rs`](https://github.com/spaceapi-community/spaceapi-server-rs/blob/master/examples/with_custom_redis_pool.rs) /// for a real example. pub fn redis_pool(mut self, redis_pool: r2d2::Pool<r2d2_redis::RedisConnectionManager>) -> Self { self.redis_info = RedisInfo::Pool(redis_pool); self } /// Add a status modifier, that modifies the status dynamically per /// request. /// /// This can be an instance of /// [`modifiers::StateFromPeopleNowPresent`](modifiers/struct.StateFromPeopleNowPresent.html), /// or your own implementation that uses the dynamic sensor data and/or /// external data. pub fn add_status_modifier<M: modifiers::StatusModifier +'static>(mut self, modifier: M) -> Self { self.status_modifiers.push(Box::new(modifier)); self } /// Add a new sensor. /// /// The first argument is a ``api::SensorTemplate`` instance containing all static data. /// The second argument specifies how to get the actual sensor value from Redis. pub fn add_sensor<T: api::SensorTemplate +'static>(mut self, template: T, data_key: String) -> Self { self.sensor_specs.push(sensors::SensorSpec { template: Box::new(template), data_key, }); self } /// Build a server instance. /// /// This can fail if not all required data has been provided. pub fn build(self) -> Result<SpaceapiServer, SpaceapiServerError> { let pool = match self.redis_info { RedisInfo::None => Err("No redis connection defined".into()), RedisInfo::Err(e) => Err(e), RedisInfo::Pool(p) => Ok(p), RedisInfo::ConnectionInfo(ci) => { // Log some useful debug information debug!("Connecting to redis database {} at {:?}", ci.db, ci.addr); let redis_manager = RedisConnectionManager::new(ci)?; // Create redis pool let redis_pool = r2d2::Pool::builder() // Provide up to 6 connections in connection pool .max_size(6) // At least 1 connection must be active .min_idle(Some(2)) // Try to get a connection for max 1 second .connection_timeout(Duration::from_secs(1)) // Don't log errors directly. // They can get quite verbose, and we're already catching and // logging the corresponding results anyways. .error_handler(Box::new(r2d2::NopErrorHandler)) // Initialize connection pool lazily. This allows the SpaceAPI // server to work even without a database connection. .build_unchecked(redis_manager); Ok(redis_pool) } }; Ok(SpaceapiServer { status: self.status, redis_pool: pool?, sensor_specs: Arc::new(self.sensor_specs), status_modifiers: self.status_modifiers, }) } } /// A SpaceAPI server instance. /// /// You can create a new instance using the ``new`` constructor method by /// passing it the host, the port, the ``Status`` object and a redis connection info object. /// /// The ``SpaceapiServer`` includes a web server through /// [Hyper](http://hyper.rs/hyper/hyper/server/index.html). Simply call the ``serve`` method. pub struct SpaceapiServer { status: api::Status, redis_pool: RedisPool, sensor_specs: sensors::SafeSensorSpecs, status_modifiers: Vec<Box<dyn modifiers::StatusModifier>>, } impl SpaceapiServer { /// Create and return a Router instance. fn route(self) -> Router
router } /// Start a HTTP server listening on ``self.host:self.port``. /// /// The call returns an `HttpResult<Listening>` object, see /// http://ironframework.io/doc/hyper/server/struct.Listening.html /// for more information. pub fn serve<S: ToSocketAddrs>(self, socket_addr: S) -> crate::HttpResult<crate::Listening> { // Launch server process let router = self.route(); println!("Starting HTTP server on:"); for a in socket_addr.to_socket_addrs()? { println!("\thttp://{}", a); } Iron::new(router).http(socket_addr) } }
{ let mut router = Router::new(); router.get( "/", handlers::ReadHandler::new( self.status.clone(), self.redis_pool.clone(), self.sensor_specs.clone(), self.status_modifiers, ), "root", ); router.put( "/sensors/:sensor/", handlers::UpdateHandler::new(self.redis_pool.clone(), self.sensor_specs.clone()), "sensors", );
identifier_body
build.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/. */ extern crate cc; extern crate gl_generator; use gl_generator::{Api, Fallbacks, Profile, Registry}; use std::env; use std::fs::File; use std::path::Path; fn main() { let target = env::var("TARGET").unwrap(); if target.contains("android") { android_main() } generate_gl_bindings(&target); } fn android_main()
println!("cargo:rustc-link-lib=static=android_native_app_glue"); println!("cargo:rustc-link-search=native={}", out_dir); println!("cargo:rustc-link-lib=log"); println!("cargo:rustc-link-lib=android"); } fn generate_gl_bindings(target: &str) { // For now, we only support EGL, and only on Windows and Android. if target.contains("android") || target.contains("windows") { let dest = env::var("OUT_DIR").unwrap(); let mut file = File::create(&Path::new(&dest).join("egl_bindings.rs")).unwrap(); if target.contains("android") { Registry::new(Api::Egl, (1, 5), Profile::Core, Fallbacks::All, []) .write_bindings(gl_generator::StaticStructGenerator, &mut file) .unwrap(); } if target.contains("windows") { Registry::new(Api::Egl, (1, 5), Profile::Core, Fallbacks::All, []) .write_bindings(gl_generator::StructGenerator, &mut file) .unwrap(); }; } }
{ // Get the NDK path from NDK_HOME env. let ndk_path = env::var_os("ANDROID_NDK").expect("Please set the ANDROID_NDK environment variable"); let ndk_path = Path::new(&ndk_path); // compiling android_native_app_glue.c let c_file = ndk_path .join("sources") .join("android") .join("native_app_glue") .join("android_native_app_glue.c"); cc::Build::new() .file(c_file) .warnings(false) .compile("android_native_app_glue"); // Get the output directory. let out_dir = env::var("OUT_DIR").expect("Cargo should have set the OUT_DIR environment variable");
identifier_body
build.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/. */ extern crate cc; extern crate gl_generator; use gl_generator::{Api, Fallbacks, Profile, Registry}; use std::env; use std::fs::File; use std::path::Path; fn main() { let target = env::var("TARGET").unwrap(); if target.contains("android") { android_main() } generate_gl_bindings(&target); } fn android_main() { // Get the NDK path from NDK_HOME env. let ndk_path = env::var_os("ANDROID_NDK").expect("Please set the ANDROID_NDK environment variable"); let ndk_path = Path::new(&ndk_path); // compiling android_native_app_glue.c let c_file = ndk_path .join("sources") .join("android") .join("native_app_glue") .join("android_native_app_glue.c"); cc::Build::new() .file(c_file) .warnings(false) .compile("android_native_app_glue"); // Get the output directory. let out_dir = env::var("OUT_DIR").expect("Cargo should have set the OUT_DIR environment variable"); println!("cargo:rustc-link-lib=static=android_native_app_glue"); println!("cargo:rustc-link-search=native={}", out_dir); println!("cargo:rustc-link-lib=log"); println!("cargo:rustc-link-lib=android"); } fn
(target: &str) { // For now, we only support EGL, and only on Windows and Android. if target.contains("android") || target.contains("windows") { let dest = env::var("OUT_DIR").unwrap(); let mut file = File::create(&Path::new(&dest).join("egl_bindings.rs")).unwrap(); if target.contains("android") { Registry::new(Api::Egl, (1, 5), Profile::Core, Fallbacks::All, []) .write_bindings(gl_generator::StaticStructGenerator, &mut file) .unwrap(); } if target.contains("windows") { Registry::new(Api::Egl, (1, 5), Profile::Core, Fallbacks::All, []) .write_bindings(gl_generator::StructGenerator, &mut file) .unwrap(); }; } }
generate_gl_bindings
identifier_name
build.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/. */ extern crate cc; extern crate gl_generator; use gl_generator::{Api, Fallbacks, Profile, Registry}; use std::env; use std::fs::File; use std::path::Path; fn main() { let target = env::var("TARGET").unwrap(); if target.contains("android") { android_main() } generate_gl_bindings(&target); } fn android_main() { // Get the NDK path from NDK_HOME env. let ndk_path =
// compiling android_native_app_glue.c let c_file = ndk_path .join("sources") .join("android") .join("native_app_glue") .join("android_native_app_glue.c"); cc::Build::new() .file(c_file) .warnings(false) .compile("android_native_app_glue"); // Get the output directory. let out_dir = env::var("OUT_DIR").expect("Cargo should have set the OUT_DIR environment variable"); println!("cargo:rustc-link-lib=static=android_native_app_glue"); println!("cargo:rustc-link-search=native={}", out_dir); println!("cargo:rustc-link-lib=log"); println!("cargo:rustc-link-lib=android"); } fn generate_gl_bindings(target: &str) { // For now, we only support EGL, and only on Windows and Android. if target.contains("android") || target.contains("windows") { let dest = env::var("OUT_DIR").unwrap(); let mut file = File::create(&Path::new(&dest).join("egl_bindings.rs")).unwrap(); if target.contains("android") { Registry::new(Api::Egl, (1, 5), Profile::Core, Fallbacks::All, []) .write_bindings(gl_generator::StaticStructGenerator, &mut file) .unwrap(); } if target.contains("windows") { Registry::new(Api::Egl, (1, 5), Profile::Core, Fallbacks::All, []) .write_bindings(gl_generator::StructGenerator, &mut file) .unwrap(); }; } }
env::var_os("ANDROID_NDK").expect("Please set the ANDROID_NDK environment variable"); let ndk_path = Path::new(&ndk_path);
random_line_split
build.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/. */ extern crate cc; extern crate gl_generator; use gl_generator::{Api, Fallbacks, Profile, Registry}; use std::env; use std::fs::File; use std::path::Path; fn main() { let target = env::var("TARGET").unwrap(); if target.contains("android")
generate_gl_bindings(&target); } fn android_main() { // Get the NDK path from NDK_HOME env. let ndk_path = env::var_os("ANDROID_NDK").expect("Please set the ANDROID_NDK environment variable"); let ndk_path = Path::new(&ndk_path); // compiling android_native_app_glue.c let c_file = ndk_path .join("sources") .join("android") .join("native_app_glue") .join("android_native_app_glue.c"); cc::Build::new() .file(c_file) .warnings(false) .compile("android_native_app_glue"); // Get the output directory. let out_dir = env::var("OUT_DIR").expect("Cargo should have set the OUT_DIR environment variable"); println!("cargo:rustc-link-lib=static=android_native_app_glue"); println!("cargo:rustc-link-search=native={}", out_dir); println!("cargo:rustc-link-lib=log"); println!("cargo:rustc-link-lib=android"); } fn generate_gl_bindings(target: &str) { // For now, we only support EGL, and only on Windows and Android. if target.contains("android") || target.contains("windows") { let dest = env::var("OUT_DIR").unwrap(); let mut file = File::create(&Path::new(&dest).join("egl_bindings.rs")).unwrap(); if target.contains("android") { Registry::new(Api::Egl, (1, 5), Profile::Core, Fallbacks::All, []) .write_bindings(gl_generator::StaticStructGenerator, &mut file) .unwrap(); } if target.contains("windows") { Registry::new(Api::Egl, (1, 5), Profile::Core, Fallbacks::All, []) .write_bindings(gl_generator::StructGenerator, &mut file) .unwrap(); }; } }
{ android_main() }
conditional_block
unary-minus-suffix-inference.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. pub fn main() {
println!("{}", a_neg); let b = 1; let b_neg: i16 = -b; println!("{}", b_neg); let c = 1; let c_neg: i32 = -c; println!("{}", c_neg); let d = 1; let d_neg: i64 = -d; println!("{}", d_neg); let e = 1; let e_neg: int = -e; println!("{}", e_neg); // intentional overflows let f = 1; let f_neg: u8 = -f; println!("{}", f_neg); let g = 1; let g_neg: u16 = -g; println!("{}", g_neg); let h = 1; let h_neg: u32 = -h; println!("{}", h_neg); let i = 1; let i_neg: u64 = -i; println!("{}", i_neg); let j = 1; let j_neg: uint = -j; println!("{}", j_neg); }
let a = 1; let a_neg: i8 = -a;
random_line_split
unary-minus-suffix-inference.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. pub fn
() { let a = 1; let a_neg: i8 = -a; println!("{}", a_neg); let b = 1; let b_neg: i16 = -b; println!("{}", b_neg); let c = 1; let c_neg: i32 = -c; println!("{}", c_neg); let d = 1; let d_neg: i64 = -d; println!("{}", d_neg); let e = 1; let e_neg: int = -e; println!("{}", e_neg); // intentional overflows let f = 1; let f_neg: u8 = -f; println!("{}", f_neg); let g = 1; let g_neg: u16 = -g; println!("{}", g_neg); let h = 1; let h_neg: u32 = -h; println!("{}", h_neg); let i = 1; let i_neg: u64 = -i; println!("{}", i_neg); let j = 1; let j_neg: uint = -j; println!("{}", j_neg); }
main
identifier_name
unary-minus-suffix-inference.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. pub fn main()
// intentional overflows let f = 1; let f_neg: u8 = -f; println!("{}", f_neg); let g = 1; let g_neg: u16 = -g; println!("{}", g_neg); let h = 1; let h_neg: u32 = -h; println!("{}", h_neg); let i = 1; let i_neg: u64 = -i; println!("{}", i_neg); let j = 1; let j_neg: uint = -j; println!("{}", j_neg); }
{ let a = 1; let a_neg: i8 = -a; println!("{}", a_neg); let b = 1; let b_neg: i16 = -b; println!("{}", b_neg); let c = 1; let c_neg: i32 = -c; println!("{}", c_neg); let d = 1; let d_neg: i64 = -d; println!("{}", d_neg); let e = 1; let e_neg: int = -e; println!("{}", e_neg);
identifier_body
pipe_windows.rs
atomic::AtomicBool, } impl Inner { fn new(handle: libc::HANDLE) -> Inner { Inner { handle: handle, lock: unsafe { mutex::NativeMutex::new() }, read_closed: atomic::AtomicBool::new(false), write_closed: atomic::AtomicBool::new(false), } } } impl Drop for Inner { fn drop(&mut self) { unsafe { let _ = libc::FlushFileBuffers(self.handle); let _ = libc::CloseHandle(self.handle); } } } unsafe fn pipe(name: *const u16, init: bool) -> libc::HANDLE { libc::CreateNamedPipeW( name, libc::PIPE_ACCESS_DUPLEX | if init {libc::FILE_FLAG_FIRST_PIPE_INSTANCE} else {0} | libc::FILE_FLAG_OVERLAPPED, libc::PIPE_TYPE_BYTE | libc::PIPE_READMODE_BYTE | libc::PIPE_WAIT, libc::PIPE_UNLIMITED_INSTANCES, 65536, 65536, 0, ptr::null_mut() ) } pub fn await(handle: libc::HANDLE, deadline: u64, events: &[libc::HANDLE]) -> IoResult<uint> { use libc::consts::os::extra::{WAIT_FAILED, WAIT_TIMEOUT, WAIT_OBJECT_0}; // If we've got a timeout, use WaitForSingleObject in tandem with CancelIo // to figure out if we should indeed get the result. let ms = if deadline == 0 { libc::INFINITE as u64 } else { let now = ::io::timer::now(); if deadline < now {0} else {deadline - now} }; let ret = unsafe { c::WaitForMultipleObjects(events.len() as libc::DWORD, events.as_ptr(), libc::FALSE, ms as libc::DWORD) }; match ret { WAIT_FAILED => Err(super::last_error()), WAIT_TIMEOUT => unsafe { let _ = c::CancelIo(handle); Err(util::timeout("operation timed out")) }, n => Ok((n - WAIT_OBJECT_0) as uint) } } fn epipe() -> IoError { IoError { code: libc::ERROR_BROKEN_PIPE as uint, extra: 0, detail: None, } } //////////////////////////////////////////////////////////////////////////////// // Unix Streams //////////////////////////////////////////////////////////////////////////////// pub struct UnixStream { inner: Arc<Inner>, write: Option<Event>, read: Option<Event>,
read_deadline: u64, write_deadline: u64, } impl UnixStream { fn try_connect(p: *const u16) -> Option<libc::HANDLE> { // Note that most of this is lifted from the libuv implementation. // The idea is that if we fail to open a pipe in read/write mode // that we try afterwards in just read or just write let mut result = unsafe { libc::CreateFileW(p, libc::GENERIC_READ | libc::GENERIC_WRITE, 0, ptr::null_mut(), libc::OPEN_EXISTING, libc::FILE_FLAG_OVERLAPPED, ptr::null_mut()) }; if result!= libc::INVALID_HANDLE_VALUE { return Some(result) } let err = unsafe { libc::GetLastError() }; if err == libc::ERROR_ACCESS_DENIED as libc::DWORD { result = unsafe { libc::CreateFileW(p, libc::GENERIC_READ | libc::FILE_WRITE_ATTRIBUTES, 0, ptr::null_mut(), libc::OPEN_EXISTING, libc::FILE_FLAG_OVERLAPPED, ptr::null_mut()) }; if result!= libc::INVALID_HANDLE_VALUE { return Some(result) } } let err = unsafe { libc::GetLastError() }; if err == libc::ERROR_ACCESS_DENIED as libc::DWORD { result = unsafe { libc::CreateFileW(p, libc::GENERIC_WRITE | libc::FILE_READ_ATTRIBUTES, 0, ptr::null_mut(), libc::OPEN_EXISTING, libc::FILE_FLAG_OVERLAPPED, ptr::null_mut()) }; if result!= libc::INVALID_HANDLE_VALUE { return Some(result) } } None } pub fn connect(addr: &CString, timeout: Option<u64>) -> IoResult<UnixStream> { let addr = try!(to_utf16(addr)); let start = ::io::timer::now(); loop { match UnixStream::try_connect(addr.as_ptr()) { Some(handle) => { let inner = Inner::new(handle); let mut mode = libc::PIPE_TYPE_BYTE | libc::PIPE_READMODE_BYTE | libc::PIPE_WAIT; let ret = unsafe { libc::SetNamedPipeHandleState(inner.handle, &mut mode, ptr::null_mut(), ptr::null_mut()) }; return if ret == 0 { Err(super::last_error()) } else { Ok(UnixStream { inner: Arc::new(inner), read: None, write: None, read_deadline: 0, write_deadline: 0, }) } } None => {} } // On windows, if you fail to connect, you may need to call the // `WaitNamedPipe` function, and this is indicated with an error // code of ERROR_PIPE_BUSY. let code = unsafe { libc::GetLastError() }; if code as int!= libc::ERROR_PIPE_BUSY as int { return Err(super::last_error()) } match timeout { Some(timeout) => { let now = ::io::timer::now(); let timed_out = (now - start) >= timeout || unsafe { let ms = (timeout - (now - start)) as libc::DWORD; libc::WaitNamedPipeW(addr.as_ptr(), ms) == 0 }; if timed_out { return Err(util::timeout("connect timed out")) } } // An example I found on Microsoft's website used 20 // seconds, libuv uses 30 seconds, hence we make the // obvious choice of waiting for 25 seconds. None => { if unsafe { libc::WaitNamedPipeW(addr.as_ptr(), 25000) } == 0 { return Err(super::last_error()) } } } } } fn handle(&self) -> libc::HANDLE { self.inner.handle } fn read_closed(&self) -> bool { self.inner.read_closed.load(atomic::SeqCst) } fn write_closed(&self) -> bool { self.inner.write_closed.load(atomic::SeqCst) } fn cancel_io(&self) -> IoResult<()> { match unsafe { c::CancelIoEx(self.handle(), ptr::null_mut()) } { 0 if os::errno() == libc::ERROR_NOT_FOUND as uint => { Ok(()) } 0 => Err(super::last_error()), _ => Ok(()) } } } impl rtio::RtioPipe for UnixStream { fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { if self.read.is_none() { self.read = Some(try!(Event::new(true, false))); } let mut bytes_read = 0; let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; overlapped.hEvent = self.read.get_ref().handle(); // Pre-flight check to see if the reading half has been closed. This // must be done before issuing the ReadFile request, but after we // acquire the lock. // // See comments in close_read() about why this lock is necessary. let guard = unsafe { self.inner.lock.lock() }; if self.read_closed() { return Err(util::eof()) } // Issue a nonblocking requests, succeeding quickly if it happened to // succeed. let ret = unsafe { libc::ReadFile(self.handle(), buf.as_ptr() as libc::LPVOID, buf.len() as libc::DWORD, &mut bytes_read, &mut overlapped) }; if ret!= 0 { return Ok(bytes_read as uint) } // If our errno doesn't say that the I/O is pending, then we hit some // legitimate error and return immediately. if os::errno()!= libc::ERROR_IO_PENDING as uint { return Err(super::last_error()) } // Now that we've issued a successful nonblocking request, we need to // wait for it to finish. This can all be done outside the lock because // we'll see any invocation of CancelIoEx. We also call this in a loop // because we're woken up if the writing half is closed, we just need to // realize that the reading half wasn't closed and we go right back to // sleep. drop(guard); loop { // Process a timeout if one is pending let wait_succeeded = await(self.handle(), self.read_deadline, [overlapped.hEvent]); let ret = unsafe { libc::GetOverlappedResult(self.handle(), &mut overlapped, &mut bytes_read, libc::TRUE) }; // If we succeeded, or we failed for some reason other than // CancelIoEx, return immediately if ret!= 0 { return Ok(bytes_read as uint) } if os::errno()!= libc::ERROR_OPERATION_ABORTED as uint { return Err(super::last_error()) } // If the reading half is now closed, then we're done. If we woke up // because the writing half was closed, keep trying. if wait_succeeded.is_err() { return Err(util::timeout("read timed out")) } if self.read_closed() { return Err(util::eof()) } } } fn write(&mut self, buf: &[u8]) -> IoResult<()> { if self.write.is_none() { self.write = Some(try!(Event::new(true, false))); } let mut offset = 0; let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; overlapped.hEvent = self.write.get_ref().handle(); while offset < buf.len() { let mut bytes_written = 0; // This sequence below is quite similar to the one found in read(). // Some careful looping is done to ensure that if close_write() is // invoked we bail out early, and if close_read() is invoked we keep // going after we woke up. // // See comments in close_read() about why this lock is necessary. let guard = unsafe { self.inner.lock.lock() }; if self.write_closed() { return Err(epipe()) } let ret = unsafe { libc::WriteFile(self.handle(), buf.slice_from(offset).as_ptr() as libc::LPVOID, (buf.len() - offset) as libc::DWORD, &mut bytes_written, &mut overlapped) }; let err = os::errno(); drop(guard); if ret == 0 { if err!= libc::ERROR_IO_PENDING as uint { return Err(IoError { code: err as uint, extra: 0, detail: Some(os::error_string(err as uint)), }) } // Process a timeout if one is pending let wait_succeeded = await(self.handle(), self.write_deadline, [overlapped.hEvent]); let ret = unsafe { libc::GetOverlappedResult(self.handle(), &mut overlapped, &mut bytes_written, libc::TRUE) }; // If we weren't aborted, this was a legit error, if we were // aborted, then check to see if the write half was actually // closed or whether we woke up from the read half closing. if ret == 0 { if os::errno()!= libc::ERROR_OPERATION_ABORTED as uint { return Err(super::last_error()) } if!wait_succeeded.is_ok() { let amt = offset + bytes_written as uint; return if amt > 0 { Err(IoError { code: libc::ERROR_OPERATION_ABORTED as uint, extra: amt, detail: Some("short write during write".to_string()), }) } else { Err(util::timeout("write timed out")) } } if self.write_closed() { return Err(epipe()) } continue // retry } } offset += bytes_written as uint; } Ok(()) } fn clone(&self) -> Box<rtio::RtioPipe + Send> { box UnixStream { inner: self.inner.clone(), read: None, write: None, read_deadline: 0, write_deadline: 0, } as Box<rtio::RtioPipe + Send> } fn close_read(&mut self) -> IoResult<()> { // On windows, there's no actual shutdown() method for pipes, so we're // forced to emulate the behavior manually at the application level. To // do this, we need to both cancel any pending requests, as well as // prevent all future requests from succeeding. These two operations are // not atomic with respect to one another, so we must use a lock to do // so. // // The read() code looks like: // // 1. Make sure the pipe is still open // 2. Submit a read request // 3. Wait for the read request to finish // // The race this lock is preventing is if another thread invokes // close_read() between steps 1 and 2. By atomically executing steps 1 // and 2 with a lock with respect to close_read(), we're guaranteed that // no thread will erroneously sit in a read forever. let _guard = unsafe { self.inner.lock.lock() }; self.inner.read_closed.store(true, atomic::SeqCst); self.cancel_io() } fn close_write(&mut self) -> IoResult<()> { // see comments in close_read() for why this lock is necessary let _guard = unsafe { self.inner.lock.lock() }; self.inner.write_closed.store(true, atomic::SeqCst); self.cancel_io() } fn set_timeout(&mut self, timeout: Option<u64>) { let deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); self.read_deadline = deadline; self.write_deadline = deadline; } fn set_read_timeout(&mut self, timeout: Option<u64>) { self.read_deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); } fn set_write_timeout(&mut self, timeout: Option<u64>) {
random_line_split
pipe_windows.rs
} } } } } fn handle(&self) -> libc::HANDLE { self.inner.handle } fn read_closed(&self) -> bool { self.inner.read_closed.load(atomic::SeqCst) } fn write_closed(&self) -> bool { self.inner.write_closed.load(atomic::SeqCst) } fn cancel_io(&self) -> IoResult<()> { match unsafe { c::CancelIoEx(self.handle(), ptr::null_mut()) } { 0 if os::errno() == libc::ERROR_NOT_FOUND as uint => { Ok(()) } 0 => Err(super::last_error()), _ => Ok(()) } } } impl rtio::RtioPipe for UnixStream { fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { if self.read.is_none() { self.read = Some(try!(Event::new(true, false))); } let mut bytes_read = 0; let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; overlapped.hEvent = self.read.get_ref().handle(); // Pre-flight check to see if the reading half has been closed. This // must be done before issuing the ReadFile request, but after we // acquire the lock. // // See comments in close_read() about why this lock is necessary. let guard = unsafe { self.inner.lock.lock() }; if self.read_closed() { return Err(util::eof()) } // Issue a nonblocking requests, succeeding quickly if it happened to // succeed. let ret = unsafe { libc::ReadFile(self.handle(), buf.as_ptr() as libc::LPVOID, buf.len() as libc::DWORD, &mut bytes_read, &mut overlapped) }; if ret!= 0 { return Ok(bytes_read as uint) } // If our errno doesn't say that the I/O is pending, then we hit some // legitimate error and return immediately. if os::errno()!= libc::ERROR_IO_PENDING as uint { return Err(super::last_error()) } // Now that we've issued a successful nonblocking request, we need to // wait for it to finish. This can all be done outside the lock because // we'll see any invocation of CancelIoEx. We also call this in a loop // because we're woken up if the writing half is closed, we just need to // realize that the reading half wasn't closed and we go right back to // sleep. drop(guard); loop { // Process a timeout if one is pending let wait_succeeded = await(self.handle(), self.read_deadline, [overlapped.hEvent]); let ret = unsafe { libc::GetOverlappedResult(self.handle(), &mut overlapped, &mut bytes_read, libc::TRUE) }; // If we succeeded, or we failed for some reason other than // CancelIoEx, return immediately if ret!= 0 { return Ok(bytes_read as uint) } if os::errno()!= libc::ERROR_OPERATION_ABORTED as uint { return Err(super::last_error()) } // If the reading half is now closed, then we're done. If we woke up // because the writing half was closed, keep trying. if wait_succeeded.is_err() { return Err(util::timeout("read timed out")) } if self.read_closed() { return Err(util::eof()) } } } fn write(&mut self, buf: &[u8]) -> IoResult<()> { if self.write.is_none() { self.write = Some(try!(Event::new(true, false))); } let mut offset = 0; let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; overlapped.hEvent = self.write.get_ref().handle(); while offset < buf.len() { let mut bytes_written = 0; // This sequence below is quite similar to the one found in read(). // Some careful looping is done to ensure that if close_write() is // invoked we bail out early, and if close_read() is invoked we keep // going after we woke up. // // See comments in close_read() about why this lock is necessary. let guard = unsafe { self.inner.lock.lock() }; if self.write_closed() { return Err(epipe()) } let ret = unsafe { libc::WriteFile(self.handle(), buf.slice_from(offset).as_ptr() as libc::LPVOID, (buf.len() - offset) as libc::DWORD, &mut bytes_written, &mut overlapped) }; let err = os::errno(); drop(guard); if ret == 0 { if err!= libc::ERROR_IO_PENDING as uint { return Err(IoError { code: err as uint, extra: 0, detail: Some(os::error_string(err as uint)), }) } // Process a timeout if one is pending let wait_succeeded = await(self.handle(), self.write_deadline, [overlapped.hEvent]); let ret = unsafe { libc::GetOverlappedResult(self.handle(), &mut overlapped, &mut bytes_written, libc::TRUE) }; // If we weren't aborted, this was a legit error, if we were // aborted, then check to see if the write half was actually // closed or whether we woke up from the read half closing. if ret == 0 { if os::errno()!= libc::ERROR_OPERATION_ABORTED as uint { return Err(super::last_error()) } if!wait_succeeded.is_ok() { let amt = offset + bytes_written as uint; return if amt > 0 { Err(IoError { code: libc::ERROR_OPERATION_ABORTED as uint, extra: amt, detail: Some("short write during write".to_string()), }) } else { Err(util::timeout("write timed out")) } } if self.write_closed() { return Err(epipe()) } continue // retry } } offset += bytes_written as uint; } Ok(()) } fn clone(&self) -> Box<rtio::RtioPipe + Send> { box UnixStream { inner: self.inner.clone(), read: None, write: None, read_deadline: 0, write_deadline: 0, } as Box<rtio::RtioPipe + Send> } fn close_read(&mut self) -> IoResult<()> { // On windows, there's no actual shutdown() method for pipes, so we're // forced to emulate the behavior manually at the application level. To // do this, we need to both cancel any pending requests, as well as // prevent all future requests from succeeding. These two operations are // not atomic with respect to one another, so we must use a lock to do // so. // // The read() code looks like: // // 1. Make sure the pipe is still open // 2. Submit a read request // 3. Wait for the read request to finish // // The race this lock is preventing is if another thread invokes // close_read() between steps 1 and 2. By atomically executing steps 1 // and 2 with a lock with respect to close_read(), we're guaranteed that // no thread will erroneously sit in a read forever. let _guard = unsafe { self.inner.lock.lock() }; self.inner.read_closed.store(true, atomic::SeqCst); self.cancel_io() } fn close_write(&mut self) -> IoResult<()> { // see comments in close_read() for why this lock is necessary let _guard = unsafe { self.inner.lock.lock() }; self.inner.write_closed.store(true, atomic::SeqCst); self.cancel_io() } fn set_timeout(&mut self, timeout: Option<u64>) { let deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); self.read_deadline = deadline; self.write_deadline = deadline; } fn set_read_timeout(&mut self, timeout: Option<u64>) { self.read_deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); } fn set_write_timeout(&mut self, timeout: Option<u64>) { self.write_deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); } } //////////////////////////////////////////////////////////////////////////////// // Unix Listener //////////////////////////////////////////////////////////////////////////////// pub struct UnixListener { handle: libc::HANDLE, name: CString, } impl UnixListener { pub fn bind(addr: &CString) -> IoResult<UnixListener> { // Although we technically don't need the pipe until much later, we // create the initial handle up front to test the validity of the name // and such. let addr_v = try!(to_utf16(addr)); let ret = unsafe { pipe(addr_v.as_ptr(), true) }; if ret == libc::INVALID_HANDLE_VALUE { Err(super::last_error()) } else { Ok(UnixListener { handle: ret, name: addr.clone() }) } } pub fn native_listen(self) -> IoResult<UnixAcceptor> { Ok(UnixAcceptor { listener: self, event: try!(Event::new(true, false)), deadline: 0, inner: Arc::new(AcceptorState { abort: try!(Event::new(true, false)), closed: atomic::AtomicBool::new(false), }), }) } } impl Drop for UnixListener { fn drop(&mut self) { unsafe { let _ = libc::CloseHandle(self.handle); } } } impl rtio::RtioUnixListener for UnixListener { fn listen(self: Box<UnixListener>) -> IoResult<Box<rtio::RtioUnixAcceptor + Send>> { self.native_listen().map(|a| { box a as Box<rtio::RtioUnixAcceptor + Send> }) } } pub struct UnixAcceptor { inner: Arc<AcceptorState>, listener: UnixListener, event: Event, deadline: u64, } struct AcceptorState { abort: Event, closed: atomic::AtomicBool, } impl UnixAcceptor { pub fn native_accept(&mut self) -> IoResult<UnixStream> { // This function has some funky implementation details when working with // unix pipes. On windows, each server named pipe handle can be // connected to a one or zero clients. To the best of my knowledge, a // named server is considered active and present if there exists at // least one server named pipe for it. // // The model of this function is to take the current known server // handle, connect a client to it, and then transfer ownership to the // UnixStream instance. The next time accept() is invoked, it'll need a // different server handle to connect a client to. // // Note that there is a possible race here. Once our server pipe is // handed off to a `UnixStream` object, the stream could be closed, // meaning that there would be no active server pipes, hence even though // we have a valid `UnixAcceptor`, no one can connect to it. For this // reason, we generate the next accept call's server pipe at the end of // this function call. // // This provides us an invariant that we always have at least one server // connection open at a time, meaning that all connects to this acceptor // should succeed while this is active. // // The actual implementation of doing this is a little tricky. Once a // server pipe is created, a client can connect to it at any time. I // assume that which server a client connects to is nondeterministic, so // we also need to guarantee that the only server able to be connected // to is the one that we're calling ConnectNamedPipe on. This means that // we have to create the second server pipe *after* we've already // accepted a connection. In order to at least somewhat gracefully // handle errors, this means that if the second server pipe creation // fails that we disconnect the connected client and then just keep // using the original server pipe. let handle = self.listener.handle; // If we've had an artificial call to close_accept, be sure to never // proceed in accepting new clients in the future if self.inner.closed.load(atomic::SeqCst) { return Err(util::eof()) } let name = try!(to_utf16(&self.listener.name)); // Once we've got a "server handle", we need to wait for a client to // connect. The ConnectNamedPipe function will block this thread until // someone on the other end connects. This function can "fail" if a // client connects after we created the pipe but before we got down // here. Thanks windows. let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; overlapped.hEvent = self.event.handle(); if unsafe { libc::ConnectNamedPipe(handle, &mut overlapped) == 0 } { let mut err = unsafe { libc::GetLastError() }; if err == libc::ERROR_IO_PENDING as libc::DWORD { // Process a timeout if one is pending let wait_succeeded = await(handle, self.deadline, [self.inner.abort.handle(), overlapped.hEvent]); // This will block until the overlapped I/O is completed. The // timeout was previously handled, so this will either block in // the normal case or succeed very quickly in the timeout case. let ret = unsafe { let mut transfer = 0; libc::GetOverlappedResult(handle, &mut overlapped, &mut transfer, libc::TRUE) }; if ret == 0 { if wait_succeeded.is_ok() { err = unsafe { libc::GetLastError() }; } else { return Err(util::timeout("accept timed out")) } } else { // we succeeded, bypass the check below err = libc::ERROR_PIPE_CONNECTED as libc::DWORD; } } if err!= libc::ERROR_PIPE_CONNECTED as libc::DWORD { return Err(super::last_error()) } } // Now that we've got a connected client to our handle, we need to // create a second server pipe. If this fails, we disconnect the // connected client and return an error (see comments above). let new_handle = unsafe { pipe(name.as_ptr(), false) }; if new_handle == libc::INVALID_HANDLE_VALUE { let ret = Err(super::last_error()); // If our disconnection fails, then there's not really a whole lot // that we can do, so fail the task. let err = unsafe { libc::DisconnectNamedPipe(handle) }; assert!(err!= 0); return ret; } else { self.listener.handle = new_handle; } // Transfer ownership of our handle into this stream Ok(UnixStream { inner: Arc::new(Inner::new(handle)), read: None, write: None, read_deadline: 0, write_deadline: 0, }) } } impl rtio::RtioUnixAcceptor for UnixAcceptor { fn accept(&mut self) -> IoResult<Box<rtio::RtioPipe + Send>> { self.native_accept().map(|s| box s as Box<rtio::RtioPipe + Send>) } fn set_timeout(&mut self, timeout: Option<u64>) { self.deadline = timeout.map(|i| i + ::io::timer::now()).unwrap_or(0); } fn clone(&self) -> Box<rtio::RtioUnixAcceptor + Send> { let name = to_utf16(&self.listener.name).ok().unwrap(); box UnixAcceptor { inner: self.inner.clone(), event: Event::new(true, false).ok().unwrap(), deadline: 0, listener: UnixListener { name: self.listener.name.clone(), handle: unsafe { let p = pipe(name.as_ptr(), false) ; assert!(p!= libc::INVALID_HANDLE_VALUE as libc::HANDLE); p }, }, } as Box<rtio::RtioUnixAcceptor + Send> } fn close_accept(&mut self) -> IoResult<()> { self.inner.closed.store(true, atomic::SeqCst); let ret = unsafe { c::SetEvent(self.inner.abort.handle()) }; if ret == 0
{ Err(super::last_error()) }
conditional_block
pipe_windows.rs
WaitForSingleObject in tandem with CancelIo // to figure out if we should indeed get the result. let ms = if deadline == 0 { libc::INFINITE as u64 } else { let now = ::io::timer::now(); if deadline < now {0} else {deadline - now} }; let ret = unsafe { c::WaitForMultipleObjects(events.len() as libc::DWORD, events.as_ptr(), libc::FALSE, ms as libc::DWORD) }; match ret { WAIT_FAILED => Err(super::last_error()), WAIT_TIMEOUT => unsafe { let _ = c::CancelIo(handle); Err(util::timeout("operation timed out")) }, n => Ok((n - WAIT_OBJECT_0) as uint) } } fn epipe() -> IoError { IoError { code: libc::ERROR_BROKEN_PIPE as uint, extra: 0, detail: None, } } //////////////////////////////////////////////////////////////////////////////// // Unix Streams //////////////////////////////////////////////////////////////////////////////// pub struct UnixStream { inner: Arc<Inner>, write: Option<Event>, read: Option<Event>, read_deadline: u64, write_deadline: u64, } impl UnixStream { fn try_connect(p: *const u16) -> Option<libc::HANDLE> { // Note that most of this is lifted from the libuv implementation. // The idea is that if we fail to open a pipe in read/write mode // that we try afterwards in just read or just write let mut result = unsafe { libc::CreateFileW(p, libc::GENERIC_READ | libc::GENERIC_WRITE, 0, ptr::null_mut(), libc::OPEN_EXISTING, libc::FILE_FLAG_OVERLAPPED, ptr::null_mut()) }; if result!= libc::INVALID_HANDLE_VALUE { return Some(result) } let err = unsafe { libc::GetLastError() }; if err == libc::ERROR_ACCESS_DENIED as libc::DWORD { result = unsafe { libc::CreateFileW(p, libc::GENERIC_READ | libc::FILE_WRITE_ATTRIBUTES, 0, ptr::null_mut(), libc::OPEN_EXISTING, libc::FILE_FLAG_OVERLAPPED, ptr::null_mut()) }; if result!= libc::INVALID_HANDLE_VALUE { return Some(result) } } let err = unsafe { libc::GetLastError() }; if err == libc::ERROR_ACCESS_DENIED as libc::DWORD { result = unsafe { libc::CreateFileW(p, libc::GENERIC_WRITE | libc::FILE_READ_ATTRIBUTES, 0, ptr::null_mut(), libc::OPEN_EXISTING, libc::FILE_FLAG_OVERLAPPED, ptr::null_mut()) }; if result!= libc::INVALID_HANDLE_VALUE { return Some(result) } } None } pub fn connect(addr: &CString, timeout: Option<u64>) -> IoResult<UnixStream> { let addr = try!(to_utf16(addr)); let start = ::io::timer::now(); loop { match UnixStream::try_connect(addr.as_ptr()) { Some(handle) => { let inner = Inner::new(handle); let mut mode = libc::PIPE_TYPE_BYTE | libc::PIPE_READMODE_BYTE | libc::PIPE_WAIT; let ret = unsafe { libc::SetNamedPipeHandleState(inner.handle, &mut mode, ptr::null_mut(), ptr::null_mut()) }; return if ret == 0 { Err(super::last_error()) } else { Ok(UnixStream { inner: Arc::new(inner), read: None, write: None, read_deadline: 0, write_deadline: 0, }) } } None => {} } // On windows, if you fail to connect, you may need to call the // `WaitNamedPipe` function, and this is indicated with an error // code of ERROR_PIPE_BUSY. let code = unsafe { libc::GetLastError() }; if code as int!= libc::ERROR_PIPE_BUSY as int { return Err(super::last_error()) } match timeout { Some(timeout) => { let now = ::io::timer::now(); let timed_out = (now - start) >= timeout || unsafe { let ms = (timeout - (now - start)) as libc::DWORD; libc::WaitNamedPipeW(addr.as_ptr(), ms) == 0 }; if timed_out { return Err(util::timeout("connect timed out")) } } // An example I found on Microsoft's website used 20 // seconds, libuv uses 30 seconds, hence we make the // obvious choice of waiting for 25 seconds. None => { if unsafe { libc::WaitNamedPipeW(addr.as_ptr(), 25000) } == 0 { return Err(super::last_error()) } } } } } fn handle(&self) -> libc::HANDLE { self.inner.handle } fn read_closed(&self) -> bool { self.inner.read_closed.load(atomic::SeqCst) } fn write_closed(&self) -> bool { self.inner.write_closed.load(atomic::SeqCst) } fn cancel_io(&self) -> IoResult<()> { match unsafe { c::CancelIoEx(self.handle(), ptr::null_mut()) } { 0 if os::errno() == libc::ERROR_NOT_FOUND as uint => { Ok(()) } 0 => Err(super::last_error()), _ => Ok(()) } } } impl rtio::RtioPipe for UnixStream { fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { if self.read.is_none() { self.read = Some(try!(Event::new(true, false))); } let mut bytes_read = 0; let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; overlapped.hEvent = self.read.get_ref().handle(); // Pre-flight check to see if the reading half has been closed. This // must be done before issuing the ReadFile request, but after we // acquire the lock. // // See comments in close_read() about why this lock is necessary. let guard = unsafe { self.inner.lock.lock() }; if self.read_closed() { return Err(util::eof()) } // Issue a nonblocking requests, succeeding quickly if it happened to // succeed. let ret = unsafe { libc::ReadFile(self.handle(), buf.as_ptr() as libc::LPVOID, buf.len() as libc::DWORD, &mut bytes_read, &mut overlapped) }; if ret!= 0 { return Ok(bytes_read as uint) } // If our errno doesn't say that the I/O is pending, then we hit some // legitimate error and return immediately. if os::errno()!= libc::ERROR_IO_PENDING as uint { return Err(super::last_error()) } // Now that we've issued a successful nonblocking request, we need to // wait for it to finish. This can all be done outside the lock because // we'll see any invocation of CancelIoEx. We also call this in a loop // because we're woken up if the writing half is closed, we just need to // realize that the reading half wasn't closed and we go right back to // sleep. drop(guard); loop { // Process a timeout if one is pending let wait_succeeded = await(self.handle(), self.read_deadline, [overlapped.hEvent]); let ret = unsafe { libc::GetOverlappedResult(self.handle(), &mut overlapped, &mut bytes_read, libc::TRUE) }; // If we succeeded, or we failed for some reason other than // CancelIoEx, return immediately if ret!= 0 { return Ok(bytes_read as uint) } if os::errno()!= libc::ERROR_OPERATION_ABORTED as uint { return Err(super::last_error()) } // If the reading half is now closed, then we're done. If we woke up // because the writing half was closed, keep trying. if wait_succeeded.is_err() { return Err(util::timeout("read timed out")) } if self.read_closed() { return Err(util::eof()) } } } fn write(&mut self, buf: &[u8]) -> IoResult<()> { if self.write.is_none() { self.write = Some(try!(Event::new(true, false))); } let mut offset = 0; let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; overlapped.hEvent = self.write.get_ref().handle(); while offset < buf.len() { let mut bytes_written = 0; // This sequence below is quite similar to the one found in read(). // Some careful looping is done to ensure that if close_write() is // invoked we bail out early, and if close_read() is invoked we keep // going after we woke up. // // See comments in close_read() about why this lock is necessary. let guard = unsafe { self.inner.lock.lock() }; if self.write_closed() { return Err(epipe()) } let ret = unsafe { libc::WriteFile(self.handle(), buf.slice_from(offset).as_ptr() as libc::LPVOID, (buf.len() - offset) as libc::DWORD, &mut bytes_written, &mut overlapped) }; let err = os::errno(); drop(guard); if ret == 0 { if err!= libc::ERROR_IO_PENDING as uint { return Err(IoError { code: err as uint, extra: 0, detail: Some(os::error_string(err as uint)), }) } // Process a timeout if one is pending let wait_succeeded = await(self.handle(), self.write_deadline, [overlapped.hEvent]); let ret = unsafe { libc::GetOverlappedResult(self.handle(), &mut overlapped, &mut bytes_written, libc::TRUE) }; // If we weren't aborted, this was a legit error, if we were // aborted, then check to see if the write half was actually // closed or whether we woke up from the read half closing. if ret == 0 { if os::errno()!= libc::ERROR_OPERATION_ABORTED as uint { return Err(super::last_error()) } if!wait_succeeded.is_ok() { let amt = offset + bytes_written as uint; return if amt > 0 { Err(IoError { code: libc::ERROR_OPERATION_ABORTED as uint, extra: amt, detail: Some("short write during write".to_string()), }) } else { Err(util::timeout("write timed out")) } } if self.write_closed() { return Err(epipe()) } continue // retry } } offset += bytes_written as uint; } Ok(()) } fn clone(&self) -> Box<rtio::RtioPipe + Send> { box UnixStream { inner: self.inner.clone(), read: None, write: None, read_deadline: 0, write_deadline: 0, } as Box<rtio::RtioPipe + Send> } fn close_read(&mut self) -> IoResult<()> { // On windows, there's no actual shutdown() method for pipes, so we're // forced to emulate the behavior manually at the application level. To // do this, we need to both cancel any pending requests, as well as // prevent all future requests from succeeding. These two operations are // not atomic with respect to one another, so we must use a lock to do // so. // // The read() code looks like: // // 1. Make sure the pipe is still open // 2. Submit a read request // 3. Wait for the read request to finish // // The race this lock is preventing is if another thread invokes // close_read() between steps 1 and 2. By atomically executing steps 1 // and 2 with a lock with respect to close_read(), we're guaranteed that // no thread will erroneously sit in a read forever. let _guard = unsafe { self.inner.lock.lock() }; self.inner.read_closed.store(true, atomic::SeqCst); self.cancel_io() } fn close_write(&mut self) -> IoResult<()> { // see comments in close_read() for why this lock is necessary let _guard = unsafe { self.inner.lock.lock() }; self.inner.write_closed.store(true, atomic::SeqCst); self.cancel_io() } fn set_timeout(&mut self, timeout: Option<u64>) { let deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); self.read_deadline = deadline; self.write_deadline = deadline; } fn set_read_timeout(&mut self, timeout: Option<u64>) { self.read_deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); } fn set_write_timeout(&mut self, timeout: Option<u64>) { self.write_deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); } } //////////////////////////////////////////////////////////////////////////////// // Unix Listener //////////////////////////////////////////////////////////////////////////////// pub struct UnixListener { handle: libc::HANDLE, name: CString, } impl UnixListener { pub fn bind(addr: &CString) -> IoResult<UnixListener> { // Although we technically don't need the pipe until much later, we // create the initial handle up front to test the validity of the name // and such. let addr_v = try!(to_utf16(addr)); let ret = unsafe { pipe(addr_v.as_ptr(), true) }; if ret == libc::INVALID_HANDLE_VALUE { Err(super::last_error()) } else { Ok(UnixListener { handle: ret, name: addr.clone() }) } } pub fn native_listen(self) -> IoResult<UnixAcceptor> { Ok(UnixAcceptor { listener: self, event: try!(Event::new(true, false)), deadline: 0, inner: Arc::new(AcceptorState { abort: try!(Event::new(true, false)), closed: atomic::AtomicBool::new(false), }), }) } } impl Drop for UnixListener { fn drop(&mut self)
{ unsafe { let _ = libc::CloseHandle(self.handle); } }
identifier_body
pipe_windows.rs
::AtomicBool, } impl Inner { fn new(handle: libc::HANDLE) -> Inner { Inner { handle: handle, lock: unsafe { mutex::NativeMutex::new() }, read_closed: atomic::AtomicBool::new(false), write_closed: atomic::AtomicBool::new(false), } } } impl Drop for Inner { fn drop(&mut self) { unsafe { let _ = libc::FlushFileBuffers(self.handle); let _ = libc::CloseHandle(self.handle); } } } unsafe fn pipe(name: *const u16, init: bool) -> libc::HANDLE { libc::CreateNamedPipeW( name, libc::PIPE_ACCESS_DUPLEX | if init {libc::FILE_FLAG_FIRST_PIPE_INSTANCE} else {0} | libc::FILE_FLAG_OVERLAPPED, libc::PIPE_TYPE_BYTE | libc::PIPE_READMODE_BYTE | libc::PIPE_WAIT, libc::PIPE_UNLIMITED_INSTANCES, 65536, 65536, 0, ptr::null_mut() ) } pub fn
(handle: libc::HANDLE, deadline: u64, events: &[libc::HANDLE]) -> IoResult<uint> { use libc::consts::os::extra::{WAIT_FAILED, WAIT_TIMEOUT, WAIT_OBJECT_0}; // If we've got a timeout, use WaitForSingleObject in tandem with CancelIo // to figure out if we should indeed get the result. let ms = if deadline == 0 { libc::INFINITE as u64 } else { let now = ::io::timer::now(); if deadline < now {0} else {deadline - now} }; let ret = unsafe { c::WaitForMultipleObjects(events.len() as libc::DWORD, events.as_ptr(), libc::FALSE, ms as libc::DWORD) }; match ret { WAIT_FAILED => Err(super::last_error()), WAIT_TIMEOUT => unsafe { let _ = c::CancelIo(handle); Err(util::timeout("operation timed out")) }, n => Ok((n - WAIT_OBJECT_0) as uint) } } fn epipe() -> IoError { IoError { code: libc::ERROR_BROKEN_PIPE as uint, extra: 0, detail: None, } } //////////////////////////////////////////////////////////////////////////////// // Unix Streams //////////////////////////////////////////////////////////////////////////////// pub struct UnixStream { inner: Arc<Inner>, write: Option<Event>, read: Option<Event>, read_deadline: u64, write_deadline: u64, } impl UnixStream { fn try_connect(p: *const u16) -> Option<libc::HANDLE> { // Note that most of this is lifted from the libuv implementation. // The idea is that if we fail to open a pipe in read/write mode // that we try afterwards in just read or just write let mut result = unsafe { libc::CreateFileW(p, libc::GENERIC_READ | libc::GENERIC_WRITE, 0, ptr::null_mut(), libc::OPEN_EXISTING, libc::FILE_FLAG_OVERLAPPED, ptr::null_mut()) }; if result!= libc::INVALID_HANDLE_VALUE { return Some(result) } let err = unsafe { libc::GetLastError() }; if err == libc::ERROR_ACCESS_DENIED as libc::DWORD { result = unsafe { libc::CreateFileW(p, libc::GENERIC_READ | libc::FILE_WRITE_ATTRIBUTES, 0, ptr::null_mut(), libc::OPEN_EXISTING, libc::FILE_FLAG_OVERLAPPED, ptr::null_mut()) }; if result!= libc::INVALID_HANDLE_VALUE { return Some(result) } } let err = unsafe { libc::GetLastError() }; if err == libc::ERROR_ACCESS_DENIED as libc::DWORD { result = unsafe { libc::CreateFileW(p, libc::GENERIC_WRITE | libc::FILE_READ_ATTRIBUTES, 0, ptr::null_mut(), libc::OPEN_EXISTING, libc::FILE_FLAG_OVERLAPPED, ptr::null_mut()) }; if result!= libc::INVALID_HANDLE_VALUE { return Some(result) } } None } pub fn connect(addr: &CString, timeout: Option<u64>) -> IoResult<UnixStream> { let addr = try!(to_utf16(addr)); let start = ::io::timer::now(); loop { match UnixStream::try_connect(addr.as_ptr()) { Some(handle) => { let inner = Inner::new(handle); let mut mode = libc::PIPE_TYPE_BYTE | libc::PIPE_READMODE_BYTE | libc::PIPE_WAIT; let ret = unsafe { libc::SetNamedPipeHandleState(inner.handle, &mut mode, ptr::null_mut(), ptr::null_mut()) }; return if ret == 0 { Err(super::last_error()) } else { Ok(UnixStream { inner: Arc::new(inner), read: None, write: None, read_deadline: 0, write_deadline: 0, }) } } None => {} } // On windows, if you fail to connect, you may need to call the // `WaitNamedPipe` function, and this is indicated with an error // code of ERROR_PIPE_BUSY. let code = unsafe { libc::GetLastError() }; if code as int!= libc::ERROR_PIPE_BUSY as int { return Err(super::last_error()) } match timeout { Some(timeout) => { let now = ::io::timer::now(); let timed_out = (now - start) >= timeout || unsafe { let ms = (timeout - (now - start)) as libc::DWORD; libc::WaitNamedPipeW(addr.as_ptr(), ms) == 0 }; if timed_out { return Err(util::timeout("connect timed out")) } } // An example I found on Microsoft's website used 20 // seconds, libuv uses 30 seconds, hence we make the // obvious choice of waiting for 25 seconds. None => { if unsafe { libc::WaitNamedPipeW(addr.as_ptr(), 25000) } == 0 { return Err(super::last_error()) } } } } } fn handle(&self) -> libc::HANDLE { self.inner.handle } fn read_closed(&self) -> bool { self.inner.read_closed.load(atomic::SeqCst) } fn write_closed(&self) -> bool { self.inner.write_closed.load(atomic::SeqCst) } fn cancel_io(&self) -> IoResult<()> { match unsafe { c::CancelIoEx(self.handle(), ptr::null_mut()) } { 0 if os::errno() == libc::ERROR_NOT_FOUND as uint => { Ok(()) } 0 => Err(super::last_error()), _ => Ok(()) } } } impl rtio::RtioPipe for UnixStream { fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { if self.read.is_none() { self.read = Some(try!(Event::new(true, false))); } let mut bytes_read = 0; let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; overlapped.hEvent = self.read.get_ref().handle(); // Pre-flight check to see if the reading half has been closed. This // must be done before issuing the ReadFile request, but after we // acquire the lock. // // See comments in close_read() about why this lock is necessary. let guard = unsafe { self.inner.lock.lock() }; if self.read_closed() { return Err(util::eof()) } // Issue a nonblocking requests, succeeding quickly if it happened to // succeed. let ret = unsafe { libc::ReadFile(self.handle(), buf.as_ptr() as libc::LPVOID, buf.len() as libc::DWORD, &mut bytes_read, &mut overlapped) }; if ret!= 0 { return Ok(bytes_read as uint) } // If our errno doesn't say that the I/O is pending, then we hit some // legitimate error and return immediately. if os::errno()!= libc::ERROR_IO_PENDING as uint { return Err(super::last_error()) } // Now that we've issued a successful nonblocking request, we need to // wait for it to finish. This can all be done outside the lock because // we'll see any invocation of CancelIoEx. We also call this in a loop // because we're woken up if the writing half is closed, we just need to // realize that the reading half wasn't closed and we go right back to // sleep. drop(guard); loop { // Process a timeout if one is pending let wait_succeeded = await(self.handle(), self.read_deadline, [overlapped.hEvent]); let ret = unsafe { libc::GetOverlappedResult(self.handle(), &mut overlapped, &mut bytes_read, libc::TRUE) }; // If we succeeded, or we failed for some reason other than // CancelIoEx, return immediately if ret!= 0 { return Ok(bytes_read as uint) } if os::errno()!= libc::ERROR_OPERATION_ABORTED as uint { return Err(super::last_error()) } // If the reading half is now closed, then we're done. If we woke up // because the writing half was closed, keep trying. if wait_succeeded.is_err() { return Err(util::timeout("read timed out")) } if self.read_closed() { return Err(util::eof()) } } } fn write(&mut self, buf: &[u8]) -> IoResult<()> { if self.write.is_none() { self.write = Some(try!(Event::new(true, false))); } let mut offset = 0; let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; overlapped.hEvent = self.write.get_ref().handle(); while offset < buf.len() { let mut bytes_written = 0; // This sequence below is quite similar to the one found in read(). // Some careful looping is done to ensure that if close_write() is // invoked we bail out early, and if close_read() is invoked we keep // going after we woke up. // // See comments in close_read() about why this lock is necessary. let guard = unsafe { self.inner.lock.lock() }; if self.write_closed() { return Err(epipe()) } let ret = unsafe { libc::WriteFile(self.handle(), buf.slice_from(offset).as_ptr() as libc::LPVOID, (buf.len() - offset) as libc::DWORD, &mut bytes_written, &mut overlapped) }; let err = os::errno(); drop(guard); if ret == 0 { if err!= libc::ERROR_IO_PENDING as uint { return Err(IoError { code: err as uint, extra: 0, detail: Some(os::error_string(err as uint)), }) } // Process a timeout if one is pending let wait_succeeded = await(self.handle(), self.write_deadline, [overlapped.hEvent]); let ret = unsafe { libc::GetOverlappedResult(self.handle(), &mut overlapped, &mut bytes_written, libc::TRUE) }; // If we weren't aborted, this was a legit error, if we were // aborted, then check to see if the write half was actually // closed or whether we woke up from the read half closing. if ret == 0 { if os::errno()!= libc::ERROR_OPERATION_ABORTED as uint { return Err(super::last_error()) } if!wait_succeeded.is_ok() { let amt = offset + bytes_written as uint; return if amt > 0 { Err(IoError { code: libc::ERROR_OPERATION_ABORTED as uint, extra: amt, detail: Some("short write during write".to_string()), }) } else { Err(util::timeout("write timed out")) } } if self.write_closed() { return Err(epipe()) } continue // retry } } offset += bytes_written as uint; } Ok(()) } fn clone(&self) -> Box<rtio::RtioPipe + Send> { box UnixStream { inner: self.inner.clone(), read: None, write: None, read_deadline: 0, write_deadline: 0, } as Box<rtio::RtioPipe + Send> } fn close_read(&mut self) -> IoResult<()> { // On windows, there's no actual shutdown() method for pipes, so we're // forced to emulate the behavior manually at the application level. To // do this, we need to both cancel any pending requests, as well as // prevent all future requests from succeeding. These two operations are // not atomic with respect to one another, so we must use a lock to do // so. // // The read() code looks like: // // 1. Make sure the pipe is still open // 2. Submit a read request // 3. Wait for the read request to finish // // The race this lock is preventing is if another thread invokes // close_read() between steps 1 and 2. By atomically executing steps 1 // and 2 with a lock with respect to close_read(), we're guaranteed that // no thread will erroneously sit in a read forever. let _guard = unsafe { self.inner.lock.lock() }; self.inner.read_closed.store(true, atomic::SeqCst); self.cancel_io() } fn close_write(&mut self) -> IoResult<()> { // see comments in close_read() for why this lock is necessary let _guard = unsafe { self.inner.lock.lock() }; self.inner.write_closed.store(true, atomic::SeqCst); self.cancel_io() } fn set_timeout(&mut self, timeout: Option<u64>) { let deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); self.read_deadline = deadline; self.write_deadline = deadline; } fn set_read_timeout(&mut self, timeout: Option<u64>) { self.read_deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); } fn set_write_timeout(&mut self, timeout: Option<u64>) {
await
identifier_name
read_to_string.rs
use super::read_to_end::read_to_end_internal; use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use futures_io::AsyncRead; use std::pin::Pin; use std::vec::Vec; use std::{io, mem, str}; /// Future for the [`read_to_string`](super::AsyncReadExt::read_to_string) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct ReadToString<'a, R:?Sized> { reader: &'a mut R, buf: &'a mut String, bytes: Vec<u8>, start_len: usize, } impl<R:?Sized + Unpin> Unpin for ReadToString<'_, R> {} impl<'a, R: AsyncRead +?Sized + Unpin> ReadToString<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut String) -> Self { let start_len = buf.len(); Self { reader, bytes: mem::replace(buf, String::new()).into_bytes(), buf, start_len } } } fn
<R: AsyncRead +?Sized>( reader: Pin<&mut R>, cx: &mut Context<'_>, buf: &mut String, bytes: &mut Vec<u8>, start_len: usize, ) -> Poll<io::Result<usize>> { let ret = ready!(read_to_end_internal(reader, cx, bytes, start_len)); if str::from_utf8(bytes).is_err() { Poll::Ready(ret.and_then(|_| { Err(io::Error::new(io::ErrorKind::InvalidData, "stream did not contain valid UTF-8")) })) } else { debug_assert!(buf.is_empty()); // Safety: `bytes` is a valid UTF-8 because `str::from_utf8` returned `Ok`. mem::swap(unsafe { buf.as_mut_vec() }, bytes); Poll::Ready(ret) } } impl<A> Future for ReadToString<'_, A> where A: AsyncRead +?Sized + Unpin, { type Output = io::Result<usize>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let Self { reader, buf, bytes, start_len } = &mut *self; read_to_string_internal(Pin::new(reader), cx, buf, bytes, *start_len) } }
read_to_string_internal
identifier_name
read_to_string.rs
use super::read_to_end::read_to_end_internal; use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use futures_io::AsyncRead; use std::pin::Pin; use std::vec::Vec; use std::{io, mem, str}; /// Future for the [`read_to_string`](super::AsyncReadExt::read_to_string) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct ReadToString<'a, R:?Sized> { reader: &'a mut R, buf: &'a mut String, bytes: Vec<u8>, start_len: usize, } impl<R:?Sized + Unpin> Unpin for ReadToString<'_, R> {} impl<'a, R: AsyncRead +?Sized + Unpin> ReadToString<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut String) -> Self { let start_len = buf.len(); Self { reader, bytes: mem::replace(buf, String::new()).into_bytes(), buf, start_len } } } fn read_to_string_internal<R: AsyncRead +?Sized>( reader: Pin<&mut R>, cx: &mut Context<'_>, buf: &mut String, bytes: &mut Vec<u8>, start_len: usize, ) -> Poll<io::Result<usize>> { let ret = ready!(read_to_end_internal(reader, cx, bytes, start_len)); if str::from_utf8(bytes).is_err()
else { debug_assert!(buf.is_empty()); // Safety: `bytes` is a valid UTF-8 because `str::from_utf8` returned `Ok`. mem::swap(unsafe { buf.as_mut_vec() }, bytes); Poll::Ready(ret) } } impl<A> Future for ReadToString<'_, A> where A: AsyncRead +?Sized + Unpin, { type Output = io::Result<usize>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let Self { reader, buf, bytes, start_len } = &mut *self; read_to_string_internal(Pin::new(reader), cx, buf, bytes, *start_len) } }
{ Poll::Ready(ret.and_then(|_| { Err(io::Error::new(io::ErrorKind::InvalidData, "stream did not contain valid UTF-8")) })) }
conditional_block
read_to_string.rs
use super::read_to_end::read_to_end_internal; use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use futures_io::AsyncRead; use std::pin::Pin; use std::vec::Vec; use std::{io, mem, str}; /// Future for the [`read_to_string`](super::AsyncReadExt::read_to_string) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct ReadToString<'a, R:?Sized> { reader: &'a mut R,
impl<R:?Sized + Unpin> Unpin for ReadToString<'_, R> {} impl<'a, R: AsyncRead +?Sized + Unpin> ReadToString<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut String) -> Self { let start_len = buf.len(); Self { reader, bytes: mem::replace(buf, String::new()).into_bytes(), buf, start_len } } } fn read_to_string_internal<R: AsyncRead +?Sized>( reader: Pin<&mut R>, cx: &mut Context<'_>, buf: &mut String, bytes: &mut Vec<u8>, start_len: usize, ) -> Poll<io::Result<usize>> { let ret = ready!(read_to_end_internal(reader, cx, bytes, start_len)); if str::from_utf8(bytes).is_err() { Poll::Ready(ret.and_then(|_| { Err(io::Error::new(io::ErrorKind::InvalidData, "stream did not contain valid UTF-8")) })) } else { debug_assert!(buf.is_empty()); // Safety: `bytes` is a valid UTF-8 because `str::from_utf8` returned `Ok`. mem::swap(unsafe { buf.as_mut_vec() }, bytes); Poll::Ready(ret) } } impl<A> Future for ReadToString<'_, A> where A: AsyncRead +?Sized + Unpin, { type Output = io::Result<usize>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let Self { reader, buf, bytes, start_len } = &mut *self; read_to_string_internal(Pin::new(reader), cx, buf, bytes, *start_len) } }
buf: &'a mut String, bytes: Vec<u8>, start_len: usize, }
random_line_split
hmac.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * This module implements the Hmac function - a Message Authentication Code using a Digest. */ use std::slice; use digest::Digest; use mac::{Mac, MacResult}; /** * The Hmac struct represents an Hmac function - a Message Authentication Code using a Digest. */ pub struct Hmac<D> { digest: D, i_key: Vec<u8>, o_key: Vec<u8>, finished: bool } fn derive_key(key: &mut [u8], mask: u8) { for elem in key.iter_mut() { *elem ^= mask; } } // The key that Hmac processes must be the same as the block size of the underlying Digest. If the // provided key is smaller than that, we just pad it with zeros. If its larger, we hash it and then // pad it with zeros. fn expand_key<D: Digest>(digest: &mut D, key: &[u8]) -> Vec<u8> { let bs = digest.block_size(); let mut expanded_key = Vec::from_elem(bs, 0u8); if key.len() <= bs { slice::bytes::copy_memory(expanded_key.as_mut_slice(), key); } else { let output_size = digest.output_bytes(); digest.input(key); digest.result(expanded_key.slice_to_mut(output_size)); digest.reset(); } expanded_key } // Hmac uses two keys derived from the provided key - one by xoring every byte with 0x36 and another // with 0x5c. fn create_keys<D: Digest>(digest: &mut D, key: &[u8]) -> (Vec<u8>, Vec<u8>) { let mut i_key = expand_key(digest, key); let mut o_key = i_key.clone(); derive_key(i_key.as_mut_slice(), 0x36); derive_key(o_key.as_mut_slice(), 0x5c); (i_key, o_key) } impl <D: Digest> Hmac<D> { /** * Create a new Hmac instance. * * # Arguments * * digest - The Digest to use. * * key - The key to use. * */ pub fn new(mut digest: D, key: &[u8]) -> Hmac<D> { let (i_key, o_key) = create_keys(&mut digest, key); digest.input(i_key[]); Hmac { digest: digest, i_key: i_key, o_key: o_key, finished: false } } } impl <D: Digest> Mac for Hmac<D> { fn input(&mut self, data: &[u8]) { assert!(!self.finished); self.digest.input(data); } fn reset(&mut self) { self.digest.reset(); self.digest.input(self.i_key[]); self.finished = false; } fn result(&mut self) -> MacResult { let output_size = self.digest.output_bytes(); let mut code = Vec::from_elem(output_size, 0u8); self.raw_result(code.as_mut_slice()); MacResult::new_from_owned(code) } fn raw_result(&mut self, output: &mut [u8]) { if!self.finished { self.digest.result(output); self.digest.reset(); self.digest.input(self.o_key[]); self.digest.input(output); self.finished = true; } self.digest.result(output); } fn output_bytes(&self) -> uint { self.digest.output_bytes() } } #[cfg(test)] mod test { use mac::{Mac, MacResult}; use hmac::Hmac; use digest::Digest; use md5::Md5; struct Test { key: Vec<u8>, data: Vec<u8>, expected: Vec<u8> } // Test vectors from: http://tools.ietf.org/html/rfc2104 fn tests() -> Vec<Test> { vec![ Test { key: Vec::from_elem(16, 0x0bu8), data: b"Hi There".to_vec(), expected: vec![ 0x92, 0x94, 0x72, 0x7a, 0x36, 0x38, 0xbb, 0x1c, 0x13, 0xf4, 0x8e, 0xf8, 0x15, 0x8b, 0xfc, 0x9d ] }, Test { key: b"Jefe".to_vec(), data: b"what do ya want for nothing?".to_vec(), expected: vec![ 0x75, 0x0c, 0x78, 0x3e, 0x6a, 0xb0, 0xb5, 0x03, 0xea, 0xa8, 0x6e, 0x31, 0x0a, 0x5d, 0xb7, 0x38 ] }, Test { key: Vec::from_elem(16, 0xaau8), data: Vec::from_elem(50, 0xddu8), expected: vec![ 0x56, 0xbe, 0x34, 0x52, 0x1d, 0x14, 0x4c, 0x88, 0xdb, 0xb8, 0xc7, 0x33, 0xf0, 0xe8, 0xb3, 0xf6 ] } ] } #[test] fn test_hmac_md5() { let tests = tests(); for t in tests.iter() { let mut hmac = Hmac::new(Md5::new(), t.key[]); hmac.input(t.data[]); let result = hmac.result(); let expected = MacResult::new(t.expected[]); assert!(result == expected); hmac.reset(); hmac.input(t.data[]); let result2 = hmac.result(); let expected2 = MacResult::new(t.expected[]); assert!(result2 == expected2); } } #[test] fn test_hmac_md5_incremental()
}
{ let tests = tests(); for t in tests.iter() { let mut hmac = Hmac::new(Md5::new(), t.key[]); for i in range(0, t.data.len()) { hmac.input(t.data.slice(i, i + 1)); } let result = hmac.result(); let expected = MacResult::new(t.expected[]); assert!(result == expected); } }
identifier_body
hmac.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * This module implements the Hmac function - a Message Authentication Code using a Digest. */ use std::slice; use digest::Digest; use mac::{Mac, MacResult}; /** * The Hmac struct represents an Hmac function - a Message Authentication Code using a Digest. */ pub struct Hmac<D> { digest: D, i_key: Vec<u8>, o_key: Vec<u8>, finished: bool } fn derive_key(key: &mut [u8], mask: u8) { for elem in key.iter_mut() { *elem ^= mask; } } // The key that Hmac processes must be the same as the block size of the underlying Digest. If the // provided key is smaller than that, we just pad it with zeros. If its larger, we hash it and then // pad it with zeros. fn expand_key<D: Digest>(digest: &mut D, key: &[u8]) -> Vec<u8> { let bs = digest.block_size(); let mut expanded_key = Vec::from_elem(bs, 0u8); if key.len() <= bs { slice::bytes::copy_memory(expanded_key.as_mut_slice(), key); } else
expanded_key } // Hmac uses two keys derived from the provided key - one by xoring every byte with 0x36 and another // with 0x5c. fn create_keys<D: Digest>(digest: &mut D, key: &[u8]) -> (Vec<u8>, Vec<u8>) { let mut i_key = expand_key(digest, key); let mut o_key = i_key.clone(); derive_key(i_key.as_mut_slice(), 0x36); derive_key(o_key.as_mut_slice(), 0x5c); (i_key, o_key) } impl <D: Digest> Hmac<D> { /** * Create a new Hmac instance. * * # Arguments * * digest - The Digest to use. * * key - The key to use. * */ pub fn new(mut digest: D, key: &[u8]) -> Hmac<D> { let (i_key, o_key) = create_keys(&mut digest, key); digest.input(i_key[]); Hmac { digest: digest, i_key: i_key, o_key: o_key, finished: false } } } impl <D: Digest> Mac for Hmac<D> { fn input(&mut self, data: &[u8]) { assert!(!self.finished); self.digest.input(data); } fn reset(&mut self) { self.digest.reset(); self.digest.input(self.i_key[]); self.finished = false; } fn result(&mut self) -> MacResult { let output_size = self.digest.output_bytes(); let mut code = Vec::from_elem(output_size, 0u8); self.raw_result(code.as_mut_slice()); MacResult::new_from_owned(code) } fn raw_result(&mut self, output: &mut [u8]) { if!self.finished { self.digest.result(output); self.digest.reset(); self.digest.input(self.o_key[]); self.digest.input(output); self.finished = true; } self.digest.result(output); } fn output_bytes(&self) -> uint { self.digest.output_bytes() } } #[cfg(test)] mod test { use mac::{Mac, MacResult}; use hmac::Hmac; use digest::Digest; use md5::Md5; struct Test { key: Vec<u8>, data: Vec<u8>, expected: Vec<u8> } // Test vectors from: http://tools.ietf.org/html/rfc2104 fn tests() -> Vec<Test> { vec![ Test { key: Vec::from_elem(16, 0x0bu8), data: b"Hi There".to_vec(), expected: vec![ 0x92, 0x94, 0x72, 0x7a, 0x36, 0x38, 0xbb, 0x1c, 0x13, 0xf4, 0x8e, 0xf8, 0x15, 0x8b, 0xfc, 0x9d ] }, Test { key: b"Jefe".to_vec(), data: b"what do ya want for nothing?".to_vec(), expected: vec![ 0x75, 0x0c, 0x78, 0x3e, 0x6a, 0xb0, 0xb5, 0x03, 0xea, 0xa8, 0x6e, 0x31, 0x0a, 0x5d, 0xb7, 0x38 ] }, Test { key: Vec::from_elem(16, 0xaau8), data: Vec::from_elem(50, 0xddu8), expected: vec![ 0x56, 0xbe, 0x34, 0x52, 0x1d, 0x14, 0x4c, 0x88, 0xdb, 0xb8, 0xc7, 0x33, 0xf0, 0xe8, 0xb3, 0xf6 ] } ] } #[test] fn test_hmac_md5() { let tests = tests(); for t in tests.iter() { let mut hmac = Hmac::new(Md5::new(), t.key[]); hmac.input(t.data[]); let result = hmac.result(); let expected = MacResult::new(t.expected[]); assert!(result == expected); hmac.reset(); hmac.input(t.data[]); let result2 = hmac.result(); let expected2 = MacResult::new(t.expected[]); assert!(result2 == expected2); } } #[test] fn test_hmac_md5_incremental() { let tests = tests(); for t in tests.iter() { let mut hmac = Hmac::new(Md5::new(), t.key[]); for i in range(0, t.data.len()) { hmac.input(t.data.slice(i, i + 1)); } let result = hmac.result(); let expected = MacResult::new(t.expected[]); assert!(result == expected); } } }
{ let output_size = digest.output_bytes(); digest.input(key); digest.result(expanded_key.slice_to_mut(output_size)); digest.reset(); }
conditional_block
hmac.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * This module implements the Hmac function - a Message Authentication Code using a Digest. */ use std::slice; use digest::Digest; use mac::{Mac, MacResult}; /** * The Hmac struct represents an Hmac function - a Message Authentication Code using a Digest. */ pub struct Hmac<D> { digest: D, i_key: Vec<u8>, o_key: Vec<u8>, finished: bool } fn derive_key(key: &mut [u8], mask: u8) { for elem in key.iter_mut() { *elem ^= mask; } } // The key that Hmac processes must be the same as the block size of the underlying Digest. If the // provided key is smaller than that, we just pad it with zeros. If its larger, we hash it and then // pad it with zeros. fn
<D: Digest>(digest: &mut D, key: &[u8]) -> Vec<u8> { let bs = digest.block_size(); let mut expanded_key = Vec::from_elem(bs, 0u8); if key.len() <= bs { slice::bytes::copy_memory(expanded_key.as_mut_slice(), key); } else { let output_size = digest.output_bytes(); digest.input(key); digest.result(expanded_key.slice_to_mut(output_size)); digest.reset(); } expanded_key } // Hmac uses two keys derived from the provided key - one by xoring every byte with 0x36 and another // with 0x5c. fn create_keys<D: Digest>(digest: &mut D, key: &[u8]) -> (Vec<u8>, Vec<u8>) { let mut i_key = expand_key(digest, key); let mut o_key = i_key.clone(); derive_key(i_key.as_mut_slice(), 0x36); derive_key(o_key.as_mut_slice(), 0x5c); (i_key, o_key) } impl <D: Digest> Hmac<D> { /** * Create a new Hmac instance. * * # Arguments * * digest - The Digest to use. * * key - The key to use. * */ pub fn new(mut digest: D, key: &[u8]) -> Hmac<D> { let (i_key, o_key) = create_keys(&mut digest, key); digest.input(i_key[]); Hmac { digest: digest, i_key: i_key, o_key: o_key, finished: false } } } impl <D: Digest> Mac for Hmac<D> { fn input(&mut self, data: &[u8]) { assert!(!self.finished); self.digest.input(data); } fn reset(&mut self) { self.digest.reset(); self.digest.input(self.i_key[]); self.finished = false; } fn result(&mut self) -> MacResult { let output_size = self.digest.output_bytes(); let mut code = Vec::from_elem(output_size, 0u8); self.raw_result(code.as_mut_slice()); MacResult::new_from_owned(code) } fn raw_result(&mut self, output: &mut [u8]) { if!self.finished { self.digest.result(output); self.digest.reset(); self.digest.input(self.o_key[]); self.digest.input(output); self.finished = true; } self.digest.result(output); } fn output_bytes(&self) -> uint { self.digest.output_bytes() } } #[cfg(test)] mod test { use mac::{Mac, MacResult}; use hmac::Hmac; use digest::Digest; use md5::Md5; struct Test { key: Vec<u8>, data: Vec<u8>, expected: Vec<u8> } // Test vectors from: http://tools.ietf.org/html/rfc2104 fn tests() -> Vec<Test> { vec![ Test { key: Vec::from_elem(16, 0x0bu8), data: b"Hi There".to_vec(), expected: vec![ 0x92, 0x94, 0x72, 0x7a, 0x36, 0x38, 0xbb, 0x1c, 0x13, 0xf4, 0x8e, 0xf8, 0x15, 0x8b, 0xfc, 0x9d ] }, Test { key: b"Jefe".to_vec(), data: b"what do ya want for nothing?".to_vec(), expected: vec![ 0x75, 0x0c, 0x78, 0x3e, 0x6a, 0xb0, 0xb5, 0x03, 0xea, 0xa8, 0x6e, 0x31, 0x0a, 0x5d, 0xb7, 0x38 ] }, Test { key: Vec::from_elem(16, 0xaau8), data: Vec::from_elem(50, 0xddu8), expected: vec![ 0x56, 0xbe, 0x34, 0x52, 0x1d, 0x14, 0x4c, 0x88, 0xdb, 0xb8, 0xc7, 0x33, 0xf0, 0xe8, 0xb3, 0xf6 ] } ] } #[test] fn test_hmac_md5() { let tests = tests(); for t in tests.iter() { let mut hmac = Hmac::new(Md5::new(), t.key[]); hmac.input(t.data[]); let result = hmac.result(); let expected = MacResult::new(t.expected[]); assert!(result == expected); hmac.reset(); hmac.input(t.data[]); let result2 = hmac.result(); let expected2 = MacResult::new(t.expected[]); assert!(result2 == expected2); } } #[test] fn test_hmac_md5_incremental() { let tests = tests(); for t in tests.iter() { let mut hmac = Hmac::new(Md5::new(), t.key[]); for i in range(0, t.data.len()) { hmac.input(t.data.slice(i, i + 1)); } let result = hmac.result(); let expected = MacResult::new(t.expected[]); assert!(result == expected); } } }
expand_key
identifier_name
hmac.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * This module implements the Hmac function - a Message Authentication Code using a Digest. */ use std::slice; use digest::Digest; use mac::{Mac, MacResult}; /** * The Hmac struct represents an Hmac function - a Message Authentication Code using a Digest. */ pub struct Hmac<D> { digest: D, i_key: Vec<u8>, o_key: Vec<u8>, finished: bool } fn derive_key(key: &mut [u8], mask: u8) { for elem in key.iter_mut() { *elem ^= mask; } } // The key that Hmac processes must be the same as the block size of the underlying Digest. If the // provided key is smaller than that, we just pad it with zeros. If its larger, we hash it and then // pad it with zeros. fn expand_key<D: Digest>(digest: &mut D, key: &[u8]) -> Vec<u8> { let bs = digest.block_size(); let mut expanded_key = Vec::from_elem(bs, 0u8); if key.len() <= bs { slice::bytes::copy_memory(expanded_key.as_mut_slice(), key); } else { let output_size = digest.output_bytes(); digest.input(key); digest.result(expanded_key.slice_to_mut(output_size)); digest.reset(); } expanded_key } // Hmac uses two keys derived from the provided key - one by xoring every byte with 0x36 and another // with 0x5c. fn create_keys<D: Digest>(digest: &mut D, key: &[u8]) -> (Vec<u8>, Vec<u8>) { let mut i_key = expand_key(digest, key); let mut o_key = i_key.clone(); derive_key(i_key.as_mut_slice(), 0x36); derive_key(o_key.as_mut_slice(), 0x5c); (i_key, o_key) } impl <D: Digest> Hmac<D> { /** * Create a new Hmac instance. * * # Arguments * * digest - The Digest to use. * * key - The key to use. * */ pub fn new(mut digest: D, key: &[u8]) -> Hmac<D> { let (i_key, o_key) = create_keys(&mut digest, key); digest.input(i_key[]); Hmac { digest: digest, i_key: i_key, o_key: o_key, finished: false } } } impl <D: Digest> Mac for Hmac<D> { fn input(&mut self, data: &[u8]) { assert!(!self.finished); self.digest.input(data); } fn reset(&mut self) { self.digest.reset(); self.digest.input(self.i_key[]); self.finished = false; } fn result(&mut self) -> MacResult { let output_size = self.digest.output_bytes(); let mut code = Vec::from_elem(output_size, 0u8); self.raw_result(code.as_mut_slice()); MacResult::new_from_owned(code) } fn raw_result(&mut self, output: &mut [u8]) { if!self.finished { self.digest.result(output); self.digest.reset(); self.digest.input(self.o_key[]); self.digest.input(output); self.finished = true; } self.digest.result(output); } fn output_bytes(&self) -> uint { self.digest.output_bytes() } } #[cfg(test)] mod test { use mac::{Mac, MacResult}; use hmac::Hmac; use digest::Digest; use md5::Md5; struct Test { key: Vec<u8>, data: Vec<u8>, expected: Vec<u8> } // Test vectors from: http://tools.ietf.org/html/rfc2104 fn tests() -> Vec<Test> { vec![ Test { key: Vec::from_elem(16, 0x0bu8), data: b"Hi There".to_vec(), expected: vec![ 0x92, 0x94, 0x72, 0x7a, 0x36, 0x38, 0xbb, 0x1c, 0x13, 0xf4, 0x8e, 0xf8, 0x15, 0x8b, 0xfc, 0x9d ] }, Test { key: b"Jefe".to_vec(), data: b"what do ya want for nothing?".to_vec(), expected: vec![ 0x75, 0x0c, 0x78, 0x3e, 0x6a, 0xb0, 0xb5, 0x03, 0xea, 0xa8, 0x6e, 0x31, 0x0a, 0x5d, 0xb7, 0x38 ] }, Test { key: Vec::from_elem(16, 0xaau8), data: Vec::from_elem(50, 0xddu8), expected: vec![ 0x56, 0xbe, 0x34, 0x52, 0x1d, 0x14, 0x4c, 0x88, 0xdb, 0xb8, 0xc7, 0x33, 0xf0, 0xe8, 0xb3, 0xf6 ] } ] } #[test] fn test_hmac_md5() { let tests = tests(); for t in tests.iter() { let mut hmac = Hmac::new(Md5::new(), t.key[]); hmac.input(t.data[]); let result = hmac.result(); let expected = MacResult::new(t.expected[]); assert!(result == expected); hmac.reset(); hmac.input(t.data[]); let result2 = hmac.result(); let expected2 = MacResult::new(t.expected[]); assert!(result2 == expected2); } } #[test]
fn test_hmac_md5_incremental() { let tests = tests(); for t in tests.iter() { let mut hmac = Hmac::new(Md5::new(), t.key[]); for i in range(0, t.data.len()) { hmac.input(t.data.slice(i, i + 1)); } let result = hmac.result(); let expected = MacResult::new(t.expected[]); assert!(result == expected); } } }
random_line_split
tls-try-with.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(stable_features)] // ignore-emscripten no threads support #![feature(thread_local_try_with)] use std::thread; static mut DROP_RUN: bool = false; struct Foo; thread_local!(static FOO: Foo = Foo {}); impl Drop for Foo { fn drop(&mut self) { assert!(FOO.try_with(|_| panic!("`try_with` closure run")).is_err()); unsafe { DROP_RUN = true; } } } fn main()
{ thread::spawn(|| { assert_eq!(FOO.try_with(|_| { 132 }).expect("`try_with` failed"), 132); }).join().unwrap(); assert!(unsafe { DROP_RUN }); }
identifier_body
tls-try-with.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(stable_features)] // ignore-emscripten no threads support
static mut DROP_RUN: bool = false; struct Foo; thread_local!(static FOO: Foo = Foo {}); impl Drop for Foo { fn drop(&mut self) { assert!(FOO.try_with(|_| panic!("`try_with` closure run")).is_err()); unsafe { DROP_RUN = true; } } } fn main() { thread::spawn(|| { assert_eq!(FOO.try_with(|_| { 132 }).expect("`try_with` failed"), 132); }).join().unwrap(); assert!(unsafe { DROP_RUN }); }
#![feature(thread_local_try_with)] use std::thread;
random_line_split
tls-try-with.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(stable_features)] // ignore-emscripten no threads support #![feature(thread_local_try_with)] use std::thread; static mut DROP_RUN: bool = false; struct Foo; thread_local!(static FOO: Foo = Foo {}); impl Drop for Foo { fn
(&mut self) { assert!(FOO.try_with(|_| panic!("`try_with` closure run")).is_err()); unsafe { DROP_RUN = true; } } } fn main() { thread::spawn(|| { assert_eq!(FOO.try_with(|_| { 132 }).expect("`try_with` failed"), 132); }).join().unwrap(); assert!(unsafe { DROP_RUN }); }
drop
identifier_name
metrics_flusher.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use std::io; use std::result::Result; use std::sync::mpsc::{self, Sender}; use std::thread::{Builder as ThreadBuilder, JoinHandle}; use std::time::{Duration, Instant}; use file_system::flush_io_metrics; use crate::engine::KvEngine; use crate::engines::Engines; use crate::raft_engine::RaftEngine; const DEFAULT_FLUSH_INTERVAL: Duration = Duration::from_millis(10_000); const FLUSHER_RESET_INTERVAL: Duration = Duration::from_millis(60_000); pub struct MetricsFlusher<K: KvEngine, R: RaftEngine> { pub engines: Engines<K, R>, interval: Duration, handle: Option<JoinHandle<()>>, sender: Option<Sender<bool>>, } impl<K: KvEngine, R: RaftEngine> MetricsFlusher<K, R> { pub fn new(engines: Engines<K, R>) -> Self { MetricsFlusher { engines, interval: DEFAULT_FLUSH_INTERVAL, handle: None, sender: None, } } pub fn set_flush_interval(&mut self, interval: Duration) { self.interval = interval; } pub fn start(&mut self) -> Result<(), io::Error> { let (kv_db, raft_db) = (self.engines.kv.clone(), self.engines.raft.clone()); let interval = self.interval; let (tx, rx) = mpsc::channel(); self.sender = Some(tx); let h = ThreadBuilder::new() .name("metrics-flusher".to_owned()) .spawn(move || { tikv_alloc::add_thread_memory_accessor(); let mut last_reset = Instant::now(); while let Err(mpsc::RecvTimeoutError::Timeout) = rx.recv_timeout(interval) { kv_db.flush_metrics("kv"); raft_db.flush_metrics("raft"); flush_io_metrics(); // TODO: better flush it in io limiter if last_reset.elapsed() >= FLUSHER_RESET_INTERVAL { kv_db.reset_statistics(); raft_db.reset_statistics(); last_reset = Instant::now(); } } tikv_alloc::remove_thread_memory_accessor(); })?; self.handle = Some(h); Ok(()) } pub fn stop(&mut self) { let h = self.handle.take(); if h.is_none() { return; } drop(self.sender.take().unwrap()); if let Err(e) = h.unwrap().join()
} }
{ error!("join metrics flusher failed"; "err" => ?e); return; }
conditional_block
metrics_flusher.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use std::io; use std::result::Result; use std::sync::mpsc::{self, Sender}; use std::thread::{Builder as ThreadBuilder, JoinHandle}; use std::time::{Duration, Instant}; use file_system::flush_io_metrics; use crate::engine::KvEngine; use crate::engines::Engines; use crate::raft_engine::RaftEngine; const DEFAULT_FLUSH_INTERVAL: Duration = Duration::from_millis(10_000); const FLUSHER_RESET_INTERVAL: Duration = Duration::from_millis(60_000); pub struct
<K: KvEngine, R: RaftEngine> { pub engines: Engines<K, R>, interval: Duration, handle: Option<JoinHandle<()>>, sender: Option<Sender<bool>>, } impl<K: KvEngine, R: RaftEngine> MetricsFlusher<K, R> { pub fn new(engines: Engines<K, R>) -> Self { MetricsFlusher { engines, interval: DEFAULT_FLUSH_INTERVAL, handle: None, sender: None, } } pub fn set_flush_interval(&mut self, interval: Duration) { self.interval = interval; } pub fn start(&mut self) -> Result<(), io::Error> { let (kv_db, raft_db) = (self.engines.kv.clone(), self.engines.raft.clone()); let interval = self.interval; let (tx, rx) = mpsc::channel(); self.sender = Some(tx); let h = ThreadBuilder::new() .name("metrics-flusher".to_owned()) .spawn(move || { tikv_alloc::add_thread_memory_accessor(); let mut last_reset = Instant::now(); while let Err(mpsc::RecvTimeoutError::Timeout) = rx.recv_timeout(interval) { kv_db.flush_metrics("kv"); raft_db.flush_metrics("raft"); flush_io_metrics(); // TODO: better flush it in io limiter if last_reset.elapsed() >= FLUSHER_RESET_INTERVAL { kv_db.reset_statistics(); raft_db.reset_statistics(); last_reset = Instant::now(); } } tikv_alloc::remove_thread_memory_accessor(); })?; self.handle = Some(h); Ok(()) } pub fn stop(&mut self) { let h = self.handle.take(); if h.is_none() { return; } drop(self.sender.take().unwrap()); if let Err(e) = h.unwrap().join() { error!("join metrics flusher failed"; "err" =>?e); return; } } }
MetricsFlusher
identifier_name
metrics_flusher.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use std::io; use std::result::Result; use std::sync::mpsc::{self, Sender}; use std::thread::{Builder as ThreadBuilder, JoinHandle}; use std::time::{Duration, Instant}; use file_system::flush_io_metrics; use crate::engine::KvEngine; use crate::engines::Engines; use crate::raft_engine::RaftEngine; const DEFAULT_FLUSH_INTERVAL: Duration = Duration::from_millis(10_000); const FLUSHER_RESET_INTERVAL: Duration = Duration::from_millis(60_000); pub struct MetricsFlusher<K: KvEngine, R: RaftEngine> { pub engines: Engines<K, R>, interval: Duration, handle: Option<JoinHandle<()>>, sender: Option<Sender<bool>>, } impl<K: KvEngine, R: RaftEngine> MetricsFlusher<K, R> { pub fn new(engines: Engines<K, R>) -> Self { MetricsFlusher { engines, interval: DEFAULT_FLUSH_INTERVAL, handle: None, sender: None, } } pub fn set_flush_interval(&mut self, interval: Duration) { self.interval = interval; } pub fn start(&mut self) -> Result<(), io::Error> { let (kv_db, raft_db) = (self.engines.kv.clone(), self.engines.raft.clone()); let interval = self.interval; let (tx, rx) = mpsc::channel(); self.sender = Some(tx); let h = ThreadBuilder::new() .name("metrics-flusher".to_owned()) .spawn(move || { tikv_alloc::add_thread_memory_accessor(); let mut last_reset = Instant::now(); while let Err(mpsc::RecvTimeoutError::Timeout) = rx.recv_timeout(interval) { kv_db.flush_metrics("kv"); raft_db.flush_metrics("raft"); flush_io_metrics(); // TODO: better flush it in io limiter if last_reset.elapsed() >= FLUSHER_RESET_INTERVAL { kv_db.reset_statistics(); raft_db.reset_statistics(); last_reset = Instant::now(); } } tikv_alloc::remove_thread_memory_accessor(); })?; self.handle = Some(h); Ok(()) } pub fn stop(&mut self) { let h = self.handle.take();
return; } drop(self.sender.take().unwrap()); if let Err(e) = h.unwrap().join() { error!("join metrics flusher failed"; "err" =>?e); return; } } }
if h.is_none() {
random_line_split
chacha.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. //! The ChaCha random number generator. use core::prelude::*; use core::num::Int; use {Rng, SeedableRng, Rand}; const KEY_WORDS : uint = 8; // 8 words for the 256-bit key const STATE_WORDS : uint = 16; const CHACHA_ROUNDS: uint = 20; // Cryptographically secure from 8 upwards as of this writing /// A random number generator that uses the ChaCha20 algorithm [1]. /// /// The ChaCha algorithm is widely accepted as suitable for /// cryptographic purposes, but this implementation has not been /// verified as such. Prefer a generator like `OsRng` that defers to /// the operating system for cases that need high security. /// /// [1]: D. J. Bernstein, [*ChaCha, a variant of /// Salsa20*](http://cr.yp.to/chacha.html) #[derive(Copy, Clone)] pub struct ChaChaRng { buffer: [u32; STATE_WORDS], // Internal buffer of output state: [u32; STATE_WORDS], // Initial state index: uint, // Index into state } static EMPTY: ChaChaRng = ChaChaRng { buffer: [0; STATE_WORDS], state: [0; STATE_WORDS], index: STATE_WORDS }; macro_rules! quarter_round{ ($a: expr, $b: expr, $c: expr, $d: expr) => {{ $a += $b; $d ^= $a; $d = $d.rotate_left(16); $c += $d; $b ^= $c; $b = $b.rotate_left(12); $a += $b; $d ^= $a; $d = $d.rotate_left( 8); $c += $d; $b ^= $c; $b = $b.rotate_left( 7); }} } macro_rules! double_round{ ($x: expr) => {{ // Column round quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]); quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]); quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]); quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]); // Diagonal round quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]); quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]); quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]); quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]); }} } #[inline] fn core(output: &mut [u32; STATE_WORDS], input: &[u32; STATE_WORDS]) { *output = *input; for _ in 0..CHACHA_ROUNDS / 2 { double_round!(output); } for i in 0..STATE_WORDS { output[i] += input[i]; } } impl ChaChaRng { /// Create an ChaCha random number generator using the default /// fixed key of 8 zero words. pub fn new_unseeded() -> ChaChaRng { let mut rng = EMPTY; rng.init(&[0; KEY_WORDS]); rng } /// Sets the internal 128-bit ChaCha counter to /// a user-provided value. This permits jumping /// arbitrarily ahead (or backwards) in the pseudorandom stream. /// /// Since the nonce words are used to extend the counter to 128 bits, /// users wishing to obtain the conventional ChaCha pseudorandom stream /// associated with a particular nonce can call this function with /// arguments `0, desired_nonce`. pub fn set_counter(&mut self, counter_low: u64, counter_high: u64) { self.state[12] = (counter_low >> 0) as u32; self.state[13] = (counter_low >> 32) as u32; self.state[14] = (counter_high >> 0) as u32; self.state[15] = (counter_high >> 32) as u32; self.index = STATE_WORDS; // force recomputation } /// Initializes `self.state` with the appropriate key and constants /// /// We deviate slightly from the ChaCha specification regarding /// the nonce, which is used to extend the counter to 128 bits. /// This is provably as strong as the original cipher, though, /// since any distinguishing attack on our variant also works /// against ChaCha with a chosen-nonce. See the XSalsa20 [1] /// security proof for a more involved example of this. /// /// The modified word layout is: /// ```text /// constant constant constant constant /// key key key key /// key key key key /// counter counter counter counter /// ``` /// [1]: Daniel J. Bernstein. [*Extending the Salsa20 /// nonce.*](http://cr.yp.to/papers.html#xsalsa) fn init(&mut self, key: &[u32; KEY_WORDS]) { self.state[0] = 0x61707865; self.state[1] = 0x3320646E; self.state[2] = 0x79622D32; self.state[3] = 0x6B206574; for i in 0..KEY_WORDS { self.state[4+i] = key[i]; } self.state[12] = 0; self.state[13] = 0; self.state[14] = 0; self.state[15] = 0; self.index = STATE_WORDS; } /// Refill the internal output buffer (`self.buffer`) fn update(&mut self) { core(&mut self.buffer, &self.state); self.index = 0; // update 128-bit counter self.state[12] += 1; if self.state[12]!= 0
; self.state[13] += 1; if self.state[13]!= 0 { return }; self.state[14] += 1; if self.state[14]!= 0 { return }; self.state[15] += 1; } } impl Rng for ChaChaRng { #[inline] fn next_u32(&mut self) -> u32 { if self.index == STATE_WORDS { self.update(); } let value = self.buffer[self.index % STATE_WORDS]; self.index += 1; value } } impl<'a> SeedableRng<&'a [u32]> for ChaChaRng { fn reseed(&mut self, seed: &'a [u32]) { // reset state self.init(&[0u32; KEY_WORDS]); // set key in place let key = &mut self.state[4.. 4+KEY_WORDS]; for (k, s) in key.iter_mut().zip(seed.iter()) { *k = *s; } } /// Create a ChaCha generator from a seed, /// obtained from a variable-length u32 array. /// Only up to 8 words are used; if less than 8 /// words are used, the remaining are set to zero. fn from_seed(seed: &'a [u32]) -> ChaChaRng { let mut rng = EMPTY; rng.reseed(seed); rng } } impl Rand for ChaChaRng { fn rand<R: Rng>(other: &mut R) -> ChaChaRng { let mut key : [u32; KEY_WORDS] = [0; KEY_WORDS]; for word in &mut key { *word = other.gen(); } SeedableRng::from_seed(key.as_slice()) } } #[cfg(test)] mod test { use std::prelude::v1::*; use core::iter::order; use {Rng, SeedableRng}; use super::ChaChaRng; #[test] fn test_rng_rand_seeded() { let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>(); let mut ra: ChaChaRng = SeedableRng::from_seed(&*s); let mut rb: ChaChaRng = SeedableRng::from_seed(&*s); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_seeded() { let seed : &[_] = &[0,1,2,3,4,5,6,7]; let mut ra: ChaChaRng = SeedableRng::from_seed(seed); let mut rb: ChaChaRng = SeedableRng::from_seed(seed); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_reseed() { let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>(); let mut r: ChaChaRng = SeedableRng::from_seed(&*s); let string1: String = r.gen_ascii_chars().take(100).collect(); r.reseed(&s); let string2: String = r.gen_ascii_chars().take(100).collect(); assert_eq!(string1, string2); } #[test] fn test_rng_true_values() { // Test vectors 1 and 2 from // http://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 let seed : &[_] = &[0u32; 8]; let mut ra: ChaChaRng = SeedableRng::from_seed(seed); let v = (0..16).map(|_| ra.next_u32()).collect::<Vec<_>>(); assert_eq!(v, vec!(0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, 0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b, 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, 0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2)); let v = (0..16).map(|_| ra.next_u32()).collect::<Vec<_>>(); assert_eq!(v, vec!(0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, 0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32, 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, 0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b)); let seed : &[_] = &[0,1,2,3,4,5,6,7]; let mut ra: ChaChaRng = SeedableRng::from_seed(seed); // Store the 17*i-th 32-bit word, // i.e., the i-th word of the i-th 16-word block let mut v : Vec<u32> = Vec::new(); for _ in 0..16 { v.push(ra.next_u32()); for _ in 0..16 { ra.next_u32(); } } assert_eq!(v, vec!(0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, 0x49884684, 0x64efec72, 0x4be2d186, 0x3615b384, 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, 0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4)); } #[test] fn test_rng_clone() { let seed : &[_] = &[0u32; 8]; let mut rng: ChaChaRng = SeedableRng::from_seed(seed); let mut clone = rng.clone(); for _ in 0..16 { assert_eq!(rng.next_u64(), clone.next_u64()); } } }
{ return }
conditional_block
chacha.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. //! The ChaCha random number generator. use core::prelude::*; use core::num::Int; use {Rng, SeedableRng, Rand}; const KEY_WORDS : uint = 8; // 8 words for the 256-bit key const STATE_WORDS : uint = 16; const CHACHA_ROUNDS: uint = 20; // Cryptographically secure from 8 upwards as of this writing /// A random number generator that uses the ChaCha20 algorithm [1]. /// /// The ChaCha algorithm is widely accepted as suitable for /// cryptographic purposes, but this implementation has not been /// verified as such. Prefer a generator like `OsRng` that defers to /// the operating system for cases that need high security. /// /// [1]: D. J. Bernstein, [*ChaCha, a variant of /// Salsa20*](http://cr.yp.to/chacha.html) #[derive(Copy, Clone)] pub struct ChaChaRng { buffer: [u32; STATE_WORDS], // Internal buffer of output state: [u32; STATE_WORDS], // Initial state index: uint, // Index into state } static EMPTY: ChaChaRng = ChaChaRng { buffer: [0; STATE_WORDS], state: [0; STATE_WORDS], index: STATE_WORDS }; macro_rules! quarter_round{ ($a: expr, $b: expr, $c: expr, $d: expr) => {{ $a += $b; $d ^= $a; $d = $d.rotate_left(16); $c += $d; $b ^= $c; $b = $b.rotate_left(12); $a += $b; $d ^= $a; $d = $d.rotate_left( 8); $c += $d; $b ^= $c; $b = $b.rotate_left( 7); }} } macro_rules! double_round{ ($x: expr) => {{ // Column round quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]); quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]); quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]); quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]); // Diagonal round quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]); quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]); quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]); quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]); }} } #[inline] fn core(output: &mut [u32; STATE_WORDS], input: &[u32; STATE_WORDS]) { *output = *input; for _ in 0..CHACHA_ROUNDS / 2 { double_round!(output); } for i in 0..STATE_WORDS { output[i] += input[i]; } } impl ChaChaRng { /// Create an ChaCha random number generator using the default /// fixed key of 8 zero words. pub fn
() -> ChaChaRng { let mut rng = EMPTY; rng.init(&[0; KEY_WORDS]); rng } /// Sets the internal 128-bit ChaCha counter to /// a user-provided value. This permits jumping /// arbitrarily ahead (or backwards) in the pseudorandom stream. /// /// Since the nonce words are used to extend the counter to 128 bits, /// users wishing to obtain the conventional ChaCha pseudorandom stream /// associated with a particular nonce can call this function with /// arguments `0, desired_nonce`. pub fn set_counter(&mut self, counter_low: u64, counter_high: u64) { self.state[12] = (counter_low >> 0) as u32; self.state[13] = (counter_low >> 32) as u32; self.state[14] = (counter_high >> 0) as u32; self.state[15] = (counter_high >> 32) as u32; self.index = STATE_WORDS; // force recomputation } /// Initializes `self.state` with the appropriate key and constants /// /// We deviate slightly from the ChaCha specification regarding /// the nonce, which is used to extend the counter to 128 bits. /// This is provably as strong as the original cipher, though, /// since any distinguishing attack on our variant also works /// against ChaCha with a chosen-nonce. See the XSalsa20 [1] /// security proof for a more involved example of this. /// /// The modified word layout is: /// ```text /// constant constant constant constant /// key key key key /// key key key key /// counter counter counter counter /// ``` /// [1]: Daniel J. Bernstein. [*Extending the Salsa20 /// nonce.*](http://cr.yp.to/papers.html#xsalsa) fn init(&mut self, key: &[u32; KEY_WORDS]) { self.state[0] = 0x61707865; self.state[1] = 0x3320646E; self.state[2] = 0x79622D32; self.state[3] = 0x6B206574; for i in 0..KEY_WORDS { self.state[4+i] = key[i]; } self.state[12] = 0; self.state[13] = 0; self.state[14] = 0; self.state[15] = 0; self.index = STATE_WORDS; } /// Refill the internal output buffer (`self.buffer`) fn update(&mut self) { core(&mut self.buffer, &self.state); self.index = 0; // update 128-bit counter self.state[12] += 1; if self.state[12]!= 0 { return }; self.state[13] += 1; if self.state[13]!= 0 { return }; self.state[14] += 1; if self.state[14]!= 0 { return }; self.state[15] += 1; } } impl Rng for ChaChaRng { #[inline] fn next_u32(&mut self) -> u32 { if self.index == STATE_WORDS { self.update(); } let value = self.buffer[self.index % STATE_WORDS]; self.index += 1; value } } impl<'a> SeedableRng<&'a [u32]> for ChaChaRng { fn reseed(&mut self, seed: &'a [u32]) { // reset state self.init(&[0u32; KEY_WORDS]); // set key in place let key = &mut self.state[4.. 4+KEY_WORDS]; for (k, s) in key.iter_mut().zip(seed.iter()) { *k = *s; } } /// Create a ChaCha generator from a seed, /// obtained from a variable-length u32 array. /// Only up to 8 words are used; if less than 8 /// words are used, the remaining are set to zero. fn from_seed(seed: &'a [u32]) -> ChaChaRng { let mut rng = EMPTY; rng.reseed(seed); rng } } impl Rand for ChaChaRng { fn rand<R: Rng>(other: &mut R) -> ChaChaRng { let mut key : [u32; KEY_WORDS] = [0; KEY_WORDS]; for word in &mut key { *word = other.gen(); } SeedableRng::from_seed(key.as_slice()) } } #[cfg(test)] mod test { use std::prelude::v1::*; use core::iter::order; use {Rng, SeedableRng}; use super::ChaChaRng; #[test] fn test_rng_rand_seeded() { let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>(); let mut ra: ChaChaRng = SeedableRng::from_seed(&*s); let mut rb: ChaChaRng = SeedableRng::from_seed(&*s); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_seeded() { let seed : &[_] = &[0,1,2,3,4,5,6,7]; let mut ra: ChaChaRng = SeedableRng::from_seed(seed); let mut rb: ChaChaRng = SeedableRng::from_seed(seed); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_reseed() { let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>(); let mut r: ChaChaRng = SeedableRng::from_seed(&*s); let string1: String = r.gen_ascii_chars().take(100).collect(); r.reseed(&s); let string2: String = r.gen_ascii_chars().take(100).collect(); assert_eq!(string1, string2); } #[test] fn test_rng_true_values() { // Test vectors 1 and 2 from // http://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 let seed : &[_] = &[0u32; 8]; let mut ra: ChaChaRng = SeedableRng::from_seed(seed); let v = (0..16).map(|_| ra.next_u32()).collect::<Vec<_>>(); assert_eq!(v, vec!(0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, 0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b, 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, 0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2)); let v = (0..16).map(|_| ra.next_u32()).collect::<Vec<_>>(); assert_eq!(v, vec!(0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, 0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32, 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, 0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b)); let seed : &[_] = &[0,1,2,3,4,5,6,7]; let mut ra: ChaChaRng = SeedableRng::from_seed(seed); // Store the 17*i-th 32-bit word, // i.e., the i-th word of the i-th 16-word block let mut v : Vec<u32> = Vec::new(); for _ in 0..16 { v.push(ra.next_u32()); for _ in 0..16 { ra.next_u32(); } } assert_eq!(v, vec!(0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, 0x49884684, 0x64efec72, 0x4be2d186, 0x3615b384, 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, 0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4)); } #[test] fn test_rng_clone() { let seed : &[_] = &[0u32; 8]; let mut rng: ChaChaRng = SeedableRng::from_seed(seed); let mut clone = rng.clone(); for _ in 0..16 { assert_eq!(rng.next_u64(), clone.next_u64()); } } }
new_unseeded
identifier_name
chacha.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. //! The ChaCha random number generator. use core::prelude::*; use core::num::Int; use {Rng, SeedableRng, Rand}; const KEY_WORDS : uint = 8; // 8 words for the 256-bit key const STATE_WORDS : uint = 16; const CHACHA_ROUNDS: uint = 20; // Cryptographically secure from 8 upwards as of this writing /// A random number generator that uses the ChaCha20 algorithm [1]. /// /// The ChaCha algorithm is widely accepted as suitable for /// cryptographic purposes, but this implementation has not been /// verified as such. Prefer a generator like `OsRng` that defers to /// the operating system for cases that need high security. /// /// [1]: D. J. Bernstein, [*ChaCha, a variant of /// Salsa20*](http://cr.yp.to/chacha.html) #[derive(Copy, Clone)] pub struct ChaChaRng { buffer: [u32; STATE_WORDS], // Internal buffer of output state: [u32; STATE_WORDS], // Initial state index: uint, // Index into state } static EMPTY: ChaChaRng = ChaChaRng { buffer: [0; STATE_WORDS], state: [0; STATE_WORDS], index: STATE_WORDS }; macro_rules! quarter_round{ ($a: expr, $b: expr, $c: expr, $d: expr) => {{ $a += $b; $d ^= $a; $d = $d.rotate_left(16); $c += $d; $b ^= $c; $b = $b.rotate_left(12); $a += $b; $d ^= $a; $d = $d.rotate_left( 8); $c += $d; $b ^= $c; $b = $b.rotate_left( 7); }} } macro_rules! double_round{ ($x: expr) => {{ // Column round quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]); quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]); quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]); quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]); // Diagonal round quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]); quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]); quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]); quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]); }} } #[inline] fn core(output: &mut [u32; STATE_WORDS], input: &[u32; STATE_WORDS]) { *output = *input; for _ in 0..CHACHA_ROUNDS / 2 { double_round!(output); } for i in 0..STATE_WORDS { output[i] += input[i]; } } impl ChaChaRng { /// Create an ChaCha random number generator using the default /// fixed key of 8 zero words. pub fn new_unseeded() -> ChaChaRng { let mut rng = EMPTY; rng.init(&[0; KEY_WORDS]); rng } /// Sets the internal 128-bit ChaCha counter to /// a user-provided value. This permits jumping /// arbitrarily ahead (or backwards) in the pseudorandom stream. /// /// Since the nonce words are used to extend the counter to 128 bits, /// users wishing to obtain the conventional ChaCha pseudorandom stream /// associated with a particular nonce can call this function with /// arguments `0, desired_nonce`. pub fn set_counter(&mut self, counter_low: u64, counter_high: u64) { self.state[12] = (counter_low >> 0) as u32; self.state[13] = (counter_low >> 32) as u32; self.state[14] = (counter_high >> 0) as u32; self.state[15] = (counter_high >> 32) as u32; self.index = STATE_WORDS; // force recomputation } /// Initializes `self.state` with the appropriate key and constants /// /// We deviate slightly from the ChaCha specification regarding /// the nonce, which is used to extend the counter to 128 bits. /// This is provably as strong as the original cipher, though, /// since any distinguishing attack on our variant also works /// against ChaCha with a chosen-nonce. See the XSalsa20 [1] /// security proof for a more involved example of this. /// /// The modified word layout is: /// ```text /// constant constant constant constant /// key key key key /// key key key key /// counter counter counter counter /// ``` /// [1]: Daniel J. Bernstein. [*Extending the Salsa20 /// nonce.*](http://cr.yp.to/papers.html#xsalsa) fn init(&mut self, key: &[u32; KEY_WORDS]) { self.state[0] = 0x61707865; self.state[1] = 0x3320646E; self.state[2] = 0x79622D32; self.state[3] = 0x6B206574; for i in 0..KEY_WORDS { self.state[4+i] = key[i]; } self.state[12] = 0; self.state[13] = 0; self.state[14] = 0; self.state[15] = 0; self.index = STATE_WORDS; } /// Refill the internal output buffer (`self.buffer`) fn update(&mut self) { core(&mut self.buffer, &self.state); self.index = 0; // update 128-bit counter self.state[12] += 1; if self.state[12]!= 0 { return }; self.state[13] += 1; if self.state[13]!= 0 { return }; self.state[14] += 1; if self.state[14]!= 0 { return }; self.state[15] += 1; } } impl Rng for ChaChaRng { #[inline] fn next_u32(&mut self) -> u32 { if self.index == STATE_WORDS { self.update(); } let value = self.buffer[self.index % STATE_WORDS]; self.index += 1; value } } impl<'a> SeedableRng<&'a [u32]> for ChaChaRng { fn reseed(&mut self, seed: &'a [u32]) { // reset state self.init(&[0u32; KEY_WORDS]); // set key in place let key = &mut self.state[4.. 4+KEY_WORDS]; for (k, s) in key.iter_mut().zip(seed.iter()) { *k = *s; } } /// Create a ChaCha generator from a seed, /// obtained from a variable-length u32 array. /// Only up to 8 words are used; if less than 8 /// words are used, the remaining are set to zero. fn from_seed(seed: &'a [u32]) -> ChaChaRng { let mut rng = EMPTY; rng.reseed(seed); rng } } impl Rand for ChaChaRng { fn rand<R: Rng>(other: &mut R) -> ChaChaRng { let mut key : [u32; KEY_WORDS] = [0; KEY_WORDS]; for word in &mut key { *word = other.gen(); } SeedableRng::from_seed(key.as_slice()) } } #[cfg(test)] mod test { use std::prelude::v1::*; use core::iter::order; use {Rng, SeedableRng}; use super::ChaChaRng; #[test] fn test_rng_rand_seeded() { let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>(); let mut ra: ChaChaRng = SeedableRng::from_seed(&*s); let mut rb: ChaChaRng = SeedableRng::from_seed(&*s); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_seeded() { let seed : &[_] = &[0,1,2,3,4,5,6,7]; let mut ra: ChaChaRng = SeedableRng::from_seed(seed); let mut rb: ChaChaRng = SeedableRng::from_seed(seed); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_reseed() { let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>(); let mut r: ChaChaRng = SeedableRng::from_seed(&*s); let string1: String = r.gen_ascii_chars().take(100).collect(); r.reseed(&s); let string2: String = r.gen_ascii_chars().take(100).collect(); assert_eq!(string1, string2); } #[test] fn test_rng_true_values() { // Test vectors 1 and 2 from // http://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 let seed : &[_] = &[0u32; 8]; let mut ra: ChaChaRng = SeedableRng::from_seed(seed); let v = (0..16).map(|_| ra.next_u32()).collect::<Vec<_>>(); assert_eq!(v, vec!(0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, 0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b, 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, 0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2)); let v = (0..16).map(|_| ra.next_u32()).collect::<Vec<_>>(); assert_eq!(v, vec!(0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, 0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32, 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, 0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b)); let seed : &[_] = &[0,1,2,3,4,5,6,7]; let mut ra: ChaChaRng = SeedableRng::from_seed(seed); // Store the 17*i-th 32-bit word, // i.e., the i-th word of the i-th 16-word block let mut v : Vec<u32> = Vec::new(); for _ in 0..16 { v.push(ra.next_u32()); for _ in 0..16 { ra.next_u32(); } } assert_eq!(v, vec!(0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, 0x49884684, 0x64efec72, 0x4be2d186, 0x3615b384, 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, 0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4)); } #[test] fn test_rng_clone()
}
{ let seed : &[_] = &[0u32; 8]; let mut rng: ChaChaRng = SeedableRng::from_seed(seed); let mut clone = rng.clone(); for _ in 0..16 { assert_eq!(rng.next_u64(), clone.next_u64()); } }
identifier_body
chacha.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. //! The ChaCha random number generator. use core::prelude::*; use core::num::Int; use {Rng, SeedableRng, Rand}; const KEY_WORDS : uint = 8; // 8 words for the 256-bit key const STATE_WORDS : uint = 16; const CHACHA_ROUNDS: uint = 20; // Cryptographically secure from 8 upwards as of this writing /// A random number generator that uses the ChaCha20 algorithm [1]. /// /// The ChaCha algorithm is widely accepted as suitable for /// cryptographic purposes, but this implementation has not been /// verified as such. Prefer a generator like `OsRng` that defers to /// the operating system for cases that need high security. /// /// [1]: D. J. Bernstein, [*ChaCha, a variant of /// Salsa20*](http://cr.yp.to/chacha.html) #[derive(Copy, Clone)] pub struct ChaChaRng { buffer: [u32; STATE_WORDS], // Internal buffer of output state: [u32; STATE_WORDS], // Initial state index: uint, // Index into state } static EMPTY: ChaChaRng = ChaChaRng { buffer: [0; STATE_WORDS], state: [0; STATE_WORDS], index: STATE_WORDS }; macro_rules! quarter_round{ ($a: expr, $b: expr, $c: expr, $d: expr) => {{ $a += $b; $d ^= $a; $d = $d.rotate_left(16); $c += $d; $b ^= $c; $b = $b.rotate_left(12); $a += $b; $d ^= $a; $d = $d.rotate_left( 8); $c += $d; $b ^= $c; $b = $b.rotate_left( 7); }} } macro_rules! double_round{ ($x: expr) => {{ // Column round quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]); quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]); quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]); quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]); // Diagonal round quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]); quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]); quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]); quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]); }} } #[inline] fn core(output: &mut [u32; STATE_WORDS], input: &[u32; STATE_WORDS]) { *output = *input; for _ in 0..CHACHA_ROUNDS / 2 { double_round!(output); } for i in 0..STATE_WORDS { output[i] += input[i]; } } impl ChaChaRng { /// Create an ChaCha random number generator using the default /// fixed key of 8 zero words. pub fn new_unseeded() -> ChaChaRng { let mut rng = EMPTY; rng.init(&[0; KEY_WORDS]); rng } /// Sets the internal 128-bit ChaCha counter to /// a user-provided value. This permits jumping /// arbitrarily ahead (or backwards) in the pseudorandom stream. /// /// Since the nonce words are used to extend the counter to 128 bits, /// users wishing to obtain the conventional ChaCha pseudorandom stream /// associated with a particular nonce can call this function with /// arguments `0, desired_nonce`. pub fn set_counter(&mut self, counter_low: u64, counter_high: u64) { self.state[12] = (counter_low >> 0) as u32; self.state[13] = (counter_low >> 32) as u32; self.state[14] = (counter_high >> 0) as u32; self.state[15] = (counter_high >> 32) as u32; self.index = STATE_WORDS; // force recomputation } /// Initializes `self.state` with the appropriate key and constants /// /// We deviate slightly from the ChaCha specification regarding /// the nonce, which is used to extend the counter to 128 bits. /// This is provably as strong as the original cipher, though, /// since any distinguishing attack on our variant also works /// against ChaCha with a chosen-nonce. See the XSalsa20 [1] /// security proof for a more involved example of this. /// /// The modified word layout is: /// ```text /// constant constant constant constant /// key key key key /// key key key key /// counter counter counter counter /// ``` /// [1]: Daniel J. Bernstein. [*Extending the Salsa20 /// nonce.*](http://cr.yp.to/papers.html#xsalsa) fn init(&mut self, key: &[u32; KEY_WORDS]) { self.state[0] = 0x61707865; self.state[1] = 0x3320646E; self.state[2] = 0x79622D32; self.state[3] = 0x6B206574; for i in 0..KEY_WORDS { self.state[4+i] = key[i]; } self.state[12] = 0; self.state[13] = 0; self.state[14] = 0; self.state[15] = 0; self.index = STATE_WORDS; } /// Refill the internal output buffer (`self.buffer`) fn update(&mut self) { core(&mut self.buffer, &self.state); self.index = 0; // update 128-bit counter self.state[12] += 1; if self.state[12]!= 0 { return }; self.state[13] += 1; if self.state[13]!= 0 { return }; self.state[14] += 1; if self.state[14]!= 0 { return }; self.state[15] += 1; } } impl Rng for ChaChaRng {
fn next_u32(&mut self) -> u32 { if self.index == STATE_WORDS { self.update(); } let value = self.buffer[self.index % STATE_WORDS]; self.index += 1; value } } impl<'a> SeedableRng<&'a [u32]> for ChaChaRng { fn reseed(&mut self, seed: &'a [u32]) { // reset state self.init(&[0u32; KEY_WORDS]); // set key in place let key = &mut self.state[4.. 4+KEY_WORDS]; for (k, s) in key.iter_mut().zip(seed.iter()) { *k = *s; } } /// Create a ChaCha generator from a seed, /// obtained from a variable-length u32 array. /// Only up to 8 words are used; if less than 8 /// words are used, the remaining are set to zero. fn from_seed(seed: &'a [u32]) -> ChaChaRng { let mut rng = EMPTY; rng.reseed(seed); rng } } impl Rand for ChaChaRng { fn rand<R: Rng>(other: &mut R) -> ChaChaRng { let mut key : [u32; KEY_WORDS] = [0; KEY_WORDS]; for word in &mut key { *word = other.gen(); } SeedableRng::from_seed(key.as_slice()) } } #[cfg(test)] mod test { use std::prelude::v1::*; use core::iter::order; use {Rng, SeedableRng}; use super::ChaChaRng; #[test] fn test_rng_rand_seeded() { let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>(); let mut ra: ChaChaRng = SeedableRng::from_seed(&*s); let mut rb: ChaChaRng = SeedableRng::from_seed(&*s); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_seeded() { let seed : &[_] = &[0,1,2,3,4,5,6,7]; let mut ra: ChaChaRng = SeedableRng::from_seed(seed); let mut rb: ChaChaRng = SeedableRng::from_seed(seed); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_reseed() { let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>(); let mut r: ChaChaRng = SeedableRng::from_seed(&*s); let string1: String = r.gen_ascii_chars().take(100).collect(); r.reseed(&s); let string2: String = r.gen_ascii_chars().take(100).collect(); assert_eq!(string1, string2); } #[test] fn test_rng_true_values() { // Test vectors 1 and 2 from // http://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 let seed : &[_] = &[0u32; 8]; let mut ra: ChaChaRng = SeedableRng::from_seed(seed); let v = (0..16).map(|_| ra.next_u32()).collect::<Vec<_>>(); assert_eq!(v, vec!(0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, 0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b, 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, 0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2)); let v = (0..16).map(|_| ra.next_u32()).collect::<Vec<_>>(); assert_eq!(v, vec!(0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, 0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32, 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, 0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b)); let seed : &[_] = &[0,1,2,3,4,5,6,7]; let mut ra: ChaChaRng = SeedableRng::from_seed(seed); // Store the 17*i-th 32-bit word, // i.e., the i-th word of the i-th 16-word block let mut v : Vec<u32> = Vec::new(); for _ in 0..16 { v.push(ra.next_u32()); for _ in 0..16 { ra.next_u32(); } } assert_eq!(v, vec!(0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, 0x49884684, 0x64efec72, 0x4be2d186, 0x3615b384, 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, 0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4)); } #[test] fn test_rng_clone() { let seed : &[_] = &[0u32; 8]; let mut rng: ChaChaRng = SeedableRng::from_seed(seed); let mut clone = rng.clone(); for _ in 0..16 { assert_eq!(rng.next_u64(), clone.next_u64()); } } }
#[inline]
random_line_split
mod.rs
// Copyright (C) 2020 Mathieu Duponchelle <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Suite 500, // Boston, MA 02110-1335, USA. use glib::prelude::*; mod imp; glib::glib_wrapper! { pub struct TextWrap(ObjectSubclass<imp::TextWrap>) @extends gst::Element, gst::Object; } unsafe impl Send for TextWrap {} unsafe impl Sync for TextWrap {} pub fn
(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { gst::Element::register( Some(plugin), "textwrap", gst::Rank::None, TextWrap::static_type(), ) }
register
identifier_name
mod.rs
// Copyright (C) 2020 Mathieu Duponchelle <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Suite 500, // Boston, MA 02110-1335, USA. use glib::prelude::*; mod imp; glib::glib_wrapper! { pub struct TextWrap(ObjectSubclass<imp::TextWrap>) @extends gst::Element, gst::Object; }
unsafe impl Send for TextWrap {} unsafe impl Sync for TextWrap {} pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { gst::Element::register( Some(plugin), "textwrap", gst::Rank::None, TextWrap::static_type(), ) }
random_line_split
mod.rs
// Copyright (C) 2020 Mathieu Duponchelle <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Suite 500, // Boston, MA 02110-1335, USA. use glib::prelude::*; mod imp; glib::glib_wrapper! { pub struct TextWrap(ObjectSubclass<imp::TextWrap>) @extends gst::Element, gst::Object; } unsafe impl Send for TextWrap {} unsafe impl Sync for TextWrap {} pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError>
{ gst::Element::register( Some(plugin), "textwrap", gst::Rank::None, TextWrap::static_type(), ) }
identifier_body
system.rs
use std::fmt; use std::process; use std::time; #[cfg(debug_assertions)] pub fn pdbg(args: fmt::Arguments) { eprintln!("[DBG ] {}", args); } #[cfg(not(debug_assertions))] pub fn
(_: fmt::Arguments) {} pub fn pdie(args: fmt::Arguments) ->! { perr(args); process::exit(1) } pub fn perr(args: fmt::Arguments) { eprintln!("[ERR ] {}", args); } pub fn pwarn(args: fmt::Arguments) { eprintln!("[WARN] {}", args); } pub fn pinfo(args: fmt::Arguments) { println!("[INFO] {}", args); } pub fn pts(t1: &time::Instant, t2: &time::Instant) { let d = t2.duration_since(*t1); let d_seconds = d.as_secs() as f64 + d.subsec_nanos() as f64 * 1e-9; pinfo(format_args!("Elapsed {} seconds", d_seconds)); }
pdbg
identifier_name
system.rs
use std::fmt; use std::process; use std::time; #[cfg(debug_assertions)] pub fn pdbg(args: fmt::Arguments) { eprintln!("[DBG ] {}", args); } #[cfg(not(debug_assertions))] pub fn pdbg(_: fmt::Arguments) {} pub fn pdie(args: fmt::Arguments) ->!
pub fn perr(args: fmt::Arguments) { eprintln!("[ERR ] {}", args); } pub fn pwarn(args: fmt::Arguments) { eprintln!("[WARN] {}", args); } pub fn pinfo(args: fmt::Arguments) { println!("[INFO] {}", args); } pub fn pts(t1: &time::Instant, t2: &time::Instant) { let d = t2.duration_since(*t1); let d_seconds = d.as_secs() as f64 + d.subsec_nanos() as f64 * 1e-9; pinfo(format_args!("Elapsed {} seconds", d_seconds)); }
{ perr(args); process::exit(1) }
identifier_body
system.rs
use std::fmt; use std::process; use std::time; #[cfg(debug_assertions)] pub fn pdbg(args: fmt::Arguments) {
pub fn pdie(args: fmt::Arguments) ->! { perr(args); process::exit(1) } pub fn perr(args: fmt::Arguments) { eprintln!("[ERR ] {}", args); } pub fn pwarn(args: fmt::Arguments) { eprintln!("[WARN] {}", args); } pub fn pinfo(args: fmt::Arguments) { println!("[INFO] {}", args); } pub fn pts(t1: &time::Instant, t2: &time::Instant) { let d = t2.duration_since(*t1); let d_seconds = d.as_secs() as f64 + d.subsec_nanos() as f64 * 1e-9; pinfo(format_args!("Elapsed {} seconds", d_seconds)); }
eprintln!("[DBG ] {}", args); } #[cfg(not(debug_assertions))] pub fn pdbg(_: fmt::Arguments) {}
random_line_split
context.rs
use machine_message::TaskStatus; use super::Task; use std::collections::vec_deque::VecDeque; use printspool_protobufs::MachineFlags; use crate::protos::{ machine_message::{ self, }, // MachineMessage, }; use crate::state_machine; use printspool_machine::{ config::MachineConfig, components::Controller, }; #[derive(Clone, Debug)] pub struct Context { pub baud_rate: u32, pub current_hotend_index: u32, pub machine_flags: MachineFlags, pub config: MachineConfig, pub controller: Controller, pub reset_when_idle: bool, pub feedback: machine_message::Feedback, gcode_history_buffer: VecDeque<machine_message::GCodeHistoryEntry>, } impl Context { pub fn new(config: MachineConfig) -> Self { let status = machine_message::Status::Disconnected as i32; let controller = config.get_controller().clone(); let feedback = Self::reset_feedback(status, &config); let gcode_history_buffer = VecDeque::with_capacity( controller.model.gcode_history_buffer_size ); Self { baud_rate: 115_200, current_hotend_index: 0, machine_flags: MachineFlags::default(), reset_when_idle: false, feedback, config, controller, gcode_history_buffer, } } fn reset_feedback(status: i32, config: &MachineConfig) -> machine_message::Feedback { machine_message::Feedback { status, heaters: config.heater_addresses().into_iter().map(|address| { machine_message::Heater { address: address, ..machine_message::Heater::default() } }).collect(), axes: config.feedrates().into_iter().map(|f| { machine_message::Axis { address: f.address, ..machine_message::Axis::default() } }).collect(), speed_controllers: config.speed_controllers.iter().map(|sc| { machine_message::SpeedController { address: sc.model.address.clone(), ..machine_message::SpeedController::default() } }).collect(), ..machine_message::Feedback::default() } } pub fn add_gcode_history_to_feedback(&mut self) -> () { // println!("History Buffer: {:?}", self.gcode_history_buffer); self.feedback.gcode_history = self.gcode_history_buffer.drain(..).collect(); } pub fn handle_state_change(&mut self, state: &state_machine::State) { use state_machine::State::*; let status = match state { Disconnected => machine_message::Status::Disconnected as i32, Connecting {..} => machine_message::Status::Connecting as i32, Ready(.. ) => machine_message::Status::Ready as i32, Errored {.. } => machine_message::Status::Errored as i32, EStopped => machine_message::Status::Estopped as i32, }; // reset everything except the new status and then move over the events from the previous struct let next_feedback = Self::reset_feedback(status, &self.config); let previous_feedback = std::mem::replace(&mut self.feedback, next_feedback); self.feedback.task_progress = previous_feedback.task_progress; self.current_hotend_index = 0; if let Errored { message } = state { let error = machine_message::Error { message: message.clone(), }; self.feedback.error = Some(error); }; } pub fn delete_task_history(&mut self, task_ids: &Vec<crate::DbId>) { self.feedback.task_progress.retain(|p| { !task_ids.contains(&p.task_id) }); } pub fn push_start_task(&mut self, task: &Task) { self.push_task_progress(task, TaskStatus::TaskStarted); } pub fn push_cancel_task(&mut self, task: &Task) { self.push_task_progress(task, TaskStatus::TaskCancelled); } pub fn push_pause_task(&mut self, task: &Task) { self.machine_flags.set(MachineFlags::PAUSED_STATE, true); self.push_task_progress(task, TaskStatus::TaskPaused); } pub fn push_finish_task(&mut self, task: &Task) { self.push_task_progress(task, TaskStatus::TaskFinished); } pub fn push_error(&mut self, task: &Task) { self.push_task_progress(task, TaskStatus::TaskErrored); } fn push_task_progress( &mut self, task: &Task, status: TaskStatus, ) { if task.client_id == "INTERNAL" { return }; // trace!("Pusing {:?} for #{:?}", status, task.id); let despooled_line_number = task.despooled_line_number .unwrap_or(0); let progress = self.feedback.task_progress .iter_mut() .find(|p| p.task_id == task.id); if let Some(mut progress) = progress { // Optimized by re-using existing progress structs if they exist progress.despooled_line_number = despooled_line_number; progress.status = status as i32; } else { // If a progress struct doesn't exist for this task we push a new one let new_progress = machine_message::TaskProgress { task_id: task.id.clone(), despooled_line_number, status: status as i32, }; self.feedback.task_progress.push(new_progress); } } pub fn push_gcode_rx(&mut self, raw_src: String, is_polling: bool) { // Placeholder: Some day we might allow a toggle to display polling gcodes if is_polling { return } let direction = machine_message::GCodeHistoryDirection::Rx as i32; self.push_gcode_history_entry(raw_src, direction) } pub fn push_gcode_tx(&mut self, raw_src: String, is_polling: bool)
fn push_gcode_history_entry(&mut self, content: String, direction: i32) { let entry = machine_message::GCodeHistoryEntry { content, direction, }; if self.gcode_history_buffer.len() >= self.controller.model.gcode_history_buffer_size { let _ = self.gcode_history_buffer.pop_front(); } self.gcode_history_buffer.push_back(entry) } }
{ // Placeholder: Some day we might allow a toggle to display polling gcodes if is_polling { return } let direction = machine_message::GCodeHistoryDirection::Tx as i32; self.push_gcode_history_entry(raw_src, direction) }
identifier_body
context.rs
use machine_message::TaskStatus; use super::Task; use std::collections::vec_deque::VecDeque; use printspool_protobufs::MachineFlags; use crate::protos::{ machine_message::{ self, }, // MachineMessage, }; use crate::state_machine; use printspool_machine::{ config::MachineConfig, components::Controller, }; #[derive(Clone, Debug)] pub struct Context { pub baud_rate: u32, pub current_hotend_index: u32, pub machine_flags: MachineFlags, pub config: MachineConfig, pub controller: Controller, pub reset_when_idle: bool, pub feedback: machine_message::Feedback, gcode_history_buffer: VecDeque<machine_message::GCodeHistoryEntry>, } impl Context { pub fn new(config: MachineConfig) -> Self { let status = machine_message::Status::Disconnected as i32; let controller = config.get_controller().clone(); let feedback = Self::reset_feedback(status, &config); let gcode_history_buffer = VecDeque::with_capacity( controller.model.gcode_history_buffer_size ); Self { baud_rate: 115_200, current_hotend_index: 0, machine_flags: MachineFlags::default(), reset_when_idle: false, feedback, config, controller, gcode_history_buffer, } } fn reset_feedback(status: i32, config: &MachineConfig) -> machine_message::Feedback { machine_message::Feedback { status, heaters: config.heater_addresses().into_iter().map(|address| { machine_message::Heater { address: address, ..machine_message::Heater::default() } }).collect(), axes: config.feedrates().into_iter().map(|f| { machine_message::Axis { address: f.address, ..machine_message::Axis::default() } }).collect(), speed_controllers: config.speed_controllers.iter().map(|sc| { machine_message::SpeedController { address: sc.model.address.clone(), ..machine_message::SpeedController::default() } }).collect(), ..machine_message::Feedback::default() } } pub fn
(&mut self) -> () { // println!("History Buffer: {:?}", self.gcode_history_buffer); self.feedback.gcode_history = self.gcode_history_buffer.drain(..).collect(); } pub fn handle_state_change(&mut self, state: &state_machine::State) { use state_machine::State::*; let status = match state { Disconnected => machine_message::Status::Disconnected as i32, Connecting {..} => machine_message::Status::Connecting as i32, Ready(.. ) => machine_message::Status::Ready as i32, Errored {.. } => machine_message::Status::Errored as i32, EStopped => machine_message::Status::Estopped as i32, }; // reset everything except the new status and then move over the events from the previous struct let next_feedback = Self::reset_feedback(status, &self.config); let previous_feedback = std::mem::replace(&mut self.feedback, next_feedback); self.feedback.task_progress = previous_feedback.task_progress; self.current_hotend_index = 0; if let Errored { message } = state { let error = machine_message::Error { message: message.clone(), }; self.feedback.error = Some(error); }; } pub fn delete_task_history(&mut self, task_ids: &Vec<crate::DbId>) { self.feedback.task_progress.retain(|p| { !task_ids.contains(&p.task_id) }); } pub fn push_start_task(&mut self, task: &Task) { self.push_task_progress(task, TaskStatus::TaskStarted); } pub fn push_cancel_task(&mut self, task: &Task) { self.push_task_progress(task, TaskStatus::TaskCancelled); } pub fn push_pause_task(&mut self, task: &Task) { self.machine_flags.set(MachineFlags::PAUSED_STATE, true); self.push_task_progress(task, TaskStatus::TaskPaused); } pub fn push_finish_task(&mut self, task: &Task) { self.push_task_progress(task, TaskStatus::TaskFinished); } pub fn push_error(&mut self, task: &Task) { self.push_task_progress(task, TaskStatus::TaskErrored); } fn push_task_progress( &mut self, task: &Task, status: TaskStatus, ) { if task.client_id == "INTERNAL" { return }; // trace!("Pusing {:?} for #{:?}", status, task.id); let despooled_line_number = task.despooled_line_number .unwrap_or(0); let progress = self.feedback.task_progress .iter_mut() .find(|p| p.task_id == task.id); if let Some(mut progress) = progress { // Optimized by re-using existing progress structs if they exist progress.despooled_line_number = despooled_line_number; progress.status = status as i32; } else { // If a progress struct doesn't exist for this task we push a new one let new_progress = machine_message::TaskProgress { task_id: task.id.clone(), despooled_line_number, status: status as i32, }; self.feedback.task_progress.push(new_progress); } } pub fn push_gcode_rx(&mut self, raw_src: String, is_polling: bool) { // Placeholder: Some day we might allow a toggle to display polling gcodes if is_polling { return } let direction = machine_message::GCodeHistoryDirection::Rx as i32; self.push_gcode_history_entry(raw_src, direction) } pub fn push_gcode_tx(&mut self, raw_src: String, is_polling: bool) { // Placeholder: Some day we might allow a toggle to display polling gcodes if is_polling { return } let direction = machine_message::GCodeHistoryDirection::Tx as i32; self.push_gcode_history_entry(raw_src, direction) } fn push_gcode_history_entry(&mut self, content: String, direction: i32) { let entry = machine_message::GCodeHistoryEntry { content, direction, }; if self.gcode_history_buffer.len() >= self.controller.model.gcode_history_buffer_size { let _ = self.gcode_history_buffer.pop_front(); } self.gcode_history_buffer.push_back(entry) } }
add_gcode_history_to_feedback
identifier_name
context.rs
use machine_message::TaskStatus; use super::Task; use std::collections::vec_deque::VecDeque; use printspool_protobufs::MachineFlags; use crate::protos::{ machine_message::{ self, }, // MachineMessage, }; use crate::state_machine; use printspool_machine::{ config::MachineConfig, components::Controller, }; #[derive(Clone, Debug)] pub struct Context { pub baud_rate: u32, pub current_hotend_index: u32, pub machine_flags: MachineFlags, pub config: MachineConfig, pub controller: Controller, pub reset_when_idle: bool, pub feedback: machine_message::Feedback, gcode_history_buffer: VecDeque<machine_message::GCodeHistoryEntry>, } impl Context { pub fn new(config: MachineConfig) -> Self { let status = machine_message::Status::Disconnected as i32; let controller = config.get_controller().clone(); let feedback = Self::reset_feedback(status, &config); let gcode_history_buffer = VecDeque::with_capacity( controller.model.gcode_history_buffer_size ); Self { baud_rate: 115_200, current_hotend_index: 0, machine_flags: MachineFlags::default(), reset_when_idle: false, feedback, config, controller, gcode_history_buffer, } } fn reset_feedback(status: i32, config: &MachineConfig) -> machine_message::Feedback { machine_message::Feedback { status, heaters: config.heater_addresses().into_iter().map(|address| { machine_message::Heater { address: address, ..machine_message::Heater::default() } }).collect(), axes: config.feedrates().into_iter().map(|f| { machine_message::Axis { address: f.address, ..machine_message::Axis::default() } }).collect(), speed_controllers: config.speed_controllers.iter().map(|sc| { machine_message::SpeedController { address: sc.model.address.clone(), ..machine_message::SpeedController::default() } }).collect(), ..machine_message::Feedback::default() } } pub fn add_gcode_history_to_feedback(&mut self) -> () { // println!("History Buffer: {:?}", self.gcode_history_buffer); self.feedback.gcode_history = self.gcode_history_buffer.drain(..).collect(); } pub fn handle_state_change(&mut self, state: &state_machine::State) { use state_machine::State::*; let status = match state { Disconnected => machine_message::Status::Disconnected as i32, Connecting {..} => machine_message::Status::Connecting as i32, Ready(.. ) => machine_message::Status::Ready as i32, Errored {.. } => machine_message::Status::Errored as i32, EStopped => machine_message::Status::Estopped as i32, }; // reset everything except the new status and then move over the events from the previous struct let next_feedback = Self::reset_feedback(status, &self.config); let previous_feedback = std::mem::replace(&mut self.feedback, next_feedback); self.feedback.task_progress = previous_feedback.task_progress; self.current_hotend_index = 0; if let Errored { message } = state { let error = machine_message::Error { message: message.clone(), }; self.feedback.error = Some(error); }; } pub fn delete_task_history(&mut self, task_ids: &Vec<crate::DbId>) { self.feedback.task_progress.retain(|p| { !task_ids.contains(&p.task_id) }); } pub fn push_start_task(&mut self, task: &Task) { self.push_task_progress(task, TaskStatus::TaskStarted); } pub fn push_cancel_task(&mut self, task: &Task) { self.push_task_progress(task, TaskStatus::TaskCancelled); } pub fn push_pause_task(&mut self, task: &Task) { self.machine_flags.set(MachineFlags::PAUSED_STATE, true); self.push_task_progress(task, TaskStatus::TaskPaused); } pub fn push_finish_task(&mut self, task: &Task) { self.push_task_progress(task, TaskStatus::TaskFinished); } pub fn push_error(&mut self, task: &Task) { self.push_task_progress(task, TaskStatus::TaskErrored); } fn push_task_progress( &mut self, task: &Task, status: TaskStatus, ) { if task.client_id == "INTERNAL" { return }; // trace!("Pusing {:?} for #{:?}", status, task.id); let despooled_line_number = task.despooled_line_number .unwrap_or(0);
.find(|p| p.task_id == task.id); if let Some(mut progress) = progress { // Optimized by re-using existing progress structs if they exist progress.despooled_line_number = despooled_line_number; progress.status = status as i32; } else { // If a progress struct doesn't exist for this task we push a new one let new_progress = machine_message::TaskProgress { task_id: task.id.clone(), despooled_line_number, status: status as i32, }; self.feedback.task_progress.push(new_progress); } } pub fn push_gcode_rx(&mut self, raw_src: String, is_polling: bool) { // Placeholder: Some day we might allow a toggle to display polling gcodes if is_polling { return } let direction = machine_message::GCodeHistoryDirection::Rx as i32; self.push_gcode_history_entry(raw_src, direction) } pub fn push_gcode_tx(&mut self, raw_src: String, is_polling: bool) { // Placeholder: Some day we might allow a toggle to display polling gcodes if is_polling { return } let direction = machine_message::GCodeHistoryDirection::Tx as i32; self.push_gcode_history_entry(raw_src, direction) } fn push_gcode_history_entry(&mut self, content: String, direction: i32) { let entry = machine_message::GCodeHistoryEntry { content, direction, }; if self.gcode_history_buffer.len() >= self.controller.model.gcode_history_buffer_size { let _ = self.gcode_history_buffer.pop_front(); } self.gcode_history_buffer.push_back(entry) } }
let progress = self.feedback.task_progress .iter_mut()
random_line_split
main.rs
extern crate ncurses; mod podcast; use ncurses::*; use self::podcast::*; const KEY_A: i32 = 97; const KEY_Q: i32 = 113; fn main() { let locale_conf = LcCategory::all; setlocale(locale_conf, "en_US.UTF-8"); /* Initialization */ initscr(); // Start ncurses raw(); // Line buffering disabled noecho(); // Don't echo() while we do getch curs_set(CURSOR_VISIBILITY::CURSOR_INVISIBLE); // Invisible cursor /* Print menu */ menu(); let mut podcasts: Vec<Podcast> = Vec::new(); /* Show Windows */ let mut pw = podcasts_window(&podcasts); let mut ch = getch(); while ch!= KEY_Q { match ch { KEY_A => { clear_line(stdscr, LINES-1); mvprintw(LINES-1, 0, "New podcast feed: "); wrefresh(stdscr);
echo(); let mut feed: String = String::new(); getstr(&mut feed); noecho(); podcasts.push(Podcast::new(feed)); destroy_window(pw); menu(); pw = podcasts_window(&podcasts); }, _ => {} } ch = getch(); } endwin(); // Terminate ncurses } fn clear_line(win: WINDOW, y: i32) { let mut lines: i32 = 0; let mut cols: i32 = 0; getmaxyx(win, &mut lines, &mut cols); for i in 0..cols { mvwprintw(win, y, i, " "); wrefresh(win); } } fn menu() { clear_line(stdscr, LINES-1); mvprintw(LINES-1, 0, "a: Add podcast | q: Quit"); wrefresh(stdscr); } fn destroy_window(win: WINDOW) { let ch ='' as chtype; wborder(win, ch, ch, ch, ch, ch, ch, ch, ch); wrefresh(win); delwin(win); } fn podcasts_window(podcasts: &Vec<Podcast>) -> WINDOW { let lines: i32 = LINES-1; let cols: i32 = 30; let x: i32 = 0; let y: i32 = 0; let win = newwin(lines, cols, y, x); // Draw a vertical line on the right side for i in 0..lines { mvwprintw(win, i, cols - 1, "|"); } // Print podcasts names for i in 0..podcasts.len() { let title: &str = &podcasts[i].title(); // Remove buggy Characters let t = title.replace("%", ""); let title = &t; mvwprintw(win, i as i32, 0, title); } wrefresh(win); return win; }
random_line_split
main.rs
extern crate ncurses; mod podcast; use ncurses::*; use self::podcast::*; const KEY_A: i32 = 97; const KEY_Q: i32 = 113; fn main() { let locale_conf = LcCategory::all; setlocale(locale_conf, "en_US.UTF-8"); /* Initialization */ initscr(); // Start ncurses raw(); // Line buffering disabled noecho(); // Don't echo() while we do getch curs_set(CURSOR_VISIBILITY::CURSOR_INVISIBLE); // Invisible cursor /* Print menu */ menu(); let mut podcasts: Vec<Podcast> = Vec::new(); /* Show Windows */ let mut pw = podcasts_window(&podcasts); let mut ch = getch(); while ch!= KEY_Q { match ch { KEY_A => { clear_line(stdscr, LINES-1); mvprintw(LINES-1, 0, "New podcast feed: "); wrefresh(stdscr); echo(); let mut feed: String = String::new(); getstr(&mut feed); noecho(); podcasts.push(Podcast::new(feed)); destroy_window(pw); menu(); pw = podcasts_window(&podcasts); }, _ => {} } ch = getch(); } endwin(); // Terminate ncurses } fn clear_line(win: WINDOW, y: i32) { let mut lines: i32 = 0; let mut cols: i32 = 0; getmaxyx(win, &mut lines, &mut cols); for i in 0..cols { mvwprintw(win, y, i, " "); wrefresh(win); } } fn menu() { clear_line(stdscr, LINES-1); mvprintw(LINES-1, 0, "a: Add podcast | q: Quit"); wrefresh(stdscr); } fn destroy_window(win: WINDOW) { let ch ='' as chtype; wborder(win, ch, ch, ch, ch, ch, ch, ch, ch); wrefresh(win); delwin(win); } fn podcasts_window(podcasts: &Vec<Podcast>) -> WINDOW
} wrefresh(win); return win; }
{ let lines: i32 = LINES-1; let cols: i32 = 30; let x: i32 = 0; let y: i32 = 0; let win = newwin(lines, cols, y, x); // Draw a vertical line on the right side for i in 0..lines { mvwprintw(win, i, cols - 1, "|"); } // Print podcasts names for i in 0..podcasts.len() { let title: &str = &podcasts[i].title(); // Remove buggy Characters let t = title.replace("%", ""); let title = &t; mvwprintw(win, i as i32, 0, title);
identifier_body
main.rs
extern crate ncurses; mod podcast; use ncurses::*; use self::podcast::*; const KEY_A: i32 = 97; const KEY_Q: i32 = 113; fn main() { let locale_conf = LcCategory::all; setlocale(locale_conf, "en_US.UTF-8"); /* Initialization */ initscr(); // Start ncurses raw(); // Line buffering disabled noecho(); // Don't echo() while we do getch curs_set(CURSOR_VISIBILITY::CURSOR_INVISIBLE); // Invisible cursor /* Print menu */ menu(); let mut podcasts: Vec<Podcast> = Vec::new(); /* Show Windows */ let mut pw = podcasts_window(&podcasts); let mut ch = getch(); while ch!= KEY_Q { match ch { KEY_A => { clear_line(stdscr, LINES-1); mvprintw(LINES-1, 0, "New podcast feed: "); wrefresh(stdscr); echo(); let mut feed: String = String::new(); getstr(&mut feed); noecho(); podcasts.push(Podcast::new(feed)); destroy_window(pw); menu(); pw = podcasts_window(&podcasts); }, _ => {} } ch = getch(); } endwin(); // Terminate ncurses } fn clear_line(win: WINDOW, y: i32) { let mut lines: i32 = 0; let mut cols: i32 = 0; getmaxyx(win, &mut lines, &mut cols); for i in 0..cols { mvwprintw(win, y, i, " "); wrefresh(win); } } fn menu() { clear_line(stdscr, LINES-1); mvprintw(LINES-1, 0, "a: Add podcast | q: Quit"); wrefresh(stdscr); } fn destroy_window(win: WINDOW) { let ch ='' as chtype; wborder(win, ch, ch, ch, ch, ch, ch, ch, ch); wrefresh(win); delwin(win); } fn
(podcasts: &Vec<Podcast>) -> WINDOW { let lines: i32 = LINES-1; let cols: i32 = 30; let x: i32 = 0; let y: i32 = 0; let win = newwin(lines, cols, y, x); // Draw a vertical line on the right side for i in 0..lines { mvwprintw(win, i, cols - 1, "|"); } // Print podcasts names for i in 0..podcasts.len() { let title: &str = &podcasts[i].title(); // Remove buggy Characters let t = title.replace("%", ""); let title = &t; mvwprintw(win, i as i32, 0, title); } wrefresh(win); return win; }
podcasts_window
identifier_name
about_loader.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 file_loader; use hyper::header::ContentType; use hyper::http::RawStatus; use hyper::mime::{Mime, SubLevel, TopLevel}; use mime_classifier::MIMEClassifier; use net_traits::ProgressMsg::Done; use net_traits::{LoadConsumer, LoadData, Metadata}; use resource_task::{CancellationListener, send_error, start_sending_sniffed_opt}; use std::sync::Arc; use url::Url; use util::resource_files::resources_dir_path; pub fn
(mut load_data: LoadData, start_chan: LoadConsumer, classifier: Arc<MIMEClassifier>, cancel_listener: CancellationListener) { let url = load_data.url.clone(); let non_relative_scheme_data = url.non_relative_scheme_data().unwrap(); match non_relative_scheme_data { "blank" => { let metadata = Metadata { final_url: load_data.url, content_type: Some(ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![]))), charset: Some("utf-8".to_owned()), headers: None, status: Some(RawStatus(200, "OK".into())), }; if let Ok(chan) = start_sending_sniffed_opt(start_chan, metadata, classifier, &[], load_data.context) { let _ = chan.send(Done(Ok(()))); } return } "crash" => panic!("Loading the about:crash URL."), "failure" | "not-found" => { let mut path = resources_dir_path(); let file_name = non_relative_scheme_data.to_owned() + ".html"; path.push(&file_name); assert!(path.exists()); load_data.url = Url::from_file_path(&*path).unwrap(); } _ => { send_error(load_data.url, "Unknown about: URL.".to_owned(), start_chan); return } }; file_loader::factory(load_data, start_chan, classifier, cancel_listener) }
factory
identifier_name
about_loader.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 file_loader; use hyper::header::ContentType; use hyper::http::RawStatus; use hyper::mime::{Mime, SubLevel, TopLevel}; use mime_classifier::MIMEClassifier; use net_traits::ProgressMsg::Done; use net_traits::{LoadConsumer, LoadData, Metadata}; use resource_task::{CancellationListener, send_error, start_sending_sniffed_opt}; use std::sync::Arc; use url::Url; use util::resource_files::resources_dir_path; pub fn factory(mut load_data: LoadData, start_chan: LoadConsumer, classifier: Arc<MIMEClassifier>, cancel_listener: CancellationListener)
} "crash" => panic!("Loading the about:crash URL."), "failure" | "not-found" => { let mut path = resources_dir_path(); let file_name = non_relative_scheme_data.to_owned() + ".html"; path.push(&file_name); assert!(path.exists()); load_data.url = Url::from_file_path(&*path).unwrap(); } _ => { send_error(load_data.url, "Unknown about: URL.".to_owned(), start_chan); return } }; file_loader::factory(load_data, start_chan, classifier, cancel_listener) }
{ let url = load_data.url.clone(); let non_relative_scheme_data = url.non_relative_scheme_data().unwrap(); match non_relative_scheme_data { "blank" => { let metadata = Metadata { final_url: load_data.url, content_type: Some(ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![]))), charset: Some("utf-8".to_owned()), headers: None, status: Some(RawStatus(200, "OK".into())), }; if let Ok(chan) = start_sending_sniffed_opt(start_chan, metadata, classifier, &[], load_data.context) { let _ = chan.send(Done(Ok(()))); } return
identifier_body
about_loader.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 file_loader; use hyper::header::ContentType; use hyper::http::RawStatus; use hyper::mime::{Mime, SubLevel, TopLevel}; use mime_classifier::MIMEClassifier; use net_traits::ProgressMsg::Done; use net_traits::{LoadConsumer, LoadData, Metadata}; use resource_task::{CancellationListener, send_error, start_sending_sniffed_opt}; use std::sync::Arc; use url::Url; use util::resource_files::resources_dir_path; pub fn factory(mut load_data: LoadData, start_chan: LoadConsumer, classifier: Arc<MIMEClassifier>, cancel_listener: CancellationListener) { let url = load_data.url.clone(); let non_relative_scheme_data = url.non_relative_scheme_data().unwrap(); match non_relative_scheme_data { "blank" => { let metadata = Metadata { final_url: load_data.url, content_type: Some(ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![]))), charset: Some("utf-8".to_owned()), headers: None, status: Some(RawStatus(200, "OK".into())),
load_data.context) { let _ = chan.send(Done(Ok(()))); } return } "crash" => panic!("Loading the about:crash URL."), "failure" | "not-found" => { let mut path = resources_dir_path(); let file_name = non_relative_scheme_data.to_owned() + ".html"; path.push(&file_name); assert!(path.exists()); load_data.url = Url::from_file_path(&*path).unwrap(); } _ => { send_error(load_data.url, "Unknown about: URL.".to_owned(), start_chan); return } }; file_loader::factory(load_data, start_chan, classifier, cancel_listener) }
}; if let Ok(chan) = start_sending_sniffed_opt(start_chan, metadata, classifier, &[],
random_line_split
about_loader.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 file_loader; use hyper::header::ContentType; use hyper::http::RawStatus; use hyper::mime::{Mime, SubLevel, TopLevel}; use mime_classifier::MIMEClassifier; use net_traits::ProgressMsg::Done; use net_traits::{LoadConsumer, LoadData, Metadata}; use resource_task::{CancellationListener, send_error, start_sending_sniffed_opt}; use std::sync::Arc; use url::Url; use util::resource_files::resources_dir_path; pub fn factory(mut load_data: LoadData, start_chan: LoadConsumer, classifier: Arc<MIMEClassifier>, cancel_listener: CancellationListener) { let url = load_data.url.clone(); let non_relative_scheme_data = url.non_relative_scheme_data().unwrap(); match non_relative_scheme_data { "blank" =>
"crash" => panic!("Loading the about:crash URL."), "failure" | "not-found" => { let mut path = resources_dir_path(); let file_name = non_relative_scheme_data.to_owned() + ".html"; path.push(&file_name); assert!(path.exists()); load_data.url = Url::from_file_path(&*path).unwrap(); } _ => { send_error(load_data.url, "Unknown about: URL.".to_owned(), start_chan); return } }; file_loader::factory(load_data, start_chan, classifier, cancel_listener) }
{ let metadata = Metadata { final_url: load_data.url, content_type: Some(ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![]))), charset: Some("utf-8".to_owned()), headers: None, status: Some(RawStatus(200, "OK".into())), }; if let Ok(chan) = start_sending_sniffed_opt(start_chan, metadata, classifier, &[], load_data.context) { let _ = chan.send(Done(Ok(()))); } return }
conditional_block
convert.rs
#include "shared.rsh" float4 f4 = { 2.0f, 4.0f, 6.0f, 8.0f }; char4 i8_4 = { -1, -2, -3, 4 }; static bool test_convert() { bool failed = false; f4 = convert_float4(i8_4); _RS_ASSERT(f4.x == -1.0f); _RS_ASSERT(f4.y == -2.0f); _RS_ASSERT(f4.z == -3.0f); _RS_ASSERT(f4.w == 4.0f); if (failed) { rsDebug("test_convert FAILED", 0); } else { rsDebug("test_convert PASSED", 0); } return failed; } void convert_test() { bool failed = false; failed |= test_convert(); if (failed)
else { rsSendToClientBlocking(RS_MSG_TEST_PASSED); } }
{ rsSendToClientBlocking(RS_MSG_TEST_FAILED); }
conditional_block
convert.rs
#include "shared.rsh" float4 f4 = { 2.0f, 4.0f, 6.0f, 8.0f };
static bool test_convert() { bool failed = false; f4 = convert_float4(i8_4); _RS_ASSERT(f4.x == -1.0f); _RS_ASSERT(f4.y == -2.0f); _RS_ASSERT(f4.z == -3.0f); _RS_ASSERT(f4.w == 4.0f); if (failed) { rsDebug("test_convert FAILED", 0); } else { rsDebug("test_convert PASSED", 0); } return failed; } void convert_test() { bool failed = false; failed |= test_convert(); if (failed) { rsSendToClientBlocking(RS_MSG_TEST_FAILED); } else { rsSendToClientBlocking(RS_MSG_TEST_PASSED); } }
char4 i8_4 = { -1, -2, -3, 4 };
random_line_split
advapi32.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> #![feature(test)] #![cfg(windows)] extern crate advapi32; extern crate test; use advapi32::*; use test::black_box as bb; #[test] fn f
) { bb(AdjustTokenPrivileges); bb(CloseServiceHandle); bb(ControlService); bb(CreateServiceA); bb(CreateServiceW); bb(CryptAcquireContextA); bb(CryptAcquireContextW); bb(CryptCreateHash); bb(CryptDestroyHash); bb(CryptGetHashParam); bb(CryptHashData); bb(CryptReleaseContext); bb(DeleteService); bb(OpenProcessToken); bb(OpenSCManagerA); bb(OpenSCManagerW); bb(OpenServiceA); bb(OpenServiceW); bb(QueryServiceStatus); bb(QueryServiceStatusEx); bb(RegCloseKey); bb(RegConnectRegistryA); bb(RegConnectRegistryW); bb(RegCopyTreeA); bb(RegCopyTreeW); bb(RegCreateKeyExA); bb(RegCreateKeyExW); bb(RegDeleteKeyA); bb(RegDeleteKeyExA); bb(RegDeleteKeyExW); bb(RegDeleteKeyValueA); bb(RegDeleteKeyValueW); bb(RegDeleteKeyW); bb(RegDeleteTreeA); bb(RegDeleteTreeW); bb(RegDeleteValueA); bb(RegDeleteValueW); bb(RegDisablePredefinedCache); bb(RegDisablePredefinedCacheEx); bb(RegDisableReflectionKey); bb(RegEnableReflectionKey); bb(RegEnumKeyExA); bb(RegEnumKeyExW); bb(RegEnumValueA); bb(RegEnumValueW); bb(RegFlushKey); bb(RegGetValueA); bb(RegGetValueW); bb(RegLoadMUIStringW); bb(RegNotifyChangeKeyValue); bb(RegOpenCurrentUser); bb(RegOpenKeyExA); bb(RegOpenKeyExW); bb(RegOpenUserClassesRoot); bb(RegOverridePredefKey); bb(RegQueryInfoKeyA); bb(RegQueryInfoKeyW); bb(RegQueryMultipleValuesA); bb(RegQueryMultipleValuesW); bb(RegQueryReflectionKey); bb(RegQueryValueExA); bb(RegQueryValueExW); bb(RegSetKeyValueA); bb(RegSetValueExA); bb(RegSetValueExW); bb(RegSetKeyValueW); bb(RegisterServiceCtrlHandlerA); bb(RegisterServiceCtrlHandlerExA); bb(RegisterServiceCtrlHandlerExW); bb(RegisterServiceCtrlHandlerW); bb(SetServiceStatus); bb(StartServiceCtrlDispatcherA); bb(StartServiceCtrlDispatcherW); }
unctions(
identifier_name